blob: 5825898b1f4681c06189084cf0cb0d722c1b3676 [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;
1561 caller_options.crypto_options.enable_gcm_crypto_suites = local_gcm_enabled;
1562 PeerConnectionFactory::Options callee_options;
1563 callee_options.crypto_options.enable_gcm_crypto_suites = remote_gcm_enabled;
1564 TestNegotiatedCipherSuite(caller_options, callee_options,
1565 expected_cipher_suite);
1566 }
1567
Seth Hampson2f0d7022018-02-20 11:54:42 -08001568 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001569 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001570
deadbeef1dcb1642017-03-29 21:08:16 -07001571 private:
1572 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001573 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001574 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001575 // |network_thread_| and |worker_thread_| are used by both
1576 // |caller_| and |callee_| so they must be destroyed
1577 // later.
1578 std::unique_ptr<rtc::Thread> network_thread_;
1579 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001580 // The turn servers and turn customizers should be accessed & deleted on the
1581 // network thread to avoid a race with the socket read/write that occurs
1582 // on the network thread.
1583 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1584 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001585 std::unique_ptr<PeerConnectionWrapper> caller_;
1586 std::unique_ptr<PeerConnectionWrapper> callee_;
1587};
1588
Seth Hampson2f0d7022018-02-20 11:54:42 -08001589class PeerConnectionIntegrationTest
1590 : public PeerConnectionIntegrationBaseTest,
1591 public ::testing::WithParamInterface<SdpSemantics> {
1592 protected:
1593 PeerConnectionIntegrationTest()
1594 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1595};
1596
1597class PeerConnectionIntegrationTestPlanB
1598 : public PeerConnectionIntegrationBaseTest {
1599 protected:
1600 PeerConnectionIntegrationTestPlanB()
1601 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1602};
1603
1604class PeerConnectionIntegrationTestUnifiedPlan
1605 : public PeerConnectionIntegrationBaseTest {
1606 protected:
1607 PeerConnectionIntegrationTestUnifiedPlan()
1608 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1609};
1610
deadbeef1dcb1642017-03-29 21:08:16 -07001611// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1612// includes testing that the callback is invoked if an observer is connected
1613// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001614TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001615 RtpReceiverObserverOnFirstPacketReceived) {
1616 ASSERT_TRUE(CreatePeerConnectionWrappers());
1617 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001618 caller()->AddAudioVideoTracks();
1619 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001620 // Start offer/answer exchange and wait for it to complete.
1621 caller()->CreateAndSetAndSignalOffer();
1622 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1623 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001624 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1625 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001626 // Wait for all "first packet received" callbacks to be fired.
1627 EXPECT_TRUE_WAIT(
1628 std::all_of(caller()->rtp_receiver_observers().begin(),
1629 caller()->rtp_receiver_observers().end(),
1630 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1631 return o->first_packet_received();
1632 }),
1633 kMaxWaitForFramesMs);
1634 EXPECT_TRUE_WAIT(
1635 std::all_of(callee()->rtp_receiver_observers().begin(),
1636 callee()->rtp_receiver_observers().end(),
1637 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1638 return o->first_packet_received();
1639 }),
1640 kMaxWaitForFramesMs);
1641 // If new observers are set after the first packet was already received, the
1642 // callback should still be invoked.
1643 caller()->ResetRtpReceiverObservers();
1644 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001645 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1646 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001647 EXPECT_TRUE(
1648 std::all_of(caller()->rtp_receiver_observers().begin(),
1649 caller()->rtp_receiver_observers().end(),
1650 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1651 return o->first_packet_received();
1652 }));
1653 EXPECT_TRUE(
1654 std::all_of(callee()->rtp_receiver_observers().begin(),
1655 callee()->rtp_receiver_observers().end(),
1656 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1657 return o->first_packet_received();
1658 }));
1659}
1660
1661class DummyDtmfObserver : public DtmfSenderObserverInterface {
1662 public:
1663 DummyDtmfObserver() : completed_(false) {}
1664
1665 // Implements DtmfSenderObserverInterface.
1666 void OnToneChange(const std::string& tone) override {
1667 tones_.push_back(tone);
1668 if (tone.empty()) {
1669 completed_ = true;
1670 }
1671 }
1672
1673 const std::vector<std::string>& tones() const { return tones_; }
1674 bool completed() const { return completed_; }
1675
1676 private:
1677 bool completed_;
1678 std::vector<std::string> tones_;
1679};
1680
1681// Assumes |sender| already has an audio track added and the offer/answer
1682// exchange is done.
1683void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1684 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001685 // We should be able to get a DTMF sender from the local sender.
1686 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1687 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1688 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001689 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001690 dtmf_sender->RegisterObserver(&observer);
1691
1692 // Test the DtmfSender object just created.
1693 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1694 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1695
1696 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1697 std::vector<std::string> tones = {"1", "a", ""};
1698 EXPECT_EQ(tones, observer.tones());
1699 dtmf_sender->UnregisterObserver();
1700 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1701}
1702
1703// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1704// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001705TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001706 ASSERT_TRUE(CreatePeerConnectionWrappers());
1707 ConnectFakeSignaling();
1708 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001709 caller()->AddAudioTrack();
1710 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001711 caller()->CreateAndSetAndSignalOffer();
1712 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001713 // DTLS must finish before the DTMF sender can be used reliably.
1714 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001715 TestDtmfFromSenderToReceiver(caller(), callee());
1716 TestDtmfFromSenderToReceiver(callee(), caller());
1717}
1718
1719// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1720// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001721TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001722 ASSERT_TRUE(CreatePeerConnectionWrappers());
1723 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001724
deadbeef1dcb1642017-03-29 21:08:16 -07001725 // Do normal offer/answer and wait for some frames to be received in each
1726 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001727 caller()->AddAudioVideoTracks();
1728 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001729 caller()->CreateAndSetAndSignalOffer();
1730 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001731 MediaExpectations media_expectations;
1732 media_expectations.ExpectBidirectionalAudioAndVideo();
1733 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001734 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1735 webrtc::kEnumCounterKeyProtocolDtls));
1736 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1737 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001738}
1739
1740// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001741TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001742 PeerConnectionInterface::RTCConfiguration sdes_config;
1743 sdes_config.enable_dtls_srtp.emplace(false);
1744 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1745 ConnectFakeSignaling();
1746
1747 // Do normal offer/answer and wait for some frames to be received in each
1748 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001749 caller()->AddAudioVideoTracks();
1750 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001751 caller()->CreateAndSetAndSignalOffer();
1752 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001753 MediaExpectations media_expectations;
1754 media_expectations.ExpectBidirectionalAudioAndVideo();
1755 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001756 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1757 webrtc::kEnumCounterKeyProtocolSdes));
1758 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1759 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001760}
1761
Steve Anton8c0f7a72017-10-03 10:03:10 -07001762// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1763// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001764TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001765 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1766 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1767 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1768 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1769 return pc->GetRemoteAudioSSLCertificate();
1770 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001771 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1772 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1773 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1774 return pc->GetRemoteAudioSSLCertChain();
1775 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001776
1777 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1778 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1779
1780 // Configure each side with a known certificate so they can be compared later.
1781 PeerConnectionInterface::RTCConfiguration caller_config;
1782 caller_config.enable_dtls_srtp.emplace(true);
1783 caller_config.certificates.push_back(caller_cert);
1784 PeerConnectionInterface::RTCConfiguration callee_config;
1785 callee_config.enable_dtls_srtp.emplace(true);
1786 callee_config.certificates.push_back(callee_cert);
1787 ASSERT_TRUE(
1788 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1789 ConnectFakeSignaling();
1790
1791 // When first initialized, there should not be a remote SSL certificate (and
1792 // calling this method should not crash).
1793 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1794 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001795 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1796 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001797
Steve Anton15324772018-01-16 10:26:49 -08001798 caller()->AddAudioTrack();
1799 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001800 caller()->CreateAndSetAndSignalOffer();
1801 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1802 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1803
1804 // Once DTLS has been connected, each side should return the other's SSL
1805 // certificate when calling GetRemoteAudioSSLCertificate.
1806
1807 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1808 ASSERT_TRUE(caller_remote_cert);
1809 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1810 caller_remote_cert->ToPEMString());
1811
1812 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1813 ASSERT_TRUE(callee_remote_cert);
1814 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1815 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001816
1817 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1818 ASSERT_TRUE(caller_remote_cert_chain);
1819 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1820 auto remote_cert = &caller_remote_cert_chain->Get(0);
1821 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1822 remote_cert->ToPEMString());
1823
1824 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1825 ASSERT_TRUE(callee_remote_cert_chain);
1826 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1827 remote_cert = &callee_remote_cert_chain->Get(0);
1828 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1829 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001830}
1831
deadbeef1dcb1642017-03-29 21:08:16 -07001832// This test sets up a call between two parties with a source resolution of
1833// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001834TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001835 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1836 ASSERT_TRUE(CreatePeerConnectionWrappers());
1837 ConnectFakeSignaling();
1838
Niels Möller5c7efe72018-05-11 10:34:46 +02001839 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1840 webrtc::FakePeriodicVideoSource::Config config;
1841 config.width = 1280;
1842 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001843 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001844 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1845 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001846
1847 // Do normal offer/answer and wait for at least one frame to be received in
1848 // each direction.
1849 caller()->CreateAndSetAndSignalOffer();
1850 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1851 callee()->min_video_frames_received_per_track() > 0,
1852 kMaxWaitForFramesMs);
1853
1854 // Check rendered aspect ratio.
1855 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1856 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1857 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1858 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1859}
1860
1861// This test sets up an one-way call, with media only from caller to
1862// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001863TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001864 ASSERT_TRUE(CreatePeerConnectionWrappers());
1865 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001866 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001867 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001868 MediaExpectations media_expectations;
1869 media_expectations.CalleeExpectsSomeAudioAndVideo();
1870 media_expectations.CallerExpectsNoAudio();
1871 media_expectations.CallerExpectsNoVideo();
1872 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001873}
1874
1875// This test sets up a audio call initially, with the callee rejecting video
1876// initially. Then later the callee decides to upgrade to audio/video, and
1877// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001878TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001879 ASSERT_TRUE(CreatePeerConnectionWrappers());
1880 ConnectFakeSignaling();
1881 // Initially, offer an audio/video stream from the caller, but refuse to
1882 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001883 caller()->AddAudioVideoTracks();
1884 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001885 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1886 PeerConnectionInterface::RTCOfferAnswerOptions options;
1887 options.offer_to_receive_video = 0;
1888 callee()->SetOfferAnswerOptions(options);
1889 } else {
1890 callee()->SetRemoteOfferHandler([this] {
1891 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1892 });
1893 }
deadbeef1dcb1642017-03-29 21:08:16 -07001894 // Do offer/answer and make sure audio is still received end-to-end.
1895 caller()->CreateAndSetAndSignalOffer();
1896 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001897 {
1898 MediaExpectations media_expectations;
1899 media_expectations.ExpectBidirectionalAudio();
1900 media_expectations.ExpectNoVideo();
1901 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1902 }
deadbeef1dcb1642017-03-29 21:08:16 -07001903 // Sanity check that the callee's description has a rejected video section.
1904 ASSERT_NE(nullptr, callee()->pc()->local_description());
1905 const ContentInfo* callee_video_content =
1906 GetFirstVideoContent(callee()->pc()->local_description()->description());
1907 ASSERT_NE(nullptr, callee_video_content);
1908 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001909
deadbeef1dcb1642017-03-29 21:08:16 -07001910 // Now negotiate with video and ensure negotiation succeeds, with video
1911 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001912 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001913 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1914 PeerConnectionInterface::RTCOfferAnswerOptions options;
1915 options.offer_to_receive_video = 1;
1916 callee()->SetOfferAnswerOptions(options);
1917 } else {
1918 callee()->SetRemoteOfferHandler(nullptr);
1919 caller()->SetRemoteOfferHandler([this] {
1920 // The caller creates a new transceiver to receive video on when receiving
1921 // the offer, but by default it is send only.
1922 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001923 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001924 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1925 transceivers[2]->receiver()->media_type());
1926 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1927 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1928 });
1929 }
deadbeef1dcb1642017-03-29 21:08:16 -07001930 callee()->CreateAndSetAndSignalOffer();
1931 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001932 {
1933 // Expect additional audio frames to be received after the upgrade.
1934 MediaExpectations media_expectations;
1935 media_expectations.ExpectBidirectionalAudioAndVideo();
1936 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1937 }
deadbeef1dcb1642017-03-29 21:08:16 -07001938}
1939
deadbeef4389b4d2017-09-07 09:07:36 -07001940// Simpler than the above test; just add an audio track to an established
1941// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001942TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07001943 ASSERT_TRUE(CreatePeerConnectionWrappers());
1944 ConnectFakeSignaling();
1945 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08001946 caller()->AddVideoTrack();
1947 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001948 caller()->CreateAndSetAndSignalOffer();
1949 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1950 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08001951 caller()->AddAudioTrack();
1952 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001953 caller()->CreateAndSetAndSignalOffer();
1954 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1955 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001956 MediaExpectations media_expectations;
1957 media_expectations.ExpectBidirectionalAudioAndVideo();
1958 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07001959}
1960
deadbeef1dcb1642017-03-29 21:08:16 -07001961// This test sets up a call that's transferred to a new caller with a different
1962// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001963TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07001964 ASSERT_TRUE(CreatePeerConnectionWrappers());
1965 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001966 caller()->AddAudioVideoTracks();
1967 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001968 caller()->CreateAndSetAndSignalOffer();
1969 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1970
1971 // Keep the original peer around which will still send packets to the
1972 // receiving client. These SRTP packets will be dropped.
1973 std::unique_ptr<PeerConnectionWrapper> original_peer(
1974 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08001975 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07001976 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1977 // directly above.
1978 original_peer->pc()->Close();
1979
1980 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001981 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001982 caller()->CreateAndSetAndSignalOffer();
1983 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1984 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001985 MediaExpectations media_expectations;
1986 media_expectations.ExpectBidirectionalAudioAndVideo();
1987 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001988}
1989
1990// This test sets up a call that's transferred to a new callee with a different
1991// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001992TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07001993 ASSERT_TRUE(CreatePeerConnectionWrappers());
1994 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001995 caller()->AddAudioVideoTracks();
1996 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001997 caller()->CreateAndSetAndSignalOffer();
1998 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1999
2000 // Keep the original peer around which will still send packets to the
2001 // receiving client. These SRTP packets will be dropped.
2002 std::unique_ptr<PeerConnectionWrapper> original_peer(
2003 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002004 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002005 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2006 // directly above.
2007 original_peer->pc()->Close();
2008
2009 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002010 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002011 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2012 caller()->CreateAndSetAndSignalOffer();
2013 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2014 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002015 MediaExpectations media_expectations;
2016 media_expectations.ExpectBidirectionalAudioAndVideo();
2017 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002018}
2019
2020// This test sets up a non-bundled call and negotiates bundling at the same
2021// time as starting an ICE restart. When bundling is in effect in the restart,
2022// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002023TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002024 ASSERT_TRUE(CreatePeerConnectionWrappers());
2025 ConnectFakeSignaling();
2026
Steve Anton15324772018-01-16 10:26:49 -08002027 caller()->AddAudioVideoTracks();
2028 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002029 // Remove the bundle group from the SDP received by the callee.
2030 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2031 desc->RemoveGroupByName("BUNDLE");
2032 });
2033 caller()->CreateAndSetAndSignalOffer();
2034 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002035 {
2036 MediaExpectations media_expectations;
2037 media_expectations.ExpectBidirectionalAudioAndVideo();
2038 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2039 }
deadbeef1dcb1642017-03-29 21:08:16 -07002040 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2041 callee()->SetReceivedSdpMunger(nullptr);
2042 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2043 caller()->CreateAndSetAndSignalOffer();
2044 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2045
2046 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002047 {
2048 MediaExpectations media_expectations;
2049 media_expectations.ExpectBidirectionalAudioAndVideo();
2050 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2051 }
deadbeef1dcb1642017-03-29 21:08:16 -07002052}
2053
2054// Test CVO (Coordination of Video Orientation). If a video source is rotated
2055// and both peers support the CVO RTP header extension, the actual video frames
2056// don't need to be encoded in different resolutions, since the rotation is
2057// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002058TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002059 ASSERT_TRUE(CreatePeerConnectionWrappers());
2060 ConnectFakeSignaling();
2061 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002062 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002063 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002064 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002065 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2066
2067 // Wait for video frames to be received by both sides.
2068 caller()->CreateAndSetAndSignalOffer();
2069 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2070 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2071 callee()->min_video_frames_received_per_track() > 0,
2072 kMaxWaitForFramesMs);
2073
2074 // Ensure that the aspect ratio is unmodified.
2075 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2076 // not just assumed.
2077 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2078 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2079 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2080 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2081 // Ensure that the CVO bits were surfaced to the renderer.
2082 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2083 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2084}
2085
2086// Test that when the CVO extension isn't supported, video is rotated the
2087// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002088TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002089 ASSERT_TRUE(CreatePeerConnectionWrappers());
2090 ConnectFakeSignaling();
2091 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002092 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002093 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002094 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002095 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2096
2097 // Remove the CVO extension from the offered SDP.
2098 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2099 cricket::VideoContentDescription* video =
2100 GetFirstVideoContentDescription(desc);
2101 video->ClearRtpHeaderExtensions();
2102 });
2103 // Wait for video frames to be received by both sides.
2104 caller()->CreateAndSetAndSignalOffer();
2105 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2106 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2107 callee()->min_video_frames_received_per_track() > 0,
2108 kMaxWaitForFramesMs);
2109
2110 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2111 // rotation.
2112 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2113 // not just assumed.
2114 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2115 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2116 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2117 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2118 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2119 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2120 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2121}
2122
deadbeef1dcb1642017-03-29 21:08:16 -07002123// Test that if the answerer rejects the audio m= section, no audio is sent or
2124// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002125TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002126 ASSERT_TRUE(CreatePeerConnectionWrappers());
2127 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002128 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002129 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2130 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2131 // it will reject the audio m= section completely.
2132 PeerConnectionInterface::RTCOfferAnswerOptions options;
2133 options.offer_to_receive_audio = 0;
2134 callee()->SetOfferAnswerOptions(options);
2135 } else {
2136 // Stopping the audio RtpTransceiver will cause the media section to be
2137 // rejected in the answer.
2138 callee()->SetRemoteOfferHandler([this] {
2139 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2140 });
2141 }
Steve Anton15324772018-01-16 10:26:49 -08002142 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002143 // Do offer/answer and wait for successful end-to-end video frames.
2144 caller()->CreateAndSetAndSignalOffer();
2145 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002146 MediaExpectations media_expectations;
2147 media_expectations.ExpectBidirectionalVideo();
2148 media_expectations.ExpectNoAudio();
2149 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2150
deadbeef1dcb1642017-03-29 21:08:16 -07002151 // Sanity check that the callee's description has a rejected audio section.
2152 ASSERT_NE(nullptr, callee()->pc()->local_description());
2153 const ContentInfo* callee_audio_content =
2154 GetFirstAudioContent(callee()->pc()->local_description()->description());
2155 ASSERT_NE(nullptr, callee_audio_content);
2156 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002157 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2158 // The caller's transceiver should have stopped after receiving the answer.
2159 EXPECT_TRUE(caller()
2160 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2161 ->stopped());
2162 }
deadbeef1dcb1642017-03-29 21:08:16 -07002163}
2164
2165// Test that if the answerer rejects the video m= section, no video is sent or
2166// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002167TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002168 ASSERT_TRUE(CreatePeerConnectionWrappers());
2169 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002170 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002171 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2172 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2173 // it will reject the video m= section completely.
2174 PeerConnectionInterface::RTCOfferAnswerOptions options;
2175 options.offer_to_receive_video = 0;
2176 callee()->SetOfferAnswerOptions(options);
2177 } else {
2178 // Stopping the video RtpTransceiver will cause the media section to be
2179 // rejected in the answer.
2180 callee()->SetRemoteOfferHandler([this] {
2181 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2182 });
2183 }
Steve Anton15324772018-01-16 10:26:49 -08002184 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002185 // Do offer/answer and wait for successful end-to-end audio frames.
2186 caller()->CreateAndSetAndSignalOffer();
2187 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002188 MediaExpectations media_expectations;
2189 media_expectations.ExpectBidirectionalAudio();
2190 media_expectations.ExpectNoVideo();
2191 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2192
deadbeef1dcb1642017-03-29 21:08:16 -07002193 // Sanity check that the callee's description has a rejected video section.
2194 ASSERT_NE(nullptr, callee()->pc()->local_description());
2195 const ContentInfo* callee_video_content =
2196 GetFirstVideoContent(callee()->pc()->local_description()->description());
2197 ASSERT_NE(nullptr, callee_video_content);
2198 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002199 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2200 // The caller's transceiver should have stopped after receiving the answer.
2201 EXPECT_TRUE(caller()
2202 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2203 ->stopped());
2204 }
deadbeef1dcb1642017-03-29 21:08:16 -07002205}
2206
2207// Test that if the answerer rejects both audio and video m= sections, nothing
2208// bad happens.
2209// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2210// test anything but the fact that negotiation succeeds, which doesn't mean
2211// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002212TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002213 ASSERT_TRUE(CreatePeerConnectionWrappers());
2214 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002215 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002216 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2217 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2218 // will reject both audio and video m= sections.
2219 PeerConnectionInterface::RTCOfferAnswerOptions options;
2220 options.offer_to_receive_audio = 0;
2221 options.offer_to_receive_video = 0;
2222 callee()->SetOfferAnswerOptions(options);
2223 } else {
2224 callee()->SetRemoteOfferHandler([this] {
2225 // Stopping all transceivers will cause all media sections to be rejected.
2226 for (auto transceiver : callee()->pc()->GetTransceivers()) {
2227 transceiver->Stop();
2228 }
2229 });
2230 }
deadbeef1dcb1642017-03-29 21:08:16 -07002231 // Do offer/answer and wait for stable signaling state.
2232 caller()->CreateAndSetAndSignalOffer();
2233 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002234
deadbeef1dcb1642017-03-29 21:08:16 -07002235 // Sanity check that the callee's description has rejected m= sections.
2236 ASSERT_NE(nullptr, callee()->pc()->local_description());
2237 const ContentInfo* callee_audio_content =
2238 GetFirstAudioContent(callee()->pc()->local_description()->description());
2239 ASSERT_NE(nullptr, callee_audio_content);
2240 EXPECT_TRUE(callee_audio_content->rejected);
2241 const ContentInfo* callee_video_content =
2242 GetFirstVideoContent(callee()->pc()->local_description()->description());
2243 ASSERT_NE(nullptr, callee_video_content);
2244 EXPECT_TRUE(callee_video_content->rejected);
2245}
2246
2247// This test sets up an audio and video call between two parties. After the
2248// call runs for a while, the caller sends an updated offer with video being
2249// rejected. Once the re-negotiation is done, the video flow should stop and
2250// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002251TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002252 ASSERT_TRUE(CreatePeerConnectionWrappers());
2253 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002254 caller()->AddAudioVideoTracks();
2255 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002256 caller()->CreateAndSetAndSignalOffer();
2257 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002258 {
2259 MediaExpectations media_expectations;
2260 media_expectations.ExpectBidirectionalAudioAndVideo();
2261 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2262 }
deadbeef1dcb1642017-03-29 21:08:16 -07002263 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002264 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2265 caller()->SetGeneratedSdpMunger(
2266 [](cricket::SessionDescription* description) {
2267 for (cricket::ContentInfo& content : description->contents()) {
2268 if (cricket::IsVideoContent(&content)) {
2269 content.rejected = true;
2270 }
2271 }
2272 });
2273 } else {
2274 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2275 }
deadbeef1dcb1642017-03-29 21:08:16 -07002276 caller()->CreateAndSetAndSignalOffer();
2277 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2278
2279 // Sanity check that the caller's description has a rejected video section.
2280 ASSERT_NE(nullptr, caller()->pc()->local_description());
2281 const ContentInfo* caller_video_content =
2282 GetFirstVideoContent(caller()->pc()->local_description()->description());
2283 ASSERT_NE(nullptr, caller_video_content);
2284 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002285 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002286 {
2287 MediaExpectations media_expectations;
2288 media_expectations.ExpectBidirectionalAudio();
2289 media_expectations.ExpectNoVideo();
2290 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2291 }
deadbeef1dcb1642017-03-29 21:08:16 -07002292}
2293
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002294// Do one offer/answer with audio, another that disables it (rejecting the m=
2295// section), and another that re-enables it. Regression test for:
2296// bugs.webrtc.org/6023
2297TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2298 ASSERT_TRUE(CreatePeerConnectionWrappers());
2299 ConnectFakeSignaling();
2300
2301 // Add audio track, do normal offer/answer.
2302 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2303 caller()->CreateLocalAudioTrack();
2304 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2305 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2306 caller()->CreateAndSetAndSignalOffer();
2307 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2308
2309 // Remove audio track, and set offer_to_receive_audio to false to cause the
2310 // m= section to be completely disabled, not just "recvonly".
2311 caller()->pc()->RemoveTrack(sender);
2312 PeerConnectionInterface::RTCOfferAnswerOptions options;
2313 options.offer_to_receive_audio = 0;
2314 caller()->SetOfferAnswerOptions(options);
2315 caller()->CreateAndSetAndSignalOffer();
2316 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2317
2318 // Add the audio track again, expecting negotiation to succeed and frames to
2319 // flow.
2320 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2321 options.offer_to_receive_audio = 1;
2322 caller()->SetOfferAnswerOptions(options);
2323 caller()->CreateAndSetAndSignalOffer();
2324 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2325
2326 MediaExpectations media_expectations;
2327 media_expectations.CalleeExpectsSomeAudio();
2328 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2329}
2330
deadbeef1dcb1642017-03-29 21:08:16 -07002331// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2332// is needed to support legacy endpoints.
2333// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2334// add a test for an end-to-end test without MID signaling either (basically,
2335// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002336TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002337 ASSERT_TRUE(CreatePeerConnectionWrappers());
2338 ConnectFakeSignaling();
2339 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002340 caller()->AddAudioVideoTracks();
2341 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002342 // Remove SSRCs and MSIDs from the received offer SDP.
2343 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002344 caller()->CreateAndSetAndSignalOffer();
2345 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002346 MediaExpectations media_expectations;
2347 media_expectations.ExpectBidirectionalAudioAndVideo();
2348 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002349}
2350
Seth Hampson5897a6e2018-04-03 11:16:33 -07002351// Basic end-to-end test, without SSRC signaling. This means that the track
2352// was created properly and frames are delivered when the MSIDs are communicated
2353// with a=msid lines and no a=ssrc lines.
2354TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2355 EndToEndCallWithoutSsrcSignaling) {
2356 const char kStreamId[] = "streamId";
2357 ASSERT_TRUE(CreatePeerConnectionWrappers());
2358 ConnectFakeSignaling();
2359 // Add just audio tracks.
2360 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2361 callee()->AddAudioTrack();
2362
2363 // Remove SSRCs from the received offer SDP.
2364 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2365 caller()->CreateAndSetAndSignalOffer();
2366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2367 MediaExpectations media_expectations;
2368 media_expectations.ExpectBidirectionalAudio();
2369 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2370}
2371
Steve Antondf527fd2018-04-27 15:52:03 -07002372// Tests that video flows between multiple video tracks when SSRCs are not
2373// signaled. This exercises the MID RTP header extension which is needed to
2374// demux the incoming video tracks.
2375TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2376 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2377 ASSERT_TRUE(CreatePeerConnectionWrappers());
2378 ConnectFakeSignaling();
2379 caller()->AddVideoTrack();
2380 caller()->AddVideoTrack();
2381 callee()->AddVideoTrack();
2382 callee()->AddVideoTrack();
2383
2384 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2385 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2386 caller()->CreateAndSetAndSignalOffer();
2387 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2388 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2389 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2390
2391 // Expect video to be received in both directions on both tracks.
2392 MediaExpectations media_expectations;
2393 media_expectations.ExpectBidirectionalVideo();
2394 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2395}
2396
deadbeef1dcb1642017-03-29 21:08:16 -07002397// Test that if two video tracks are sent (from caller to callee, in this test),
2398// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002399TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002400 ASSERT_TRUE(CreatePeerConnectionWrappers());
2401 ConnectFakeSignaling();
2402 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002403 caller()->AddAudioVideoTracks();
2404 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002405 caller()->CreateAndSetAndSignalOffer();
2406 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002407 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002408
2409 MediaExpectations media_expectations;
2410 media_expectations.CalleeExpectsSomeAudioAndVideo();
2411 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002412}
2413
2414static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2415 bool first = true;
2416 for (cricket::ContentInfo& content : desc->contents()) {
2417 if (first) {
2418 first = false;
2419 continue;
2420 }
2421 content.bundle_only = true;
2422 }
2423 first = true;
2424 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2425 if (first) {
2426 first = false;
2427 continue;
2428 }
2429 transport.description.ice_ufrag.clear();
2430 transport.description.ice_pwd.clear();
2431 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2432 transport.description.identity_fingerprint.reset(nullptr);
2433 }
2434}
2435
2436// Test that if applying a true "max bundle" offer, which uses ports of 0,
2437// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2438// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2439// successfully and media flows.
2440// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2441// TODO(deadbeef): Won't need this test once we start generating actual
2442// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002443TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002444 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2445 ASSERT_TRUE(CreatePeerConnectionWrappers());
2446 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002447 caller()->AddAudioVideoTracks();
2448 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002449 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2450 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2451 // but the first m= section.
2452 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2453 caller()->CreateAndSetAndSignalOffer();
2454 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002455 MediaExpectations media_expectations;
2456 media_expectations.ExpectBidirectionalAudioAndVideo();
2457 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002458}
2459
2460// Test that we can receive the audio output level from a remote audio track.
2461// TODO(deadbeef): Use a fake audio source and verify that the output level is
2462// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002463TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002464 ASSERT_TRUE(CreatePeerConnectionWrappers());
2465 ConnectFakeSignaling();
2466 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002467 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002468 caller()->CreateAndSetAndSignalOffer();
2469 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2470
2471 // Get the audio output level stats. Note that the level is not available
2472 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002473 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002474 kMaxWaitForFramesMs);
2475}
2476
2477// Test that an audio input level is reported.
2478// TODO(deadbeef): Use a fake audio source and verify that the input level is
2479// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002480TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002481 ASSERT_TRUE(CreatePeerConnectionWrappers());
2482 ConnectFakeSignaling();
2483 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002484 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002485 caller()->CreateAndSetAndSignalOffer();
2486 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2487
2488 // Get the audio input level stats. The level should be available very
2489 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002490 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002491 kMaxWaitForStatsMs);
2492}
2493
2494// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002495TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002496 ASSERT_TRUE(CreatePeerConnectionWrappers());
2497 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002498 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002499 // Do offer/answer, wait for the callee to receive some frames.
2500 caller()->CreateAndSetAndSignalOffer();
2501 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002502
2503 MediaExpectations media_expectations;
2504 media_expectations.CalleeExpectsSomeAudioAndVideo();
2505 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002506
2507 // Get a handle to the remote tracks created, so they can be used as GetStats
2508 // filters.
Steve Anton15324772018-01-16 10:26:49 -08002509 for (auto receiver : callee()->pc()->GetReceivers()) {
2510 // We received frames, so we definitely should have nonzero "received bytes"
2511 // stats at this point.
2512 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2513 0);
2514 }
deadbeef1dcb1642017-03-29 21:08:16 -07002515}
2516
2517// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002518TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002519 ASSERT_TRUE(CreatePeerConnectionWrappers());
2520 ConnectFakeSignaling();
2521 auto audio_track = caller()->CreateLocalAudioTrack();
2522 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002523 caller()->AddTrack(audio_track);
2524 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002525 // Do offer/answer, wait for the callee to receive some frames.
2526 caller()->CreateAndSetAndSignalOffer();
2527 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002528 MediaExpectations media_expectations;
2529 media_expectations.CalleeExpectsSomeAudioAndVideo();
2530 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002531
2532 // The callee received frames, so we definitely should have nonzero "sent
2533 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002534 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2535 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2536}
2537
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002538// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002539TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002540 ASSERT_TRUE(CreatePeerConnectionWrappers());
2541 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002542 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002543
Steve Anton15324772018-01-16 10:26:49 -08002544 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002545
2546 // Do offer/answer, wait for the callee to receive some frames.
2547 caller()->CreateAndSetAndSignalOffer();
2548 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2549
2550 // Get the remote audio track created on the receiver, so they can be used as
2551 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002552 auto receivers = callee()->pc()->GetReceivers();
2553 ASSERT_EQ(1u, receivers.size());
2554 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002555
2556 // Get the audio output level stats. Note that the level is not available
2557 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002558 EXPECT_TRUE_WAIT(
2559 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2560 0,
2561 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002562}
2563
deadbeefd8ad7882017-04-18 16:01:17 -07002564// Test that we can get stats (using the new stats implemnetation) for
2565// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2566// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002567TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002568 GetStatsForUnsignaledStreamWithNewStatsApi) {
2569 ASSERT_TRUE(CreatePeerConnectionWrappers());
2570 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002571 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002572 // Remove SSRCs and MSIDs from the received offer SDP.
2573 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2574 caller()->CreateAndSetAndSignalOffer();
2575 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002576 MediaExpectations media_expectations;
2577 media_expectations.CalleeExpectsSomeAudio(1);
2578 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002579
2580 // We received a frame, so we should have nonzero "bytes received" stats for
2581 // the unsignaled stream, if stats are working for it.
2582 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2583 callee()->NewGetStats();
2584 ASSERT_NE(nullptr, report);
2585 auto inbound_stream_stats =
2586 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2587 ASSERT_EQ(1U, inbound_stream_stats.size());
2588 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2589 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002590 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2591}
2592
Taylor Brandstettera4653442018-06-19 09:44:26 -07002593// Same as above but for the legacy stats implementation.
2594TEST_P(PeerConnectionIntegrationTest,
2595 GetStatsForUnsignaledStreamWithOldStatsApi) {
2596 ASSERT_TRUE(CreatePeerConnectionWrappers());
2597 ConnectFakeSignaling();
2598 caller()->AddAudioTrack();
2599 // Remove SSRCs and MSIDs from the received offer SDP.
2600 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2601 caller()->CreateAndSetAndSignalOffer();
2602 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2603
2604 // Note that, since the old stats implementation associates SSRCs with tracks
2605 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2606 // associated track ID. So we can't use the track "selector" argument.
2607 //
2608 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2609 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002610 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002611 kDefaultTimeout);
2612}
2613
zhihuangf8164932017-05-19 13:09:47 -07002614// Test that we can successfully get the media related stats (audio level
2615// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002616TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002617 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2618 ASSERT_TRUE(CreatePeerConnectionWrappers());
2619 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002620 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002621 // Remove SSRCs and MSIDs from the received offer SDP.
2622 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2623 caller()->CreateAndSetAndSignalOffer();
2624 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002625 MediaExpectations media_expectations;
2626 media_expectations.CalleeExpectsSomeAudio(1);
2627 media_expectations.CalleeExpectsSomeVideo(1);
2628 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002629
2630 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2631 callee()->NewGetStats();
2632 ASSERT_NE(nullptr, report);
2633
2634 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2635 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2636 ASSERT_GE(audio_index, 0);
2637 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002638}
2639
deadbeef4e2deab2017-09-20 13:56:21 -07002640// Helper for test below.
2641void ModifySsrcs(cricket::SessionDescription* desc) {
2642 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002643 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002644 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002645 for (uint32_t& ssrc : stream.ssrcs) {
2646 ssrc = rtc::CreateRandomId();
2647 }
2648 }
2649 }
2650}
2651
2652// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2653// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2654// This should result in two "RTCInboundRTPStreamStats", but only one
2655// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2656// being reset to 0 once the SSRC change occurs.
2657//
2658// Regression test for this bug:
2659// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2660//
2661// The bug causes the track stats to only represent one of the two streams:
2662// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2663// that the track stat counters would reset to 0 when the new stream is
2664// received, and a 50% chance that they'll stop updating (while
2665// "concealed_samples" continues increasing, due to silence being generated for
2666// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002667TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002668 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002669 ASSERT_TRUE(CreatePeerConnectionWrappers());
2670 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002671 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002672 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2673 // that doesn't signal SSRCs (from the callee's perspective).
2674 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2675 caller()->CreateAndSetAndSignalOffer();
2676 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2677 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002678 {
2679 MediaExpectations media_expectations;
2680 media_expectations.CalleeExpectsSomeAudio(50);
2681 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2682 }
deadbeef4e2deab2017-09-20 13:56:21 -07002683 // Some audio frames were received, so we should have nonzero "samples
2684 // received" for the track.
2685 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2686 callee()->NewGetStats();
2687 ASSERT_NE(nullptr, report);
2688 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2689 ASSERT_EQ(1U, track_stats.size());
2690 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2691 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2692 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2693
2694 // Create a new offer and munge it to cause the caller to use a new SSRC.
2695 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2696 caller()->CreateAndSetAndSignalOffer();
2697 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2698 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2699 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002700 {
2701 MediaExpectations media_expectations;
2702 media_expectations.CalleeExpectsSomeAudio(25);
2703 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2704 }
deadbeef4e2deab2017-09-20 13:56:21 -07002705
2706 report = callee()->NewGetStats();
2707 ASSERT_NE(nullptr, report);
2708 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2709 ASSERT_EQ(1U, track_stats.size());
2710 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2711 // The "total samples received" stat should only be greater than it was
2712 // before.
2713 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2714 // Right now, the new SSRC will cause the counters to reset to 0.
2715 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2716
2717 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002718 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002719 // good sign that we're seeing stats from the old stream that's no longer
2720 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002721 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002722 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2723 EXPECT_LT(*track_stats[0]->concealed_samples,
2724 *track_stats[0]->total_samples_received *
2725 kAcceptableConcealedSamplesPercentage);
2726
2727 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2728 // sanity check that the SSRC really changed.
2729 // TODO(deadbeef): This isn't working right now, because we're not returning
2730 // *any* stats for the inactive stream. Uncomment when the bug is completely
2731 // fixed.
2732 // auto inbound_stream_stats =
2733 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2734 // ASSERT_EQ(2U, inbound_stream_stats.size());
2735}
2736
deadbeef1dcb1642017-03-29 21:08:16 -07002737// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002738TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002739 PeerConnectionFactory::Options dtls_10_options;
2740 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2741 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2742 dtls_10_options));
2743 ConnectFakeSignaling();
2744 // Do normal offer/answer and wait for some frames to be received in each
2745 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002746 caller()->AddAudioVideoTracks();
2747 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002748 caller()->CreateAndSetAndSignalOffer();
2749 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002750 MediaExpectations media_expectations;
2751 media_expectations.ExpectBidirectionalAudioAndVideo();
2752 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002753}
2754
2755// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002756TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002757 PeerConnectionFactory::Options dtls_10_options;
2758 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2759 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2760 dtls_10_options));
2761 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002762 caller()->AddAudioVideoTracks();
2763 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002764 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002765 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002766 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002767 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002768 kDefaultTimeout);
2769 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002770 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002771 // TODO(bugs.webrtc.org/9456): Fix it.
2772 EXPECT_EQ(1, webrtc::metrics::NumEvents(
2773 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2774 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002775}
2776
2777// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002778TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002779 PeerConnectionFactory::Options dtls_12_options;
2780 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2781 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2782 dtls_12_options));
2783 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002784 caller()->AddAudioVideoTracks();
2785 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002786 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002787 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002788 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002789 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002790 kDefaultTimeout);
2791 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002792 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002793 // TODO(bugs.webrtc.org/9456): Fix it.
2794 EXPECT_EQ(1, webrtc::metrics::NumEvents(
2795 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2796 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002797}
2798
2799// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2800// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002801TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002802 PeerConnectionFactory::Options caller_options;
2803 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2804 PeerConnectionFactory::Options callee_options;
2805 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2806 ASSERT_TRUE(
2807 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2808 ConnectFakeSignaling();
2809 // Do normal offer/answer and wait for some frames to be received in each
2810 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002811 caller()->AddAudioVideoTracks();
2812 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002813 caller()->CreateAndSetAndSignalOffer();
2814 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002815 MediaExpectations media_expectations;
2816 media_expectations.ExpectBidirectionalAudioAndVideo();
2817 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002818}
2819
2820// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2821// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002822TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07002823 PeerConnectionFactory::Options caller_options;
2824 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2825 PeerConnectionFactory::Options callee_options;
2826 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2827 ASSERT_TRUE(
2828 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2829 ConnectFakeSignaling();
2830 // Do normal offer/answer and wait for some frames to be received in each
2831 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002832 caller()->AddAudioVideoTracks();
2833 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002834 caller()->CreateAndSetAndSignalOffer();
2835 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002836 MediaExpectations media_expectations;
2837 media_expectations.ExpectBidirectionalAudioAndVideo();
2838 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002839}
2840
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002841// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
2842// works as expected; the cipher should only be used if enabled by both sides.
2843TEST_P(PeerConnectionIntegrationTest,
2844 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
2845 PeerConnectionFactory::Options caller_options;
2846 caller_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = true;
2847 PeerConnectionFactory::Options callee_options;
2848 callee_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = false;
2849 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2850 TestNegotiatedCipherSuite(caller_options, callee_options,
2851 expected_cipher_suite);
2852}
2853
2854TEST_P(PeerConnectionIntegrationTest,
2855 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
2856 PeerConnectionFactory::Options caller_options;
2857 caller_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = false;
2858 PeerConnectionFactory::Options callee_options;
2859 callee_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = true;
2860 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2861 TestNegotiatedCipherSuite(caller_options, callee_options,
2862 expected_cipher_suite);
2863}
2864
2865TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
2866 PeerConnectionFactory::Options caller_options;
2867 caller_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = true;
2868 PeerConnectionFactory::Options callee_options;
2869 callee_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = true;
2870 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
2871 TestNegotiatedCipherSuite(caller_options, callee_options,
2872 expected_cipher_suite);
2873}
2874
deadbeef1dcb1642017-03-29 21:08:16 -07002875// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002876TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07002877 bool local_gcm_enabled = false;
2878 bool remote_gcm_enabled = false;
2879 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2880 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2881 expected_cipher_suite);
2882}
2883
2884// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002885TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07002886 bool local_gcm_enabled = true;
2887 bool remote_gcm_enabled = true;
2888 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2889 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2890 expected_cipher_suite);
2891}
2892
2893// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002894TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002895 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2896 bool local_gcm_enabled = true;
2897 bool remote_gcm_enabled = false;
2898 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2899 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2900 expected_cipher_suite);
2901}
2902
2903// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002904TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002905 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2906 bool local_gcm_enabled = false;
2907 bool remote_gcm_enabled = true;
2908 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2909 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2910 expected_cipher_suite);
2911}
2912
deadbeef7914b8c2017-04-21 03:23:33 -07002913// Verify that media can be transmitted end-to-end when GCM crypto suites are
2914// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2915// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2916// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002917TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07002918 PeerConnectionFactory::Options gcm_options;
2919 gcm_options.crypto_options.enable_gcm_crypto_suites = true;
2920 ASSERT_TRUE(
2921 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2922 ConnectFakeSignaling();
2923 // Do normal offer/answer and wait for some frames to be received in each
2924 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002925 caller()->AddAudioVideoTracks();
2926 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002927 caller()->CreateAndSetAndSignalOffer();
2928 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002929 MediaExpectations media_expectations;
2930 media_expectations.ExpectBidirectionalAudioAndVideo();
2931 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07002932}
2933
deadbeef1dcb1642017-03-29 21:08:16 -07002934// This test sets up a call between two parties with audio, video and an RTP
2935// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002936TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02002937 PeerConnectionInterface::RTCConfiguration rtc_config;
2938 rtc_config.enable_rtp_data_channel = true;
2939 rtc_config.enable_dtls_srtp = false;
2940 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07002941 ConnectFakeSignaling();
2942 // Expect that data channel created on caller side will show up for callee as
2943 // well.
2944 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002945 caller()->AddAudioVideoTracks();
2946 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002947 caller()->CreateAndSetAndSignalOffer();
2948 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2949 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002950 MediaExpectations media_expectations;
2951 media_expectations.ExpectBidirectionalAudioAndVideo();
2952 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002953 ASSERT_NE(nullptr, caller()->data_channel());
2954 ASSERT_NE(nullptr, callee()->data_channel());
2955 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2956 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2957
2958 // Ensure data can be sent in both directions.
2959 std::string data = "hello world";
2960 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2961 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2962 kDefaultTimeout);
2963 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2964 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2965 kDefaultTimeout);
2966}
2967
2968// Ensure that an RTP data channel is signaled as closed for the caller when
2969// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002970TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002971 RtpDataChannelSignaledClosedInCalleeOffer) {
2972 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02002973 PeerConnectionInterface::RTCConfiguration rtc_config;
2974 rtc_config.enable_rtp_data_channel = true;
2975 rtc_config.enable_dtls_srtp = false;
2976 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07002977 ConnectFakeSignaling();
2978 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002979 caller()->AddAudioVideoTracks();
2980 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002981 caller()->CreateAndSetAndSignalOffer();
2982 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2983 ASSERT_NE(nullptr, caller()->data_channel());
2984 ASSERT_NE(nullptr, callee()->data_channel());
2985 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2986 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2987
2988 // Close the data channel on the callee, and do an updated offer/answer.
2989 callee()->data_channel()->Close();
2990 callee()->CreateAndSetAndSignalOffer();
2991 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2992 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2993 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2994}
2995
2996// Tests that data is buffered in an RTP data channel until an observer is
2997// registered for it.
2998//
2999// NOTE: RTP data channels can receive data before the underlying
3000// transport has detected that a channel is writable and thus data can be
3001// received before the data channel state changes to open. That is hard to test
3002// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003003TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003004 DataBufferedUntilRtpDataChannelObserverRegistered) {
3005 // Use fake clock and simulated network delay so that we predictably can wait
3006 // until an SCTP message has been delivered without "sleep()"ing.
3007 rtc::ScopedFakeClock fake_clock;
3008 // Some things use a time of "0" as a special value, so we need to start out
3009 // the fake clock at a nonzero time.
3010 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003011 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003012 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3013 virtual_socket_server()->UpdateDelayDistribution();
3014
Niels Möllerf06f9232018-08-07 12:32:18 +02003015 PeerConnectionInterface::RTCConfiguration rtc_config;
3016 rtc_config.enable_rtp_data_channel = true;
3017 rtc_config.enable_dtls_srtp = false;
3018 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003019 ConnectFakeSignaling();
3020 caller()->CreateDataChannel();
3021 caller()->CreateAndSetAndSignalOffer();
3022 ASSERT_TRUE(caller()->data_channel() != nullptr);
3023 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3024 kDefaultTimeout, fake_clock);
3025 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3026 kDefaultTimeout, fake_clock);
3027 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3028 callee()->data_channel()->state(), kDefaultTimeout,
3029 fake_clock);
3030
3031 // Unregister the observer which is normally automatically registered.
3032 callee()->data_channel()->UnregisterObserver();
3033 // Send data and advance fake clock until it should have been received.
3034 std::string data = "hello world";
3035 caller()->data_channel()->Send(DataBuffer(data));
3036 SIMULATED_WAIT(false, 50, fake_clock);
3037
3038 // Attach data channel and expect data to be received immediately. Note that
3039 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3040 // further, but data can be received even if the callback is asynchronous.
3041 MockDataChannelObserver new_observer(callee()->data_channel());
3042 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3043 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003044 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3045 // If this is not done a DCHECK can be hit in ports.cc, because a large
3046 // negative number is calculated for the rtt due to the global clock changing.
3047 caller()->pc()->Close();
3048 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07003049}
3050
3051// This test sets up a call between two parties with audio, video and but only
3052// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003053TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003054 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3055 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003056 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003057 rtc_config_1.enable_dtls_srtp = false;
3058 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3059 rtc_config_2.enable_dtls_srtp = false;
3060 rtc_config_2.enable_dtls_srtp = false;
3061 ASSERT_TRUE(
3062 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003063 ConnectFakeSignaling();
3064 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003065 caller()->AddAudioVideoTracks();
3066 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003067 caller()->CreateAndSetAndSignalOffer();
3068 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3069 // The caller should still have a data channel, but it should be closed, and
3070 // one should ever have been created for the callee.
3071 EXPECT_TRUE(caller()->data_channel() != nullptr);
3072 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3073 EXPECT_EQ(nullptr, callee()->data_channel());
3074}
3075
3076// This test sets up a call between two parties with audio, and video. When
3077// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003078TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003079 PeerConnectionInterface::RTCConfiguration rtc_config;
3080 rtc_config.enable_rtp_data_channel = true;
3081 rtc_config.enable_dtls_srtp = false;
3082 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003083 ConnectFakeSignaling();
3084 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003085 caller()->AddAudioVideoTracks();
3086 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003087 caller()->CreateAndSetAndSignalOffer();
3088 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3089 // Create data channel and do new offer and answer.
3090 caller()->CreateDataChannel();
3091 caller()->CreateAndSetAndSignalOffer();
3092 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3093 ASSERT_NE(nullptr, caller()->data_channel());
3094 ASSERT_NE(nullptr, callee()->data_channel());
3095 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3096 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3097 // Ensure data can be sent in both directions.
3098 std::string data = "hello world";
3099 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3100 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3101 kDefaultTimeout);
3102 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3103 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3104 kDefaultTimeout);
3105}
3106
3107#ifdef HAVE_SCTP
3108
3109// This test sets up a call between two parties with audio, video and an SCTP
3110// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003111TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003112 ASSERT_TRUE(CreatePeerConnectionWrappers());
3113 ConnectFakeSignaling();
3114 // Expect that data channel created on caller side will show up for callee as
3115 // well.
3116 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003117 caller()->AddAudioVideoTracks();
3118 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003119 caller()->CreateAndSetAndSignalOffer();
3120 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3121 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003122 MediaExpectations media_expectations;
3123 media_expectations.ExpectBidirectionalAudioAndVideo();
3124 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003125 // Caller data channel should already exist (it created one). Callee data
3126 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3127 ASSERT_NE(nullptr, caller()->data_channel());
3128 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3129 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3130 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3131
3132 // Ensure data can be sent in both directions.
3133 std::string data = "hello world";
3134 caller()->data_channel()->Send(DataBuffer(data));
3135 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3136 kDefaultTimeout);
3137 callee()->data_channel()->Send(DataBuffer(data));
3138 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3139 kDefaultTimeout);
3140}
3141
3142// Ensure that when the callee closes an SCTP data channel, the closing
3143// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003144TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003145 // Same procedure as above test.
3146 ASSERT_TRUE(CreatePeerConnectionWrappers());
3147 ConnectFakeSignaling();
3148 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003149 caller()->AddAudioVideoTracks();
3150 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003151 caller()->CreateAndSetAndSignalOffer();
3152 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3153 ASSERT_NE(nullptr, caller()->data_channel());
3154 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3155 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3156 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3157
3158 // Close the data channel on the callee side, and wait for it to reach the
3159 // "closed" state on both sides.
3160 callee()->data_channel()->Close();
3161 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3162 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3163}
3164
Seth Hampson2f0d7022018-02-20 11:54:42 -08003165TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003166 ASSERT_TRUE(CreatePeerConnectionWrappers());
3167 ConnectFakeSignaling();
3168 webrtc::DataChannelInit init;
3169 init.id = 53;
3170 init.maxRetransmits = 52;
3171 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003172 caller()->AddAudioVideoTracks();
3173 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003174 caller()->CreateAndSetAndSignalOffer();
3175 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003176 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3177 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07003178 EXPECT_EQ(init.id, callee()->data_channel()->id());
3179 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3180 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3181 EXPECT_FALSE(callee()->data_channel()->negotiated());
3182}
3183
deadbeef1dcb1642017-03-29 21:08:16 -07003184// Test usrsctp's ability to process unordered data stream, where data actually
3185// arrives out of order using simulated delays. Previously there have been some
3186// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003187TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003188 // Introduce random network delays.
3189 // Otherwise it's not a true "unordered" test.
3190 virtual_socket_server()->set_delay_mean(20);
3191 virtual_socket_server()->set_delay_stddev(5);
3192 virtual_socket_server()->UpdateDelayDistribution();
3193 // Normal procedure, but with unordered data channel config.
3194 ASSERT_TRUE(CreatePeerConnectionWrappers());
3195 ConnectFakeSignaling();
3196 webrtc::DataChannelInit init;
3197 init.ordered = false;
3198 caller()->CreateDataChannel(&init);
3199 caller()->CreateAndSetAndSignalOffer();
3200 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3201 ASSERT_NE(nullptr, caller()->data_channel());
3202 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3203 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3204 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3205
3206 static constexpr int kNumMessages = 100;
3207 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3208 static constexpr size_t kMaxMessageSize = 4096;
3209 // Create and send random messages.
3210 std::vector<std::string> sent_messages;
3211 for (int i = 0; i < kNumMessages; ++i) {
3212 size_t length =
3213 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3214 std::string message;
3215 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3216 caller()->data_channel()->Send(DataBuffer(message));
3217 callee()->data_channel()->Send(DataBuffer(message));
3218 sent_messages.push_back(message);
3219 }
3220
3221 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003222 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003223 caller()->data_observer()->received_message_count(),
3224 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003225 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003226 callee()->data_observer()->received_message_count(),
3227 kDefaultTimeout);
3228
3229 // Sort and compare to make sure none of the messages were corrupted.
3230 std::vector<std::string> caller_received_messages =
3231 caller()->data_observer()->messages();
3232 std::vector<std::string> callee_received_messages =
3233 callee()->data_observer()->messages();
3234 std::sort(sent_messages.begin(), sent_messages.end());
3235 std::sort(caller_received_messages.begin(), caller_received_messages.end());
3236 std::sort(callee_received_messages.begin(), callee_received_messages.end());
3237 EXPECT_EQ(sent_messages, caller_received_messages);
3238 EXPECT_EQ(sent_messages, callee_received_messages);
3239}
3240
3241// This test sets up a call between two parties with audio, and video. When
3242// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003243TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003244 ASSERT_TRUE(CreatePeerConnectionWrappers());
3245 ConnectFakeSignaling();
3246 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003247 caller()->AddAudioVideoTracks();
3248 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003249 caller()->CreateAndSetAndSignalOffer();
3250 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3251 // Create data channel and do new offer and answer.
3252 caller()->CreateDataChannel();
3253 caller()->CreateAndSetAndSignalOffer();
3254 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3255 // Caller data channel should already exist (it created one). Callee data
3256 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3257 ASSERT_NE(nullptr, caller()->data_channel());
3258 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3259 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3260 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3261 // Ensure data can be sent in both directions.
3262 std::string data = "hello world";
3263 caller()->data_channel()->Send(DataBuffer(data));
3264 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3265 kDefaultTimeout);
3266 callee()->data_channel()->Send(DataBuffer(data));
3267 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3268 kDefaultTimeout);
3269}
3270
deadbeef7914b8c2017-04-21 03:23:33 -07003271// Set up a connection initially just using SCTP data channels, later upgrading
3272// to audio/video, ensuring frames are received end-to-end. Effectively the
3273// inverse of the test above.
3274// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003275TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003276 ASSERT_TRUE(CreatePeerConnectionWrappers());
3277 ConnectFakeSignaling();
3278 // Do initial offer/answer with just data channel.
3279 caller()->CreateDataChannel();
3280 caller()->CreateAndSetAndSignalOffer();
3281 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3282 // Wait until data can be sent over the data channel.
3283 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3284 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3285 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3286
3287 // Do subsequent offer/answer with two-way audio and video. Audio and video
3288 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003289 caller()->AddAudioVideoTracks();
3290 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003291 caller()->CreateAndSetAndSignalOffer();
3292 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003293 MediaExpectations media_expectations;
3294 media_expectations.ExpectBidirectionalAudioAndVideo();
3295 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003296}
3297
deadbeef8b7e9ad2017-05-25 09:38:55 -07003298static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07003299 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08003300 GetFirstDataContentDescription(desc);
3301 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003302 dcd_offer->set_use_sctpmap(false);
3303 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3304}
3305
3306// Test that the data channel works when a spec-compliant SCTP m= section is
3307// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3308// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003309TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003310 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3311 ASSERT_TRUE(CreatePeerConnectionWrappers());
3312 ConnectFakeSignaling();
3313 caller()->CreateDataChannel();
3314 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3315 caller()->CreateAndSetAndSignalOffer();
3316 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3317 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3318 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3319 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3320
3321 // Ensure data can be sent in both directions.
3322 std::string data = "hello world";
3323 caller()->data_channel()->Send(DataBuffer(data));
3324 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3325 kDefaultTimeout);
3326 callee()->data_channel()->Send(DataBuffer(data));
3327 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3328 kDefaultTimeout);
3329}
3330
deadbeef1dcb1642017-03-29 21:08:16 -07003331#endif // HAVE_SCTP
3332
3333// Test that the ICE connection and gathering states eventually reach
3334// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003335TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003336 ASSERT_TRUE(CreatePeerConnectionWrappers());
3337 ConnectFakeSignaling();
3338 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003339 caller()->AddAudioVideoTracks();
3340 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003341 caller()->CreateAndSetAndSignalOffer();
3342 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3343 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3344 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3345 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3346 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3347 // After the best candidate pair is selected and all candidates are signaled,
3348 // the ICE connection state should reach "complete".
3349 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3350 // answerer/"callee" by default) only reaches "connected". When this is
3351 // fixed, this test should be updated.
3352 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3353 caller()->ice_connection_state(), kDefaultTimeout);
3354 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3355 callee()->ice_connection_state(), kDefaultTimeout);
3356}
3357
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003358// Replaces the first candidate with a static address and configures a
3359// MockAsyncResolver to return the replaced address the first time the static
3360// address is resolved. Candidates past the first will not be signaled.
3361class ReplaceFirstCandidateAddressDropOthers final
3362 : public IceCandidateReplacerInterface {
3363 public:
3364 ReplaceFirstCandidateAddressDropOthers(
3365 const SocketAddress& new_address,
3366 rtc::MockAsyncResolver* mock_async_resolver)
3367 : mock_async_resolver_(mock_async_resolver), new_address_(new_address) {
3368 RTC_DCHECK(mock_async_resolver);
3369 }
3370
3371 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3372 const webrtc::IceCandidateInterface* candidate) override {
3373 if (replaced_candidate_) {
3374 return nullptr;
3375 }
3376
3377 replaced_candidate_ = true;
3378 cricket::Candidate new_candidate(candidate->candidate());
3379 new_candidate.set_address(new_address_);
3380 EXPECT_CALL(*mock_async_resolver_, GetResolvedAddress(_, _))
3381 .WillOnce(DoAll(SetArgPointee<1>(candidate->candidate().address()),
3382 Return(true)));
3383 EXPECT_CALL(*mock_async_resolver_, Destroy(_));
3384 return webrtc::CreateIceCandidate(
3385 candidate->sdp_mid(), candidate->sdp_mline_index(), new_candidate);
3386 }
3387
3388 private:
3389 rtc::MockAsyncResolver* mock_async_resolver_;
3390 SocketAddress new_address_;
3391 bool replaced_candidate_ = false;
3392};
3393
3394// Drops all candidates before they are signaled.
3395class DropAllCandidates final : public IceCandidateReplacerInterface {
3396 public:
3397 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3398 const webrtc::IceCandidateInterface*) override {
3399 return nullptr;
3400 }
3401};
3402
3403// Replace the first caller ICE candidate IP with a fake hostname and drop the
3404// other candidates. Drop all candidates on the callee side (to avoid a prflx
3405// connection). Use a mock resolver to resolve the hostname back to the original
3406// IP on the callee side and check that the ice connection connects.
3407TEST_P(PeerConnectionIntegrationTest,
3408 IceStatesReachCompletionWithRemoteHostname) {
3409 webrtc::MockAsyncResolverFactory* callee_mock_async_resolver_factory;
3410 {
3411 auto resolver_factory =
3412 absl::make_unique<webrtc::MockAsyncResolverFactory>();
3413 callee_mock_async_resolver_factory = resolver_factory.get();
3414 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3415 callee_deps.async_resolver_factory = std::move(resolver_factory);
3416
3417 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3418 RTCConfiguration(), webrtc::PeerConnectionDependencies(nullptr),
3419 RTCConfiguration(), std::move(callee_deps)));
3420 }
3421
3422 rtc::MockAsyncResolver mock_async_resolver;
3423
3424 // This also verifies that the injected AsyncResolverFactory is used by
3425 // P2PTransportChannel.
3426 EXPECT_CALL(*callee_mock_async_resolver_factory, Create())
3427 .WillOnce(Return(&mock_async_resolver));
3428 caller()->SetLocalIceCandidateReplacer(
3429 absl::make_unique<ReplaceFirstCandidateAddressDropOthers>(
3430 SocketAddress("a.b", 10000), &mock_async_resolver));
3431 callee()->SetLocalIceCandidateReplacer(
3432 absl::make_unique<DropAllCandidates>());
3433
3434 ConnectFakeSignaling();
3435 caller()->AddAudioVideoTracks();
3436 callee()->AddAudioVideoTracks();
3437 caller()->CreateAndSetAndSignalOffer();
3438 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3439 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3440 caller()->ice_connection_state(), kDefaultTimeout);
3441 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3442 callee()->ice_connection_state(), kDefaultTimeout);
3443}
3444
Steve Antonede9ca52017-10-16 13:04:27 -07003445// Test that firewalling the ICE connection causes the clients to identify the
3446// disconnected state and then removing the firewall causes them to reconnect.
3447class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003448 : public PeerConnectionIntegrationBaseTest,
3449 public ::testing::WithParamInterface<
3450 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003451 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003452 PeerConnectionIntegrationIceStatesTest()
3453 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3454 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003455 }
3456
3457 void StartStunServer(const SocketAddress& server_address) {
3458 stun_server_.reset(
3459 cricket::TestStunServer::Create(network_thread(), server_address));
3460 }
3461
3462 bool TestIPv6() {
3463 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3464 }
3465
3466 void SetPortAllocatorFlags() {
Qingsi Wanga2d60672018-04-11 16:57:45 -07003467 network_thread()->Invoke<void>(
3468 RTC_FROM_HERE,
3469 rtc::Bind(&cricket::PortAllocator::set_flags,
3470 caller()->port_allocator(), port_allocator_flags_));
3471 network_thread()->Invoke<void>(
3472 RTC_FROM_HERE,
3473 rtc::Bind(&cricket::PortAllocator::set_flags,
3474 callee()->port_allocator(), port_allocator_flags_));
Steve Antonede9ca52017-10-16 13:04:27 -07003475 }
3476
3477 std::vector<SocketAddress> CallerAddresses() {
3478 std::vector<SocketAddress> addresses;
3479 addresses.push_back(SocketAddress("1.1.1.1", 0));
3480 if (TestIPv6()) {
3481 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3482 }
3483 return addresses;
3484 }
3485
3486 std::vector<SocketAddress> CalleeAddresses() {
3487 std::vector<SocketAddress> addresses;
3488 addresses.push_back(SocketAddress("2.2.2.2", 0));
3489 if (TestIPv6()) {
3490 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3491 }
3492 return addresses;
3493 }
3494
3495 void SetUpNetworkInterfaces() {
3496 // Remove the default interfaces added by the test infrastructure.
3497 caller()->network()->RemoveInterface(kDefaultLocalAddress);
3498 callee()->network()->RemoveInterface(kDefaultLocalAddress);
3499
3500 // Add network addresses for test.
3501 for (const auto& caller_address : CallerAddresses()) {
3502 caller()->network()->AddInterface(caller_address);
3503 }
3504 for (const auto& callee_address : CalleeAddresses()) {
3505 callee()->network()->AddInterface(callee_address);
3506 }
3507 }
3508
3509 private:
3510 uint32_t port_allocator_flags_;
3511 std::unique_ptr<cricket::TestStunServer> stun_server_;
3512};
3513
3514// Tests that the PeerConnection goes through all the ICE gathering/connection
3515// states over the duration of the call. This includes Disconnected and Failed
3516// states, induced by putting a firewall between the peers and waiting for them
3517// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003518TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
3519 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
3520 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
3521 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07003522
3523 const SocketAddress kStunServerAddress =
3524 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3525 StartStunServer(kStunServerAddress);
3526
3527 PeerConnectionInterface::RTCConfiguration config;
3528 PeerConnectionInterface::IceServer ice_stun_server;
3529 ice_stun_server.urls.push_back(
3530 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3531 kStunServerAddress.PortAsString());
3532 config.servers.push_back(ice_stun_server);
3533
3534 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3535 ConnectFakeSignaling();
3536 SetPortAllocatorFlags();
3537 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003538 caller()->AddAudioVideoTracks();
3539 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003540
3541 // Initial state before anything happens.
3542 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3543 caller()->ice_gathering_state());
3544 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3545 caller()->ice_connection_state());
3546
3547 // Start the call by creating the offer, setting it as the local description,
3548 // then sending it to the peer who will respond with an answer. This happens
3549 // asynchronously so that we can watch the states as it runs in the
3550 // background.
3551 caller()->CreateAndSetAndSignalOffer();
3552
Steve Anton83119dd2017-11-10 16:19:52 -08003553 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3554 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003555
3556 // Verify that the observer was notified of the intermediate transitions.
3557 EXPECT_THAT(caller()->ice_connection_state_history(),
3558 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3559 PeerConnectionInterface::kIceConnectionConnected,
3560 PeerConnectionInterface::kIceConnectionCompleted));
3561 EXPECT_THAT(caller()->ice_gathering_state_history(),
3562 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
3563 PeerConnectionInterface::kIceGatheringComplete));
3564
3565 // Block connections to/from the caller and wait for ICE to become
3566 // disconnected.
3567 for (const auto& caller_address : CallerAddresses()) {
3568 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3569 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003570 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08003571 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
3572 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003573
3574 // Let ICE re-establish by removing the firewall rules.
3575 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01003576 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08003577 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3578 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003579
3580 // According to RFC7675, if there is no response within 30 seconds then the
3581 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08003582 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07003583 constexpr int kConsentTimeout = 30000;
3584 for (const auto& caller_address : CallerAddresses()) {
3585 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3586 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003587 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08003588 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
3589 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003590}
3591
3592// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
3593// and that the statistics in the metric observers are updated correctly.
3594TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
3595 ASSERT_TRUE(CreatePeerConnectionWrappers());
3596 ConnectFakeSignaling();
3597 SetPortAllocatorFlags();
3598 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003599 caller()->AddAudioVideoTracks();
3600 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003601 caller()->CreateAndSetAndSignalOffer();
3602
3603 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3604
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003605 // TODO(bugs.webrtc.org/9456): Fix it.
3606 const int num_best_ipv4 = webrtc::metrics::NumEvents(
3607 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
3608 const int num_best_ipv6 = webrtc::metrics::NumEvents(
3609 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003610 if (TestIPv6()) {
3611 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
3612 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003613 EXPECT_EQ(0, num_best_ipv4);
3614 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003615 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003616 EXPECT_EQ(1, num_best_ipv4);
3617 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003618 }
3619
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003620 EXPECT_EQ(0, webrtc::metrics::NumEvents(
3621 "WebRTC.PeerConnection.CandidatePairType_UDP",
3622 webrtc::kIceCandidatePairHostHost));
3623 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3624 "WebRTC.PeerConnection.CandidatePairType_UDP",
3625 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07003626}
3627
3628constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
3629 cricket::PORTALLOCATOR_DISABLE_STUN |
3630 cricket::PORTALLOCATOR_DISABLE_RELAY;
3631constexpr uint32_t kFlagsIPv6NoStun =
3632 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
3633 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
3634constexpr uint32_t kFlagsIPv4Stun =
3635 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
3636
Seth Hampson2f0d7022018-02-20 11:54:42 -08003637INSTANTIATE_TEST_CASE_P(
3638 PeerConnectionIntegrationTest,
3639 PeerConnectionIntegrationIceStatesTest,
3640 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3641 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
3642 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
3643 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07003644
deadbeef1dcb1642017-03-29 21:08:16 -07003645// This test sets up a call between two parties with audio and video.
3646// During the call, the caller restarts ICE and the test verifies that
3647// new ICE candidates are generated and audio and video still can flow, and the
3648// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003649TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07003650 ASSERT_TRUE(CreatePeerConnectionWrappers());
3651 ConnectFakeSignaling();
3652 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08003653 caller()->AddAudioVideoTracks();
3654 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003655 caller()->CreateAndSetAndSignalOffer();
3656 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3657 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3658 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3659 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3660 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3661
3662 // To verify that the ICE restart actually occurs, get
3663 // ufrag/password/candidates before and after restart.
3664 // Create an SDP string of the first audio candidate for both clients.
3665 const webrtc::IceCandidateCollection* audio_candidates_caller =
3666 caller()->pc()->local_description()->candidates(0);
3667 const webrtc::IceCandidateCollection* audio_candidates_callee =
3668 callee()->pc()->local_description()->candidates(0);
3669 ASSERT_GT(audio_candidates_caller->count(), 0u);
3670 ASSERT_GT(audio_candidates_callee->count(), 0u);
3671 std::string caller_candidate_pre_restart;
3672 ASSERT_TRUE(
3673 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
3674 std::string callee_candidate_pre_restart;
3675 ASSERT_TRUE(
3676 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3677 const cricket::SessionDescription* desc =
3678 caller()->pc()->local_description()->description();
3679 std::string caller_ufrag_pre_restart =
3680 desc->transport_infos()[0].description.ice_ufrag;
3681 desc = callee()->pc()->local_description()->description();
3682 std::string callee_ufrag_pre_restart =
3683 desc->transport_infos()[0].description.ice_ufrag;
3684
3685 // Have the caller initiate an ICE restart.
3686 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3687 caller()->CreateAndSetAndSignalOffer();
3688 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3689 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3690 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3691 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3692 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3693
3694 // Grab the ufrags/candidates again.
3695 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3696 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3697 ASSERT_GT(audio_candidates_caller->count(), 0u);
3698 ASSERT_GT(audio_candidates_callee->count(), 0u);
3699 std::string caller_candidate_post_restart;
3700 ASSERT_TRUE(
3701 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3702 std::string callee_candidate_post_restart;
3703 ASSERT_TRUE(
3704 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
3705 desc = caller()->pc()->local_description()->description();
3706 std::string caller_ufrag_post_restart =
3707 desc->transport_infos()[0].description.ice_ufrag;
3708 desc = callee()->pc()->local_description()->description();
3709 std::string callee_ufrag_post_restart =
3710 desc->transport_infos()[0].description.ice_ufrag;
3711 // Sanity check that an ICE restart was actually negotiated in SDP.
3712 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
3713 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3714 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3715 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3716
3717 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003718 MediaExpectations media_expectations;
3719 media_expectations.ExpectBidirectionalAudioAndVideo();
3720 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003721}
3722
3723// Verify that audio/video can be received end-to-end when ICE renomination is
3724// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003725TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07003726 PeerConnectionInterface::RTCConfiguration config;
3727 config.enable_ice_renomination = true;
3728 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3729 ConnectFakeSignaling();
3730 // Do normal offer/answer and wait for some frames to be received in each
3731 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003732 caller()->AddAudioVideoTracks();
3733 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003734 caller()->CreateAndSetAndSignalOffer();
3735 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3736 // Sanity check that ICE renomination was actually negotiated.
3737 const cricket::SessionDescription* desc =
3738 caller()->pc()->local_description()->description();
3739 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003740 ASSERT_NE(
3741 info.description.transport_options.end(),
3742 std::find(info.description.transport_options.begin(),
3743 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003744 }
3745 desc = callee()->pc()->local_description()->description();
3746 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003747 ASSERT_NE(
3748 info.description.transport_options.end(),
3749 std::find(info.description.transport_options.begin(),
3750 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003751 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003752 MediaExpectations media_expectations;
3753 media_expectations.ExpectBidirectionalAudioAndVideo();
3754 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003755}
3756
Steve Anton6f25b092017-10-23 09:39:20 -07003757// With a max bundle policy and RTCP muxing, adding a new media description to
3758// the connection should not affect ICE at all because the new media will use
3759// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003760TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003761 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07003762 PeerConnectionInterface::RTCConfiguration config;
3763 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3764 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3765 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
3766 config, PeerConnectionInterface::RTCConfiguration()));
3767 ConnectFakeSignaling();
3768
Steve Anton15324772018-01-16 10:26:49 -08003769 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003770 caller()->CreateAndSetAndSignalOffer();
3771 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07003772 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3773 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07003774
3775 caller()->clear_ice_connection_state_history();
3776
Steve Anton15324772018-01-16 10:26:49 -08003777 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003778 caller()->CreateAndSetAndSignalOffer();
3779 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3780
3781 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
3782}
3783
deadbeef1dcb1642017-03-29 21:08:16 -07003784// This test sets up a call between two parties with audio and video. It then
3785// renegotiates setting the video m-line to "port 0", then later renegotiates
3786// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003787TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003788 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
3789 ASSERT_TRUE(CreatePeerConnectionWrappers());
3790 ConnectFakeSignaling();
3791
3792 // Do initial negotiation, only sending media from the caller. Will result in
3793 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08003794 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003795 caller()->CreateAndSetAndSignalOffer();
3796 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3797
3798 // Negotiate again, disabling the video "m=" section (the callee will set the
3799 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003800 if (sdp_semantics_ == SdpSemantics::kPlanB) {
3801 PeerConnectionInterface::RTCOfferAnswerOptions options;
3802 options.offer_to_receive_video = 0;
3803 callee()->SetOfferAnswerOptions(options);
3804 } else {
3805 callee()->SetRemoteOfferHandler([this] {
3806 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
3807 });
3808 }
deadbeef1dcb1642017-03-29 21:08:16 -07003809 caller()->CreateAndSetAndSignalOffer();
3810 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3811 // Sanity check that video "m=" section was actually rejected.
3812 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
3813 callee()->pc()->local_description()->description());
3814 ASSERT_NE(nullptr, answer_video_content);
3815 ASSERT_TRUE(answer_video_content->rejected);
3816
3817 // Enable video and do negotiation again, making sure video is received
3818 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003819 if (sdp_semantics_ == SdpSemantics::kPlanB) {
3820 PeerConnectionInterface::RTCOfferAnswerOptions options;
3821 options.offer_to_receive_video = 1;
3822 callee()->SetOfferAnswerOptions(options);
3823 } else {
3824 // The caller's transceiver is stopped, so we need to add another track.
3825 auto caller_transceiver =
3826 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
3827 EXPECT_TRUE(caller_transceiver->stopped());
3828 caller()->AddVideoTrack();
3829 }
3830 callee()->AddVideoTrack();
3831 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07003832 caller()->CreateAndSetAndSignalOffer();
3833 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003834
deadbeef1dcb1642017-03-29 21:08:16 -07003835 // Verify the caller receives frames from the newly added stream, and the
3836 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003837 MediaExpectations media_expectations;
3838 media_expectations.CalleeExpectsSomeAudio();
3839 media_expectations.ExpectBidirectionalVideo();
3840 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003841}
3842
deadbeef1dcb1642017-03-29 21:08:16 -07003843// This tests that if we negotiate after calling CreateSender but before we
3844// have a track, then set a track later, frames from the newly-set track are
3845// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003846TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07003847 MediaFlowsAfterEarlyWarmupWithCreateSender) {
3848 ASSERT_TRUE(CreatePeerConnectionWrappers());
3849 ConnectFakeSignaling();
3850 auto caller_audio_sender =
3851 caller()->pc()->CreateSender("audio", "caller_stream");
3852 auto caller_video_sender =
3853 caller()->pc()->CreateSender("video", "caller_stream");
3854 auto callee_audio_sender =
3855 callee()->pc()->CreateSender("audio", "callee_stream");
3856 auto callee_video_sender =
3857 callee()->pc()->CreateSender("video", "callee_stream");
3858 caller()->CreateAndSetAndSignalOffer();
3859 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3860 // Wait for ICE to complete, without any tracks being set.
3861 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3862 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3863 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3864 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3865 // Now set the tracks, and expect frames to immediately start flowing.
3866 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3867 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3868 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3869 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08003870 MediaExpectations media_expectations;
3871 media_expectations.ExpectBidirectionalAudioAndVideo();
3872 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3873}
3874
3875// This tests that if we negotiate after calling AddTransceiver but before we
3876// have a track, then set a track later, frames from the newly-set tracks are
3877// received end-to-end.
3878TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
3879 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
3880 ASSERT_TRUE(CreatePeerConnectionWrappers());
3881 ConnectFakeSignaling();
3882 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
3883 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
3884 auto caller_audio_sender = audio_result.MoveValue()->sender();
3885 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
3886 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
3887 auto caller_video_sender = video_result.MoveValue()->sender();
3888 callee()->SetRemoteOfferHandler([this] {
3889 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
3890 callee()->pc()->GetTransceivers()[0]->SetDirection(
3891 RtpTransceiverDirection::kSendRecv);
3892 callee()->pc()->GetTransceivers()[1]->SetDirection(
3893 RtpTransceiverDirection::kSendRecv);
3894 });
3895 caller()->CreateAndSetAndSignalOffer();
3896 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3897 // Wait for ICE to complete, without any tracks being set.
3898 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3899 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3900 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3901 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3902 // Now set the tracks, and expect frames to immediately start flowing.
3903 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
3904 auto callee_video_sender = callee()->pc()->GetSenders()[1];
3905 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3906 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3907 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3908 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
3909 MediaExpectations media_expectations;
3910 media_expectations.ExpectBidirectionalAudioAndVideo();
3911 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003912}
3913
3914// This test verifies that a remote video track can be added via AddStream,
3915// and sent end-to-end. For this particular test, it's simply echoed back
3916// from the caller to the callee, rather than being forwarded to a third
3917// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003918TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07003919 ASSERT_TRUE(CreatePeerConnectionWrappers());
3920 ConnectFakeSignaling();
3921 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08003922 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07003923 caller()->CreateAndSetAndSignalOffer();
3924 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003925 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07003926
3927 // Echo the stream back, and do a new offer/anwer (initiated by callee this
3928 // time).
3929 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
3930 callee()->CreateAndSetAndSignalOffer();
3931 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3932
Seth Hampson2f0d7022018-02-20 11:54:42 -08003933 MediaExpectations media_expectations;
3934 media_expectations.ExpectBidirectionalVideo();
3935 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003936}
3937
3938// Test that we achieve the expected end-to-end connection time, using a
3939// fake clock and simulated latency on the media and signaling paths.
3940// We use a TURN<->TURN connection because this is usually the quickest to
3941// set up initially, especially when we're confident the connection will work
3942// and can start sending media before we get a STUN response.
3943//
3944// With various optimizations enabled, here are the network delays we expect to
3945// be on the critical path:
3946// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
3947// signaling answer (with DTLS fingerprint).
3948// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
3949// using TURN<->TURN pair, and DTLS exchange is 4 packets,
3950// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003951TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07003952 rtc::ScopedFakeClock fake_clock;
3953 // Some things use a time of "0" as a special value, so we need to start out
3954 // the fake clock at a nonzero time.
3955 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003956 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003957
3958 static constexpr int media_hop_delay_ms = 50;
3959 static constexpr int signaling_trip_delay_ms = 500;
3960 // For explanation of these values, see comment above.
3961 static constexpr int required_media_hops = 9;
3962 static constexpr int required_signaling_trips = 2;
3963 // For internal delays (such as posting an event asychronously).
3964 static constexpr int allowed_internal_delay_ms = 20;
3965 static constexpr int total_connection_time_ms =
3966 media_hop_delay_ms * required_media_hops +
3967 signaling_trip_delay_ms * required_signaling_trips +
3968 allowed_internal_delay_ms;
3969
3970 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3971 3478};
3972 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3973 0};
3974 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3975 3478};
3976 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3977 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07003978 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
3979 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02003980
Seth Hampsonaed71642018-06-11 07:41:32 -07003981 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
3982 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07003983 // Bypass permission check on received packets so media can be sent before
3984 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07003985 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
3986 turn_server_1->set_enable_permission_checks(false);
3987 });
3988 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
3989 turn_server_2->set_enable_permission_checks(false);
3990 });
deadbeef1dcb1642017-03-29 21:08:16 -07003991
3992 PeerConnectionInterface::RTCConfiguration client_1_config;
3993 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3994 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3995 ice_server_1.username = "test";
3996 ice_server_1.password = "test";
3997 client_1_config.servers.push_back(ice_server_1);
3998 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3999 client_1_config.presume_writable_when_fully_relayed = true;
4000
4001 PeerConnectionInterface::RTCConfiguration client_2_config;
4002 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4003 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4004 ice_server_2.username = "test";
4005 ice_server_2.password = "test";
4006 client_2_config.servers.push_back(ice_server_2);
4007 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4008 client_2_config.presume_writable_when_fully_relayed = true;
4009
4010 ASSERT_TRUE(
4011 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4012 // Set up the simulated delays.
4013 SetSignalingDelayMs(signaling_trip_delay_ms);
4014 ConnectFakeSignaling();
4015 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4016 virtual_socket_server()->UpdateDelayDistribution();
4017
4018 // Set "offer to receive audio/video" without adding any tracks, so we just
4019 // set up ICE/DTLS with no media.
4020 PeerConnectionInterface::RTCOfferAnswerOptions options;
4021 options.offer_to_receive_audio = 1;
4022 options.offer_to_receive_video = 1;
4023 caller()->SetOfferAnswerOptions(options);
4024 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004025 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4026 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004027 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4028 // If this is not done a DCHECK can be hit in ports.cc, because a large
4029 // negative number is calculated for the rtt due to the global clock changing.
4030 caller()->pc()->Close();
4031 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07004032}
4033
Jonas Orelandbdcee282017-10-10 14:01:40 +02004034// Verify that a TurnCustomizer passed in through RTCConfiguration
4035// is actually used by the underlying TURN candidate pair.
4036// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004037TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004038 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4039 3478};
4040 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4041 0};
4042 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4043 3478};
4044 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4045 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004046 CreateTurnServer(turn_server_1_internal_address,
4047 turn_server_1_external_address);
4048 CreateTurnServer(turn_server_2_internal_address,
4049 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004050
4051 PeerConnectionInterface::RTCConfiguration client_1_config;
4052 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4053 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4054 ice_server_1.username = "test";
4055 ice_server_1.password = "test";
4056 client_1_config.servers.push_back(ice_server_1);
4057 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004058 auto* customizer1 = CreateTurnCustomizer();
4059 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004060
4061 PeerConnectionInterface::RTCConfiguration client_2_config;
4062 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4063 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4064 ice_server_2.username = "test";
4065 ice_server_2.password = "test";
4066 client_2_config.servers.push_back(ice_server_2);
4067 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004068 auto* customizer2 = CreateTurnCustomizer();
4069 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004070
4071 ASSERT_TRUE(
4072 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4073 ConnectFakeSignaling();
4074
4075 // Set "offer to receive audio/video" without adding any tracks, so we just
4076 // set up ICE/DTLS with no media.
4077 PeerConnectionInterface::RTCOfferAnswerOptions options;
4078 options.offer_to_receive_audio = 1;
4079 options.offer_to_receive_video = 1;
4080 caller()->SetOfferAnswerOptions(options);
4081 caller()->CreateAndSetAndSignalOffer();
4082 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4083
Seth Hampsonaed71642018-06-11 07:41:32 -07004084 ExpectTurnCustomizerCountersIncremented(customizer1);
4085 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004086}
4087
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004088// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4089// send media between the caller and the callee.
4090TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4091 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4092 3478};
4093 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4094
4095 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004096 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4097 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004098
4099 webrtc::PeerConnectionInterface::IceServer ice_server;
4100 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4101 ice_server.username = "test";
4102 ice_server.password = "test";
4103
4104 PeerConnectionInterface::RTCConfiguration client_1_config;
4105 client_1_config.servers.push_back(ice_server);
4106 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4107
4108 PeerConnectionInterface::RTCConfiguration client_2_config;
4109 client_2_config.servers.push_back(ice_server);
4110 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4111
4112 ASSERT_TRUE(
4113 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4114
4115 // Do normal offer/answer and wait for ICE to complete.
4116 ConnectFakeSignaling();
4117 caller()->AddAudioVideoTracks();
4118 callee()->AddAudioVideoTracks();
4119 caller()->CreateAndSetAndSignalOffer();
4120 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4121 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4122 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4123
4124 MediaExpectations media_expectations;
4125 media_expectations.ExpectBidirectionalAudioAndVideo();
4126 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4127}
4128
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004129// Verify that a SSLCertificateVerifier passed in through
4130// PeerConnectionDependencies is actually used by the underlying SSL
4131// implementation to determine whether a certificate presented by the TURN
4132// server is accepted by the client. Note that openssladapter_unittest.cc
4133// contains more detailed, lower-level tests.
4134TEST_P(PeerConnectionIntegrationTest,
4135 SSLCertificateVerifierUsedForTurnConnections) {
4136 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4137 3478};
4138 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4139
4140 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4141 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004142 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4143 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004144
4145 webrtc::PeerConnectionInterface::IceServer ice_server;
4146 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4147 ice_server.username = "test";
4148 ice_server.password = "test";
4149
4150 PeerConnectionInterface::RTCConfiguration client_1_config;
4151 client_1_config.servers.push_back(ice_server);
4152 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4153
4154 PeerConnectionInterface::RTCConfiguration client_2_config;
4155 client_2_config.servers.push_back(ice_server);
4156 // Setting the type to kRelay forces the connection to go through a TURN
4157 // server.
4158 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4159
4160 // Get a copy to the pointer so we can verify calls later.
4161 rtc::TestCertificateVerifier* client_1_cert_verifier =
4162 new rtc::TestCertificateVerifier();
4163 client_1_cert_verifier->verify_certificate_ = true;
4164 rtc::TestCertificateVerifier* client_2_cert_verifier =
4165 new rtc::TestCertificateVerifier();
4166 client_2_cert_verifier->verify_certificate_ = true;
4167
4168 // Create the dependencies with the test certificate verifier.
4169 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4170 client_1_deps.tls_cert_verifier =
4171 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4172 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4173 client_2_deps.tls_cert_verifier =
4174 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4175
4176 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4177 client_1_config, std::move(client_1_deps), client_2_config,
4178 std::move(client_2_deps)));
4179 ConnectFakeSignaling();
4180
4181 // Set "offer to receive audio/video" without adding any tracks, so we just
4182 // set up ICE/DTLS with no media.
4183 PeerConnectionInterface::RTCOfferAnswerOptions options;
4184 options.offer_to_receive_audio = 1;
4185 options.offer_to_receive_video = 1;
4186 caller()->SetOfferAnswerOptions(options);
4187 caller()->CreateAndSetAndSignalOffer();
4188 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4189
4190 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4191 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004192}
4193
4194TEST_P(PeerConnectionIntegrationTest,
4195 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4196 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4197 3478};
4198 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4199
4200 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4201 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004202 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4203 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004204
4205 webrtc::PeerConnectionInterface::IceServer ice_server;
4206 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4207 ice_server.username = "test";
4208 ice_server.password = "test";
4209
4210 PeerConnectionInterface::RTCConfiguration client_1_config;
4211 client_1_config.servers.push_back(ice_server);
4212 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4213
4214 PeerConnectionInterface::RTCConfiguration client_2_config;
4215 client_2_config.servers.push_back(ice_server);
4216 // Setting the type to kRelay forces the connection to go through a TURN
4217 // server.
4218 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4219
4220 // Get a copy to the pointer so we can verify calls later.
4221 rtc::TestCertificateVerifier* client_1_cert_verifier =
4222 new rtc::TestCertificateVerifier();
4223 client_1_cert_verifier->verify_certificate_ = false;
4224 rtc::TestCertificateVerifier* client_2_cert_verifier =
4225 new rtc::TestCertificateVerifier();
4226 client_2_cert_verifier->verify_certificate_ = false;
4227
4228 // Create the dependencies with the test certificate verifier.
4229 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4230 client_1_deps.tls_cert_verifier =
4231 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4232 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4233 client_2_deps.tls_cert_verifier =
4234 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4235
4236 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4237 client_1_config, std::move(client_1_deps), client_2_config,
4238 std::move(client_2_deps)));
4239 ConnectFakeSignaling();
4240
4241 // Set "offer to receive audio/video" without adding any tracks, so we just
4242 // set up ICE/DTLS with no media.
4243 PeerConnectionInterface::RTCOfferAnswerOptions options;
4244 options.offer_to_receive_audio = 1;
4245 options.offer_to_receive_video = 1;
4246 caller()->SetOfferAnswerOptions(options);
4247 caller()->CreateAndSetAndSignalOffer();
4248 bool wait_res = true;
4249 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4250 // properly, should be able to just wait for a state of "failed" instead of
4251 // waiting a fixed 10 seconds.
4252 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4253 ASSERT_FALSE(wait_res);
4254
4255 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4256 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004257}
4258
deadbeefc964d0b2017-04-03 10:03:35 -07004259// Test that audio and video flow end-to-end when codec names don't use the
4260// expected casing, given that they're supposed to be case insensitive. To test
4261// this, all but one codec is removed from each media description, and its
4262// casing is changed.
4263//
4264// In the past, this has regressed and caused crashes/black video, due to the
4265// fact that code at some layers was doing case-insensitive comparisons and
4266// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004267TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004268 ASSERT_TRUE(CreatePeerConnectionWrappers());
4269 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004270 caller()->AddAudioVideoTracks();
4271 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004272
4273 // Remove all but one audio/video codec (opus and VP8), and change the
4274 // casing of the caller's generated offer.
4275 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4276 cricket::AudioContentDescription* audio =
4277 GetFirstAudioContentDescription(description);
4278 ASSERT_NE(nullptr, audio);
4279 auto audio_codecs = audio->codecs();
4280 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4281 [](const cricket::AudioCodec& codec) {
4282 return codec.name != "opus";
4283 }),
4284 audio_codecs.end());
4285 ASSERT_EQ(1u, audio_codecs.size());
4286 audio_codecs[0].name = "OpUs";
4287 audio->set_codecs(audio_codecs);
4288
4289 cricket::VideoContentDescription* video =
4290 GetFirstVideoContentDescription(description);
4291 ASSERT_NE(nullptr, video);
4292 auto video_codecs = video->codecs();
4293 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4294 [](const cricket::VideoCodec& codec) {
4295 return codec.name != "VP8";
4296 }),
4297 video_codecs.end());
4298 ASSERT_EQ(1u, video_codecs.size());
4299 video_codecs[0].name = "vP8";
4300 video->set_codecs(video_codecs);
4301 });
4302
4303 caller()->CreateAndSetAndSignalOffer();
4304 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4305
4306 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004307 MediaExpectations media_expectations;
4308 media_expectations.ExpectBidirectionalAudioAndVideo();
4309 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004310}
4311
Jonas Oreland49ac5952018-09-26 16:04:32 +02004312TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004313 ASSERT_TRUE(CreatePeerConnectionWrappers());
4314 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004315 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004316 caller()->CreateAndSetAndSignalOffer();
4317 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004318 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004319 MediaExpectations media_expectations;
4320 media_expectations.CalleeExpectsSomeAudio(1);
4321 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004322 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004323 auto receiver = callee()->pc()->GetReceivers()[0];
4324 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004325 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004326 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4327 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004328 sources[0].source_id());
4329 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4330}
4331
4332TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4333 ASSERT_TRUE(CreatePeerConnectionWrappers());
4334 ConnectFakeSignaling();
4335 caller()->AddVideoTrack();
4336 caller()->CreateAndSetAndSignalOffer();
4337 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4338 // Wait for one video frame to be received by the callee.
4339 MediaExpectations media_expectations;
4340 media_expectations.CalleeExpectsSomeVideo(1);
4341 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4342 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4343 auto receiver = callee()->pc()->GetReceivers()[0];
4344 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4345 auto sources = receiver->GetSources();
4346 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4347 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4348 sources[0].source_id());
4349 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004350}
4351
deadbeef2f425aa2017-04-14 10:41:32 -07004352// Test that if a track is removed and added again with a different stream ID,
4353// the new stream ID is successfully communicated in SDP and media continues to
4354// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004355// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4356// it will not reuse a transceiver that has already been sending. After creating
4357// a new transceiver it tries to create an offer with two senders of the same
4358// track ids and it fails.
4359TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004360 ASSERT_TRUE(CreatePeerConnectionWrappers());
4361 ConnectFakeSignaling();
4362
deadbeef2f425aa2017-04-14 10:41:32 -07004363 // Add track using stream 1, do offer/answer.
4364 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4365 caller()->CreateLocalAudioTrack();
4366 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004367 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004368 caller()->CreateAndSetAndSignalOffer();
4369 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004370 {
4371 MediaExpectations media_expectations;
4372 media_expectations.CalleeExpectsSomeAudio(1);
4373 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4374 }
deadbeef2f425aa2017-04-14 10:41:32 -07004375 // Remove the sender, and create a new one with the new stream.
4376 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004377 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004378 caller()->CreateAndSetAndSignalOffer();
4379 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4380 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004381 {
4382 MediaExpectations media_expectations;
4383 media_expectations.CalleeExpectsSomeAudio();
4384 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4385 }
deadbeef2f425aa2017-04-14 10:41:32 -07004386}
4387
Seth Hampson2f0d7022018-02-20 11:54:42 -08004388TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004389 ASSERT_TRUE(CreatePeerConnectionWrappers());
4390 ConnectFakeSignaling();
4391
Karl Wiberg918f50c2018-07-05 11:40:33 +02004392 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Elad Alon99c3fe52017-10-13 16:29:40 +02004393 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
4394 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
4395 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004396 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4397 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004398
Steve Anton15324772018-01-16 10:26:49 -08004399 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004400 caller()->CreateAndSetAndSignalOffer();
4401 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4402}
4403
Steve Antonede9ca52017-10-16 13:04:27 -07004404// Test that if candidates are only signaled by applying full session
4405// descriptions (instead of using AddIceCandidate), the peers can connect to
4406// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004407TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004408 ASSERT_TRUE(CreatePeerConnectionWrappers());
4409 // Each side will signal the session descriptions but not candidates.
4410 ConnectFakeSignalingForSdpOnly();
4411
4412 // Add audio video track and exchange the initial offer/answer with media
4413 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004414 caller()->AddAudioVideoTracks();
4415 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004416 caller()->CreateAndSetAndSignalOffer();
4417
4418 // Wait for all candidates to be gathered on both the caller and callee.
4419 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4420 caller()->ice_gathering_state(), kDefaultTimeout);
4421 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4422 callee()->ice_gathering_state(), kDefaultTimeout);
4423
4424 // The candidates will now be included in the session description, so
4425 // signaling them will start the ICE connection.
4426 caller()->CreateAndSetAndSignalOffer();
4427 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4428
4429 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004430 MediaExpectations media_expectations;
4431 media_expectations.ExpectBidirectionalAudioAndVideo();
4432 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004433}
4434
henrika5f6bf242017-11-01 11:06:56 +01004435// Test that SetAudioPlayout can be used to disable audio playout from the
4436// start, then later enable it. This may be useful, for example, if the caller
4437// needs to play a local ringtone until some event occurs, after which it
4438// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004439TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004440 ASSERT_TRUE(CreatePeerConnectionWrappers());
4441 ConnectFakeSignaling();
4442
4443 // Set up audio-only call where audio playout is disabled on caller's side.
4444 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004445 caller()->AddAudioTrack();
4446 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004447 caller()->CreateAndSetAndSignalOffer();
4448 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4449
4450 // Pump messages for a second.
4451 WAIT(false, 1000);
4452 // Since audio playout is disabled, the caller shouldn't have received
4453 // anything (at the playout level, at least).
4454 EXPECT_EQ(0, caller()->audio_frames_received());
4455 // As a sanity check, make sure the callee (for which playout isn't disabled)
4456 // did still see frames on its audio level.
4457 ASSERT_GT(callee()->audio_frames_received(), 0);
4458
4459 // Enable playout again, and ensure audio starts flowing.
4460 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004461 MediaExpectations media_expectations;
4462 media_expectations.ExpectBidirectionalAudio();
4463 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004464}
4465
4466double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4467 auto report = pc->NewGetStats();
4468 auto track_stats_list =
4469 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4470 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4471 for (const auto* track_stats : track_stats_list) {
4472 if (track_stats->remote_source.is_defined() &&
4473 *track_stats->remote_source) {
4474 remote_track_stats = track_stats;
4475 break;
4476 }
4477 }
4478
4479 if (!remote_track_stats->total_audio_energy.is_defined()) {
4480 return 0.0;
4481 }
4482 return *remote_track_stats->total_audio_energy;
4483}
4484
4485// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4486// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004487TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004488 DisableAudioPlayoutStillGeneratesAudioStats) {
4489 ASSERT_TRUE(CreatePeerConnectionWrappers());
4490 ConnectFakeSignaling();
4491
4492 // Set up audio-only call where playout is disabled but audio-processing is
4493 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004494 caller()->AddAudioTrack();
4495 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004496 caller()->pc()->SetAudioPlayout(false);
4497
4498 caller()->CreateAndSetAndSignalOffer();
4499 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4500
4501 // Wait for the callee to receive audio stats.
4502 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4503}
4504
henrika4f167df2017-11-01 14:45:55 +01004505// Test that SetAudioRecording can be used to disable audio recording from the
4506// start, then later enable it. This may be useful, for example, if the caller
4507// wants to ensure that no audio resources are active before a certain state
4508// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004509TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004510 ASSERT_TRUE(CreatePeerConnectionWrappers());
4511 ConnectFakeSignaling();
4512
4513 // Set up audio-only call where audio recording is disabled on caller's side.
4514 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08004515 caller()->AddAudioTrack();
4516 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01004517 caller()->CreateAndSetAndSignalOffer();
4518 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4519
4520 // Pump messages for a second.
4521 WAIT(false, 1000);
4522 // Since caller has disabled audio recording, the callee shouldn't have
4523 // received anything.
4524 EXPECT_EQ(0, callee()->audio_frames_received());
4525 // As a sanity check, make sure the caller did still see frames on its
4526 // audio level since audio recording is enabled on the calle side.
4527 ASSERT_GT(caller()->audio_frames_received(), 0);
4528
4529 // Enable audio recording again, and ensure audio starts flowing.
4530 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004531 MediaExpectations media_expectations;
4532 media_expectations.ExpectBidirectionalAudio();
4533 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01004534}
4535
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004536// Test that after closing PeerConnections, they stop sending any packets (ICE,
4537// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004538TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004539 // Set up audio/video/data, wait for some frames to be received.
4540 ASSERT_TRUE(CreatePeerConnectionWrappers());
4541 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004542 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004543#ifdef HAVE_SCTP
4544 caller()->CreateDataChannel();
4545#endif
4546 caller()->CreateAndSetAndSignalOffer();
4547 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004548 MediaExpectations media_expectations;
4549 media_expectations.CalleeExpectsSomeAudioAndVideo();
4550 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004551 // Close PeerConnections.
4552 caller()->pc()->Close();
4553 callee()->pc()->Close();
4554 // Pump messages for a second, and ensure no new packets end up sent.
4555 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
4556 WAIT(false, 1000);
4557 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
4558 EXPECT_EQ(sent_packets_a, sent_packets_b);
4559}
4560
Steve Anton7eca0932018-03-30 15:18:41 -07004561// Test that transport stats are generated by the RTCStatsCollector for a
4562// connection that only involves data channels. This is a regression test for
4563// crbug.com/826972.
4564#ifdef HAVE_SCTP
4565TEST_P(PeerConnectionIntegrationTest,
4566 TransportStatsReportedForDataChannelOnlyConnection) {
4567 ASSERT_TRUE(CreatePeerConnectionWrappers());
4568 ConnectFakeSignaling();
4569 caller()->CreateDataChannel();
4570
4571 caller()->CreateAndSetAndSignalOffer();
4572 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4573 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
4574
4575 auto caller_report = caller()->NewGetStats();
4576 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
4577 auto callee_report = callee()->NewGetStats();
4578 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
4579}
4580#endif // HAVE_SCTP
4581
Qingsi Wang7685e862018-06-11 20:15:46 -07004582TEST_P(PeerConnectionIntegrationTest,
4583 IceEventsGeneratedAndLoggedInRtcEventLog) {
4584 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
4585 ConnectFakeSignaling();
4586 PeerConnectionInterface::RTCOfferAnswerOptions options;
4587 options.offer_to_receive_audio = 1;
4588 caller()->SetOfferAnswerOptions(options);
4589 caller()->CreateAndSetAndSignalOffer();
4590 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4591 ASSERT_NE(nullptr, caller()->event_log_factory());
4592 ASSERT_NE(nullptr, callee()->event_log_factory());
4593 webrtc::FakeRtcEventLog* caller_event_log =
4594 static_cast<webrtc::FakeRtcEventLog*>(
4595 caller()->event_log_factory()->last_log_created());
4596 webrtc::FakeRtcEventLog* callee_event_log =
4597 static_cast<webrtc::FakeRtcEventLog*>(
4598 callee()->event_log_factory()->last_log_created());
4599 ASSERT_NE(nullptr, caller_event_log);
4600 ASSERT_NE(nullptr, callee_event_log);
4601 int caller_ice_config_count = caller_event_log->GetEventCount(
4602 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4603 int caller_ice_event_count = caller_event_log->GetEventCount(
4604 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4605 int callee_ice_config_count = callee_event_log->GetEventCount(
4606 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4607 int callee_ice_event_count = callee_event_log->GetEventCount(
4608 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4609 EXPECT_LT(0, caller_ice_config_count);
4610 EXPECT_LT(0, caller_ice_event_count);
4611 EXPECT_LT(0, callee_ice_config_count);
4612 EXPECT_LT(0, callee_ice_event_count);
4613}
4614
Seth Hampson2f0d7022018-02-20 11:54:42 -08004615INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
4616 PeerConnectionIntegrationTest,
4617 Values(SdpSemantics::kPlanB,
4618 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08004619
Steve Anton74255ff2018-01-24 18:32:57 -08004620// Tests that verify interoperability between Plan B and Unified Plan
4621// PeerConnections.
4622class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004623 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08004624 public ::testing::WithParamInterface<
4625 std::tuple<SdpSemantics, SdpSemantics>> {
4626 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004627 // Setting the SdpSemantics for the base test to kDefault does not matter
4628 // because we specify not to use the test semantics when creating
4629 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08004630 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07004631 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08004632 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08004633 callee_semantics_(std::get<1>(GetParam())) {}
4634
4635 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07004636 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
4637 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08004638 }
4639
4640 const SdpSemantics caller_semantics_;
4641 const SdpSemantics callee_semantics_;
4642};
4643
4644TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
4645 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4646 ConnectFakeSignaling();
4647
4648 caller()->CreateAndSetAndSignalOffer();
4649 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4650}
4651
4652TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
4653 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4654 ConnectFakeSignaling();
4655 auto audio_sender = caller()->AddAudioTrack();
4656
4657 caller()->CreateAndSetAndSignalOffer();
4658 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4659
4660 // Verify that one audio receiver has been created on the remote and that it
4661 // has the same track ID as the sending track.
4662 auto receivers = callee()->pc()->GetReceivers();
4663 ASSERT_EQ(1u, receivers.size());
4664 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
4665 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
4666
Seth Hampson2f0d7022018-02-20 11:54:42 -08004667 MediaExpectations media_expectations;
4668 media_expectations.CalleeExpectsSomeAudio();
4669 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004670}
4671
4672TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
4673 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4674 ConnectFakeSignaling();
4675 auto video_sender = caller()->AddVideoTrack();
4676 auto audio_sender = caller()->AddAudioTrack();
4677
4678 caller()->CreateAndSetAndSignalOffer();
4679 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4680
4681 // Verify that one audio and one video receiver have been created on the
4682 // remote and that they have the same track IDs as the sending tracks.
4683 auto audio_receivers =
4684 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
4685 ASSERT_EQ(1u, audio_receivers.size());
4686 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
4687 auto video_receivers =
4688 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
4689 ASSERT_EQ(1u, video_receivers.size());
4690 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
4691
Seth Hampson2f0d7022018-02-20 11:54:42 -08004692 MediaExpectations media_expectations;
4693 media_expectations.CalleeExpectsSomeAudioAndVideo();
4694 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004695}
4696
4697TEST_P(PeerConnectionIntegrationInteropTest,
4698 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
4699 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4700 ConnectFakeSignaling();
4701 caller()->AddAudioVideoTracks();
4702 callee()->AddAudioVideoTracks();
4703
4704 caller()->CreateAndSetAndSignalOffer();
4705 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4706
Seth Hampson2f0d7022018-02-20 11:54:42 -08004707 MediaExpectations media_expectations;
4708 media_expectations.ExpectBidirectionalAudioAndVideo();
4709 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004710}
4711
4712TEST_P(PeerConnectionIntegrationInteropTest,
4713 ReverseRolesOneAudioLocalToOneVideoRemote) {
4714 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4715 ConnectFakeSignaling();
4716 caller()->AddAudioTrack();
4717 callee()->AddVideoTrack();
4718
4719 caller()->CreateAndSetAndSignalOffer();
4720 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4721
4722 // Verify that only the audio track has been negotiated.
4723 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
4724 // Might also check that the callee's NegotiationNeeded flag is set.
4725
4726 // Reverse roles.
4727 callee()->CreateAndSetAndSignalOffer();
4728 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4729
Seth Hampson2f0d7022018-02-20 11:54:42 -08004730 MediaExpectations media_expectations;
4731 media_expectations.CallerExpectsSomeVideo();
4732 media_expectations.CalleeExpectsSomeAudio();
4733 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004734}
4735
Steve Antonba42e992018-04-09 14:10:01 -07004736INSTANTIATE_TEST_CASE_P(
4737 PeerConnectionIntegrationTest,
4738 PeerConnectionIntegrationInteropTest,
4739 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4740 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
4741
4742// Test that if the Unified Plan side offers two video tracks then the Plan B
4743// side will only see the first one and ignore the second.
4744TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07004745 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
4746 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08004747 ConnectFakeSignaling();
4748 auto first_sender = caller()->AddVideoTrack();
4749 caller()->AddVideoTrack();
4750
4751 caller()->CreateAndSetAndSignalOffer();
4752 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4753
4754 // Verify that there is only one receiver and it corresponds to the first
4755 // added track.
4756 auto receivers = callee()->pc()->GetReceivers();
4757 ASSERT_EQ(1u, receivers.size());
4758 EXPECT_TRUE(receivers[0]->track()->enabled());
4759 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
4760
Seth Hampson2f0d7022018-02-20 11:54:42 -08004761 MediaExpectations media_expectations;
4762 media_expectations.CalleeExpectsSomeVideo();
4763 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004764}
4765
deadbeef1dcb1642017-03-29 21:08:16 -07004766} // namespace
4767
4768#endif // if !defined(THREAD_SANITIZER)