blob: 36a832c0fbe62febf68cccb031a049fe3c56e534 [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
17#include <algorithm>
18#include <functional>
19#include <list>
20#include <map>
21#include <memory>
22#include <utility>
23#include <vector>
24
Karl Wiberg1b0eae32017-10-17 14:48:54 +020025#include "api/audio_codecs/builtin_audio_decoder_factory.h"
26#include "api/audio_codecs/builtin_audio_encoder_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "api/mediastreaminterface.h"
28#include "api/peerconnectioninterface.h"
Steve Anton8c0f7a72017-10-03 10:03:10 -070029#include "api/peerconnectionproxy.h"
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +010030#include "api/rtpreceiverinterface.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020031#include "api/umametrics.h"
Anders Carlsson67537952018-05-03 11:28:29 +020032#include "api/video_codecs/builtin_video_decoder_factory.h"
33#include "api/video_codecs/builtin_video_encoder_factory.h"
34#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070035#include "call/call.h"
36#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
37#include "logging/rtc_event_log/rtc_event_log_factory_interface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "media/engine/fakewebrtcvideoengine.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070039#include "media/engine/webrtcmediaengine.h"
40#include "modules/audio_processing/include/audio_processing.h"
Zach Stein6fcdc2f2018-08-23 16:25:55 -070041#include "p2p/base/mockasyncresolver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "p2p/base/p2pconstants.h"
43#include "p2p/base/portinterface.h"
Steve Antonede9ca52017-10-16 13:04:27 -070044#include "p2p/base/teststunserver.h"
Jonas Orelandbdcee282017-10-10 14:01:40 +020045#include "p2p/base/testturncustomizer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "p2p/base/testturnserver.h"
47#include "p2p/client/basicportallocator.h"
48#include "pc/dtmfsender.h"
49#include "pc/localaudiosource.h"
50#include "pc/mediasession.h"
51#include "pc/peerconnection.h"
52#include "pc/peerconnectionfactory.h"
Seth Hampson2f0d7022018-02-20 11:54:42 -080053#include "pc/rtpmediautils.h"
Steve Anton4ab68ee2017-12-19 14:26:11 -080054#include "pc/sessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020055#include "pc/test/fakeaudiocapturemodule.h"
Niels Möller0f405822018-05-17 09:16:41 +020056#include "pc/test/fakeperiodicvideotracksource.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020057#include "pc/test/fakertccertificategenerator.h"
58#include "pc/test/fakevideotrackrenderer.h"
59#include "pc/test/mockpeerconnectionobservers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#include "rtc_base/fakenetwork.h"
Steve Antonede9ca52017-10-16 13:04:27 -070061#include "rtc_base/firewallsocketserver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020062#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020063#include "rtc_base/numerics/safe_conversions.h"
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070064#include "rtc_base/testcertificateverifier.h"
Johannes Kron965e7942018-09-13 15:36:20 +020065#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020066#include "rtc_base/virtualsocketserver.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020067#include "system_wrappers/include/metrics.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020068#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070069
70using cricket::ContentInfo;
71using cricket::FakeWebRtcVideoDecoder;
72using cricket::FakeWebRtcVideoDecoderFactory;
73using cricket::FakeWebRtcVideoEncoder;
74using cricket::FakeWebRtcVideoEncoderFactory;
75using cricket::MediaContentDescription;
Steve Antondf527fd2018-04-27 15:52:03 -070076using cricket::StreamParams;
Steve Antonede9ca52017-10-16 13:04:27 -070077using rtc::SocketAddress;
Seth Hampson2f0d7022018-02-20 11:54:42 -080078using ::testing::Combine;
Steve Antonede9ca52017-10-16 13:04:27 -070079using ::testing::ElementsAre;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070080using ::testing::Return;
81using ::testing::SetArgPointee;
Steve Antonede9ca52017-10-16 13:04:27 -070082using ::testing::Values;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070083using ::testing::_;
deadbeef1dcb1642017-03-29 21:08:16 -070084using webrtc::DataBuffer;
85using webrtc::DataChannelInterface;
86using webrtc::DtmfSender;
87using webrtc::DtmfSenderInterface;
88using webrtc::DtmfSenderObserverInterface;
Steve Anton15324772018-01-16 10:26:49 -080089using webrtc::FakeVideoTrackRenderer;
deadbeef1dcb1642017-03-29 21:08:16 -070090using webrtc::MediaStreamInterface;
91using webrtc::MediaStreamTrackInterface;
92using webrtc::MockCreateSessionDescriptionObserver;
93using webrtc::MockDataChannelObserver;
94using webrtc::MockSetSessionDescriptionObserver;
95using webrtc::MockStatsObserver;
96using webrtc::ObserverInterface;
Steve Anton8c0f7a72017-10-03 10:03:10 -070097using webrtc::PeerConnection;
deadbeef1dcb1642017-03-29 21:08:16 -070098using webrtc::PeerConnectionInterface;
Steve Anton74255ff2018-01-24 18:32:57 -080099using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -0700100using webrtc::PeerConnectionFactory;
Steve Anton8c0f7a72017-10-03 10:03:10 -0700101using webrtc::PeerConnectionProxy;
Steve Anton15324772018-01-16 10:26:49 -0800102using webrtc::RTCErrorType;
Steve Anton7eca0932018-03-30 15:18:41 -0700103using webrtc::RTCTransportStats;
Steve Anton74255ff2018-01-24 18:32:57 -0800104using webrtc::RtpSenderInterface;
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100105using webrtc::RtpReceiverInterface;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800106using webrtc::RtpSenderInterface;
107using webrtc::RtpTransceiverDirection;
108using webrtc::RtpTransceiverInit;
109using webrtc::RtpTransceiverInterface;
Steve Antond3679212018-01-17 17:41:02 -0800110using webrtc::SdpSemantics;
Steve Antona3a92c22017-12-07 10:27:41 -0800111using webrtc::SdpType;
deadbeef1dcb1642017-03-29 21:08:16 -0700112using webrtc::SessionDescriptionInterface;
113using webrtc::StreamCollectionInterface;
Steve Anton15324772018-01-16 10:26:49 -0800114using webrtc::VideoTrackInterface;
deadbeef1dcb1642017-03-29 21:08:16 -0700115
116namespace {
117
118static const int kDefaultTimeout = 10000;
119static const int kMaxWaitForStatsMs = 3000;
120static const int kMaxWaitForActivationMs = 5000;
121static const int kMaxWaitForFramesMs = 10000;
122// Default number of audio/video frames to wait for before considering a test
123// successful.
124static const int kDefaultExpectedAudioFrameCount = 3;
125static const int kDefaultExpectedVideoFrameCount = 3;
126
deadbeef1dcb1642017-03-29 21:08:16 -0700127static const char kDataChannelLabel[] = "data_channel";
128
129// SRTP cipher name negotiated by the tests. This must be updated if the
130// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700131static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700132static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
133
Steve Antonede9ca52017-10-16 13:04:27 -0700134static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
135
deadbeef1dcb1642017-03-29 21:08:16 -0700136// Helper function for constructing offer/answer options to initiate an ICE
137// restart.
138PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
139 PeerConnectionInterface::RTCOfferAnswerOptions options;
140 options.ice_restart = true;
141 return options;
142}
143
deadbeefd8ad7882017-04-18 16:01:17 -0700144// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
145// attribute from received SDP, simulating a legacy endpoint.
146void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
147 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800148 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700149 }
150 desc->set_msid_supported(false);
151}
152
Seth Hampson5897a6e2018-04-03 11:16:33 -0700153// Removes all stream information besides the stream ids, simulating an
154// endpoint that only signals a=msid lines to convey stream_ids.
155void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
156 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700157 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700158 std::vector<std::string> stream_ids;
159 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700160 const StreamParams& first_stream =
161 content.media_description()->streams()[0];
162 track_id = first_stream.id;
163 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700164 }
165 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700166 StreamParams new_stream;
167 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700168 new_stream.set_stream_ids(stream_ids);
169 content.media_description()->AddStream(new_stream);
170 }
171}
172
zhihuangf8164932017-05-19 13:09:47 -0700173int FindFirstMediaStatsIndexByKind(
174 const std::string& kind,
175 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
176 media_stats_vec) {
177 for (size_t i = 0; i < media_stats_vec.size(); i++) {
178 if (media_stats_vec[i]->kind.ValueToString() == kind) {
179 return i;
180 }
181 }
182 return -1;
183}
184
deadbeef1dcb1642017-03-29 21:08:16 -0700185class SignalingMessageReceiver {
186 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800187 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700188 virtual void ReceiveIceMessage(const std::string& sdp_mid,
189 int sdp_mline_index,
190 const std::string& msg) = 0;
191
192 protected:
193 SignalingMessageReceiver() {}
194 virtual ~SignalingMessageReceiver() {}
195};
196
197class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
198 public:
199 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
200 : expected_media_type_(media_type) {}
201
202 void OnFirstPacketReceived(cricket::MediaType media_type) override {
203 ASSERT_EQ(expected_media_type_, media_type);
204 first_packet_received_ = true;
205 }
206
207 bool first_packet_received() const { return first_packet_received_; }
208
209 virtual ~MockRtpReceiverObserver() {}
210
211 private:
212 bool first_packet_received_ = false;
213 cricket::MediaType expected_media_type_;
214};
215
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700216// Used by PeerConnectionWrapper::OnIceCandidate to allow a test to modify an
217// ICE candidate before it is signaled.
218class IceCandidateReplacerInterface {
219 public:
220 virtual ~IceCandidateReplacerInterface() = default;
221 // Return nullptr to drop the candidate (it won't be signaled to the other
222 // side).
223 virtual std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
224 const webrtc::IceCandidateInterface*) = 0;
225};
226
deadbeef1dcb1642017-03-29 21:08:16 -0700227// Helper class that wraps a peer connection, observes it, and can accept
228// signaling messages from another wrapper.
229//
230// Uses a fake network, fake A/V capture, and optionally fake
231// encoders/decoders, though they aren't used by default since they don't
232// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700233// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800234// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700235class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800236 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700237 public:
238 // Different factory methods for convenience.
239 // TODO(deadbeef): Could use the pattern of:
240 //
241 // PeerConnectionWrapper =
242 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
243 //
244 // To reduce some code duplication.
245 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
246 const std::string& debug_name,
247 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
248 rtc::Thread* network_thread,
249 rtc::Thread* worker_thread) {
250 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700251 webrtc::PeerConnectionDependencies dependencies(nullptr);
252 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200253 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
254 worker_thread, nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700255 delete client;
256 return nullptr;
257 }
258 return client;
259 }
260
deadbeef2f425aa2017-04-14 10:41:32 -0700261 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
262 return peer_connection_factory_.get();
263 }
264
deadbeef1dcb1642017-03-29 21:08:16 -0700265 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
266
267 // If a signaling message receiver is set (via ConnectFakeSignaling), this
268 // will set the whole offer/answer exchange in motion. Just need to wait for
269 // the signaling state to reach "stable".
270 void CreateAndSetAndSignalOffer() {
271 auto offer = CreateOffer();
272 ASSERT_NE(nullptr, offer);
273 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
274 }
275
276 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
277 // when a remote offer is received (via fake signaling) and an answer is
278 // generated. By default, uses default options.
279 void SetOfferAnswerOptions(
280 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
281 offer_answer_options_ = options;
282 }
283
284 // Set a callback to be invoked when SDP is received via the fake signaling
285 // channel, which provides an opportunity to munge (modify) the SDP. This is
286 // used to test SDP being applied that a PeerConnection would normally not
287 // generate, but a non-JSEP endpoint might.
288 void SetReceivedSdpMunger(
289 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100290 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700291 }
292
deadbeefc964d0b2017-04-03 10:03:35 -0700293 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700294 // generated.
295 void SetGeneratedSdpMunger(
296 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100297 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700298 }
299
Seth Hampson2f0d7022018-02-20 11:54:42 -0800300 // Set a callback to be invoked when a remote offer is received via the fake
301 // signaling channel. This provides an opportunity to change the
302 // PeerConnection state before an answer is created and sent to the caller.
303 void SetRemoteOfferHandler(std::function<void()> handler) {
304 remote_offer_handler_ = std::move(handler);
305 }
306
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700307 void SetLocalIceCandidateReplacer(
308 std::unique_ptr<IceCandidateReplacerInterface> replacer) {
309 local_ice_candidate_replacer_ = std::move(replacer);
310 }
311
Steve Antonede9ca52017-10-16 13:04:27 -0700312 // Every ICE connection state in order that has been seen by the observer.
313 std::vector<PeerConnectionInterface::IceConnectionState>
314 ice_connection_state_history() const {
315 return ice_connection_state_history_;
316 }
Steve Anton6f25b092017-10-23 09:39:20 -0700317 void clear_ice_connection_state_history() {
318 ice_connection_state_history_.clear();
319 }
Steve Antonede9ca52017-10-16 13:04:27 -0700320
321 // Every ICE gathering state in order that has been seen by the observer.
322 std::vector<PeerConnectionInterface::IceGatheringState>
323 ice_gathering_state_history() const {
324 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700325 }
326
Steve Anton15324772018-01-16 10:26:49 -0800327 void AddAudioVideoTracks() {
328 AddAudioTrack();
329 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700330 }
331
Steve Anton74255ff2018-01-24 18:32:57 -0800332 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
333 return AddTrack(CreateLocalAudioTrack());
334 }
deadbeef1dcb1642017-03-29 21:08:16 -0700335
Steve Anton74255ff2018-01-24 18:32:57 -0800336 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
337 return AddTrack(CreateLocalVideoTrack());
338 }
deadbeef1dcb1642017-03-29 21:08:16 -0700339
340 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200341 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700342 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200343 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700344 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200345 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700346 // TODO(perkj): Test audio source when it is implemented. Currently audio
347 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700348 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700349 source);
350 }
351
352 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200353 webrtc::FakePeriodicVideoSource::Config config;
354 config.timestamp_offset_ms = rtc::TimeMillis();
355 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700356 }
357
358 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200359 CreateLocalVideoTrackWithConfig(
360 webrtc::FakePeriodicVideoSource::Config config) {
361 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700362 }
363
364 rtc::scoped_refptr<webrtc::VideoTrackInterface>
365 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200366 webrtc::FakePeriodicVideoSource::Config config;
367 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200368 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200369 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700370 }
371
Steve Anton74255ff2018-01-24 18:32:57 -0800372 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
373 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800374 const std::vector<std::string>& stream_ids = {}) {
375 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800376 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800377 return result.MoveValue();
378 }
379
380 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
381 cricket::MediaType media_type) {
382 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
383 for (auto receiver : pc()->GetReceivers()) {
384 if (receiver->media_type() == media_type) {
385 receivers.push_back(receiver);
386 }
387 }
388 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700389 }
390
Seth Hampson2f0d7022018-02-20 11:54:42 -0800391 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
392 cricket::MediaType media_type) {
393 for (auto transceiver : pc()->GetTransceivers()) {
394 if (transceiver->receiver()->media_type() == media_type) {
395 return transceiver;
396 }
397 }
398 return nullptr;
399 }
400
deadbeef1dcb1642017-03-29 21:08:16 -0700401 bool SignalingStateStable() {
402 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
403 }
404
405 void CreateDataChannel() { CreateDataChannel(nullptr); }
406
407 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700408 CreateDataChannel(kDataChannelLabel, init);
409 }
410
411 void CreateDataChannel(const std::string& label,
412 const webrtc::DataChannelInit* init) {
413 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700414 ASSERT_TRUE(data_channel_.get() != nullptr);
415 data_observer_.reset(new MockDataChannelObserver(data_channel_));
416 }
417
418 DataChannelInterface* data_channel() { return data_channel_; }
419 const MockDataChannelObserver* data_observer() const {
420 return data_observer_.get();
421 }
422
423 int audio_frames_received() const {
424 return fake_audio_capture_module_->frames_received();
425 }
426
427 // Takes minimum of video frames received for each track.
428 //
429 // Can be used like:
430 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
431 //
432 // To ensure that all video tracks received at least a certain number of
433 // frames.
434 int min_video_frames_received_per_track() const {
435 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200436 if (fake_video_renderers_.empty()) {
437 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700438 }
deadbeef1dcb1642017-03-29 21:08:16 -0700439
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200440 for (const auto& pair : fake_video_renderers_) {
441 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700442 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200443 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700444 }
445
446 // Returns a MockStatsObserver in a state after stats gathering finished,
447 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700448 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700449 webrtc::MediaStreamTrackInterface* track) {
450 rtc::scoped_refptr<MockStatsObserver> observer(
451 new rtc::RefCountedObject<MockStatsObserver>());
452 EXPECT_TRUE(peer_connection_->GetStats(
453 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
454 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
455 return observer;
456 }
457
458 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700459 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
460 return OldGetStatsForTrack(nullptr);
461 }
462
463 // Synchronously gets stats and returns them. If it times out, fails the test
464 // and returns null.
465 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
466 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
467 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
468 peer_connection_->GetStats(callback);
469 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
470 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700471 }
472
473 int rendered_width() {
474 EXPECT_FALSE(fake_video_renderers_.empty());
475 return fake_video_renderers_.empty()
476 ? 0
477 : fake_video_renderers_.begin()->second->width();
478 }
479
480 int rendered_height() {
481 EXPECT_FALSE(fake_video_renderers_.empty());
482 return fake_video_renderers_.empty()
483 ? 0
484 : fake_video_renderers_.begin()->second->height();
485 }
486
487 double rendered_aspect_ratio() {
488 if (rendered_height() == 0) {
489 return 0.0;
490 }
491 return static_cast<double>(rendered_width()) / rendered_height();
492 }
493
494 webrtc::VideoRotation rendered_rotation() {
495 EXPECT_FALSE(fake_video_renderers_.empty());
496 return fake_video_renderers_.empty()
497 ? webrtc::kVideoRotation_0
498 : fake_video_renderers_.begin()->second->rotation();
499 }
500
501 int local_rendered_width() {
502 return local_video_renderer_ ? local_video_renderer_->width() : 0;
503 }
504
505 int local_rendered_height() {
506 return local_video_renderer_ ? local_video_renderer_->height() : 0;
507 }
508
509 double local_rendered_aspect_ratio() {
510 if (local_rendered_height() == 0) {
511 return 0.0;
512 }
513 return static_cast<double>(local_rendered_width()) /
514 local_rendered_height();
515 }
516
517 size_t number_of_remote_streams() {
518 if (!pc()) {
519 return 0;
520 }
521 return pc()->remote_streams()->count();
522 }
523
524 StreamCollectionInterface* remote_streams() const {
525 if (!pc()) {
526 ADD_FAILURE();
527 return nullptr;
528 }
529 return pc()->remote_streams();
530 }
531
532 StreamCollectionInterface* local_streams() {
533 if (!pc()) {
534 ADD_FAILURE();
535 return nullptr;
536 }
537 return pc()->local_streams();
538 }
539
540 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
541 return pc()->signaling_state();
542 }
543
544 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
545 return pc()->ice_connection_state();
546 }
547
548 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
549 return pc()->ice_gathering_state();
550 }
551
552 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
553 // GetReceivers. They're updated automatically when a remote offer/answer
554 // from the fake signaling channel is applied, or when
555 // ResetRtpReceiverObservers below is called.
556 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
557 rtp_receiver_observers() {
558 return rtp_receiver_observers_;
559 }
560
561 void ResetRtpReceiverObservers() {
562 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100563 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
564 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700565 std::unique_ptr<MockRtpReceiverObserver> observer(
566 new MockRtpReceiverObserver(receiver->media_type()));
567 receiver->SetObserver(observer.get());
568 rtp_receiver_observers_.push_back(std::move(observer));
569 }
570 }
571
Steve Antonede9ca52017-10-16 13:04:27 -0700572 rtc::FakeNetworkManager* network() const {
573 return fake_network_manager_.get();
574 }
575 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
576
Qingsi Wang7685e862018-06-11 20:15:46 -0700577 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
578 return event_log_factory_;
579 }
580
deadbeef1dcb1642017-03-29 21:08:16 -0700581 private:
582 explicit PeerConnectionWrapper(const std::string& debug_name)
583 : debug_name_(debug_name) {}
584
Niels Möllerf06f9232018-08-07 12:32:18 +0200585 bool Init(const PeerConnectionFactory::Options* options,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700586 const PeerConnectionInterface::RTCConfiguration* config,
587 webrtc::PeerConnectionDependencies dependencies,
588 rtc::Thread* network_thread,
Qingsi Wang7685e862018-06-11 20:15:46 -0700589 rtc::Thread* worker_thread,
590 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700591 // There's an error in this test code if Init ends up being called twice.
592 RTC_DCHECK(!peer_connection_);
593 RTC_DCHECK(!peer_connection_factory_);
594
595 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700596 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700597
598 std::unique_ptr<cricket::PortAllocator> port_allocator(
599 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700600 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700601 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
602 if (!fake_audio_capture_module_) {
603 return false;
604 }
deadbeef1dcb1642017-03-29 21:08:16 -0700605 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700606
607 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
608 pc_factory_dependencies.network_thread = network_thread;
609 pc_factory_dependencies.worker_thread = worker_thread;
610 pc_factory_dependencies.signaling_thread = signaling_thread;
611 pc_factory_dependencies.media_engine =
612 cricket::WebRtcMediaEngineFactory::Create(
613 rtc::scoped_refptr<webrtc::AudioDeviceModule>(
614 fake_audio_capture_module_),
615 webrtc::CreateBuiltinAudioEncoderFactory(),
616 webrtc::CreateBuiltinAudioDecoderFactory(),
617 webrtc::CreateBuiltinVideoEncoderFactory(),
618 webrtc::CreateBuiltinVideoDecoderFactory(), nullptr,
619 webrtc::AudioProcessingBuilder().Create());
620 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
621 if (event_log_factory) {
622 event_log_factory_ = event_log_factory.get();
623 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
624 } else {
625 pc_factory_dependencies.event_log_factory =
626 webrtc::CreateRtcEventLogFactory();
627 }
628 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
629 std::move(pc_factory_dependencies));
630
deadbeef1dcb1642017-03-29 21:08:16 -0700631 if (!peer_connection_factory_) {
632 return false;
633 }
634 if (options) {
635 peer_connection_factory_->SetOptions(*options);
636 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800637 if (config) {
638 sdp_semantics_ = config->sdp_semantics;
639 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700640
641 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200642 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700643 return peer_connection_.get() != nullptr;
644 }
645
646 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700647 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700648 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700649 PeerConnectionInterface::RTCConfiguration modified_config;
650 // If |config| is null, this will result in a default configuration being
651 // used.
652 if (config) {
653 modified_config = *config;
654 }
655 // Disable resolution adaptation; we don't want it interfering with the
656 // test results.
657 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
658 // ratios and not specific resolutions, is this even necessary?
659 modified_config.set_cpu_adaptation(false);
660
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700661 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700662 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700663 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700664 }
665
666 void set_signaling_message_receiver(
667 SignalingMessageReceiver* signaling_message_receiver) {
668 signaling_message_receiver_ = signaling_message_receiver;
669 }
670
671 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
672
Steve Antonede9ca52017-10-16 13:04:27 -0700673 void set_signal_ice_candidates(bool signal) {
674 signal_ice_candidates_ = signal;
675 }
676
deadbeef1dcb1642017-03-29 21:08:16 -0700677 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200678 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700679 // Set max frame rate to 10fps to reduce the risk of test flakiness.
680 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200681 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700682
Niels Möller5c7efe72018-05-11 10:34:46 +0200683 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200684 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
685 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700686 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200687 peer_connection_factory_->CreateVideoTrack(
688 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700689 if (!local_video_renderer_) {
690 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
691 }
692 return track;
693 }
694
695 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100696 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800697 std::unique_ptr<SessionDescriptionInterface> desc =
698 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700699 if (received_sdp_munger_) {
700 received_sdp_munger_(desc->description());
701 }
702
703 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
704 // Setting a remote description may have changed the number of receivers,
705 // so reset the receiver observers.
706 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800707 if (remote_offer_handler_) {
708 remote_offer_handler_();
709 }
deadbeef1dcb1642017-03-29 21:08:16 -0700710 auto answer = CreateAnswer();
711 ASSERT_NE(nullptr, answer);
712 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
713 }
714
715 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100716 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800717 std::unique_ptr<SessionDescriptionInterface> desc =
718 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700719 if (received_sdp_munger_) {
720 received_sdp_munger_(desc->description());
721 }
722
723 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
724 // Set the RtpReceiverObserver after receivers are created.
725 ResetRtpReceiverObservers();
726 }
727
728 // Returns null on failure.
729 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
730 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
731 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
732 pc()->CreateOffer(observer, offer_answer_options_);
733 return WaitForDescriptionFromObserver(observer);
734 }
735
736 // Returns null on failure.
737 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
738 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
739 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
740 pc()->CreateAnswer(observer, offer_answer_options_);
741 return WaitForDescriptionFromObserver(observer);
742 }
743
744 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100745 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700746 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
747 if (!observer->result()) {
748 return nullptr;
749 }
750 auto description = observer->MoveDescription();
751 if (generated_sdp_munger_) {
752 generated_sdp_munger_(description->description());
753 }
754 return description;
755 }
756
757 // Setting the local description and sending the SDP message over the fake
758 // signaling channel are combined into the same method because the SDP
759 // message needs to be sent as soon as SetLocalDescription finishes, without
760 // waiting for the observer to be called. This ensures that ICE candidates
761 // don't outrace the description.
762 bool SetLocalDescriptionAndSendSdpMessage(
763 std::unique_ptr<SessionDescriptionInterface> desc) {
764 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
765 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100766 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800767 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700768 std::string sdp;
769 EXPECT_TRUE(desc->ToString(&sdp));
770 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800771 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
772 RemoveUnusedVideoRenderers();
773 }
deadbeef1dcb1642017-03-29 21:08:16 -0700774 // As mentioned above, we need to send the message immediately after
775 // SetLocalDescription.
776 SendSdpMessage(type, sdp);
777 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
778 return true;
779 }
780
781 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
782 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
783 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100784 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700785 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800786 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
787 RemoveUnusedVideoRenderers();
788 }
deadbeef1dcb1642017-03-29 21:08:16 -0700789 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
790 return observer->result();
791 }
792
Seth Hampson2f0d7022018-02-20 11:54:42 -0800793 // This is a work around to remove unused fake_video_renderers from
794 // transceivers that have either stopped or are no longer receiving.
795 void RemoveUnusedVideoRenderers() {
796 auto transceivers = pc()->GetTransceivers();
797 for (auto& transceiver : transceivers) {
798 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
799 continue;
800 }
801 // Remove fake video renderers from any stopped transceivers.
802 if (transceiver->stopped()) {
803 auto it =
804 fake_video_renderers_.find(transceiver->receiver()->track()->id());
805 if (it != fake_video_renderers_.end()) {
806 fake_video_renderers_.erase(it);
807 }
808 }
809 // Remove fake video renderers from any transceivers that are no longer
810 // receiving.
811 if ((transceiver->current_direction() &&
812 !webrtc::RtpTransceiverDirectionHasRecv(
813 *transceiver->current_direction()))) {
814 auto it =
815 fake_video_renderers_.find(transceiver->receiver()->track()->id());
816 if (it != fake_video_renderers_.end()) {
817 fake_video_renderers_.erase(it);
818 }
819 }
820 }
821 }
822
deadbeef1dcb1642017-03-29 21:08:16 -0700823 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
824 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800825 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700826 if (signaling_delay_ms_ == 0) {
827 RelaySdpMessageIfReceiverExists(type, msg);
828 } else {
829 invoker_.AsyncInvokeDelayed<void>(
830 RTC_FROM_HERE, rtc::Thread::Current(),
831 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
832 this, type, msg),
833 signaling_delay_ms_);
834 }
835 }
836
Steve Antona3a92c22017-12-07 10:27:41 -0800837 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700838 if (signaling_message_receiver_) {
839 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
840 }
841 }
842
843 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
844 // default).
845 void SendIceMessage(const std::string& sdp_mid,
846 int sdp_mline_index,
847 const std::string& msg) {
848 if (signaling_delay_ms_ == 0) {
849 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
850 } else {
851 invoker_.AsyncInvokeDelayed<void>(
852 RTC_FROM_HERE, rtc::Thread::Current(),
853 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
854 this, sdp_mid, sdp_mline_index, msg),
855 signaling_delay_ms_);
856 }
857 }
858
859 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
860 int sdp_mline_index,
861 const std::string& msg) {
862 if (signaling_message_receiver_) {
863 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
864 msg);
865 }
866 }
867
868 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800869 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
870 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700871 HandleIncomingOffer(msg);
872 } else {
873 HandleIncomingAnswer(msg);
874 }
875 }
876
877 void ReceiveIceMessage(const std::string& sdp_mid,
878 int sdp_mline_index,
879 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100880 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700881 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
882 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
883 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
884 }
885
886 // PeerConnectionObserver callbacks.
887 void OnSignalingChange(
888 webrtc::PeerConnectionInterface::SignalingState new_state) override {
889 EXPECT_EQ(pc()->signaling_state(), new_state);
890 }
Steve Anton15324772018-01-16 10:26:49 -0800891 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
892 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
893 streams) override {
894 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
895 rtc::scoped_refptr<VideoTrackInterface> video_track(
896 static_cast<VideoTrackInterface*>(receiver->track().get()));
897 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700898 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800899 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200900 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700901 }
902 }
Steve Anton15324772018-01-16 10:26:49 -0800903 void OnRemoveTrack(
904 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
905 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
906 auto it = fake_video_renderers_.find(receiver->track()->id());
907 RTC_DCHECK(it != fake_video_renderers_.end());
908 fake_video_renderers_.erase(it);
909 }
910 }
deadbeef1dcb1642017-03-29 21:08:16 -0700911 void OnRenegotiationNeeded() override {}
912 void OnIceConnectionChange(
913 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
914 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700915 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700916 }
917 void OnIceGatheringChange(
918 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700919 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700920 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700921 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700922 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceIceCandidate(
923 const webrtc::IceCandidateInterface* candidate) {
924 std::string candidate_string;
925 candidate->ToString(&candidate_string);
926
927 auto owned_candidate =
928 local_ice_candidate_replacer_->ReplaceCandidate(candidate);
929 if (!owned_candidate) {
930 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer dropped \""
931 << candidate_string << "\"";
932 return nullptr;
933 }
934 std::string owned_candidate_string;
935 owned_candidate->ToString(&owned_candidate_string);
936 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer changed \""
937 << candidate_string << "\" to \"" << owned_candidate_string
938 << "\"";
939 return owned_candidate;
940 }
deadbeef1dcb1642017-03-29 21:08:16 -0700941 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100942 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700943
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700944 const webrtc::IceCandidateInterface* new_candidate = candidate;
945 std::unique_ptr<webrtc::IceCandidateInterface> owned_candidate;
946 if (local_ice_candidate_replacer_) {
947 owned_candidate = ReplaceIceCandidate(candidate);
948 if (!owned_candidate) {
949 return; // The candidate was dropped.
950 }
951 new_candidate = owned_candidate.get();
952 }
953
deadbeef1dcb1642017-03-29 21:08:16 -0700954 std::string ice_sdp;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700955 EXPECT_TRUE(new_candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700956 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700957 // Remote party may be deleted.
958 return;
959 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700960 SendIceMessage(new_candidate->sdp_mid(), new_candidate->sdp_mline_index(),
961 ice_sdp);
deadbeef1dcb1642017-03-29 21:08:16 -0700962 }
963 void OnDataChannel(
964 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100965 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700966 data_channel_ = data_channel;
967 data_observer_.reset(new MockDataChannelObserver(data_channel));
968 }
969
deadbeef1dcb1642017-03-29 21:08:16 -0700970 std::string debug_name_;
971
972 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
973
974 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
975 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
976 peer_connection_factory_;
977
Steve Antonede9ca52017-10-16 13:04:27 -0700978 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700979 // Needed to keep track of number of frames sent.
980 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
981 // Needed to keep track of number of frames received.
982 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
983 fake_video_renderers_;
984 // Needed to ensure frames aren't received for removed tracks.
985 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
986 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -0700987
988 // For remote peer communication.
989 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
990 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -0700991 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -0700992
Niels Möller5c7efe72018-05-11 10:34:46 +0200993 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -0700994 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +0200995 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
996 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -0700997 // |local_video_renderer_| attached to the first created local video track.
998 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
999
Seth Hampson2f0d7022018-02-20 11:54:42 -08001000 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001001 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1002 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1003 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001004 std::function<void()> remote_offer_handler_;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07001005 std::unique_ptr<IceCandidateReplacerInterface> local_ice_candidate_replacer_;
deadbeef1dcb1642017-03-29 21:08:16 -07001006 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1007 std::unique_ptr<MockDataChannelObserver> data_observer_;
1008
1009 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1010
Steve Antonede9ca52017-10-16 13:04:27 -07001011 std::vector<PeerConnectionInterface::IceConnectionState>
1012 ice_connection_state_history_;
1013 std::vector<PeerConnectionInterface::IceGatheringState>
1014 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001015
Qingsi Wang7685e862018-06-11 20:15:46 -07001016 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1017
deadbeef1dcb1642017-03-29 21:08:16 -07001018 rtc::AsyncInvoker invoker_;
1019
Seth Hampson2f0d7022018-02-20 11:54:42 -08001020 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001021};
1022
Elad Alon99c3fe52017-10-13 16:29:40 +02001023class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1024 public:
1025 virtual ~MockRtcEventLogOutput() = default;
1026 MOCK_CONST_METHOD0(IsActive, bool());
1027 MOCK_METHOD1(Write, bool(const std::string&));
1028};
1029
Seth Hampson2f0d7022018-02-20 11:54:42 -08001030// This helper object is used for both specifying how many audio/video frames
1031// are expected to be received for a caller/callee. It provides helper functions
1032// to specify these expectations. The object initially starts in a state of no
1033// expectations.
1034class MediaExpectations {
1035 public:
1036 enum ExpectFrames {
1037 kExpectSomeFrames,
1038 kExpectNoFrames,
1039 kNoExpectation,
1040 };
1041
1042 void ExpectBidirectionalAudioAndVideo() {
1043 ExpectBidirectionalAudio();
1044 ExpectBidirectionalVideo();
1045 }
1046
1047 void ExpectBidirectionalAudio() {
1048 CallerExpectsSomeAudio();
1049 CalleeExpectsSomeAudio();
1050 }
1051
1052 void ExpectNoAudio() {
1053 CallerExpectsNoAudio();
1054 CalleeExpectsNoAudio();
1055 }
1056
1057 void ExpectBidirectionalVideo() {
1058 CallerExpectsSomeVideo();
1059 CalleeExpectsSomeVideo();
1060 }
1061
1062 void ExpectNoVideo() {
1063 CallerExpectsNoVideo();
1064 CalleeExpectsNoVideo();
1065 }
1066
1067 void CallerExpectsSomeAudioAndVideo() {
1068 CallerExpectsSomeAudio();
1069 CallerExpectsSomeVideo();
1070 }
1071
1072 void CalleeExpectsSomeAudioAndVideo() {
1073 CalleeExpectsSomeAudio();
1074 CalleeExpectsSomeVideo();
1075 }
1076
1077 // Caller's audio functions.
1078 void CallerExpectsSomeAudio(
1079 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1080 caller_audio_expectation_ = kExpectSomeFrames;
1081 caller_audio_frames_expected_ = expected_audio_frames;
1082 }
1083
1084 void CallerExpectsNoAudio() {
1085 caller_audio_expectation_ = kExpectNoFrames;
1086 caller_audio_frames_expected_ = 0;
1087 }
1088
1089 // Caller's video functions.
1090 void CallerExpectsSomeVideo(
1091 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1092 caller_video_expectation_ = kExpectSomeFrames;
1093 caller_video_frames_expected_ = expected_video_frames;
1094 }
1095
1096 void CallerExpectsNoVideo() {
1097 caller_video_expectation_ = kExpectNoFrames;
1098 caller_video_frames_expected_ = 0;
1099 }
1100
1101 // Callee's audio functions.
1102 void CalleeExpectsSomeAudio(
1103 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1104 callee_audio_expectation_ = kExpectSomeFrames;
1105 callee_audio_frames_expected_ = expected_audio_frames;
1106 }
1107
1108 void CalleeExpectsNoAudio() {
1109 callee_audio_expectation_ = kExpectNoFrames;
1110 callee_audio_frames_expected_ = 0;
1111 }
1112
1113 // Callee's video functions.
1114 void CalleeExpectsSomeVideo(
1115 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1116 callee_video_expectation_ = kExpectSomeFrames;
1117 callee_video_frames_expected_ = expected_video_frames;
1118 }
1119
1120 void CalleeExpectsNoVideo() {
1121 callee_video_expectation_ = kExpectNoFrames;
1122 callee_video_frames_expected_ = 0;
1123 }
1124
1125 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1126 ExpectFrames caller_video_expectation_ = kNoExpectation;
1127 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1128 ExpectFrames callee_video_expectation_ = kNoExpectation;
1129 int caller_audio_frames_expected_ = 0;
1130 int caller_video_frames_expected_ = 0;
1131 int callee_audio_frames_expected_ = 0;
1132 int callee_video_frames_expected_ = 0;
1133};
1134
deadbeef1dcb1642017-03-29 21:08:16 -07001135// Tests two PeerConnections connecting to each other end-to-end, using a
1136// virtual network, fake A/V capture and fake encoder/decoders. The
1137// PeerConnections share the threads/socket servers, but use separate versions
1138// of everything else (including "PeerConnectionFactory"s).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001139class PeerConnectionIntegrationBaseTest : public testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001140 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001141 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1142 : sdp_semantics_(sdp_semantics),
1143 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001144 fss_(new rtc::FirewallSocketServer(ss_.get())),
1145 network_thread_(new rtc::Thread(fss_.get())),
deadbeef1dcb1642017-03-29 21:08:16 -07001146 worker_thread_(rtc::Thread::Create()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001147 network_thread_->SetName("PCNetworkThread", this);
1148 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001149 RTC_CHECK(network_thread_->Start());
1150 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001151 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001152 }
1153
Seth Hampson2f0d7022018-02-20 11:54:42 -08001154 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001155 // The PeerConnections should deleted before the TurnCustomizers.
1156 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1157 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1158 // that the TurnCustomizer outlives the life of the PeerConnection or else
1159 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001160 if (caller_) {
1161 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001162 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001163 }
1164 if (callee_) {
1165 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001166 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001167 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001168
1169 // If turn servers were created for the test they need to be destroyed on
1170 // the network thread.
1171 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1172 turn_servers_.clear();
1173 turn_customizers_.clear();
1174 });
deadbeef1dcb1642017-03-29 21:08:16 -07001175 }
1176
1177 bool SignalingStateStable() {
1178 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1179 }
1180
deadbeef71452802017-05-07 17:21:01 -07001181 bool DtlsConnected() {
1182 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1183 // are connected. This is an important distinction. Once we have separate
1184 // ICE and DTLS state, this check needs to use the DTLS state.
1185 return (callee()->ice_connection_state() ==
1186 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1187 callee()->ice_connection_state() ==
1188 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1189 (caller()->ice_connection_state() ==
1190 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1191 caller()->ice_connection_state() ==
1192 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
1193 }
1194
Qingsi Wang7685e862018-06-11 20:15:46 -07001195 // When |event_log_factory| is null, the default implementation of the event
1196 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001197 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1198 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001199 const PeerConnectionFactory::Options* options,
1200 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001201 webrtc::PeerConnectionDependencies dependencies,
1202 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001203 RTCConfiguration modified_config;
1204 if (config) {
1205 modified_config = *config;
1206 }
Steve Anton3acffc32018-04-12 17:21:03 -07001207 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001208 if (!dependencies.cert_generator) {
1209 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001210 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001211 }
1212 std::unique_ptr<PeerConnectionWrapper> client(
1213 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001214
Niels Möllerf06f9232018-08-07 12:32:18 +02001215 if (!client->Init(options, &modified_config, std::move(dependencies),
1216 network_thread_.get(), worker_thread_.get(),
1217 std::move(event_log_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001218 return nullptr;
1219 }
1220 return client;
1221 }
1222
Qingsi Wang7685e862018-06-11 20:15:46 -07001223 std::unique_ptr<PeerConnectionWrapper>
1224 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1225 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001226 const PeerConnectionFactory::Options* options,
1227 const RTCConfiguration* config,
1228 webrtc::PeerConnectionDependencies dependencies) {
1229 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1230 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001231 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001232 std::move(dependencies),
1233 std::move(event_log_factory));
1234 }
1235
deadbeef1dcb1642017-03-29 21:08:16 -07001236 bool CreatePeerConnectionWrappers() {
1237 return CreatePeerConnectionWrappersWithConfig(
1238 PeerConnectionInterface::RTCConfiguration(),
1239 PeerConnectionInterface::RTCConfiguration());
1240 }
1241
Steve Anton3acffc32018-04-12 17:21:03 -07001242 bool CreatePeerConnectionWrappersWithSdpSemantics(
1243 SdpSemantics caller_semantics,
1244 SdpSemantics callee_semantics) {
1245 // Can't specify the sdp_semantics in the passed-in configuration since it
1246 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1247 // stored in sdp_semantics_. So get around this by modifying the instance
1248 // variable before calling CreatePeerConnectionWrapper for the caller and
1249 // callee PeerConnections.
1250 SdpSemantics original_semantics = sdp_semantics_;
1251 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001252 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001253 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1254 nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001255 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001256 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001257 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1258 nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001259 sdp_semantics_ = original_semantics;
1260 return caller_ && callee_;
1261 }
1262
deadbeef1dcb1642017-03-29 21:08:16 -07001263 bool CreatePeerConnectionWrappersWithConfig(
1264 const PeerConnectionInterface::RTCConfiguration& caller_config,
1265 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001266 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001267 "Caller", nullptr, &caller_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001268 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001269 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001270 "Callee", nullptr, &callee_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001271 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001272 return caller_ && callee_;
1273 }
1274
1275 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1276 const PeerConnectionInterface::RTCConfiguration& caller_config,
1277 webrtc::PeerConnectionDependencies caller_dependencies,
1278 const PeerConnectionInterface::RTCConfiguration& callee_config,
1279 webrtc::PeerConnectionDependencies callee_dependencies) {
1280 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001281 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001282 std::move(caller_dependencies), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001283 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001284 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001285 std::move(callee_dependencies), nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001286 return caller_ && callee_;
1287 }
1288
1289 bool CreatePeerConnectionWrappersWithOptions(
1290 const PeerConnectionFactory::Options& caller_options,
1291 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001292 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001293 "Caller", &caller_options, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001294 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001295 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001296 "Callee", &callee_options, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001297 webrtc::PeerConnectionDependencies(nullptr), nullptr);
1298 return caller_ && callee_;
1299 }
1300
1301 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1302 PeerConnectionInterface::RTCConfiguration default_config;
1303 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001304 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001305 webrtc::PeerConnectionDependencies(nullptr));
1306 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001307 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001308 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001309 return caller_ && callee_;
1310 }
1311
Seth Hampson2f0d7022018-02-20 11:54:42 -08001312 std::unique_ptr<PeerConnectionWrapper>
1313 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001314 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1315 new FakeRTCCertificateGenerator());
1316 cert_generator->use_alternate_key();
1317
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001318 webrtc::PeerConnectionDependencies dependencies(nullptr);
1319 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001320 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001321 std::move(dependencies), nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001322 }
1323
Seth Hampsonaed71642018-06-11 07:41:32 -07001324 cricket::TestTurnServer* CreateTurnServer(
1325 rtc::SocketAddress internal_address,
1326 rtc::SocketAddress external_address,
1327 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1328 const std::string& common_name = "test turn server") {
1329 rtc::Thread* thread = network_thread();
1330 std::unique_ptr<cricket::TestTurnServer> turn_server =
1331 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1332 RTC_FROM_HERE,
1333 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001334 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001335 thread, internal_address, external_address, type,
1336 /*ignore_bad_certs=*/true, common_name);
1337 });
1338 turn_servers_.push_back(std::move(turn_server));
1339 // Interactions with the turn server should be done on the network thread.
1340 return turn_servers_.back().get();
1341 }
1342
1343 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1344 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1345 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1346 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001347 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001348 turn_customizers_.push_back(std::move(turn_customizer));
1349 // Interactions with the turn customizer should be done on the network
1350 // thread.
1351 return turn_customizers_.back().get();
1352 }
1353
1354 // Checks that the function counters for a TestTurnCustomizer are greater than
1355 // 0.
1356 void ExpectTurnCustomizerCountersIncremented(
1357 cricket::TestTurnCustomizer* turn_customizer) {
1358 unsigned int allow_channel_data_counter =
1359 network_thread()->Invoke<unsigned int>(
1360 RTC_FROM_HERE, [turn_customizer] {
1361 return turn_customizer->allow_channel_data_cnt_;
1362 });
1363 EXPECT_GT(allow_channel_data_counter, 0u);
1364 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1365 RTC_FROM_HERE,
1366 [turn_customizer] { return turn_customizer->modify_cnt_; });
1367 EXPECT_GT(modify_counter, 0u);
1368 }
1369
deadbeef1dcb1642017-03-29 21:08:16 -07001370 // Once called, SDP blobs and ICE candidates will be automatically signaled
1371 // between PeerConnections.
1372 void ConnectFakeSignaling() {
1373 caller_->set_signaling_message_receiver(callee_.get());
1374 callee_->set_signaling_message_receiver(caller_.get());
1375 }
1376
Steve Antonede9ca52017-10-16 13:04:27 -07001377 // Once called, SDP blobs will be automatically signaled between
1378 // PeerConnections. Note that ICE candidates will not be signaled unless they
1379 // are in the exchanged SDP blobs.
1380 void ConnectFakeSignalingForSdpOnly() {
1381 ConnectFakeSignaling();
1382 SetSignalIceCandidates(false);
1383 }
1384
deadbeef1dcb1642017-03-29 21:08:16 -07001385 void SetSignalingDelayMs(int delay_ms) {
1386 caller_->set_signaling_delay_ms(delay_ms);
1387 callee_->set_signaling_delay_ms(delay_ms);
1388 }
1389
Steve Antonede9ca52017-10-16 13:04:27 -07001390 void SetSignalIceCandidates(bool signal) {
1391 caller_->set_signal_ice_candidates(signal);
1392 callee_->set_signal_ice_candidates(signal);
1393 }
1394
deadbeef1dcb1642017-03-29 21:08:16 -07001395 // Messages may get lost on the unreliable DataChannel, so we send multiple
1396 // times to avoid test flakiness.
1397 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1398 const std::string& data,
1399 int retries) {
1400 for (int i = 0; i < retries; ++i) {
1401 dc->Send(DataBuffer(data));
1402 }
1403 }
1404
1405 rtc::Thread* network_thread() { return network_thread_.get(); }
1406
1407 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1408
1409 PeerConnectionWrapper* caller() { return caller_.get(); }
1410
1411 // Set the |caller_| to the |wrapper| passed in and return the
1412 // original |caller_|.
1413 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1414 PeerConnectionWrapper* wrapper) {
1415 PeerConnectionWrapper* old = caller_.release();
1416 caller_.reset(wrapper);
1417 return old;
1418 }
1419
1420 PeerConnectionWrapper* callee() { return callee_.get(); }
1421
1422 // Set the |callee_| to the |wrapper| passed in and return the
1423 // original |callee_|.
1424 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1425 PeerConnectionWrapper* wrapper) {
1426 PeerConnectionWrapper* old = callee_.release();
1427 callee_.reset(wrapper);
1428 return old;
1429 }
1430
Steve Antonede9ca52017-10-16 13:04:27 -07001431 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1432
Seth Hampson2f0d7022018-02-20 11:54:42 -08001433 // Expects the provided number of new frames to be received within
1434 // kMaxWaitForFramesMs. The new expected frames are specified in
1435 // |media_expectations|. Returns false if any of the expectations were
1436 // not met.
1437 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1438 // First initialize the expected frame counts based upon the current
1439 // frame count.
1440 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1441 if (media_expectations.caller_audio_expectation_ ==
1442 MediaExpectations::kExpectSomeFrames) {
1443 total_caller_audio_frames_expected +=
1444 media_expectations.caller_audio_frames_expected_;
1445 }
1446 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001447 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001448 if (media_expectations.caller_video_expectation_ ==
1449 MediaExpectations::kExpectSomeFrames) {
1450 total_caller_video_frames_expected +=
1451 media_expectations.caller_video_frames_expected_;
1452 }
1453 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1454 if (media_expectations.callee_audio_expectation_ ==
1455 MediaExpectations::kExpectSomeFrames) {
1456 total_callee_audio_frames_expected +=
1457 media_expectations.callee_audio_frames_expected_;
1458 }
1459 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001460 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001461 if (media_expectations.callee_video_expectation_ ==
1462 MediaExpectations::kExpectSomeFrames) {
1463 total_callee_video_frames_expected +=
1464 media_expectations.callee_video_frames_expected_;
1465 }
deadbeef1dcb1642017-03-29 21:08:16 -07001466
Seth Hampson2f0d7022018-02-20 11:54:42 -08001467 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001468 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001469 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001470 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001471 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001472 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001473 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001474 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001475 total_callee_video_frames_expected,
1476 kMaxWaitForFramesMs);
1477 bool expectations_correct =
1478 caller()->audio_frames_received() >=
1479 total_caller_audio_frames_expected &&
1480 caller()->min_video_frames_received_per_track() >=
1481 total_caller_video_frames_expected &&
1482 callee()->audio_frames_received() >=
1483 total_callee_audio_frames_expected &&
1484 callee()->min_video_frames_received_per_track() >=
1485 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001486
Seth Hampson2f0d7022018-02-20 11:54:42 -08001487 // After the combined wait, print out a more detailed message upon
1488 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001489 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001490 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001491 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001492 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001493 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001494 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001495 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001496 total_callee_video_frames_expected);
1497
1498 // We want to make sure nothing unexpected was received.
1499 if (media_expectations.caller_audio_expectation_ ==
1500 MediaExpectations::kExpectNoFrames) {
1501 EXPECT_EQ(caller()->audio_frames_received(),
1502 total_caller_audio_frames_expected);
1503 if (caller()->audio_frames_received() !=
1504 total_caller_audio_frames_expected) {
1505 expectations_correct = false;
1506 }
1507 }
1508 if (media_expectations.caller_video_expectation_ ==
1509 MediaExpectations::kExpectNoFrames) {
1510 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1511 total_caller_video_frames_expected);
1512 if (caller()->min_video_frames_received_per_track() !=
1513 total_caller_video_frames_expected) {
1514 expectations_correct = false;
1515 }
1516 }
1517 if (media_expectations.callee_audio_expectation_ ==
1518 MediaExpectations::kExpectNoFrames) {
1519 EXPECT_EQ(callee()->audio_frames_received(),
1520 total_callee_audio_frames_expected);
1521 if (callee()->audio_frames_received() !=
1522 total_callee_audio_frames_expected) {
1523 expectations_correct = false;
1524 }
1525 }
1526 if (media_expectations.callee_video_expectation_ ==
1527 MediaExpectations::kExpectNoFrames) {
1528 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1529 total_callee_video_frames_expected);
1530 if (callee()->min_video_frames_received_per_track() !=
1531 total_callee_video_frames_expected) {
1532 expectations_correct = false;
1533 }
1534 }
1535 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001536 }
1537
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001538 void TestNegotiatedCipherSuite(
1539 const PeerConnectionFactory::Options& caller_options,
1540 const PeerConnectionFactory::Options& callee_options,
1541 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001542 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1543 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001544 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001545 caller()->AddAudioVideoTracks();
1546 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001547 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001548 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001549 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001550 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001551 // TODO(bugs.webrtc.org/9456): Fix it.
1552 EXPECT_EQ(1, webrtc::metrics::NumEvents(
1553 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1554 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001555 }
1556
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001557 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1558 bool remote_gcm_enabled,
1559 int expected_cipher_suite) {
1560 PeerConnectionFactory::Options caller_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07001561 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1562 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001563 PeerConnectionFactory::Options callee_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07001564 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1565 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001566 TestNegotiatedCipherSuite(caller_options, callee_options,
1567 expected_cipher_suite);
1568 }
1569
Seth Hampson2f0d7022018-02-20 11:54:42 -08001570 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001571 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001572
deadbeef1dcb1642017-03-29 21:08:16 -07001573 private:
1574 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001575 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001576 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001577 // |network_thread_| and |worker_thread_| are used by both
1578 // |caller_| and |callee_| so they must be destroyed
1579 // later.
1580 std::unique_ptr<rtc::Thread> network_thread_;
1581 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001582 // The turn servers and turn customizers should be accessed & deleted on the
1583 // network thread to avoid a race with the socket read/write that occurs
1584 // on the network thread.
1585 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1586 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001587 std::unique_ptr<PeerConnectionWrapper> caller_;
1588 std::unique_ptr<PeerConnectionWrapper> callee_;
1589};
1590
Seth Hampson2f0d7022018-02-20 11:54:42 -08001591class PeerConnectionIntegrationTest
1592 : public PeerConnectionIntegrationBaseTest,
1593 public ::testing::WithParamInterface<SdpSemantics> {
1594 protected:
1595 PeerConnectionIntegrationTest()
1596 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1597};
1598
1599class PeerConnectionIntegrationTestPlanB
1600 : public PeerConnectionIntegrationBaseTest {
1601 protected:
1602 PeerConnectionIntegrationTestPlanB()
1603 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1604};
1605
1606class PeerConnectionIntegrationTestUnifiedPlan
1607 : public PeerConnectionIntegrationBaseTest {
1608 protected:
1609 PeerConnectionIntegrationTestUnifiedPlan()
1610 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1611};
1612
deadbeef1dcb1642017-03-29 21:08:16 -07001613// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1614// includes testing that the callback is invoked if an observer is connected
1615// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001616TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001617 RtpReceiverObserverOnFirstPacketReceived) {
1618 ASSERT_TRUE(CreatePeerConnectionWrappers());
1619 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001620 caller()->AddAudioVideoTracks();
1621 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001622 // Start offer/answer exchange and wait for it to complete.
1623 caller()->CreateAndSetAndSignalOffer();
1624 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1625 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001626 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1627 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001628 // Wait for all "first packet received" callbacks to be fired.
1629 EXPECT_TRUE_WAIT(
1630 std::all_of(caller()->rtp_receiver_observers().begin(),
1631 caller()->rtp_receiver_observers().end(),
1632 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1633 return o->first_packet_received();
1634 }),
1635 kMaxWaitForFramesMs);
1636 EXPECT_TRUE_WAIT(
1637 std::all_of(callee()->rtp_receiver_observers().begin(),
1638 callee()->rtp_receiver_observers().end(),
1639 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1640 return o->first_packet_received();
1641 }),
1642 kMaxWaitForFramesMs);
1643 // If new observers are set after the first packet was already received, the
1644 // callback should still be invoked.
1645 caller()->ResetRtpReceiverObservers();
1646 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001647 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1648 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001649 EXPECT_TRUE(
1650 std::all_of(caller()->rtp_receiver_observers().begin(),
1651 caller()->rtp_receiver_observers().end(),
1652 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1653 return o->first_packet_received();
1654 }));
1655 EXPECT_TRUE(
1656 std::all_of(callee()->rtp_receiver_observers().begin(),
1657 callee()->rtp_receiver_observers().end(),
1658 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1659 return o->first_packet_received();
1660 }));
1661}
1662
1663class DummyDtmfObserver : public DtmfSenderObserverInterface {
1664 public:
1665 DummyDtmfObserver() : completed_(false) {}
1666
1667 // Implements DtmfSenderObserverInterface.
1668 void OnToneChange(const std::string& tone) override {
1669 tones_.push_back(tone);
1670 if (tone.empty()) {
1671 completed_ = true;
1672 }
1673 }
1674
1675 const std::vector<std::string>& tones() const { return tones_; }
1676 bool completed() const { return completed_; }
1677
1678 private:
1679 bool completed_;
1680 std::vector<std::string> tones_;
1681};
1682
1683// Assumes |sender| already has an audio track added and the offer/answer
1684// exchange is done.
1685void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1686 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001687 // We should be able to get a DTMF sender from the local sender.
1688 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1689 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1690 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001691 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001692 dtmf_sender->RegisterObserver(&observer);
1693
1694 // Test the DtmfSender object just created.
1695 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1696 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1697
1698 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1699 std::vector<std::string> tones = {"1", "a", ""};
1700 EXPECT_EQ(tones, observer.tones());
1701 dtmf_sender->UnregisterObserver();
1702 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1703}
1704
1705// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1706// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001707TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001708 ASSERT_TRUE(CreatePeerConnectionWrappers());
1709 ConnectFakeSignaling();
1710 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001711 caller()->AddAudioTrack();
1712 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001713 caller()->CreateAndSetAndSignalOffer();
1714 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001715 // DTLS must finish before the DTMF sender can be used reliably.
1716 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001717 TestDtmfFromSenderToReceiver(caller(), callee());
1718 TestDtmfFromSenderToReceiver(callee(), caller());
1719}
1720
1721// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1722// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001723TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001724 ASSERT_TRUE(CreatePeerConnectionWrappers());
1725 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001726
deadbeef1dcb1642017-03-29 21:08:16 -07001727 // Do normal offer/answer and wait for some frames to be received in each
1728 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001729 caller()->AddAudioVideoTracks();
1730 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001731 caller()->CreateAndSetAndSignalOffer();
1732 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001733 MediaExpectations media_expectations;
1734 media_expectations.ExpectBidirectionalAudioAndVideo();
1735 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001736 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1737 webrtc::kEnumCounterKeyProtocolDtls));
1738 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1739 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001740}
1741
1742// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001743TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001744 PeerConnectionInterface::RTCConfiguration sdes_config;
1745 sdes_config.enable_dtls_srtp.emplace(false);
1746 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1747 ConnectFakeSignaling();
1748
1749 // Do normal offer/answer and wait for some frames to be received in each
1750 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001751 caller()->AddAudioVideoTracks();
1752 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001753 caller()->CreateAndSetAndSignalOffer();
1754 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001755 MediaExpectations media_expectations;
1756 media_expectations.ExpectBidirectionalAudioAndVideo();
1757 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001758 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1759 webrtc::kEnumCounterKeyProtocolSdes));
1760 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1761 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001762}
1763
Steve Anton8c0f7a72017-10-03 10:03:10 -07001764// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1765// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001766TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001767 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1768 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1769 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1770 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1771 return pc->GetRemoteAudioSSLCertificate();
1772 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001773 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1774 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1775 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1776 return pc->GetRemoteAudioSSLCertChain();
1777 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001778
1779 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1780 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1781
1782 // Configure each side with a known certificate so they can be compared later.
1783 PeerConnectionInterface::RTCConfiguration caller_config;
1784 caller_config.enable_dtls_srtp.emplace(true);
1785 caller_config.certificates.push_back(caller_cert);
1786 PeerConnectionInterface::RTCConfiguration callee_config;
1787 callee_config.enable_dtls_srtp.emplace(true);
1788 callee_config.certificates.push_back(callee_cert);
1789 ASSERT_TRUE(
1790 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1791 ConnectFakeSignaling();
1792
1793 // When first initialized, there should not be a remote SSL certificate (and
1794 // calling this method should not crash).
1795 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1796 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001797 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1798 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001799
Steve Anton15324772018-01-16 10:26:49 -08001800 caller()->AddAudioTrack();
1801 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001802 caller()->CreateAndSetAndSignalOffer();
1803 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1804 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1805
1806 // Once DTLS has been connected, each side should return the other's SSL
1807 // certificate when calling GetRemoteAudioSSLCertificate.
1808
1809 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1810 ASSERT_TRUE(caller_remote_cert);
1811 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1812 caller_remote_cert->ToPEMString());
1813
1814 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1815 ASSERT_TRUE(callee_remote_cert);
1816 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1817 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001818
1819 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1820 ASSERT_TRUE(caller_remote_cert_chain);
1821 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1822 auto remote_cert = &caller_remote_cert_chain->Get(0);
1823 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1824 remote_cert->ToPEMString());
1825
1826 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1827 ASSERT_TRUE(callee_remote_cert_chain);
1828 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1829 remote_cert = &callee_remote_cert_chain->Get(0);
1830 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1831 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001832}
1833
deadbeef1dcb1642017-03-29 21:08:16 -07001834// This test sets up a call between two parties with a source resolution of
1835// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001836TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001837 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1838 ASSERT_TRUE(CreatePeerConnectionWrappers());
1839 ConnectFakeSignaling();
1840
Niels Möller5c7efe72018-05-11 10:34:46 +02001841 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1842 webrtc::FakePeriodicVideoSource::Config config;
1843 config.width = 1280;
1844 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001845 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001846 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1847 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001848
1849 // Do normal offer/answer and wait for at least one frame to be received in
1850 // each direction.
1851 caller()->CreateAndSetAndSignalOffer();
1852 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1853 callee()->min_video_frames_received_per_track() > 0,
1854 kMaxWaitForFramesMs);
1855
1856 // Check rendered aspect ratio.
1857 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1858 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1859 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1860 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1861}
1862
1863// This test sets up an one-way call, with media only from caller to
1864// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001865TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001866 ASSERT_TRUE(CreatePeerConnectionWrappers());
1867 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001868 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001869 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001870 MediaExpectations media_expectations;
1871 media_expectations.CalleeExpectsSomeAudioAndVideo();
1872 media_expectations.CallerExpectsNoAudio();
1873 media_expectations.CallerExpectsNoVideo();
1874 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001875}
1876
1877// This test sets up a audio call initially, with the callee rejecting video
1878// initially. Then later the callee decides to upgrade to audio/video, and
1879// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001880TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001881 ASSERT_TRUE(CreatePeerConnectionWrappers());
1882 ConnectFakeSignaling();
1883 // Initially, offer an audio/video stream from the caller, but refuse to
1884 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001885 caller()->AddAudioVideoTracks();
1886 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001887 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1888 PeerConnectionInterface::RTCOfferAnswerOptions options;
1889 options.offer_to_receive_video = 0;
1890 callee()->SetOfferAnswerOptions(options);
1891 } else {
1892 callee()->SetRemoteOfferHandler([this] {
1893 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1894 });
1895 }
deadbeef1dcb1642017-03-29 21:08:16 -07001896 // Do offer/answer and make sure audio is still received end-to-end.
1897 caller()->CreateAndSetAndSignalOffer();
1898 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001899 {
1900 MediaExpectations media_expectations;
1901 media_expectations.ExpectBidirectionalAudio();
1902 media_expectations.ExpectNoVideo();
1903 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1904 }
deadbeef1dcb1642017-03-29 21:08:16 -07001905 // Sanity check that the callee's description has a rejected video section.
1906 ASSERT_NE(nullptr, callee()->pc()->local_description());
1907 const ContentInfo* callee_video_content =
1908 GetFirstVideoContent(callee()->pc()->local_description()->description());
1909 ASSERT_NE(nullptr, callee_video_content);
1910 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001911
deadbeef1dcb1642017-03-29 21:08:16 -07001912 // Now negotiate with video and ensure negotiation succeeds, with video
1913 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001914 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001915 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1916 PeerConnectionInterface::RTCOfferAnswerOptions options;
1917 options.offer_to_receive_video = 1;
1918 callee()->SetOfferAnswerOptions(options);
1919 } else {
1920 callee()->SetRemoteOfferHandler(nullptr);
1921 caller()->SetRemoteOfferHandler([this] {
1922 // The caller creates a new transceiver to receive video on when receiving
1923 // the offer, but by default it is send only.
1924 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001925 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001926 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1927 transceivers[2]->receiver()->media_type());
1928 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1929 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1930 });
1931 }
deadbeef1dcb1642017-03-29 21:08:16 -07001932 callee()->CreateAndSetAndSignalOffer();
1933 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001934 {
1935 // Expect additional audio frames to be received after the upgrade.
1936 MediaExpectations media_expectations;
1937 media_expectations.ExpectBidirectionalAudioAndVideo();
1938 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1939 }
deadbeef1dcb1642017-03-29 21:08:16 -07001940}
1941
deadbeef4389b4d2017-09-07 09:07:36 -07001942// Simpler than the above test; just add an audio track to an established
1943// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001944TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07001945 ASSERT_TRUE(CreatePeerConnectionWrappers());
1946 ConnectFakeSignaling();
1947 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08001948 caller()->AddVideoTrack();
1949 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001950 caller()->CreateAndSetAndSignalOffer();
1951 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1952 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08001953 caller()->AddAudioTrack();
1954 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001955 caller()->CreateAndSetAndSignalOffer();
1956 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1957 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001958 MediaExpectations media_expectations;
1959 media_expectations.ExpectBidirectionalAudioAndVideo();
1960 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07001961}
1962
deadbeef1dcb1642017-03-29 21:08:16 -07001963// This test sets up a call that's transferred to a new caller with a different
1964// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001965TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07001966 ASSERT_TRUE(CreatePeerConnectionWrappers());
1967 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001968 caller()->AddAudioVideoTracks();
1969 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001970 caller()->CreateAndSetAndSignalOffer();
1971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1972
1973 // Keep the original peer around which will still send packets to the
1974 // receiving client. These SRTP packets will be dropped.
1975 std::unique_ptr<PeerConnectionWrapper> original_peer(
1976 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08001977 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07001978 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1979 // directly above.
1980 original_peer->pc()->Close();
1981
1982 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001983 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001984 caller()->CreateAndSetAndSignalOffer();
1985 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1986 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001987 MediaExpectations media_expectations;
1988 media_expectations.ExpectBidirectionalAudioAndVideo();
1989 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001990}
1991
1992// This test sets up a call that's transferred to a new callee with a different
1993// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001994TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07001995 ASSERT_TRUE(CreatePeerConnectionWrappers());
1996 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001997 caller()->AddAudioVideoTracks();
1998 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001999 caller()->CreateAndSetAndSignalOffer();
2000 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2001
2002 // Keep the original peer around which will still send packets to the
2003 // receiving client. These SRTP packets will be dropped.
2004 std::unique_ptr<PeerConnectionWrapper> original_peer(
2005 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002006 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002007 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2008 // directly above.
2009 original_peer->pc()->Close();
2010
2011 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002012 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002013 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2014 caller()->CreateAndSetAndSignalOffer();
2015 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2016 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002017 MediaExpectations media_expectations;
2018 media_expectations.ExpectBidirectionalAudioAndVideo();
2019 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002020}
2021
2022// This test sets up a non-bundled call and negotiates bundling at the same
2023// time as starting an ICE restart. When bundling is in effect in the restart,
2024// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002025TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002026 ASSERT_TRUE(CreatePeerConnectionWrappers());
2027 ConnectFakeSignaling();
2028
Steve Anton15324772018-01-16 10:26:49 -08002029 caller()->AddAudioVideoTracks();
2030 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002031 // Remove the bundle group from the SDP received by the callee.
2032 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2033 desc->RemoveGroupByName("BUNDLE");
2034 });
2035 caller()->CreateAndSetAndSignalOffer();
2036 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002037 {
2038 MediaExpectations media_expectations;
2039 media_expectations.ExpectBidirectionalAudioAndVideo();
2040 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2041 }
deadbeef1dcb1642017-03-29 21:08:16 -07002042 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2043 callee()->SetReceivedSdpMunger(nullptr);
2044 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2045 caller()->CreateAndSetAndSignalOffer();
2046 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2047
2048 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002049 {
2050 MediaExpectations media_expectations;
2051 media_expectations.ExpectBidirectionalAudioAndVideo();
2052 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2053 }
deadbeef1dcb1642017-03-29 21:08:16 -07002054}
2055
2056// Test CVO (Coordination of Video Orientation). If a video source is rotated
2057// and both peers support the CVO RTP header extension, the actual video frames
2058// don't need to be encoded in different resolutions, since the rotation is
2059// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002060TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002061 ASSERT_TRUE(CreatePeerConnectionWrappers());
2062 ConnectFakeSignaling();
2063 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002064 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002065 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002066 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002067 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2068
2069 // Wait for video frames to be received by both sides.
2070 caller()->CreateAndSetAndSignalOffer();
2071 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2072 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2073 callee()->min_video_frames_received_per_track() > 0,
2074 kMaxWaitForFramesMs);
2075
2076 // Ensure that the aspect ratio is unmodified.
2077 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2078 // not just assumed.
2079 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2080 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2081 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2082 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2083 // Ensure that the CVO bits were surfaced to the renderer.
2084 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2085 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2086}
2087
2088// Test that when the CVO extension isn't supported, video is rotated the
2089// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002090TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002091 ASSERT_TRUE(CreatePeerConnectionWrappers());
2092 ConnectFakeSignaling();
2093 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002094 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002095 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002096 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002097 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2098
2099 // Remove the CVO extension from the offered SDP.
2100 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2101 cricket::VideoContentDescription* video =
2102 GetFirstVideoContentDescription(desc);
2103 video->ClearRtpHeaderExtensions();
2104 });
2105 // Wait for video frames to be received by both sides.
2106 caller()->CreateAndSetAndSignalOffer();
2107 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2108 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2109 callee()->min_video_frames_received_per_track() > 0,
2110 kMaxWaitForFramesMs);
2111
2112 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2113 // rotation.
2114 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2115 // not just assumed.
2116 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2117 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2118 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2119 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2120 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2121 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2122 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2123}
2124
deadbeef1dcb1642017-03-29 21:08:16 -07002125// Test that if the answerer rejects the audio m= section, no audio is sent or
2126// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002127TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002128 ASSERT_TRUE(CreatePeerConnectionWrappers());
2129 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002130 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002131 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2132 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2133 // it will reject the audio m= section completely.
2134 PeerConnectionInterface::RTCOfferAnswerOptions options;
2135 options.offer_to_receive_audio = 0;
2136 callee()->SetOfferAnswerOptions(options);
2137 } else {
2138 // Stopping the audio RtpTransceiver will cause the media section to be
2139 // rejected in the answer.
2140 callee()->SetRemoteOfferHandler([this] {
2141 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2142 });
2143 }
Steve Anton15324772018-01-16 10:26:49 -08002144 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002145 // Do offer/answer and wait for successful end-to-end video frames.
2146 caller()->CreateAndSetAndSignalOffer();
2147 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002148 MediaExpectations media_expectations;
2149 media_expectations.ExpectBidirectionalVideo();
2150 media_expectations.ExpectNoAudio();
2151 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2152
deadbeef1dcb1642017-03-29 21:08:16 -07002153 // Sanity check that the callee's description has a rejected audio section.
2154 ASSERT_NE(nullptr, callee()->pc()->local_description());
2155 const ContentInfo* callee_audio_content =
2156 GetFirstAudioContent(callee()->pc()->local_description()->description());
2157 ASSERT_NE(nullptr, callee_audio_content);
2158 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002159 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2160 // The caller's transceiver should have stopped after receiving the answer.
2161 EXPECT_TRUE(caller()
2162 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2163 ->stopped());
2164 }
deadbeef1dcb1642017-03-29 21:08:16 -07002165}
2166
2167// Test that if the answerer rejects the video m= section, no video is sent or
2168// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002169TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002170 ASSERT_TRUE(CreatePeerConnectionWrappers());
2171 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002172 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002173 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2174 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2175 // it will reject the video m= section completely.
2176 PeerConnectionInterface::RTCOfferAnswerOptions options;
2177 options.offer_to_receive_video = 0;
2178 callee()->SetOfferAnswerOptions(options);
2179 } else {
2180 // Stopping the video RtpTransceiver will cause the media section to be
2181 // rejected in the answer.
2182 callee()->SetRemoteOfferHandler([this] {
2183 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2184 });
2185 }
Steve Anton15324772018-01-16 10:26:49 -08002186 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002187 // Do offer/answer and wait for successful end-to-end audio frames.
2188 caller()->CreateAndSetAndSignalOffer();
2189 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002190 MediaExpectations media_expectations;
2191 media_expectations.ExpectBidirectionalAudio();
2192 media_expectations.ExpectNoVideo();
2193 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2194
deadbeef1dcb1642017-03-29 21:08:16 -07002195 // Sanity check that the callee's description has a rejected video section.
2196 ASSERT_NE(nullptr, callee()->pc()->local_description());
2197 const ContentInfo* callee_video_content =
2198 GetFirstVideoContent(callee()->pc()->local_description()->description());
2199 ASSERT_NE(nullptr, callee_video_content);
2200 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002201 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2202 // The caller's transceiver should have stopped after receiving the answer.
2203 EXPECT_TRUE(caller()
2204 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2205 ->stopped());
2206 }
deadbeef1dcb1642017-03-29 21:08:16 -07002207}
2208
2209// Test that if the answerer rejects both audio and video m= sections, nothing
2210// bad happens.
2211// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2212// test anything but the fact that negotiation succeeds, which doesn't mean
2213// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002214TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002215 ASSERT_TRUE(CreatePeerConnectionWrappers());
2216 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002217 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002218 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2219 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2220 // will reject both audio and video m= sections.
2221 PeerConnectionInterface::RTCOfferAnswerOptions options;
2222 options.offer_to_receive_audio = 0;
2223 options.offer_to_receive_video = 0;
2224 callee()->SetOfferAnswerOptions(options);
2225 } else {
2226 callee()->SetRemoteOfferHandler([this] {
2227 // Stopping all transceivers will cause all media sections to be rejected.
2228 for (auto transceiver : callee()->pc()->GetTransceivers()) {
2229 transceiver->Stop();
2230 }
2231 });
2232 }
deadbeef1dcb1642017-03-29 21:08:16 -07002233 // Do offer/answer and wait for stable signaling state.
2234 caller()->CreateAndSetAndSignalOffer();
2235 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002236
deadbeef1dcb1642017-03-29 21:08:16 -07002237 // Sanity check that the callee's description has rejected m= sections.
2238 ASSERT_NE(nullptr, callee()->pc()->local_description());
2239 const ContentInfo* callee_audio_content =
2240 GetFirstAudioContent(callee()->pc()->local_description()->description());
2241 ASSERT_NE(nullptr, callee_audio_content);
2242 EXPECT_TRUE(callee_audio_content->rejected);
2243 const ContentInfo* callee_video_content =
2244 GetFirstVideoContent(callee()->pc()->local_description()->description());
2245 ASSERT_NE(nullptr, callee_video_content);
2246 EXPECT_TRUE(callee_video_content->rejected);
2247}
2248
2249// This test sets up an audio and video call between two parties. After the
2250// call runs for a while, the caller sends an updated offer with video being
2251// rejected. Once the re-negotiation is done, the video flow should stop and
2252// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002253TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002254 ASSERT_TRUE(CreatePeerConnectionWrappers());
2255 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002256 caller()->AddAudioVideoTracks();
2257 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002258 caller()->CreateAndSetAndSignalOffer();
2259 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002260 {
2261 MediaExpectations media_expectations;
2262 media_expectations.ExpectBidirectionalAudioAndVideo();
2263 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2264 }
deadbeef1dcb1642017-03-29 21:08:16 -07002265 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002266 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2267 caller()->SetGeneratedSdpMunger(
2268 [](cricket::SessionDescription* description) {
2269 for (cricket::ContentInfo& content : description->contents()) {
2270 if (cricket::IsVideoContent(&content)) {
2271 content.rejected = true;
2272 }
2273 }
2274 });
2275 } else {
2276 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2277 }
deadbeef1dcb1642017-03-29 21:08:16 -07002278 caller()->CreateAndSetAndSignalOffer();
2279 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2280
2281 // Sanity check that the caller's description has a rejected video section.
2282 ASSERT_NE(nullptr, caller()->pc()->local_description());
2283 const ContentInfo* caller_video_content =
2284 GetFirstVideoContent(caller()->pc()->local_description()->description());
2285 ASSERT_NE(nullptr, caller_video_content);
2286 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002287 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002288 {
2289 MediaExpectations media_expectations;
2290 media_expectations.ExpectBidirectionalAudio();
2291 media_expectations.ExpectNoVideo();
2292 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2293 }
deadbeef1dcb1642017-03-29 21:08:16 -07002294}
2295
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002296// Do one offer/answer with audio, another that disables it (rejecting the m=
2297// section), and another that re-enables it. Regression test for:
2298// bugs.webrtc.org/6023
2299TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2300 ASSERT_TRUE(CreatePeerConnectionWrappers());
2301 ConnectFakeSignaling();
2302
2303 // Add audio track, do normal offer/answer.
2304 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2305 caller()->CreateLocalAudioTrack();
2306 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2307 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2308 caller()->CreateAndSetAndSignalOffer();
2309 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2310
2311 // Remove audio track, and set offer_to_receive_audio to false to cause the
2312 // m= section to be completely disabled, not just "recvonly".
2313 caller()->pc()->RemoveTrack(sender);
2314 PeerConnectionInterface::RTCOfferAnswerOptions options;
2315 options.offer_to_receive_audio = 0;
2316 caller()->SetOfferAnswerOptions(options);
2317 caller()->CreateAndSetAndSignalOffer();
2318 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2319
2320 // Add the audio track again, expecting negotiation to succeed and frames to
2321 // flow.
2322 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2323 options.offer_to_receive_audio = 1;
2324 caller()->SetOfferAnswerOptions(options);
2325 caller()->CreateAndSetAndSignalOffer();
2326 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2327
2328 MediaExpectations media_expectations;
2329 media_expectations.CalleeExpectsSomeAudio();
2330 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2331}
2332
deadbeef1dcb1642017-03-29 21:08:16 -07002333// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2334// is needed to support legacy endpoints.
2335// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2336// add a test for an end-to-end test without MID signaling either (basically,
2337// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002338TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002339 ASSERT_TRUE(CreatePeerConnectionWrappers());
2340 ConnectFakeSignaling();
2341 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002342 caller()->AddAudioVideoTracks();
2343 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002344 // Remove SSRCs and MSIDs from the received offer SDP.
2345 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002346 caller()->CreateAndSetAndSignalOffer();
2347 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002348 MediaExpectations media_expectations;
2349 media_expectations.ExpectBidirectionalAudioAndVideo();
2350 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002351}
2352
Seth Hampson5897a6e2018-04-03 11:16:33 -07002353// Basic end-to-end test, without SSRC signaling. This means that the track
2354// was created properly and frames are delivered when the MSIDs are communicated
2355// with a=msid lines and no a=ssrc lines.
2356TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2357 EndToEndCallWithoutSsrcSignaling) {
2358 const char kStreamId[] = "streamId";
2359 ASSERT_TRUE(CreatePeerConnectionWrappers());
2360 ConnectFakeSignaling();
2361 // Add just audio tracks.
2362 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2363 callee()->AddAudioTrack();
2364
2365 // Remove SSRCs from the received offer SDP.
2366 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2367 caller()->CreateAndSetAndSignalOffer();
2368 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2369 MediaExpectations media_expectations;
2370 media_expectations.ExpectBidirectionalAudio();
2371 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2372}
2373
Steve Antondf527fd2018-04-27 15:52:03 -07002374// Tests that video flows between multiple video tracks when SSRCs are not
2375// signaled. This exercises the MID RTP header extension which is needed to
2376// demux the incoming video tracks.
2377TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2378 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2379 ASSERT_TRUE(CreatePeerConnectionWrappers());
2380 ConnectFakeSignaling();
2381 caller()->AddVideoTrack();
2382 caller()->AddVideoTrack();
2383 callee()->AddVideoTrack();
2384 callee()->AddVideoTrack();
2385
2386 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2387 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2388 caller()->CreateAndSetAndSignalOffer();
2389 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2390 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2391 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2392
2393 // Expect video to be received in both directions on both tracks.
2394 MediaExpectations media_expectations;
2395 media_expectations.ExpectBidirectionalVideo();
2396 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2397}
2398
deadbeef1dcb1642017-03-29 21:08:16 -07002399// Test that if two video tracks are sent (from caller to callee, in this test),
2400// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002401TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002402 ASSERT_TRUE(CreatePeerConnectionWrappers());
2403 ConnectFakeSignaling();
2404 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002405 caller()->AddAudioVideoTracks();
2406 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002407 caller()->CreateAndSetAndSignalOffer();
2408 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002409 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002410
2411 MediaExpectations media_expectations;
2412 media_expectations.CalleeExpectsSomeAudioAndVideo();
2413 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002414}
2415
2416static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2417 bool first = true;
2418 for (cricket::ContentInfo& content : desc->contents()) {
2419 if (first) {
2420 first = false;
2421 continue;
2422 }
2423 content.bundle_only = true;
2424 }
2425 first = true;
2426 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2427 if (first) {
2428 first = false;
2429 continue;
2430 }
2431 transport.description.ice_ufrag.clear();
2432 transport.description.ice_pwd.clear();
2433 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2434 transport.description.identity_fingerprint.reset(nullptr);
2435 }
2436}
2437
2438// Test that if applying a true "max bundle" offer, which uses ports of 0,
2439// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2440// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2441// successfully and media flows.
2442// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2443// TODO(deadbeef): Won't need this test once we start generating actual
2444// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002445TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002446 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2447 ASSERT_TRUE(CreatePeerConnectionWrappers());
2448 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002449 caller()->AddAudioVideoTracks();
2450 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002451 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2452 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2453 // but the first m= section.
2454 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2455 caller()->CreateAndSetAndSignalOffer();
2456 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002457 MediaExpectations media_expectations;
2458 media_expectations.ExpectBidirectionalAudioAndVideo();
2459 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002460}
2461
2462// Test that we can receive the audio output level from a remote audio track.
2463// TODO(deadbeef): Use a fake audio source and verify that the output level is
2464// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002465TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002466 ASSERT_TRUE(CreatePeerConnectionWrappers());
2467 ConnectFakeSignaling();
2468 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002469 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002470 caller()->CreateAndSetAndSignalOffer();
2471 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2472
2473 // Get the audio output level stats. Note that the level is not available
2474 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002475 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002476 kMaxWaitForFramesMs);
2477}
2478
2479// Test that an audio input level is reported.
2480// TODO(deadbeef): Use a fake audio source and verify that the input level is
2481// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002482TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002483 ASSERT_TRUE(CreatePeerConnectionWrappers());
2484 ConnectFakeSignaling();
2485 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002486 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002487 caller()->CreateAndSetAndSignalOffer();
2488 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2489
2490 // Get the audio input level stats. The level should be available very
2491 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002492 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002493 kMaxWaitForStatsMs);
2494}
2495
2496// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002497TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002498 ASSERT_TRUE(CreatePeerConnectionWrappers());
2499 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002500 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002501 // Do offer/answer, wait for the callee to receive some frames.
2502 caller()->CreateAndSetAndSignalOffer();
2503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002504
2505 MediaExpectations media_expectations;
2506 media_expectations.CalleeExpectsSomeAudioAndVideo();
2507 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002508
2509 // Get a handle to the remote tracks created, so they can be used as GetStats
2510 // filters.
Steve Anton15324772018-01-16 10:26:49 -08002511 for (auto receiver : callee()->pc()->GetReceivers()) {
2512 // We received frames, so we definitely should have nonzero "received bytes"
2513 // stats at this point.
2514 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2515 0);
2516 }
deadbeef1dcb1642017-03-29 21:08:16 -07002517}
2518
2519// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002520TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002521 ASSERT_TRUE(CreatePeerConnectionWrappers());
2522 ConnectFakeSignaling();
2523 auto audio_track = caller()->CreateLocalAudioTrack();
2524 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002525 caller()->AddTrack(audio_track);
2526 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002527 // Do offer/answer, wait for the callee to receive some frames.
2528 caller()->CreateAndSetAndSignalOffer();
2529 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002530 MediaExpectations media_expectations;
2531 media_expectations.CalleeExpectsSomeAudioAndVideo();
2532 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002533
2534 // The callee received frames, so we definitely should have nonzero "sent
2535 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002536 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2537 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2538}
2539
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002540// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002541TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002542 ASSERT_TRUE(CreatePeerConnectionWrappers());
2543 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002544 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002545
Steve Anton15324772018-01-16 10:26:49 -08002546 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002547
2548 // Do offer/answer, wait for the callee to receive some frames.
2549 caller()->CreateAndSetAndSignalOffer();
2550 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2551
2552 // Get the remote audio track created on the receiver, so they can be used as
2553 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002554 auto receivers = callee()->pc()->GetReceivers();
2555 ASSERT_EQ(1u, receivers.size());
2556 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002557
2558 // Get the audio output level stats. Note that the level is not available
2559 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002560 EXPECT_TRUE_WAIT(
2561 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2562 0,
2563 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002564}
2565
deadbeefd8ad7882017-04-18 16:01:17 -07002566// Test that we can get stats (using the new stats implemnetation) for
2567// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2568// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002569TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002570 GetStatsForUnsignaledStreamWithNewStatsApi) {
2571 ASSERT_TRUE(CreatePeerConnectionWrappers());
2572 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002573 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002574 // Remove SSRCs and MSIDs from the received offer SDP.
2575 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2576 caller()->CreateAndSetAndSignalOffer();
2577 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002578 MediaExpectations media_expectations;
2579 media_expectations.CalleeExpectsSomeAudio(1);
2580 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002581
2582 // We received a frame, so we should have nonzero "bytes received" stats for
2583 // the unsignaled stream, if stats are working for it.
2584 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2585 callee()->NewGetStats();
2586 ASSERT_NE(nullptr, report);
2587 auto inbound_stream_stats =
2588 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2589 ASSERT_EQ(1U, inbound_stream_stats.size());
2590 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2591 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002592 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2593}
2594
Taylor Brandstettera4653442018-06-19 09:44:26 -07002595// Same as above but for the legacy stats implementation.
2596TEST_P(PeerConnectionIntegrationTest,
2597 GetStatsForUnsignaledStreamWithOldStatsApi) {
2598 ASSERT_TRUE(CreatePeerConnectionWrappers());
2599 ConnectFakeSignaling();
2600 caller()->AddAudioTrack();
2601 // Remove SSRCs and MSIDs from the received offer SDP.
2602 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2603 caller()->CreateAndSetAndSignalOffer();
2604 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2605
2606 // Note that, since the old stats implementation associates SSRCs with tracks
2607 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2608 // associated track ID. So we can't use the track "selector" argument.
2609 //
2610 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2611 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002612 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002613 kDefaultTimeout);
2614}
2615
zhihuangf8164932017-05-19 13:09:47 -07002616// Test that we can successfully get the media related stats (audio level
2617// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002618TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002619 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2620 ASSERT_TRUE(CreatePeerConnectionWrappers());
2621 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002622 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002623 // Remove SSRCs and MSIDs from the received offer SDP.
2624 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2625 caller()->CreateAndSetAndSignalOffer();
2626 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002627 MediaExpectations media_expectations;
2628 media_expectations.CalleeExpectsSomeAudio(1);
2629 media_expectations.CalleeExpectsSomeVideo(1);
2630 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002631
2632 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2633 callee()->NewGetStats();
2634 ASSERT_NE(nullptr, report);
2635
2636 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2637 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2638 ASSERT_GE(audio_index, 0);
2639 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002640}
2641
deadbeef4e2deab2017-09-20 13:56:21 -07002642// Helper for test below.
2643void ModifySsrcs(cricket::SessionDescription* desc) {
2644 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002645 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002646 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002647 for (uint32_t& ssrc : stream.ssrcs) {
2648 ssrc = rtc::CreateRandomId();
2649 }
2650 }
2651 }
2652}
2653
2654// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2655// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2656// This should result in two "RTCInboundRTPStreamStats", but only one
2657// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2658// being reset to 0 once the SSRC change occurs.
2659//
2660// Regression test for this bug:
2661// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2662//
2663// The bug causes the track stats to only represent one of the two streams:
2664// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2665// that the track stat counters would reset to 0 when the new stream is
2666// received, and a 50% chance that they'll stop updating (while
2667// "concealed_samples" continues increasing, due to silence being generated for
2668// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002669TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002670 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002671 ASSERT_TRUE(CreatePeerConnectionWrappers());
2672 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002673 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002674 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2675 // that doesn't signal SSRCs (from the callee's perspective).
2676 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2677 caller()->CreateAndSetAndSignalOffer();
2678 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2679 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002680 {
2681 MediaExpectations media_expectations;
2682 media_expectations.CalleeExpectsSomeAudio(50);
2683 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2684 }
deadbeef4e2deab2017-09-20 13:56:21 -07002685 // Some audio frames were received, so we should have nonzero "samples
2686 // received" for the track.
2687 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2688 callee()->NewGetStats();
2689 ASSERT_NE(nullptr, report);
2690 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2691 ASSERT_EQ(1U, track_stats.size());
2692 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2693 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2694 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2695
2696 // Create a new offer and munge it to cause the caller to use a new SSRC.
2697 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2698 caller()->CreateAndSetAndSignalOffer();
2699 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2700 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2701 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002702 {
2703 MediaExpectations media_expectations;
2704 media_expectations.CalleeExpectsSomeAudio(25);
2705 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2706 }
deadbeef4e2deab2017-09-20 13:56:21 -07002707
2708 report = callee()->NewGetStats();
2709 ASSERT_NE(nullptr, report);
2710 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2711 ASSERT_EQ(1U, track_stats.size());
2712 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2713 // The "total samples received" stat should only be greater than it was
2714 // before.
2715 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2716 // Right now, the new SSRC will cause the counters to reset to 0.
2717 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2718
2719 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002720 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002721 // good sign that we're seeing stats from the old stream that's no longer
2722 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002723 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002724 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2725 EXPECT_LT(*track_stats[0]->concealed_samples,
2726 *track_stats[0]->total_samples_received *
2727 kAcceptableConcealedSamplesPercentage);
2728
2729 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2730 // sanity check that the SSRC really changed.
2731 // TODO(deadbeef): This isn't working right now, because we're not returning
2732 // *any* stats for the inactive stream. Uncomment when the bug is completely
2733 // fixed.
2734 // auto inbound_stream_stats =
2735 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2736 // ASSERT_EQ(2U, inbound_stream_stats.size());
2737}
2738
deadbeef1dcb1642017-03-29 21:08:16 -07002739// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002740TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002741 PeerConnectionFactory::Options dtls_10_options;
2742 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2743 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2744 dtls_10_options));
2745 ConnectFakeSignaling();
2746 // Do normal offer/answer and wait for some frames to be received in each
2747 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002748 caller()->AddAudioVideoTracks();
2749 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002750 caller()->CreateAndSetAndSignalOffer();
2751 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002752 MediaExpectations media_expectations;
2753 media_expectations.ExpectBidirectionalAudioAndVideo();
2754 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002755}
2756
2757// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002758TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002759 PeerConnectionFactory::Options dtls_10_options;
2760 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2761 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2762 dtls_10_options));
2763 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002764 caller()->AddAudioVideoTracks();
2765 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002766 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002767 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002768 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002769 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002770 kDefaultTimeout);
2771 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002772 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002773 // TODO(bugs.webrtc.org/9456): Fix it.
2774 EXPECT_EQ(1, webrtc::metrics::NumEvents(
2775 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2776 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002777}
2778
2779// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002780TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002781 PeerConnectionFactory::Options dtls_12_options;
2782 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2783 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2784 dtls_12_options));
2785 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002786 caller()->AddAudioVideoTracks();
2787 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002788 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002789 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002790 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002791 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002792 kDefaultTimeout);
2793 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002794 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002795 // TODO(bugs.webrtc.org/9456): Fix it.
2796 EXPECT_EQ(1, webrtc::metrics::NumEvents(
2797 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2798 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002799}
2800
2801// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2802// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002803TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002804 PeerConnectionFactory::Options caller_options;
2805 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2806 PeerConnectionFactory::Options callee_options;
2807 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2808 ASSERT_TRUE(
2809 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2810 ConnectFakeSignaling();
2811 // Do normal offer/answer and wait for some frames to be received in each
2812 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002813 caller()->AddAudioVideoTracks();
2814 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002815 caller()->CreateAndSetAndSignalOffer();
2816 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002817 MediaExpectations media_expectations;
2818 media_expectations.ExpectBidirectionalAudioAndVideo();
2819 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002820}
2821
2822// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2823// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002824TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07002825 PeerConnectionFactory::Options caller_options;
2826 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2827 PeerConnectionFactory::Options callee_options;
2828 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2829 ASSERT_TRUE(
2830 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2831 ConnectFakeSignaling();
2832 // Do normal offer/answer and wait for some frames to be received in each
2833 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002834 caller()->AddAudioVideoTracks();
2835 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002836 caller()->CreateAndSetAndSignalOffer();
2837 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002838 MediaExpectations media_expectations;
2839 media_expectations.ExpectBidirectionalAudioAndVideo();
2840 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002841}
2842
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002843// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
2844// works as expected; the cipher should only be used if enabled by both sides.
2845TEST_P(PeerConnectionIntegrationTest,
2846 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
2847 PeerConnectionFactory::Options caller_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07002848 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002849 PeerConnectionFactory::Options callee_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07002850 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
2851 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002852 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2853 TestNegotiatedCipherSuite(caller_options, callee_options,
2854 expected_cipher_suite);
2855}
2856
2857TEST_P(PeerConnectionIntegrationTest,
2858 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
2859 PeerConnectionFactory::Options caller_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07002860 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
2861 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002862 PeerConnectionFactory::Options callee_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07002863 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002864 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2865 TestNegotiatedCipherSuite(caller_options, callee_options,
2866 expected_cipher_suite);
2867}
2868
2869TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
2870 PeerConnectionFactory::Options caller_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07002871 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002872 PeerConnectionFactory::Options callee_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07002873 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002874 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
2875 TestNegotiatedCipherSuite(caller_options, callee_options,
2876 expected_cipher_suite);
2877}
2878
deadbeef1dcb1642017-03-29 21:08:16 -07002879// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002880TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07002881 bool local_gcm_enabled = false;
2882 bool remote_gcm_enabled = false;
2883 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2884 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2885 expected_cipher_suite);
2886}
2887
2888// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002889TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07002890 bool local_gcm_enabled = true;
2891 bool remote_gcm_enabled = true;
2892 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2893 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2894 expected_cipher_suite);
2895}
2896
2897// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002898TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002899 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2900 bool local_gcm_enabled = true;
2901 bool remote_gcm_enabled = false;
2902 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2903 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2904 expected_cipher_suite);
2905}
2906
2907// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002908TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002909 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2910 bool local_gcm_enabled = false;
2911 bool remote_gcm_enabled = true;
2912 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2913 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2914 expected_cipher_suite);
2915}
2916
deadbeef7914b8c2017-04-21 03:23:33 -07002917// Verify that media can be transmitted end-to-end when GCM crypto suites are
2918// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2919// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2920// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002921TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07002922 PeerConnectionFactory::Options gcm_options;
Benjamin Wrightac2f3d12018-10-10 17:21:08 -07002923 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07002924 ASSERT_TRUE(
2925 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2926 ConnectFakeSignaling();
2927 // Do normal offer/answer and wait for some frames to be received in each
2928 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002929 caller()->AddAudioVideoTracks();
2930 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002931 caller()->CreateAndSetAndSignalOffer();
2932 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002933 MediaExpectations media_expectations;
2934 media_expectations.ExpectBidirectionalAudioAndVideo();
2935 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07002936}
2937
deadbeef1dcb1642017-03-29 21:08:16 -07002938// This test sets up a call between two parties with audio, video and an RTP
2939// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002940TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02002941 PeerConnectionInterface::RTCConfiguration rtc_config;
2942 rtc_config.enable_rtp_data_channel = true;
2943 rtc_config.enable_dtls_srtp = false;
2944 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07002945 ConnectFakeSignaling();
2946 // Expect that data channel created on caller side will show up for callee as
2947 // well.
2948 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002949 caller()->AddAudioVideoTracks();
2950 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002951 caller()->CreateAndSetAndSignalOffer();
2952 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2953 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002954 MediaExpectations media_expectations;
2955 media_expectations.ExpectBidirectionalAudioAndVideo();
2956 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002957 ASSERT_NE(nullptr, caller()->data_channel());
2958 ASSERT_NE(nullptr, callee()->data_channel());
2959 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2960 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2961
2962 // Ensure data can be sent in both directions.
2963 std::string data = "hello world";
2964 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2965 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2966 kDefaultTimeout);
2967 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2968 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2969 kDefaultTimeout);
2970}
2971
2972// Ensure that an RTP data channel is signaled as closed for the caller when
2973// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002974TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002975 RtpDataChannelSignaledClosedInCalleeOffer) {
2976 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02002977 PeerConnectionInterface::RTCConfiguration rtc_config;
2978 rtc_config.enable_rtp_data_channel = true;
2979 rtc_config.enable_dtls_srtp = false;
2980 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07002981 ConnectFakeSignaling();
2982 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002983 caller()->AddAudioVideoTracks();
2984 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002985 caller()->CreateAndSetAndSignalOffer();
2986 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2987 ASSERT_NE(nullptr, caller()->data_channel());
2988 ASSERT_NE(nullptr, callee()->data_channel());
2989 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2990 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2991
2992 // Close the data channel on the callee, and do an updated offer/answer.
2993 callee()->data_channel()->Close();
2994 callee()->CreateAndSetAndSignalOffer();
2995 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2996 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2997 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2998}
2999
3000// Tests that data is buffered in an RTP data channel until an observer is
3001// registered for it.
3002//
3003// NOTE: RTP data channels can receive data before the underlying
3004// transport has detected that a channel is writable and thus data can be
3005// received before the data channel state changes to open. That is hard to test
3006// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003007TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003008 DataBufferedUntilRtpDataChannelObserverRegistered) {
3009 // Use fake clock and simulated network delay so that we predictably can wait
3010 // until an SCTP message has been delivered without "sleep()"ing.
3011 rtc::ScopedFakeClock fake_clock;
3012 // Some things use a time of "0" as a special value, so we need to start out
3013 // the fake clock at a nonzero time.
3014 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003015 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003016 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3017 virtual_socket_server()->UpdateDelayDistribution();
3018
Niels Möllerf06f9232018-08-07 12:32:18 +02003019 PeerConnectionInterface::RTCConfiguration rtc_config;
3020 rtc_config.enable_rtp_data_channel = true;
3021 rtc_config.enable_dtls_srtp = false;
3022 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003023 ConnectFakeSignaling();
3024 caller()->CreateDataChannel();
3025 caller()->CreateAndSetAndSignalOffer();
3026 ASSERT_TRUE(caller()->data_channel() != nullptr);
3027 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3028 kDefaultTimeout, fake_clock);
3029 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3030 kDefaultTimeout, fake_clock);
3031 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3032 callee()->data_channel()->state(), kDefaultTimeout,
3033 fake_clock);
3034
3035 // Unregister the observer which is normally automatically registered.
3036 callee()->data_channel()->UnregisterObserver();
3037 // Send data and advance fake clock until it should have been received.
3038 std::string data = "hello world";
3039 caller()->data_channel()->Send(DataBuffer(data));
3040 SIMULATED_WAIT(false, 50, fake_clock);
3041
3042 // Attach data channel and expect data to be received immediately. Note that
3043 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3044 // further, but data can be received even if the callback is asynchronous.
3045 MockDataChannelObserver new_observer(callee()->data_channel());
3046 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3047 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003048 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3049 // If this is not done a DCHECK can be hit in ports.cc, because a large
3050 // negative number is calculated for the rtt due to the global clock changing.
3051 caller()->pc()->Close();
3052 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07003053}
3054
3055// This test sets up a call between two parties with audio, video and but only
3056// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003057TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003058 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3059 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003060 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003061 rtc_config_1.enable_dtls_srtp = false;
3062 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3063 rtc_config_2.enable_dtls_srtp = false;
3064 rtc_config_2.enable_dtls_srtp = false;
3065 ASSERT_TRUE(
3066 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003067 ConnectFakeSignaling();
3068 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003069 caller()->AddAudioVideoTracks();
3070 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003071 caller()->CreateAndSetAndSignalOffer();
3072 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3073 // The caller should still have a data channel, but it should be closed, and
3074 // one should ever have been created for the callee.
3075 EXPECT_TRUE(caller()->data_channel() != nullptr);
3076 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3077 EXPECT_EQ(nullptr, callee()->data_channel());
3078}
3079
3080// This test sets up a call between two parties with audio, and video. When
3081// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003082TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003083 PeerConnectionInterface::RTCConfiguration rtc_config;
3084 rtc_config.enable_rtp_data_channel = true;
3085 rtc_config.enable_dtls_srtp = false;
3086 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003087 ConnectFakeSignaling();
3088 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003089 caller()->AddAudioVideoTracks();
3090 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003091 caller()->CreateAndSetAndSignalOffer();
3092 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3093 // Create data channel and do new offer and answer.
3094 caller()->CreateDataChannel();
3095 caller()->CreateAndSetAndSignalOffer();
3096 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3097 ASSERT_NE(nullptr, caller()->data_channel());
3098 ASSERT_NE(nullptr, callee()->data_channel());
3099 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3100 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3101 // Ensure data can be sent in both directions.
3102 std::string data = "hello world";
3103 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3104 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3105 kDefaultTimeout);
3106 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3107 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3108 kDefaultTimeout);
3109}
3110
3111#ifdef HAVE_SCTP
3112
3113// This test sets up a call between two parties with audio, video and an SCTP
3114// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003115TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003116 ASSERT_TRUE(CreatePeerConnectionWrappers());
3117 ConnectFakeSignaling();
3118 // Expect that data channel created on caller side will show up for callee as
3119 // well.
3120 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003121 caller()->AddAudioVideoTracks();
3122 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003123 caller()->CreateAndSetAndSignalOffer();
3124 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3125 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003126 MediaExpectations media_expectations;
3127 media_expectations.ExpectBidirectionalAudioAndVideo();
3128 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003129 // Caller data channel should already exist (it created one). Callee data
3130 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3131 ASSERT_NE(nullptr, caller()->data_channel());
3132 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3133 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3134 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3135
3136 // Ensure data can be sent in both directions.
3137 std::string data = "hello world";
3138 caller()->data_channel()->Send(DataBuffer(data));
3139 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3140 kDefaultTimeout);
3141 callee()->data_channel()->Send(DataBuffer(data));
3142 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3143 kDefaultTimeout);
3144}
3145
3146// Ensure that when the callee closes an SCTP data channel, the closing
3147// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003148TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003149 // Same procedure as above test.
3150 ASSERT_TRUE(CreatePeerConnectionWrappers());
3151 ConnectFakeSignaling();
3152 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003153 caller()->AddAudioVideoTracks();
3154 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003155 caller()->CreateAndSetAndSignalOffer();
3156 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3157 ASSERT_NE(nullptr, caller()->data_channel());
3158 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3159 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3160 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3161
3162 // Close the data channel on the callee side, and wait for it to reach the
3163 // "closed" state on both sides.
3164 callee()->data_channel()->Close();
3165 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3166 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3167}
3168
Seth Hampson2f0d7022018-02-20 11:54:42 -08003169TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003170 ASSERT_TRUE(CreatePeerConnectionWrappers());
3171 ConnectFakeSignaling();
3172 webrtc::DataChannelInit init;
3173 init.id = 53;
3174 init.maxRetransmits = 52;
3175 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003176 caller()->AddAudioVideoTracks();
3177 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003178 caller()->CreateAndSetAndSignalOffer();
3179 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003180 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3181 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07003182 EXPECT_EQ(init.id, callee()->data_channel()->id());
3183 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3184 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3185 EXPECT_FALSE(callee()->data_channel()->negotiated());
3186}
3187
deadbeef1dcb1642017-03-29 21:08:16 -07003188// Test usrsctp's ability to process unordered data stream, where data actually
3189// arrives out of order using simulated delays. Previously there have been some
3190// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003191TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003192 // Introduce random network delays.
3193 // Otherwise it's not a true "unordered" test.
3194 virtual_socket_server()->set_delay_mean(20);
3195 virtual_socket_server()->set_delay_stddev(5);
3196 virtual_socket_server()->UpdateDelayDistribution();
3197 // Normal procedure, but with unordered data channel config.
3198 ASSERT_TRUE(CreatePeerConnectionWrappers());
3199 ConnectFakeSignaling();
3200 webrtc::DataChannelInit init;
3201 init.ordered = false;
3202 caller()->CreateDataChannel(&init);
3203 caller()->CreateAndSetAndSignalOffer();
3204 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3205 ASSERT_NE(nullptr, caller()->data_channel());
3206 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3207 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3208 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3209
3210 static constexpr int kNumMessages = 100;
3211 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3212 static constexpr size_t kMaxMessageSize = 4096;
3213 // Create and send random messages.
3214 std::vector<std::string> sent_messages;
3215 for (int i = 0; i < kNumMessages; ++i) {
3216 size_t length =
3217 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3218 std::string message;
3219 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3220 caller()->data_channel()->Send(DataBuffer(message));
3221 callee()->data_channel()->Send(DataBuffer(message));
3222 sent_messages.push_back(message);
3223 }
3224
3225 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003226 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003227 caller()->data_observer()->received_message_count(),
3228 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003229 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003230 callee()->data_observer()->received_message_count(),
3231 kDefaultTimeout);
3232
3233 // Sort and compare to make sure none of the messages were corrupted.
3234 std::vector<std::string> caller_received_messages =
3235 caller()->data_observer()->messages();
3236 std::vector<std::string> callee_received_messages =
3237 callee()->data_observer()->messages();
3238 std::sort(sent_messages.begin(), sent_messages.end());
3239 std::sort(caller_received_messages.begin(), caller_received_messages.end());
3240 std::sort(callee_received_messages.begin(), callee_received_messages.end());
3241 EXPECT_EQ(sent_messages, caller_received_messages);
3242 EXPECT_EQ(sent_messages, callee_received_messages);
3243}
3244
3245// This test sets up a call between two parties with audio, and video. When
3246// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003247TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003248 ASSERT_TRUE(CreatePeerConnectionWrappers());
3249 ConnectFakeSignaling();
3250 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003251 caller()->AddAudioVideoTracks();
3252 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003253 caller()->CreateAndSetAndSignalOffer();
3254 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3255 // Create data channel and do new offer and answer.
3256 caller()->CreateDataChannel();
3257 caller()->CreateAndSetAndSignalOffer();
3258 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3259 // Caller data channel should already exist (it created one). Callee data
3260 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3261 ASSERT_NE(nullptr, caller()->data_channel());
3262 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3263 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3264 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3265 // Ensure data can be sent in both directions.
3266 std::string data = "hello world";
3267 caller()->data_channel()->Send(DataBuffer(data));
3268 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3269 kDefaultTimeout);
3270 callee()->data_channel()->Send(DataBuffer(data));
3271 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3272 kDefaultTimeout);
3273}
3274
deadbeef7914b8c2017-04-21 03:23:33 -07003275// Set up a connection initially just using SCTP data channels, later upgrading
3276// to audio/video, ensuring frames are received end-to-end. Effectively the
3277// inverse of the test above.
3278// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003279TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003280 ASSERT_TRUE(CreatePeerConnectionWrappers());
3281 ConnectFakeSignaling();
3282 // Do initial offer/answer with just data channel.
3283 caller()->CreateDataChannel();
3284 caller()->CreateAndSetAndSignalOffer();
3285 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3286 // Wait until data can be sent over the data channel.
3287 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3288 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3289 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3290
3291 // Do subsequent offer/answer with two-way audio and video. Audio and video
3292 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003293 caller()->AddAudioVideoTracks();
3294 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003295 caller()->CreateAndSetAndSignalOffer();
3296 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003297 MediaExpectations media_expectations;
3298 media_expectations.ExpectBidirectionalAudioAndVideo();
3299 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003300}
3301
deadbeef8b7e9ad2017-05-25 09:38:55 -07003302static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07003303 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08003304 GetFirstDataContentDescription(desc);
3305 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003306 dcd_offer->set_use_sctpmap(false);
3307 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3308}
3309
3310// Test that the data channel works when a spec-compliant SCTP m= section is
3311// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3312// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003313TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003314 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3315 ASSERT_TRUE(CreatePeerConnectionWrappers());
3316 ConnectFakeSignaling();
3317 caller()->CreateDataChannel();
3318 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3319 caller()->CreateAndSetAndSignalOffer();
3320 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3321 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3322 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3323 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3324
3325 // Ensure data can be sent in both directions.
3326 std::string data = "hello world";
3327 caller()->data_channel()->Send(DataBuffer(data));
3328 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3329 kDefaultTimeout);
3330 callee()->data_channel()->Send(DataBuffer(data));
3331 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3332 kDefaultTimeout);
3333}
3334
deadbeef1dcb1642017-03-29 21:08:16 -07003335#endif // HAVE_SCTP
3336
3337// Test that the ICE connection and gathering states eventually reach
3338// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003339TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003340 ASSERT_TRUE(CreatePeerConnectionWrappers());
3341 ConnectFakeSignaling();
3342 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003343 caller()->AddAudioVideoTracks();
3344 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003345 caller()->CreateAndSetAndSignalOffer();
3346 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3347 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3348 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3349 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3350 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3351 // After the best candidate pair is selected and all candidates are signaled,
3352 // the ICE connection state should reach "complete".
3353 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3354 // answerer/"callee" by default) only reaches "connected". When this is
3355 // fixed, this test should be updated.
3356 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3357 caller()->ice_connection_state(), kDefaultTimeout);
3358 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3359 callee()->ice_connection_state(), kDefaultTimeout);
3360}
3361
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003362// Replaces the first candidate with a static address and configures a
3363// MockAsyncResolver to return the replaced address the first time the static
3364// address is resolved. Candidates past the first will not be signaled.
3365class ReplaceFirstCandidateAddressDropOthers final
3366 : public IceCandidateReplacerInterface {
3367 public:
3368 ReplaceFirstCandidateAddressDropOthers(
3369 const SocketAddress& new_address,
3370 rtc::MockAsyncResolver* mock_async_resolver)
3371 : mock_async_resolver_(mock_async_resolver), new_address_(new_address) {
3372 RTC_DCHECK(mock_async_resolver);
3373 }
3374
3375 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3376 const webrtc::IceCandidateInterface* candidate) override {
3377 if (replaced_candidate_) {
3378 return nullptr;
3379 }
3380
3381 replaced_candidate_ = true;
3382 cricket::Candidate new_candidate(candidate->candidate());
3383 new_candidate.set_address(new_address_);
3384 EXPECT_CALL(*mock_async_resolver_, GetResolvedAddress(_, _))
3385 .WillOnce(DoAll(SetArgPointee<1>(candidate->candidate().address()),
3386 Return(true)));
3387 EXPECT_CALL(*mock_async_resolver_, Destroy(_));
3388 return webrtc::CreateIceCandidate(
3389 candidate->sdp_mid(), candidate->sdp_mline_index(), new_candidate);
3390 }
3391
3392 private:
3393 rtc::MockAsyncResolver* mock_async_resolver_;
3394 SocketAddress new_address_;
3395 bool replaced_candidate_ = false;
3396};
3397
3398// Drops all candidates before they are signaled.
3399class DropAllCandidates final : public IceCandidateReplacerInterface {
3400 public:
3401 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3402 const webrtc::IceCandidateInterface*) override {
3403 return nullptr;
3404 }
3405};
3406
3407// Replace the first caller ICE candidate IP with a fake hostname and drop the
3408// other candidates. Drop all candidates on the callee side (to avoid a prflx
3409// connection). Use a mock resolver to resolve the hostname back to the original
3410// IP on the callee side and check that the ice connection connects.
3411TEST_P(PeerConnectionIntegrationTest,
3412 IceStatesReachCompletionWithRemoteHostname) {
3413 webrtc::MockAsyncResolverFactory* callee_mock_async_resolver_factory;
3414 {
3415 auto resolver_factory =
3416 absl::make_unique<webrtc::MockAsyncResolverFactory>();
3417 callee_mock_async_resolver_factory = resolver_factory.get();
3418 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3419 callee_deps.async_resolver_factory = std::move(resolver_factory);
3420
3421 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3422 RTCConfiguration(), webrtc::PeerConnectionDependencies(nullptr),
3423 RTCConfiguration(), std::move(callee_deps)));
3424 }
3425
3426 rtc::MockAsyncResolver mock_async_resolver;
3427
3428 // This also verifies that the injected AsyncResolverFactory is used by
3429 // P2PTransportChannel.
3430 EXPECT_CALL(*callee_mock_async_resolver_factory, Create())
3431 .WillOnce(Return(&mock_async_resolver));
3432 caller()->SetLocalIceCandidateReplacer(
3433 absl::make_unique<ReplaceFirstCandidateAddressDropOthers>(
3434 SocketAddress("a.b", 10000), &mock_async_resolver));
3435 callee()->SetLocalIceCandidateReplacer(
3436 absl::make_unique<DropAllCandidates>());
3437
3438 ConnectFakeSignaling();
3439 caller()->AddAudioVideoTracks();
3440 callee()->AddAudioVideoTracks();
3441 caller()->CreateAndSetAndSignalOffer();
3442 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3443 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3444 caller()->ice_connection_state(), kDefaultTimeout);
3445 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3446 callee()->ice_connection_state(), kDefaultTimeout);
3447}
3448
Steve Antonede9ca52017-10-16 13:04:27 -07003449// Test that firewalling the ICE connection causes the clients to identify the
3450// disconnected state and then removing the firewall causes them to reconnect.
3451class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003452 : public PeerConnectionIntegrationBaseTest,
3453 public ::testing::WithParamInterface<
3454 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003455 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003456 PeerConnectionIntegrationIceStatesTest()
3457 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3458 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003459 }
3460
3461 void StartStunServer(const SocketAddress& server_address) {
3462 stun_server_.reset(
3463 cricket::TestStunServer::Create(network_thread(), server_address));
3464 }
3465
3466 bool TestIPv6() {
3467 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3468 }
3469
3470 void SetPortAllocatorFlags() {
Qingsi Wanga2d60672018-04-11 16:57:45 -07003471 network_thread()->Invoke<void>(
3472 RTC_FROM_HERE,
3473 rtc::Bind(&cricket::PortAllocator::set_flags,
3474 caller()->port_allocator(), port_allocator_flags_));
3475 network_thread()->Invoke<void>(
3476 RTC_FROM_HERE,
3477 rtc::Bind(&cricket::PortAllocator::set_flags,
3478 callee()->port_allocator(), port_allocator_flags_));
Steve Antonede9ca52017-10-16 13:04:27 -07003479 }
3480
3481 std::vector<SocketAddress> CallerAddresses() {
3482 std::vector<SocketAddress> addresses;
3483 addresses.push_back(SocketAddress("1.1.1.1", 0));
3484 if (TestIPv6()) {
3485 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3486 }
3487 return addresses;
3488 }
3489
3490 std::vector<SocketAddress> CalleeAddresses() {
3491 std::vector<SocketAddress> addresses;
3492 addresses.push_back(SocketAddress("2.2.2.2", 0));
3493 if (TestIPv6()) {
3494 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3495 }
3496 return addresses;
3497 }
3498
3499 void SetUpNetworkInterfaces() {
3500 // Remove the default interfaces added by the test infrastructure.
3501 caller()->network()->RemoveInterface(kDefaultLocalAddress);
3502 callee()->network()->RemoveInterface(kDefaultLocalAddress);
3503
3504 // Add network addresses for test.
3505 for (const auto& caller_address : CallerAddresses()) {
3506 caller()->network()->AddInterface(caller_address);
3507 }
3508 for (const auto& callee_address : CalleeAddresses()) {
3509 callee()->network()->AddInterface(callee_address);
3510 }
3511 }
3512
3513 private:
3514 uint32_t port_allocator_flags_;
3515 std::unique_ptr<cricket::TestStunServer> stun_server_;
3516};
3517
3518// Tests that the PeerConnection goes through all the ICE gathering/connection
3519// states over the duration of the call. This includes Disconnected and Failed
3520// states, induced by putting a firewall between the peers and waiting for them
3521// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003522TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
3523 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
3524 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
3525 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07003526
3527 const SocketAddress kStunServerAddress =
3528 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3529 StartStunServer(kStunServerAddress);
3530
3531 PeerConnectionInterface::RTCConfiguration config;
3532 PeerConnectionInterface::IceServer ice_stun_server;
3533 ice_stun_server.urls.push_back(
3534 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3535 kStunServerAddress.PortAsString());
3536 config.servers.push_back(ice_stun_server);
3537
3538 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3539 ConnectFakeSignaling();
3540 SetPortAllocatorFlags();
3541 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003542 caller()->AddAudioVideoTracks();
3543 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003544
3545 // Initial state before anything happens.
3546 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3547 caller()->ice_gathering_state());
3548 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3549 caller()->ice_connection_state());
3550
3551 // Start the call by creating the offer, setting it as the local description,
3552 // then sending it to the peer who will respond with an answer. This happens
3553 // asynchronously so that we can watch the states as it runs in the
3554 // background.
3555 caller()->CreateAndSetAndSignalOffer();
3556
Steve Anton83119dd2017-11-10 16:19:52 -08003557 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3558 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003559
3560 // Verify that the observer was notified of the intermediate transitions.
3561 EXPECT_THAT(caller()->ice_connection_state_history(),
3562 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3563 PeerConnectionInterface::kIceConnectionConnected,
3564 PeerConnectionInterface::kIceConnectionCompleted));
3565 EXPECT_THAT(caller()->ice_gathering_state_history(),
3566 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
3567 PeerConnectionInterface::kIceGatheringComplete));
3568
3569 // Block connections to/from the caller and wait for ICE to become
3570 // disconnected.
3571 for (const auto& caller_address : CallerAddresses()) {
3572 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3573 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003574 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08003575 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
3576 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003577
3578 // Let ICE re-establish by removing the firewall rules.
3579 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01003580 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08003581 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3582 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003583
3584 // According to RFC7675, if there is no response within 30 seconds then the
3585 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08003586 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07003587 constexpr int kConsentTimeout = 30000;
3588 for (const auto& caller_address : CallerAddresses()) {
3589 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3590 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003591 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08003592 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
3593 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003594}
3595
3596// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
3597// and that the statistics in the metric observers are updated correctly.
3598TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
3599 ASSERT_TRUE(CreatePeerConnectionWrappers());
3600 ConnectFakeSignaling();
3601 SetPortAllocatorFlags();
3602 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003603 caller()->AddAudioVideoTracks();
3604 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003605 caller()->CreateAndSetAndSignalOffer();
3606
3607 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3608
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003609 // TODO(bugs.webrtc.org/9456): Fix it.
3610 const int num_best_ipv4 = webrtc::metrics::NumEvents(
3611 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
3612 const int num_best_ipv6 = webrtc::metrics::NumEvents(
3613 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003614 if (TestIPv6()) {
3615 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
3616 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003617 EXPECT_EQ(0, num_best_ipv4);
3618 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003619 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003620 EXPECT_EQ(1, num_best_ipv4);
3621 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003622 }
3623
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003624 EXPECT_EQ(0, webrtc::metrics::NumEvents(
3625 "WebRTC.PeerConnection.CandidatePairType_UDP",
3626 webrtc::kIceCandidatePairHostHost));
3627 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3628 "WebRTC.PeerConnection.CandidatePairType_UDP",
3629 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07003630}
3631
3632constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
3633 cricket::PORTALLOCATOR_DISABLE_STUN |
3634 cricket::PORTALLOCATOR_DISABLE_RELAY;
3635constexpr uint32_t kFlagsIPv6NoStun =
3636 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
3637 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
3638constexpr uint32_t kFlagsIPv4Stun =
3639 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
3640
Seth Hampson2f0d7022018-02-20 11:54:42 -08003641INSTANTIATE_TEST_CASE_P(
3642 PeerConnectionIntegrationTest,
3643 PeerConnectionIntegrationIceStatesTest,
3644 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3645 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
3646 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
3647 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07003648
deadbeef1dcb1642017-03-29 21:08:16 -07003649// This test sets up a call between two parties with audio and video.
3650// During the call, the caller restarts ICE and the test verifies that
3651// new ICE candidates are generated and audio and video still can flow, and the
3652// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003653TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07003654 ASSERT_TRUE(CreatePeerConnectionWrappers());
3655 ConnectFakeSignaling();
3656 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08003657 caller()->AddAudioVideoTracks();
3658 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003659 caller()->CreateAndSetAndSignalOffer();
3660 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3661 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3662 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3663 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3664 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3665
3666 // To verify that the ICE restart actually occurs, get
3667 // ufrag/password/candidates before and after restart.
3668 // Create an SDP string of the first audio candidate for both clients.
3669 const webrtc::IceCandidateCollection* audio_candidates_caller =
3670 caller()->pc()->local_description()->candidates(0);
3671 const webrtc::IceCandidateCollection* audio_candidates_callee =
3672 callee()->pc()->local_description()->candidates(0);
3673 ASSERT_GT(audio_candidates_caller->count(), 0u);
3674 ASSERT_GT(audio_candidates_callee->count(), 0u);
3675 std::string caller_candidate_pre_restart;
3676 ASSERT_TRUE(
3677 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
3678 std::string callee_candidate_pre_restart;
3679 ASSERT_TRUE(
3680 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3681 const cricket::SessionDescription* desc =
3682 caller()->pc()->local_description()->description();
3683 std::string caller_ufrag_pre_restart =
3684 desc->transport_infos()[0].description.ice_ufrag;
3685 desc = callee()->pc()->local_description()->description();
3686 std::string callee_ufrag_pre_restart =
3687 desc->transport_infos()[0].description.ice_ufrag;
3688
3689 // Have the caller initiate an ICE restart.
3690 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3691 caller()->CreateAndSetAndSignalOffer();
3692 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3693 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3694 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3695 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3696 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3697
3698 // Grab the ufrags/candidates again.
3699 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3700 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3701 ASSERT_GT(audio_candidates_caller->count(), 0u);
3702 ASSERT_GT(audio_candidates_callee->count(), 0u);
3703 std::string caller_candidate_post_restart;
3704 ASSERT_TRUE(
3705 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3706 std::string callee_candidate_post_restart;
3707 ASSERT_TRUE(
3708 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
3709 desc = caller()->pc()->local_description()->description();
3710 std::string caller_ufrag_post_restart =
3711 desc->transport_infos()[0].description.ice_ufrag;
3712 desc = callee()->pc()->local_description()->description();
3713 std::string callee_ufrag_post_restart =
3714 desc->transport_infos()[0].description.ice_ufrag;
3715 // Sanity check that an ICE restart was actually negotiated in SDP.
3716 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
3717 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3718 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3719 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3720
3721 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003722 MediaExpectations media_expectations;
3723 media_expectations.ExpectBidirectionalAudioAndVideo();
3724 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003725}
3726
3727// Verify that audio/video can be received end-to-end when ICE renomination is
3728// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003729TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07003730 PeerConnectionInterface::RTCConfiguration config;
3731 config.enable_ice_renomination = true;
3732 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3733 ConnectFakeSignaling();
3734 // Do normal offer/answer and wait for some frames to be received in each
3735 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003736 caller()->AddAudioVideoTracks();
3737 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003738 caller()->CreateAndSetAndSignalOffer();
3739 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3740 // Sanity check that ICE renomination was actually negotiated.
3741 const cricket::SessionDescription* desc =
3742 caller()->pc()->local_description()->description();
3743 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003744 ASSERT_NE(
3745 info.description.transport_options.end(),
3746 std::find(info.description.transport_options.begin(),
3747 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003748 }
3749 desc = callee()->pc()->local_description()->description();
3750 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003751 ASSERT_NE(
3752 info.description.transport_options.end(),
3753 std::find(info.description.transport_options.begin(),
3754 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003755 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003756 MediaExpectations media_expectations;
3757 media_expectations.ExpectBidirectionalAudioAndVideo();
3758 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003759}
3760
Steve Anton6f25b092017-10-23 09:39:20 -07003761// With a max bundle policy and RTCP muxing, adding a new media description to
3762// the connection should not affect ICE at all because the new media will use
3763// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003764TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003765 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07003766 PeerConnectionInterface::RTCConfiguration config;
3767 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3768 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3769 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
3770 config, PeerConnectionInterface::RTCConfiguration()));
3771 ConnectFakeSignaling();
3772
Steve Anton15324772018-01-16 10:26:49 -08003773 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003774 caller()->CreateAndSetAndSignalOffer();
3775 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07003776 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3777 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07003778
3779 caller()->clear_ice_connection_state_history();
3780
Steve Anton15324772018-01-16 10:26:49 -08003781 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003782 caller()->CreateAndSetAndSignalOffer();
3783 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3784
3785 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
3786}
3787
deadbeef1dcb1642017-03-29 21:08:16 -07003788// This test sets up a call between two parties with audio and video. It then
3789// renegotiates setting the video m-line to "port 0", then later renegotiates
3790// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003791TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003792 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
3793 ASSERT_TRUE(CreatePeerConnectionWrappers());
3794 ConnectFakeSignaling();
3795
3796 // Do initial negotiation, only sending media from the caller. Will result in
3797 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08003798 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003799 caller()->CreateAndSetAndSignalOffer();
3800 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3801
3802 // Negotiate again, disabling the video "m=" section (the callee will set the
3803 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003804 if (sdp_semantics_ == SdpSemantics::kPlanB) {
3805 PeerConnectionInterface::RTCOfferAnswerOptions options;
3806 options.offer_to_receive_video = 0;
3807 callee()->SetOfferAnswerOptions(options);
3808 } else {
3809 callee()->SetRemoteOfferHandler([this] {
3810 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
3811 });
3812 }
deadbeef1dcb1642017-03-29 21:08:16 -07003813 caller()->CreateAndSetAndSignalOffer();
3814 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3815 // Sanity check that video "m=" section was actually rejected.
3816 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
3817 callee()->pc()->local_description()->description());
3818 ASSERT_NE(nullptr, answer_video_content);
3819 ASSERT_TRUE(answer_video_content->rejected);
3820
3821 // Enable video and do negotiation again, making sure video is received
3822 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003823 if (sdp_semantics_ == SdpSemantics::kPlanB) {
3824 PeerConnectionInterface::RTCOfferAnswerOptions options;
3825 options.offer_to_receive_video = 1;
3826 callee()->SetOfferAnswerOptions(options);
3827 } else {
3828 // The caller's transceiver is stopped, so we need to add another track.
3829 auto caller_transceiver =
3830 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
3831 EXPECT_TRUE(caller_transceiver->stopped());
3832 caller()->AddVideoTrack();
3833 }
3834 callee()->AddVideoTrack();
3835 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07003836 caller()->CreateAndSetAndSignalOffer();
3837 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003838
deadbeef1dcb1642017-03-29 21:08:16 -07003839 // Verify the caller receives frames from the newly added stream, and the
3840 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003841 MediaExpectations media_expectations;
3842 media_expectations.CalleeExpectsSomeAudio();
3843 media_expectations.ExpectBidirectionalVideo();
3844 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003845}
3846
deadbeef1dcb1642017-03-29 21:08:16 -07003847// This tests that if we negotiate after calling CreateSender but before we
3848// have a track, then set a track later, frames from the newly-set track are
3849// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003850TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07003851 MediaFlowsAfterEarlyWarmupWithCreateSender) {
3852 ASSERT_TRUE(CreatePeerConnectionWrappers());
3853 ConnectFakeSignaling();
3854 auto caller_audio_sender =
3855 caller()->pc()->CreateSender("audio", "caller_stream");
3856 auto caller_video_sender =
3857 caller()->pc()->CreateSender("video", "caller_stream");
3858 auto callee_audio_sender =
3859 callee()->pc()->CreateSender("audio", "callee_stream");
3860 auto callee_video_sender =
3861 callee()->pc()->CreateSender("video", "callee_stream");
3862 caller()->CreateAndSetAndSignalOffer();
3863 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3864 // Wait for ICE to complete, without any tracks being set.
3865 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3866 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3867 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3868 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3869 // Now set the tracks, and expect frames to immediately start flowing.
3870 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3871 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3872 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3873 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08003874 MediaExpectations media_expectations;
3875 media_expectations.ExpectBidirectionalAudioAndVideo();
3876 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3877}
3878
3879// This tests that if we negotiate after calling AddTransceiver but before we
3880// have a track, then set a track later, frames from the newly-set tracks are
3881// received end-to-end.
3882TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
3883 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
3884 ASSERT_TRUE(CreatePeerConnectionWrappers());
3885 ConnectFakeSignaling();
3886 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
3887 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
3888 auto caller_audio_sender = audio_result.MoveValue()->sender();
3889 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
3890 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
3891 auto caller_video_sender = video_result.MoveValue()->sender();
3892 callee()->SetRemoteOfferHandler([this] {
3893 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
3894 callee()->pc()->GetTransceivers()[0]->SetDirection(
3895 RtpTransceiverDirection::kSendRecv);
3896 callee()->pc()->GetTransceivers()[1]->SetDirection(
3897 RtpTransceiverDirection::kSendRecv);
3898 });
3899 caller()->CreateAndSetAndSignalOffer();
3900 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3901 // Wait for ICE to complete, without any tracks being set.
3902 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3903 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3904 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3905 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3906 // Now set the tracks, and expect frames to immediately start flowing.
3907 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
3908 auto callee_video_sender = callee()->pc()->GetSenders()[1];
3909 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3910 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3911 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3912 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
3913 MediaExpectations media_expectations;
3914 media_expectations.ExpectBidirectionalAudioAndVideo();
3915 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003916}
3917
3918// This test verifies that a remote video track can be added via AddStream,
3919// and sent end-to-end. For this particular test, it's simply echoed back
3920// from the caller to the callee, rather than being forwarded to a third
3921// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003922TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07003923 ASSERT_TRUE(CreatePeerConnectionWrappers());
3924 ConnectFakeSignaling();
3925 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08003926 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07003927 caller()->CreateAndSetAndSignalOffer();
3928 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003929 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07003930
3931 // Echo the stream back, and do a new offer/anwer (initiated by callee this
3932 // time).
3933 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
3934 callee()->CreateAndSetAndSignalOffer();
3935 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3936
Seth Hampson2f0d7022018-02-20 11:54:42 -08003937 MediaExpectations media_expectations;
3938 media_expectations.ExpectBidirectionalVideo();
3939 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003940}
3941
3942// Test that we achieve the expected end-to-end connection time, using a
3943// fake clock and simulated latency on the media and signaling paths.
3944// We use a TURN<->TURN connection because this is usually the quickest to
3945// set up initially, especially when we're confident the connection will work
3946// and can start sending media before we get a STUN response.
3947//
3948// With various optimizations enabled, here are the network delays we expect to
3949// be on the critical path:
3950// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
3951// signaling answer (with DTLS fingerprint).
3952// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
3953// using TURN<->TURN pair, and DTLS exchange is 4 packets,
3954// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003955TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07003956 rtc::ScopedFakeClock fake_clock;
3957 // Some things use a time of "0" as a special value, so we need to start out
3958 // the fake clock at a nonzero time.
3959 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003960 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003961
3962 static constexpr int media_hop_delay_ms = 50;
3963 static constexpr int signaling_trip_delay_ms = 500;
3964 // For explanation of these values, see comment above.
3965 static constexpr int required_media_hops = 9;
3966 static constexpr int required_signaling_trips = 2;
3967 // For internal delays (such as posting an event asychronously).
3968 static constexpr int allowed_internal_delay_ms = 20;
3969 static constexpr int total_connection_time_ms =
3970 media_hop_delay_ms * required_media_hops +
3971 signaling_trip_delay_ms * required_signaling_trips +
3972 allowed_internal_delay_ms;
3973
3974 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3975 3478};
3976 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3977 0};
3978 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3979 3478};
3980 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3981 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07003982 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
3983 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02003984
Seth Hampsonaed71642018-06-11 07:41:32 -07003985 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
3986 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07003987 // Bypass permission check on received packets so media can be sent before
3988 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07003989 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
3990 turn_server_1->set_enable_permission_checks(false);
3991 });
3992 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
3993 turn_server_2->set_enable_permission_checks(false);
3994 });
deadbeef1dcb1642017-03-29 21:08:16 -07003995
3996 PeerConnectionInterface::RTCConfiguration client_1_config;
3997 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3998 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3999 ice_server_1.username = "test";
4000 ice_server_1.password = "test";
4001 client_1_config.servers.push_back(ice_server_1);
4002 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4003 client_1_config.presume_writable_when_fully_relayed = true;
4004
4005 PeerConnectionInterface::RTCConfiguration client_2_config;
4006 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4007 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4008 ice_server_2.username = "test";
4009 ice_server_2.password = "test";
4010 client_2_config.servers.push_back(ice_server_2);
4011 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4012 client_2_config.presume_writable_when_fully_relayed = true;
4013
4014 ASSERT_TRUE(
4015 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4016 // Set up the simulated delays.
4017 SetSignalingDelayMs(signaling_trip_delay_ms);
4018 ConnectFakeSignaling();
4019 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4020 virtual_socket_server()->UpdateDelayDistribution();
4021
4022 // Set "offer to receive audio/video" without adding any tracks, so we just
4023 // set up ICE/DTLS with no media.
4024 PeerConnectionInterface::RTCOfferAnswerOptions options;
4025 options.offer_to_receive_audio = 1;
4026 options.offer_to_receive_video = 1;
4027 caller()->SetOfferAnswerOptions(options);
4028 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004029 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4030 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004031 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4032 // If this is not done a DCHECK can be hit in ports.cc, because a large
4033 // negative number is calculated for the rtt due to the global clock changing.
4034 caller()->pc()->Close();
4035 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07004036}
4037
Jonas Orelandbdcee282017-10-10 14:01:40 +02004038// Verify that a TurnCustomizer passed in through RTCConfiguration
4039// is actually used by the underlying TURN candidate pair.
4040// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004041TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004042 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4043 3478};
4044 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4045 0};
4046 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4047 3478};
4048 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4049 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004050 CreateTurnServer(turn_server_1_internal_address,
4051 turn_server_1_external_address);
4052 CreateTurnServer(turn_server_2_internal_address,
4053 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004054
4055 PeerConnectionInterface::RTCConfiguration client_1_config;
4056 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4057 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4058 ice_server_1.username = "test";
4059 ice_server_1.password = "test";
4060 client_1_config.servers.push_back(ice_server_1);
4061 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004062 auto* customizer1 = CreateTurnCustomizer();
4063 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004064
4065 PeerConnectionInterface::RTCConfiguration client_2_config;
4066 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4067 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4068 ice_server_2.username = "test";
4069 ice_server_2.password = "test";
4070 client_2_config.servers.push_back(ice_server_2);
4071 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004072 auto* customizer2 = CreateTurnCustomizer();
4073 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004074
4075 ASSERT_TRUE(
4076 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4077 ConnectFakeSignaling();
4078
4079 // Set "offer to receive audio/video" without adding any tracks, so we just
4080 // set up ICE/DTLS with no media.
4081 PeerConnectionInterface::RTCOfferAnswerOptions options;
4082 options.offer_to_receive_audio = 1;
4083 options.offer_to_receive_video = 1;
4084 caller()->SetOfferAnswerOptions(options);
4085 caller()->CreateAndSetAndSignalOffer();
4086 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4087
Seth Hampsonaed71642018-06-11 07:41:32 -07004088 ExpectTurnCustomizerCountersIncremented(customizer1);
4089 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004090}
4091
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004092// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4093// send media between the caller and the callee.
4094TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4095 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4096 3478};
4097 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4098
4099 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004100 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4101 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004102
4103 webrtc::PeerConnectionInterface::IceServer ice_server;
4104 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4105 ice_server.username = "test";
4106 ice_server.password = "test";
4107
4108 PeerConnectionInterface::RTCConfiguration client_1_config;
4109 client_1_config.servers.push_back(ice_server);
4110 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4111
4112 PeerConnectionInterface::RTCConfiguration client_2_config;
4113 client_2_config.servers.push_back(ice_server);
4114 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4115
4116 ASSERT_TRUE(
4117 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4118
4119 // Do normal offer/answer and wait for ICE to complete.
4120 ConnectFakeSignaling();
4121 caller()->AddAudioVideoTracks();
4122 callee()->AddAudioVideoTracks();
4123 caller()->CreateAndSetAndSignalOffer();
4124 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4125 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4126 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4127
4128 MediaExpectations media_expectations;
4129 media_expectations.ExpectBidirectionalAudioAndVideo();
4130 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4131}
4132
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004133// Verify that a SSLCertificateVerifier passed in through
4134// PeerConnectionDependencies is actually used by the underlying SSL
4135// implementation to determine whether a certificate presented by the TURN
4136// server is accepted by the client. Note that openssladapter_unittest.cc
4137// contains more detailed, lower-level tests.
4138TEST_P(PeerConnectionIntegrationTest,
4139 SSLCertificateVerifierUsedForTurnConnections) {
4140 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4141 3478};
4142 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4143
4144 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4145 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004146 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4147 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004148
4149 webrtc::PeerConnectionInterface::IceServer ice_server;
4150 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4151 ice_server.username = "test";
4152 ice_server.password = "test";
4153
4154 PeerConnectionInterface::RTCConfiguration client_1_config;
4155 client_1_config.servers.push_back(ice_server);
4156 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4157
4158 PeerConnectionInterface::RTCConfiguration client_2_config;
4159 client_2_config.servers.push_back(ice_server);
4160 // Setting the type to kRelay forces the connection to go through a TURN
4161 // server.
4162 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4163
4164 // Get a copy to the pointer so we can verify calls later.
4165 rtc::TestCertificateVerifier* client_1_cert_verifier =
4166 new rtc::TestCertificateVerifier();
4167 client_1_cert_verifier->verify_certificate_ = true;
4168 rtc::TestCertificateVerifier* client_2_cert_verifier =
4169 new rtc::TestCertificateVerifier();
4170 client_2_cert_verifier->verify_certificate_ = true;
4171
4172 // Create the dependencies with the test certificate verifier.
4173 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4174 client_1_deps.tls_cert_verifier =
4175 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4176 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4177 client_2_deps.tls_cert_verifier =
4178 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4179
4180 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4181 client_1_config, std::move(client_1_deps), client_2_config,
4182 std::move(client_2_deps)));
4183 ConnectFakeSignaling();
4184
4185 // Set "offer to receive audio/video" without adding any tracks, so we just
4186 // set up ICE/DTLS with no media.
4187 PeerConnectionInterface::RTCOfferAnswerOptions options;
4188 options.offer_to_receive_audio = 1;
4189 options.offer_to_receive_video = 1;
4190 caller()->SetOfferAnswerOptions(options);
4191 caller()->CreateAndSetAndSignalOffer();
4192 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4193
4194 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4195 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004196}
4197
4198TEST_P(PeerConnectionIntegrationTest,
4199 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4200 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4201 3478};
4202 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4203
4204 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4205 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004206 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4207 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004208
4209 webrtc::PeerConnectionInterface::IceServer ice_server;
4210 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4211 ice_server.username = "test";
4212 ice_server.password = "test";
4213
4214 PeerConnectionInterface::RTCConfiguration client_1_config;
4215 client_1_config.servers.push_back(ice_server);
4216 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4217
4218 PeerConnectionInterface::RTCConfiguration client_2_config;
4219 client_2_config.servers.push_back(ice_server);
4220 // Setting the type to kRelay forces the connection to go through a TURN
4221 // server.
4222 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4223
4224 // Get a copy to the pointer so we can verify calls later.
4225 rtc::TestCertificateVerifier* client_1_cert_verifier =
4226 new rtc::TestCertificateVerifier();
4227 client_1_cert_verifier->verify_certificate_ = false;
4228 rtc::TestCertificateVerifier* client_2_cert_verifier =
4229 new rtc::TestCertificateVerifier();
4230 client_2_cert_verifier->verify_certificate_ = false;
4231
4232 // Create the dependencies with the test certificate verifier.
4233 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4234 client_1_deps.tls_cert_verifier =
4235 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4236 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4237 client_2_deps.tls_cert_verifier =
4238 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4239
4240 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4241 client_1_config, std::move(client_1_deps), client_2_config,
4242 std::move(client_2_deps)));
4243 ConnectFakeSignaling();
4244
4245 // Set "offer to receive audio/video" without adding any tracks, so we just
4246 // set up ICE/DTLS with no media.
4247 PeerConnectionInterface::RTCOfferAnswerOptions options;
4248 options.offer_to_receive_audio = 1;
4249 options.offer_to_receive_video = 1;
4250 caller()->SetOfferAnswerOptions(options);
4251 caller()->CreateAndSetAndSignalOffer();
4252 bool wait_res = true;
4253 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4254 // properly, should be able to just wait for a state of "failed" instead of
4255 // waiting a fixed 10 seconds.
4256 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4257 ASSERT_FALSE(wait_res);
4258
4259 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4260 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004261}
4262
deadbeefc964d0b2017-04-03 10:03:35 -07004263// Test that audio and video flow end-to-end when codec names don't use the
4264// expected casing, given that they're supposed to be case insensitive. To test
4265// this, all but one codec is removed from each media description, and its
4266// casing is changed.
4267//
4268// In the past, this has regressed and caused crashes/black video, due to the
4269// fact that code at some layers was doing case-insensitive comparisons and
4270// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004271TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004272 ASSERT_TRUE(CreatePeerConnectionWrappers());
4273 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004274 caller()->AddAudioVideoTracks();
4275 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004276
4277 // Remove all but one audio/video codec (opus and VP8), and change the
4278 // casing of the caller's generated offer.
4279 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4280 cricket::AudioContentDescription* audio =
4281 GetFirstAudioContentDescription(description);
4282 ASSERT_NE(nullptr, audio);
4283 auto audio_codecs = audio->codecs();
4284 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4285 [](const cricket::AudioCodec& codec) {
4286 return codec.name != "opus";
4287 }),
4288 audio_codecs.end());
4289 ASSERT_EQ(1u, audio_codecs.size());
4290 audio_codecs[0].name = "OpUs";
4291 audio->set_codecs(audio_codecs);
4292
4293 cricket::VideoContentDescription* video =
4294 GetFirstVideoContentDescription(description);
4295 ASSERT_NE(nullptr, video);
4296 auto video_codecs = video->codecs();
4297 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4298 [](const cricket::VideoCodec& codec) {
4299 return codec.name != "VP8";
4300 }),
4301 video_codecs.end());
4302 ASSERT_EQ(1u, video_codecs.size());
4303 video_codecs[0].name = "vP8";
4304 video->set_codecs(video_codecs);
4305 });
4306
4307 caller()->CreateAndSetAndSignalOffer();
4308 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4309
4310 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004311 MediaExpectations media_expectations;
4312 media_expectations.ExpectBidirectionalAudioAndVideo();
4313 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004314}
4315
Jonas Oreland49ac5952018-09-26 16:04:32 +02004316TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004317 ASSERT_TRUE(CreatePeerConnectionWrappers());
4318 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004319 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004320 caller()->CreateAndSetAndSignalOffer();
4321 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004322 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004323 MediaExpectations media_expectations;
4324 media_expectations.CalleeExpectsSomeAudio(1);
4325 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004326 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004327 auto receiver = callee()->pc()->GetReceivers()[0];
4328 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004329 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004330 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4331 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004332 sources[0].source_id());
4333 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4334}
4335
4336TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4337 ASSERT_TRUE(CreatePeerConnectionWrappers());
4338 ConnectFakeSignaling();
4339 caller()->AddVideoTrack();
4340 caller()->CreateAndSetAndSignalOffer();
4341 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4342 // Wait for one video frame to be received by the callee.
4343 MediaExpectations media_expectations;
4344 media_expectations.CalleeExpectsSomeVideo(1);
4345 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4346 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4347 auto receiver = callee()->pc()->GetReceivers()[0];
4348 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4349 auto sources = receiver->GetSources();
4350 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4351 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4352 sources[0].source_id());
4353 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004354}
4355
deadbeef2f425aa2017-04-14 10:41:32 -07004356// Test that if a track is removed and added again with a different stream ID,
4357// the new stream ID is successfully communicated in SDP and media continues to
4358// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004359// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4360// it will not reuse a transceiver that has already been sending. After creating
4361// a new transceiver it tries to create an offer with two senders of the same
4362// track ids and it fails.
4363TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004364 ASSERT_TRUE(CreatePeerConnectionWrappers());
4365 ConnectFakeSignaling();
4366
deadbeef2f425aa2017-04-14 10:41:32 -07004367 // Add track using stream 1, do offer/answer.
4368 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4369 caller()->CreateLocalAudioTrack();
4370 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004371 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004372 caller()->CreateAndSetAndSignalOffer();
4373 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004374 {
4375 MediaExpectations media_expectations;
4376 media_expectations.CalleeExpectsSomeAudio(1);
4377 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4378 }
deadbeef2f425aa2017-04-14 10:41:32 -07004379 // Remove the sender, and create a new one with the new stream.
4380 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004381 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004382 caller()->CreateAndSetAndSignalOffer();
4383 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4384 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004385 {
4386 MediaExpectations media_expectations;
4387 media_expectations.CalleeExpectsSomeAudio();
4388 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4389 }
deadbeef2f425aa2017-04-14 10:41:32 -07004390}
4391
Seth Hampson2f0d7022018-02-20 11:54:42 -08004392TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004393 ASSERT_TRUE(CreatePeerConnectionWrappers());
4394 ConnectFakeSignaling();
4395
Karl Wiberg918f50c2018-07-05 11:40:33 +02004396 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Elad Alon99c3fe52017-10-13 16:29:40 +02004397 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
4398 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
4399 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004400 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4401 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004402
Steve Anton15324772018-01-16 10:26:49 -08004403 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004404 caller()->CreateAndSetAndSignalOffer();
4405 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4406}
4407
Steve Antonede9ca52017-10-16 13:04:27 -07004408// Test that if candidates are only signaled by applying full session
4409// descriptions (instead of using AddIceCandidate), the peers can connect to
4410// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004411TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004412 ASSERT_TRUE(CreatePeerConnectionWrappers());
4413 // Each side will signal the session descriptions but not candidates.
4414 ConnectFakeSignalingForSdpOnly();
4415
4416 // Add audio video track and exchange the initial offer/answer with media
4417 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004418 caller()->AddAudioVideoTracks();
4419 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004420 caller()->CreateAndSetAndSignalOffer();
4421
4422 // Wait for all candidates to be gathered on both the caller and callee.
4423 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4424 caller()->ice_gathering_state(), kDefaultTimeout);
4425 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4426 callee()->ice_gathering_state(), kDefaultTimeout);
4427
4428 // The candidates will now be included in the session description, so
4429 // signaling them will start the ICE connection.
4430 caller()->CreateAndSetAndSignalOffer();
4431 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4432
4433 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004434 MediaExpectations media_expectations;
4435 media_expectations.ExpectBidirectionalAudioAndVideo();
4436 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004437}
4438
henrika5f6bf242017-11-01 11:06:56 +01004439// Test that SetAudioPlayout can be used to disable audio playout from the
4440// start, then later enable it. This may be useful, for example, if the caller
4441// needs to play a local ringtone until some event occurs, after which it
4442// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004443TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004444 ASSERT_TRUE(CreatePeerConnectionWrappers());
4445 ConnectFakeSignaling();
4446
4447 // Set up audio-only call where audio playout is disabled on caller's side.
4448 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004449 caller()->AddAudioTrack();
4450 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004451 caller()->CreateAndSetAndSignalOffer();
4452 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4453
4454 // Pump messages for a second.
4455 WAIT(false, 1000);
4456 // Since audio playout is disabled, the caller shouldn't have received
4457 // anything (at the playout level, at least).
4458 EXPECT_EQ(0, caller()->audio_frames_received());
4459 // As a sanity check, make sure the callee (for which playout isn't disabled)
4460 // did still see frames on its audio level.
4461 ASSERT_GT(callee()->audio_frames_received(), 0);
4462
4463 // Enable playout again, and ensure audio starts flowing.
4464 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004465 MediaExpectations media_expectations;
4466 media_expectations.ExpectBidirectionalAudio();
4467 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004468}
4469
4470double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4471 auto report = pc->NewGetStats();
4472 auto track_stats_list =
4473 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4474 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4475 for (const auto* track_stats : track_stats_list) {
4476 if (track_stats->remote_source.is_defined() &&
4477 *track_stats->remote_source) {
4478 remote_track_stats = track_stats;
4479 break;
4480 }
4481 }
4482
4483 if (!remote_track_stats->total_audio_energy.is_defined()) {
4484 return 0.0;
4485 }
4486 return *remote_track_stats->total_audio_energy;
4487}
4488
4489// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4490// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004491TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004492 DisableAudioPlayoutStillGeneratesAudioStats) {
4493 ASSERT_TRUE(CreatePeerConnectionWrappers());
4494 ConnectFakeSignaling();
4495
4496 // Set up audio-only call where playout is disabled but audio-processing is
4497 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004498 caller()->AddAudioTrack();
4499 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004500 caller()->pc()->SetAudioPlayout(false);
4501
4502 caller()->CreateAndSetAndSignalOffer();
4503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4504
4505 // Wait for the callee to receive audio stats.
4506 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4507}
4508
henrika4f167df2017-11-01 14:45:55 +01004509// Test that SetAudioRecording can be used to disable audio recording from the
4510// start, then later enable it. This may be useful, for example, if the caller
4511// wants to ensure that no audio resources are active before a certain state
4512// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004513TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004514 ASSERT_TRUE(CreatePeerConnectionWrappers());
4515 ConnectFakeSignaling();
4516
4517 // Set up audio-only call where audio recording is disabled on caller's side.
4518 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08004519 caller()->AddAudioTrack();
4520 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01004521 caller()->CreateAndSetAndSignalOffer();
4522 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4523
4524 // Pump messages for a second.
4525 WAIT(false, 1000);
4526 // Since caller has disabled audio recording, the callee shouldn't have
4527 // received anything.
4528 EXPECT_EQ(0, callee()->audio_frames_received());
4529 // As a sanity check, make sure the caller did still see frames on its
4530 // audio level since audio recording is enabled on the calle side.
4531 ASSERT_GT(caller()->audio_frames_received(), 0);
4532
4533 // Enable audio recording again, and ensure audio starts flowing.
4534 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004535 MediaExpectations media_expectations;
4536 media_expectations.ExpectBidirectionalAudio();
4537 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01004538}
4539
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004540// Test that after closing PeerConnections, they stop sending any packets (ICE,
4541// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004542TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004543 // Set up audio/video/data, wait for some frames to be received.
4544 ASSERT_TRUE(CreatePeerConnectionWrappers());
4545 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004546 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004547#ifdef HAVE_SCTP
4548 caller()->CreateDataChannel();
4549#endif
4550 caller()->CreateAndSetAndSignalOffer();
4551 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004552 MediaExpectations media_expectations;
4553 media_expectations.CalleeExpectsSomeAudioAndVideo();
4554 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004555 // Close PeerConnections.
4556 caller()->pc()->Close();
4557 callee()->pc()->Close();
4558 // Pump messages for a second, and ensure no new packets end up sent.
4559 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
4560 WAIT(false, 1000);
4561 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
4562 EXPECT_EQ(sent_packets_a, sent_packets_b);
4563}
4564
Steve Anton7eca0932018-03-30 15:18:41 -07004565// Test that transport stats are generated by the RTCStatsCollector for a
4566// connection that only involves data channels. This is a regression test for
4567// crbug.com/826972.
4568#ifdef HAVE_SCTP
4569TEST_P(PeerConnectionIntegrationTest,
4570 TransportStatsReportedForDataChannelOnlyConnection) {
4571 ASSERT_TRUE(CreatePeerConnectionWrappers());
4572 ConnectFakeSignaling();
4573 caller()->CreateDataChannel();
4574
4575 caller()->CreateAndSetAndSignalOffer();
4576 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4577 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
4578
4579 auto caller_report = caller()->NewGetStats();
4580 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
4581 auto callee_report = callee()->NewGetStats();
4582 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
4583}
4584#endif // HAVE_SCTP
4585
Qingsi Wang7685e862018-06-11 20:15:46 -07004586TEST_P(PeerConnectionIntegrationTest,
4587 IceEventsGeneratedAndLoggedInRtcEventLog) {
4588 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
4589 ConnectFakeSignaling();
4590 PeerConnectionInterface::RTCOfferAnswerOptions options;
4591 options.offer_to_receive_audio = 1;
4592 caller()->SetOfferAnswerOptions(options);
4593 caller()->CreateAndSetAndSignalOffer();
4594 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4595 ASSERT_NE(nullptr, caller()->event_log_factory());
4596 ASSERT_NE(nullptr, callee()->event_log_factory());
4597 webrtc::FakeRtcEventLog* caller_event_log =
4598 static_cast<webrtc::FakeRtcEventLog*>(
4599 caller()->event_log_factory()->last_log_created());
4600 webrtc::FakeRtcEventLog* callee_event_log =
4601 static_cast<webrtc::FakeRtcEventLog*>(
4602 callee()->event_log_factory()->last_log_created());
4603 ASSERT_NE(nullptr, caller_event_log);
4604 ASSERT_NE(nullptr, callee_event_log);
4605 int caller_ice_config_count = caller_event_log->GetEventCount(
4606 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4607 int caller_ice_event_count = caller_event_log->GetEventCount(
4608 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4609 int callee_ice_config_count = callee_event_log->GetEventCount(
4610 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4611 int callee_ice_event_count = callee_event_log->GetEventCount(
4612 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4613 EXPECT_LT(0, caller_ice_config_count);
4614 EXPECT_LT(0, caller_ice_event_count);
4615 EXPECT_LT(0, callee_ice_config_count);
4616 EXPECT_LT(0, callee_ice_event_count);
4617}
4618
Seth Hampson2f0d7022018-02-20 11:54:42 -08004619INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
4620 PeerConnectionIntegrationTest,
4621 Values(SdpSemantics::kPlanB,
4622 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08004623
Steve Anton74255ff2018-01-24 18:32:57 -08004624// Tests that verify interoperability between Plan B and Unified Plan
4625// PeerConnections.
4626class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004627 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08004628 public ::testing::WithParamInterface<
4629 std::tuple<SdpSemantics, SdpSemantics>> {
4630 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004631 // Setting the SdpSemantics for the base test to kDefault does not matter
4632 // because we specify not to use the test semantics when creating
4633 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08004634 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07004635 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08004636 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08004637 callee_semantics_(std::get<1>(GetParam())) {}
4638
4639 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07004640 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
4641 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08004642 }
4643
4644 const SdpSemantics caller_semantics_;
4645 const SdpSemantics callee_semantics_;
4646};
4647
4648TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
4649 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4650 ConnectFakeSignaling();
4651
4652 caller()->CreateAndSetAndSignalOffer();
4653 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4654}
4655
4656TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
4657 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4658 ConnectFakeSignaling();
4659 auto audio_sender = caller()->AddAudioTrack();
4660
4661 caller()->CreateAndSetAndSignalOffer();
4662 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4663
4664 // Verify that one audio receiver has been created on the remote and that it
4665 // has the same track ID as the sending track.
4666 auto receivers = callee()->pc()->GetReceivers();
4667 ASSERT_EQ(1u, receivers.size());
4668 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
4669 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
4670
Seth Hampson2f0d7022018-02-20 11:54:42 -08004671 MediaExpectations media_expectations;
4672 media_expectations.CalleeExpectsSomeAudio();
4673 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004674}
4675
4676TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
4677 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4678 ConnectFakeSignaling();
4679 auto video_sender = caller()->AddVideoTrack();
4680 auto audio_sender = caller()->AddAudioTrack();
4681
4682 caller()->CreateAndSetAndSignalOffer();
4683 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4684
4685 // Verify that one audio and one video receiver have been created on the
4686 // remote and that they have the same track IDs as the sending tracks.
4687 auto audio_receivers =
4688 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
4689 ASSERT_EQ(1u, audio_receivers.size());
4690 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
4691 auto video_receivers =
4692 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
4693 ASSERT_EQ(1u, video_receivers.size());
4694 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
4695
Seth Hampson2f0d7022018-02-20 11:54:42 -08004696 MediaExpectations media_expectations;
4697 media_expectations.CalleeExpectsSomeAudioAndVideo();
4698 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004699}
4700
4701TEST_P(PeerConnectionIntegrationInteropTest,
4702 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
4703 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4704 ConnectFakeSignaling();
4705 caller()->AddAudioVideoTracks();
4706 callee()->AddAudioVideoTracks();
4707
4708 caller()->CreateAndSetAndSignalOffer();
4709 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4710
Seth Hampson2f0d7022018-02-20 11:54:42 -08004711 MediaExpectations media_expectations;
4712 media_expectations.ExpectBidirectionalAudioAndVideo();
4713 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004714}
4715
4716TEST_P(PeerConnectionIntegrationInteropTest,
4717 ReverseRolesOneAudioLocalToOneVideoRemote) {
4718 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4719 ConnectFakeSignaling();
4720 caller()->AddAudioTrack();
4721 callee()->AddVideoTrack();
4722
4723 caller()->CreateAndSetAndSignalOffer();
4724 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4725
4726 // Verify that only the audio track has been negotiated.
4727 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
4728 // Might also check that the callee's NegotiationNeeded flag is set.
4729
4730 // Reverse roles.
4731 callee()->CreateAndSetAndSignalOffer();
4732 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4733
Seth Hampson2f0d7022018-02-20 11:54:42 -08004734 MediaExpectations media_expectations;
4735 media_expectations.CallerExpectsSomeVideo();
4736 media_expectations.CalleeExpectsSomeAudio();
4737 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004738}
4739
Steve Antonba42e992018-04-09 14:10:01 -07004740INSTANTIATE_TEST_CASE_P(
4741 PeerConnectionIntegrationTest,
4742 PeerConnectionIntegrationInteropTest,
4743 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4744 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
4745
4746// Test that if the Unified Plan side offers two video tracks then the Plan B
4747// side will only see the first one and ignore the second.
4748TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07004749 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
4750 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08004751 ConnectFakeSignaling();
4752 auto first_sender = caller()->AddVideoTrack();
4753 caller()->AddVideoTrack();
4754
4755 caller()->CreateAndSetAndSignalOffer();
4756 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4757
4758 // Verify that there is only one receiver and it corresponds to the first
4759 // added track.
4760 auto receivers = callee()->pc()->GetReceivers();
4761 ASSERT_EQ(1u, receivers.size());
4762 EXPECT_TRUE(receivers[0]->track()->enabled());
4763 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
4764
Seth Hampson2f0d7022018-02-20 11:54:42 -08004765 MediaExpectations media_expectations;
4766 media_expectations.CalleeExpectsSomeVideo();
4767 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004768}
4769
deadbeef1dcb1642017-03-29 21:08:16 -07004770} // namespace
4771
4772#endif // if !defined(THREAD_SANITIZER)