blob: 87a4c8571f27435f585fbda99a6dc0f783cdb59f [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"
Jiawei Oube142172018-10-10 01:16:20 -070032#include "api/video/builtin_video_bitrate_allocator_factory.h"
Anders Carlsson67537952018-05-03 11:28:29 +020033#include "api/video_codecs/builtin_video_decoder_factory.h"
34#include "api/video_codecs/builtin_video_encoder_factory.h"
35#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070036#include "call/call.h"
37#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
38#include "logging/rtc_event_log/rtc_event_log_factory_interface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "media/engine/fakewebrtcvideoengine.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070040#include "media/engine/webrtcmediaengine.h"
41#include "modules/audio_processing/include/audio_processing.h"
Zach Stein6fcdc2f2018-08-23 16:25:55 -070042#include "p2p/base/mockasyncresolver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "p2p/base/p2pconstants.h"
44#include "p2p/base/portinterface.h"
Steve Antonede9ca52017-10-16 13:04:27 -070045#include "p2p/base/teststunserver.h"
Jonas Orelandbdcee282017-10-10 14:01:40 +020046#include "p2p/base/testturncustomizer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "p2p/base/testturnserver.h"
48#include "p2p/client/basicportallocator.h"
49#include "pc/dtmfsender.h"
50#include "pc/localaudiosource.h"
51#include "pc/mediasession.h"
52#include "pc/peerconnection.h"
53#include "pc/peerconnectionfactory.h"
Seth Hampson2f0d7022018-02-20 11:54:42 -080054#include "pc/rtpmediautils.h"
Steve Anton4ab68ee2017-12-19 14:26:11 -080055#include "pc/sessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020056#include "pc/test/fakeaudiocapturemodule.h"
Niels Möller0f405822018-05-17 09:16:41 +020057#include "pc/test/fakeperiodicvideotracksource.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020058#include "pc/test/fakertccertificategenerator.h"
59#include "pc/test/fakevideotrackrenderer.h"
60#include "pc/test/mockpeerconnectionobservers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020061#include "rtc_base/fakenetwork.h"
Steve Antonede9ca52017-10-16 13:04:27 -070062#include "rtc_base/firewallsocketserver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020063#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020064#include "rtc_base/numerics/safe_conversions.h"
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070065#include "rtc_base/testcertificateverifier.h"
Johannes Kron965e7942018-09-13 15:36:20 +020066#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020067#include "rtc_base/virtualsocketserver.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020068#include "system_wrappers/include/metrics.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020069#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070070
71using cricket::ContentInfo;
72using cricket::FakeWebRtcVideoDecoder;
73using cricket::FakeWebRtcVideoDecoderFactory;
74using cricket::FakeWebRtcVideoEncoder;
75using cricket::FakeWebRtcVideoEncoderFactory;
76using cricket::MediaContentDescription;
Steve Antondf527fd2018-04-27 15:52:03 -070077using cricket::StreamParams;
Steve Antonede9ca52017-10-16 13:04:27 -070078using rtc::SocketAddress;
Seth Hampson2f0d7022018-02-20 11:54:42 -080079using ::testing::Combine;
Steve Antonede9ca52017-10-16 13:04:27 -070080using ::testing::ElementsAre;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070081using ::testing::Return;
82using ::testing::SetArgPointee;
Steve Antonede9ca52017-10-16 13:04:27 -070083using ::testing::Values;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070084using ::testing::_;
deadbeef1dcb1642017-03-29 21:08:16 -070085using webrtc::DataBuffer;
86using webrtc::DataChannelInterface;
87using webrtc::DtmfSender;
88using webrtc::DtmfSenderInterface;
89using webrtc::DtmfSenderObserverInterface;
Steve Anton15324772018-01-16 10:26:49 -080090using webrtc::FakeVideoTrackRenderer;
deadbeef1dcb1642017-03-29 21:08:16 -070091using webrtc::MediaStreamInterface;
92using webrtc::MediaStreamTrackInterface;
93using webrtc::MockCreateSessionDescriptionObserver;
94using webrtc::MockDataChannelObserver;
95using webrtc::MockSetSessionDescriptionObserver;
96using webrtc::MockStatsObserver;
97using webrtc::ObserverInterface;
Steve Anton8c0f7a72017-10-03 10:03:10 -070098using webrtc::PeerConnection;
deadbeef1dcb1642017-03-29 21:08:16 -070099using webrtc::PeerConnectionInterface;
Steve Anton74255ff2018-01-24 18:32:57 -0800100using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -0700101using webrtc::PeerConnectionFactory;
Steve Anton8c0f7a72017-10-03 10:03:10 -0700102using webrtc::PeerConnectionProxy;
Steve Anton15324772018-01-16 10:26:49 -0800103using webrtc::RTCErrorType;
Steve Anton7eca0932018-03-30 15:18:41 -0700104using webrtc::RTCTransportStats;
Steve Anton74255ff2018-01-24 18:32:57 -0800105using webrtc::RtpSenderInterface;
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100106using webrtc::RtpReceiverInterface;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800107using webrtc::RtpSenderInterface;
108using webrtc::RtpTransceiverDirection;
109using webrtc::RtpTransceiverInit;
110using webrtc::RtpTransceiverInterface;
Steve Antond3679212018-01-17 17:41:02 -0800111using webrtc::SdpSemantics;
Steve Antona3a92c22017-12-07 10:27:41 -0800112using webrtc::SdpType;
deadbeef1dcb1642017-03-29 21:08:16 -0700113using webrtc::SessionDescriptionInterface;
114using webrtc::StreamCollectionInterface;
Steve Anton15324772018-01-16 10:26:49 -0800115using webrtc::VideoTrackInterface;
deadbeef1dcb1642017-03-29 21:08:16 -0700116
117namespace {
118
119static const int kDefaultTimeout = 10000;
120static const int kMaxWaitForStatsMs = 3000;
121static const int kMaxWaitForActivationMs = 5000;
122static const int kMaxWaitForFramesMs = 10000;
123// Default number of audio/video frames to wait for before considering a test
124// successful.
125static const int kDefaultExpectedAudioFrameCount = 3;
126static const int kDefaultExpectedVideoFrameCount = 3;
127
deadbeef1dcb1642017-03-29 21:08:16 -0700128static const char kDataChannelLabel[] = "data_channel";
129
130// SRTP cipher name negotiated by the tests. This must be updated if the
131// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700132static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700133static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
134
Steve Antonede9ca52017-10-16 13:04:27 -0700135static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
136
deadbeef1dcb1642017-03-29 21:08:16 -0700137// Helper function for constructing offer/answer options to initiate an ICE
138// restart.
139PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
140 PeerConnectionInterface::RTCOfferAnswerOptions options;
141 options.ice_restart = true;
142 return options;
143}
144
deadbeefd8ad7882017-04-18 16:01:17 -0700145// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
146// attribute from received SDP, simulating a legacy endpoint.
147void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
148 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800149 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700150 }
151 desc->set_msid_supported(false);
152}
153
Seth Hampson5897a6e2018-04-03 11:16:33 -0700154// Removes all stream information besides the stream ids, simulating an
155// endpoint that only signals a=msid lines to convey stream_ids.
156void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
157 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700158 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700159 std::vector<std::string> stream_ids;
160 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700161 const StreamParams& first_stream =
162 content.media_description()->streams()[0];
163 track_id = first_stream.id;
164 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700165 }
166 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700167 StreamParams new_stream;
168 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700169 new_stream.set_stream_ids(stream_ids);
170 content.media_description()->AddStream(new_stream);
171 }
172}
173
zhihuangf8164932017-05-19 13:09:47 -0700174int FindFirstMediaStatsIndexByKind(
175 const std::string& kind,
176 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
177 media_stats_vec) {
178 for (size_t i = 0; i < media_stats_vec.size(); i++) {
179 if (media_stats_vec[i]->kind.ValueToString() == kind) {
180 return i;
181 }
182 }
183 return -1;
184}
185
deadbeef1dcb1642017-03-29 21:08:16 -0700186class SignalingMessageReceiver {
187 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800188 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700189 virtual void ReceiveIceMessage(const std::string& sdp_mid,
190 int sdp_mline_index,
191 const std::string& msg) = 0;
192
193 protected:
194 SignalingMessageReceiver() {}
195 virtual ~SignalingMessageReceiver() {}
196};
197
198class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
199 public:
200 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
201 : expected_media_type_(media_type) {}
202
203 void OnFirstPacketReceived(cricket::MediaType media_type) override {
204 ASSERT_EQ(expected_media_type_, media_type);
205 first_packet_received_ = true;
206 }
207
208 bool first_packet_received() const { return first_packet_received_; }
209
210 virtual ~MockRtpReceiverObserver() {}
211
212 private:
213 bool first_packet_received_ = false;
214 cricket::MediaType expected_media_type_;
215};
216
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700217// Used by PeerConnectionWrapper::OnIceCandidate to allow a test to modify an
218// ICE candidate before it is signaled.
219class IceCandidateReplacerInterface {
220 public:
221 virtual ~IceCandidateReplacerInterface() = default;
222 // Return nullptr to drop the candidate (it won't be signaled to the other
223 // side).
224 virtual std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
225 const webrtc::IceCandidateInterface*) = 0;
226};
227
deadbeef1dcb1642017-03-29 21:08:16 -0700228// Helper class that wraps a peer connection, observes it, and can accept
229// signaling messages from another wrapper.
230//
231// Uses a fake network, fake A/V capture, and optionally fake
232// encoders/decoders, though they aren't used by default since they don't
233// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700234// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800235// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700236class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800237 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700238 public:
239 // Different factory methods for convenience.
240 // TODO(deadbeef): Could use the pattern of:
241 //
242 // PeerConnectionWrapper =
243 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
244 //
245 // To reduce some code duplication.
246 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
247 const std::string& debug_name,
248 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
249 rtc::Thread* network_thread,
250 rtc::Thread* worker_thread) {
251 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700252 webrtc::PeerConnectionDependencies dependencies(nullptr);
253 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200254 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
255 worker_thread, nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700256 delete client;
257 return nullptr;
258 }
259 return client;
260 }
261
deadbeef2f425aa2017-04-14 10:41:32 -0700262 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
263 return peer_connection_factory_.get();
264 }
265
deadbeef1dcb1642017-03-29 21:08:16 -0700266 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
267
268 // If a signaling message receiver is set (via ConnectFakeSignaling), this
269 // will set the whole offer/answer exchange in motion. Just need to wait for
270 // the signaling state to reach "stable".
271 void CreateAndSetAndSignalOffer() {
272 auto offer = CreateOffer();
273 ASSERT_NE(nullptr, offer);
274 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
275 }
276
277 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
278 // when a remote offer is received (via fake signaling) and an answer is
279 // generated. By default, uses default options.
280 void SetOfferAnswerOptions(
281 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
282 offer_answer_options_ = options;
283 }
284
285 // Set a callback to be invoked when SDP is received via the fake signaling
286 // channel, which provides an opportunity to munge (modify) the SDP. This is
287 // used to test SDP being applied that a PeerConnection would normally not
288 // generate, but a non-JSEP endpoint might.
289 void SetReceivedSdpMunger(
290 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100291 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700292 }
293
deadbeefc964d0b2017-04-03 10:03:35 -0700294 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700295 // generated.
296 void SetGeneratedSdpMunger(
297 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100298 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700299 }
300
Seth Hampson2f0d7022018-02-20 11:54:42 -0800301 // Set a callback to be invoked when a remote offer is received via the fake
302 // signaling channel. This provides an opportunity to change the
303 // PeerConnection state before an answer is created and sent to the caller.
304 void SetRemoteOfferHandler(std::function<void()> handler) {
305 remote_offer_handler_ = std::move(handler);
306 }
307
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700308 void SetLocalIceCandidateReplacer(
309 std::unique_ptr<IceCandidateReplacerInterface> replacer) {
310 local_ice_candidate_replacer_ = std::move(replacer);
311 }
312
Steve Antonede9ca52017-10-16 13:04:27 -0700313 // Every ICE connection state in order that has been seen by the observer.
314 std::vector<PeerConnectionInterface::IceConnectionState>
315 ice_connection_state_history() const {
316 return ice_connection_state_history_;
317 }
Steve Anton6f25b092017-10-23 09:39:20 -0700318 void clear_ice_connection_state_history() {
319 ice_connection_state_history_.clear();
320 }
Steve Antonede9ca52017-10-16 13:04:27 -0700321
Jonas Olsson635474e2018-10-18 15:58:17 +0200322 // Every PeerConnection state in order that has been seen by the observer.
323 std::vector<PeerConnectionInterface::PeerConnectionState>
324 peer_connection_state_history() const {
325 return peer_connection_state_history_;
326 }
327
Steve Antonede9ca52017-10-16 13:04:27 -0700328 // Every ICE gathering state in order that has been seen by the observer.
329 std::vector<PeerConnectionInterface::IceGatheringState>
330 ice_gathering_state_history() const {
331 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700332 }
333
Steve Anton15324772018-01-16 10:26:49 -0800334 void AddAudioVideoTracks() {
335 AddAudioTrack();
336 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700337 }
338
Steve Anton74255ff2018-01-24 18:32:57 -0800339 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
340 return AddTrack(CreateLocalAudioTrack());
341 }
deadbeef1dcb1642017-03-29 21:08:16 -0700342
Steve Anton74255ff2018-01-24 18:32:57 -0800343 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
344 return AddTrack(CreateLocalVideoTrack());
345 }
deadbeef1dcb1642017-03-29 21:08:16 -0700346
347 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200348 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700349 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200350 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700351 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200352 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700353 // TODO(perkj): Test audio source when it is implemented. Currently audio
354 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700355 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700356 source);
357 }
358
359 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200360 webrtc::FakePeriodicVideoSource::Config config;
361 config.timestamp_offset_ms = rtc::TimeMillis();
362 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700363 }
364
365 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200366 CreateLocalVideoTrackWithConfig(
367 webrtc::FakePeriodicVideoSource::Config config) {
368 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700369 }
370
371 rtc::scoped_refptr<webrtc::VideoTrackInterface>
372 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200373 webrtc::FakePeriodicVideoSource::Config config;
374 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200375 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200376 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700377 }
378
Steve Anton74255ff2018-01-24 18:32:57 -0800379 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
380 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800381 const std::vector<std::string>& stream_ids = {}) {
382 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800383 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800384 return result.MoveValue();
385 }
386
387 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
388 cricket::MediaType media_type) {
389 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
390 for (auto receiver : pc()->GetReceivers()) {
391 if (receiver->media_type() == media_type) {
392 receivers.push_back(receiver);
393 }
394 }
395 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700396 }
397
Seth Hampson2f0d7022018-02-20 11:54:42 -0800398 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
399 cricket::MediaType media_type) {
400 for (auto transceiver : pc()->GetTransceivers()) {
401 if (transceiver->receiver()->media_type() == media_type) {
402 return transceiver;
403 }
404 }
405 return nullptr;
406 }
407
deadbeef1dcb1642017-03-29 21:08:16 -0700408 bool SignalingStateStable() {
409 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
410 }
411
412 void CreateDataChannel() { CreateDataChannel(nullptr); }
413
414 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700415 CreateDataChannel(kDataChannelLabel, init);
416 }
417
418 void CreateDataChannel(const std::string& label,
419 const webrtc::DataChannelInit* init) {
420 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700421 ASSERT_TRUE(data_channel_.get() != nullptr);
422 data_observer_.reset(new MockDataChannelObserver(data_channel_));
423 }
424
425 DataChannelInterface* data_channel() { return data_channel_; }
426 const MockDataChannelObserver* data_observer() const {
427 return data_observer_.get();
428 }
429
430 int audio_frames_received() const {
431 return fake_audio_capture_module_->frames_received();
432 }
433
434 // Takes minimum of video frames received for each track.
435 //
436 // Can be used like:
437 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
438 //
439 // To ensure that all video tracks received at least a certain number of
440 // frames.
441 int min_video_frames_received_per_track() const {
442 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200443 if (fake_video_renderers_.empty()) {
444 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700445 }
deadbeef1dcb1642017-03-29 21:08:16 -0700446
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200447 for (const auto& pair : fake_video_renderers_) {
448 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700449 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200450 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700451 }
452
453 // Returns a MockStatsObserver in a state after stats gathering finished,
454 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700455 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700456 webrtc::MediaStreamTrackInterface* track) {
457 rtc::scoped_refptr<MockStatsObserver> observer(
458 new rtc::RefCountedObject<MockStatsObserver>());
459 EXPECT_TRUE(peer_connection_->GetStats(
460 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
461 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
462 return observer;
463 }
464
465 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700466 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
467 return OldGetStatsForTrack(nullptr);
468 }
469
470 // Synchronously gets stats and returns them. If it times out, fails the test
471 // and returns null.
472 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
473 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
474 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
475 peer_connection_->GetStats(callback);
476 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
477 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700478 }
479
480 int rendered_width() {
481 EXPECT_FALSE(fake_video_renderers_.empty());
482 return fake_video_renderers_.empty()
483 ? 0
484 : fake_video_renderers_.begin()->second->width();
485 }
486
487 int rendered_height() {
488 EXPECT_FALSE(fake_video_renderers_.empty());
489 return fake_video_renderers_.empty()
490 ? 0
491 : fake_video_renderers_.begin()->second->height();
492 }
493
494 double rendered_aspect_ratio() {
495 if (rendered_height() == 0) {
496 return 0.0;
497 }
498 return static_cast<double>(rendered_width()) / rendered_height();
499 }
500
501 webrtc::VideoRotation rendered_rotation() {
502 EXPECT_FALSE(fake_video_renderers_.empty());
503 return fake_video_renderers_.empty()
504 ? webrtc::kVideoRotation_0
505 : fake_video_renderers_.begin()->second->rotation();
506 }
507
508 int local_rendered_width() {
509 return local_video_renderer_ ? local_video_renderer_->width() : 0;
510 }
511
512 int local_rendered_height() {
513 return local_video_renderer_ ? local_video_renderer_->height() : 0;
514 }
515
516 double local_rendered_aspect_ratio() {
517 if (local_rendered_height() == 0) {
518 return 0.0;
519 }
520 return static_cast<double>(local_rendered_width()) /
521 local_rendered_height();
522 }
523
524 size_t number_of_remote_streams() {
525 if (!pc()) {
526 return 0;
527 }
528 return pc()->remote_streams()->count();
529 }
530
531 StreamCollectionInterface* remote_streams() const {
532 if (!pc()) {
533 ADD_FAILURE();
534 return nullptr;
535 }
536 return pc()->remote_streams();
537 }
538
539 StreamCollectionInterface* local_streams() {
540 if (!pc()) {
541 ADD_FAILURE();
542 return nullptr;
543 }
544 return pc()->local_streams();
545 }
546
547 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
548 return pc()->signaling_state();
549 }
550
551 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
552 return pc()->ice_connection_state();
553 }
554
555 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
556 return pc()->ice_gathering_state();
557 }
558
559 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
560 // GetReceivers. They're updated automatically when a remote offer/answer
561 // from the fake signaling channel is applied, or when
562 // ResetRtpReceiverObservers below is called.
563 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
564 rtp_receiver_observers() {
565 return rtp_receiver_observers_;
566 }
567
568 void ResetRtpReceiverObservers() {
569 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100570 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
571 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700572 std::unique_ptr<MockRtpReceiverObserver> observer(
573 new MockRtpReceiverObserver(receiver->media_type()));
574 receiver->SetObserver(observer.get());
575 rtp_receiver_observers_.push_back(std::move(observer));
576 }
577 }
578
Steve Antonede9ca52017-10-16 13:04:27 -0700579 rtc::FakeNetworkManager* network() const {
580 return fake_network_manager_.get();
581 }
582 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
583
Qingsi Wang7685e862018-06-11 20:15:46 -0700584 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
585 return event_log_factory_;
586 }
587
deadbeef1dcb1642017-03-29 21:08:16 -0700588 private:
589 explicit PeerConnectionWrapper(const std::string& debug_name)
590 : debug_name_(debug_name) {}
591
Niels Möllerf06f9232018-08-07 12:32:18 +0200592 bool Init(const PeerConnectionFactory::Options* options,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700593 const PeerConnectionInterface::RTCConfiguration* config,
594 webrtc::PeerConnectionDependencies dependencies,
595 rtc::Thread* network_thread,
Qingsi Wang7685e862018-06-11 20:15:46 -0700596 rtc::Thread* worker_thread,
597 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700598 // There's an error in this test code if Init ends up being called twice.
599 RTC_DCHECK(!peer_connection_);
600 RTC_DCHECK(!peer_connection_factory_);
601
602 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700603 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700604
605 std::unique_ptr<cricket::PortAllocator> port_allocator(
606 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700607 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700608 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
609 if (!fake_audio_capture_module_) {
610 return false;
611 }
deadbeef1dcb1642017-03-29 21:08:16 -0700612 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700613
614 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
615 pc_factory_dependencies.network_thread = network_thread;
616 pc_factory_dependencies.worker_thread = worker_thread;
617 pc_factory_dependencies.signaling_thread = signaling_thread;
618 pc_factory_dependencies.media_engine =
619 cricket::WebRtcMediaEngineFactory::Create(
620 rtc::scoped_refptr<webrtc::AudioDeviceModule>(
621 fake_audio_capture_module_),
622 webrtc::CreateBuiltinAudioEncoderFactory(),
623 webrtc::CreateBuiltinAudioDecoderFactory(),
624 webrtc::CreateBuiltinVideoEncoderFactory(),
Jiawei Oube142172018-10-10 01:16:20 -0700625 webrtc::CreateBuiltinVideoDecoderFactory(),
626 webrtc::CreateBuiltinVideoBitrateAllocatorFactory(),
627 nullptr /* audio_mixer */,
Qingsi Wang7685e862018-06-11 20:15:46 -0700628 webrtc::AudioProcessingBuilder().Create());
629 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
630 if (event_log_factory) {
631 event_log_factory_ = event_log_factory.get();
632 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
633 } else {
634 pc_factory_dependencies.event_log_factory =
635 webrtc::CreateRtcEventLogFactory();
636 }
637 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
638 std::move(pc_factory_dependencies));
639
deadbeef1dcb1642017-03-29 21:08:16 -0700640 if (!peer_connection_factory_) {
641 return false;
642 }
643 if (options) {
644 peer_connection_factory_->SetOptions(*options);
645 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800646 if (config) {
647 sdp_semantics_ = config->sdp_semantics;
648 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700649
650 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200651 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700652 return peer_connection_.get() != nullptr;
653 }
654
655 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700656 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700657 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700658 PeerConnectionInterface::RTCConfiguration modified_config;
659 // If |config| is null, this will result in a default configuration being
660 // used.
661 if (config) {
662 modified_config = *config;
663 }
664 // Disable resolution adaptation; we don't want it interfering with the
665 // test results.
666 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
667 // ratios and not specific resolutions, is this even necessary?
668 modified_config.set_cpu_adaptation(false);
669
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700670 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700671 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700672 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700673 }
674
675 void set_signaling_message_receiver(
676 SignalingMessageReceiver* signaling_message_receiver) {
677 signaling_message_receiver_ = signaling_message_receiver;
678 }
679
680 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
681
Steve Antonede9ca52017-10-16 13:04:27 -0700682 void set_signal_ice_candidates(bool signal) {
683 signal_ice_candidates_ = signal;
684 }
685
deadbeef1dcb1642017-03-29 21:08:16 -0700686 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200687 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700688 // Set max frame rate to 10fps to reduce the risk of test flakiness.
689 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200690 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700691
Niels Möller5c7efe72018-05-11 10:34:46 +0200692 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200693 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
694 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700695 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200696 peer_connection_factory_->CreateVideoTrack(
697 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700698 if (!local_video_renderer_) {
699 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
700 }
701 return track;
702 }
703
704 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100705 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800706 std::unique_ptr<SessionDescriptionInterface> desc =
707 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700708 if (received_sdp_munger_) {
709 received_sdp_munger_(desc->description());
710 }
711
712 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
713 // Setting a remote description may have changed the number of receivers,
714 // so reset the receiver observers.
715 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800716 if (remote_offer_handler_) {
717 remote_offer_handler_();
718 }
deadbeef1dcb1642017-03-29 21:08:16 -0700719 auto answer = CreateAnswer();
720 ASSERT_NE(nullptr, answer);
721 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
722 }
723
724 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100725 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800726 std::unique_ptr<SessionDescriptionInterface> desc =
727 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700728 if (received_sdp_munger_) {
729 received_sdp_munger_(desc->description());
730 }
731
732 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
733 // Set the RtpReceiverObserver after receivers are created.
734 ResetRtpReceiverObservers();
735 }
736
737 // Returns null on failure.
738 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
739 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
740 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
741 pc()->CreateOffer(observer, offer_answer_options_);
742 return WaitForDescriptionFromObserver(observer);
743 }
744
745 // Returns null on failure.
746 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
747 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
748 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
749 pc()->CreateAnswer(observer, offer_answer_options_);
750 return WaitForDescriptionFromObserver(observer);
751 }
752
753 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100754 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700755 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
756 if (!observer->result()) {
757 return nullptr;
758 }
759 auto description = observer->MoveDescription();
760 if (generated_sdp_munger_) {
761 generated_sdp_munger_(description->description());
762 }
763 return description;
764 }
765
766 // Setting the local description and sending the SDP message over the fake
767 // signaling channel are combined into the same method because the SDP
768 // message needs to be sent as soon as SetLocalDescription finishes, without
769 // waiting for the observer to be called. This ensures that ICE candidates
770 // don't outrace the description.
771 bool SetLocalDescriptionAndSendSdpMessage(
772 std::unique_ptr<SessionDescriptionInterface> desc) {
773 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
774 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100775 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800776 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700777 std::string sdp;
778 EXPECT_TRUE(desc->ToString(&sdp));
779 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800780 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
781 RemoveUnusedVideoRenderers();
782 }
deadbeef1dcb1642017-03-29 21:08:16 -0700783 // As mentioned above, we need to send the message immediately after
784 // SetLocalDescription.
785 SendSdpMessage(type, sdp);
786 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
787 return true;
788 }
789
790 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
791 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
792 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100793 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700794 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800795 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
796 RemoveUnusedVideoRenderers();
797 }
deadbeef1dcb1642017-03-29 21:08:16 -0700798 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
799 return observer->result();
800 }
801
Seth Hampson2f0d7022018-02-20 11:54:42 -0800802 // This is a work around to remove unused fake_video_renderers from
803 // transceivers that have either stopped or are no longer receiving.
804 void RemoveUnusedVideoRenderers() {
805 auto transceivers = pc()->GetTransceivers();
806 for (auto& transceiver : transceivers) {
807 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
808 continue;
809 }
810 // Remove fake video renderers from any stopped transceivers.
811 if (transceiver->stopped()) {
812 auto it =
813 fake_video_renderers_.find(transceiver->receiver()->track()->id());
814 if (it != fake_video_renderers_.end()) {
815 fake_video_renderers_.erase(it);
816 }
817 }
818 // Remove fake video renderers from any transceivers that are no longer
819 // receiving.
820 if ((transceiver->current_direction() &&
821 !webrtc::RtpTransceiverDirectionHasRecv(
822 *transceiver->current_direction()))) {
823 auto it =
824 fake_video_renderers_.find(transceiver->receiver()->track()->id());
825 if (it != fake_video_renderers_.end()) {
826 fake_video_renderers_.erase(it);
827 }
828 }
829 }
830 }
831
deadbeef1dcb1642017-03-29 21:08:16 -0700832 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
833 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800834 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700835 if (signaling_delay_ms_ == 0) {
836 RelaySdpMessageIfReceiverExists(type, msg);
837 } else {
838 invoker_.AsyncInvokeDelayed<void>(
839 RTC_FROM_HERE, rtc::Thread::Current(),
840 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
841 this, type, msg),
842 signaling_delay_ms_);
843 }
844 }
845
Steve Antona3a92c22017-12-07 10:27:41 -0800846 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700847 if (signaling_message_receiver_) {
848 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
849 }
850 }
851
852 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
853 // default).
854 void SendIceMessage(const std::string& sdp_mid,
855 int sdp_mline_index,
856 const std::string& msg) {
857 if (signaling_delay_ms_ == 0) {
858 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
859 } else {
860 invoker_.AsyncInvokeDelayed<void>(
861 RTC_FROM_HERE, rtc::Thread::Current(),
862 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
863 this, sdp_mid, sdp_mline_index, msg),
864 signaling_delay_ms_);
865 }
866 }
867
868 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
869 int sdp_mline_index,
870 const std::string& msg) {
871 if (signaling_message_receiver_) {
872 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
873 msg);
874 }
875 }
876
877 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800878 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
879 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700880 HandleIncomingOffer(msg);
881 } else {
882 HandleIncomingAnswer(msg);
883 }
884 }
885
886 void ReceiveIceMessage(const std::string& sdp_mid,
887 int sdp_mline_index,
888 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100889 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700890 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
891 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
892 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
893 }
894
895 // PeerConnectionObserver callbacks.
896 void OnSignalingChange(
897 webrtc::PeerConnectionInterface::SignalingState new_state) override {
898 EXPECT_EQ(pc()->signaling_state(), new_state);
899 }
Steve Anton15324772018-01-16 10:26:49 -0800900 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
901 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
902 streams) override {
903 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
904 rtc::scoped_refptr<VideoTrackInterface> video_track(
905 static_cast<VideoTrackInterface*>(receiver->track().get()));
906 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700907 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800908 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200909 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700910 }
911 }
Steve Anton15324772018-01-16 10:26:49 -0800912 void OnRemoveTrack(
913 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
914 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
915 auto it = fake_video_renderers_.find(receiver->track()->id());
916 RTC_DCHECK(it != fake_video_renderers_.end());
917 fake_video_renderers_.erase(it);
918 }
919 }
deadbeef1dcb1642017-03-29 21:08:16 -0700920 void OnRenegotiationNeeded() override {}
921 void OnIceConnectionChange(
922 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
923 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700924 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700925 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200926 void OnConnectionChange(
927 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
928 peer_connection_state_history_.push_back(new_state);
929 }
930
deadbeef1dcb1642017-03-29 21:08:16 -0700931 void OnIceGatheringChange(
932 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700933 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700934 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700935 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700936 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceIceCandidate(
937 const webrtc::IceCandidateInterface* candidate) {
938 std::string candidate_string;
939 candidate->ToString(&candidate_string);
940
941 auto owned_candidate =
942 local_ice_candidate_replacer_->ReplaceCandidate(candidate);
943 if (!owned_candidate) {
944 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer dropped \""
945 << candidate_string << "\"";
946 return nullptr;
947 }
948 std::string owned_candidate_string;
949 owned_candidate->ToString(&owned_candidate_string);
950 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer changed \""
951 << candidate_string << "\" to \"" << owned_candidate_string
952 << "\"";
953 return owned_candidate;
954 }
deadbeef1dcb1642017-03-29 21:08:16 -0700955 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100956 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700957
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700958 const webrtc::IceCandidateInterface* new_candidate = candidate;
959 std::unique_ptr<webrtc::IceCandidateInterface> owned_candidate;
960 if (local_ice_candidate_replacer_) {
961 owned_candidate = ReplaceIceCandidate(candidate);
962 if (!owned_candidate) {
963 return; // The candidate was dropped.
964 }
965 new_candidate = owned_candidate.get();
966 }
967
deadbeef1dcb1642017-03-29 21:08:16 -0700968 std::string ice_sdp;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700969 EXPECT_TRUE(new_candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700970 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700971 // Remote party may be deleted.
972 return;
973 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700974 SendIceMessage(new_candidate->sdp_mid(), new_candidate->sdp_mline_index(),
975 ice_sdp);
deadbeef1dcb1642017-03-29 21:08:16 -0700976 }
977 void OnDataChannel(
978 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100979 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700980 data_channel_ = data_channel;
981 data_observer_.reset(new MockDataChannelObserver(data_channel));
982 }
983
deadbeef1dcb1642017-03-29 21:08:16 -0700984 std::string debug_name_;
985
986 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
987
988 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
989 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
990 peer_connection_factory_;
991
Steve Antonede9ca52017-10-16 13:04:27 -0700992 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700993 // Needed to keep track of number of frames sent.
994 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
995 // Needed to keep track of number of frames received.
996 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
997 fake_video_renderers_;
998 // Needed to ensure frames aren't received for removed tracks.
999 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1000 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001001
1002 // For remote peer communication.
1003 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1004 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001005 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -07001006
Niels Möller5c7efe72018-05-11 10:34:46 +02001007 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001008 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001009 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1010 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001011 // |local_video_renderer_| attached to the first created local video track.
1012 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1013
Seth Hampson2f0d7022018-02-20 11:54:42 -08001014 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001015 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1016 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1017 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001018 std::function<void()> remote_offer_handler_;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07001019 std::unique_ptr<IceCandidateReplacerInterface> local_ice_candidate_replacer_;
deadbeef1dcb1642017-03-29 21:08:16 -07001020 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1021 std::unique_ptr<MockDataChannelObserver> data_observer_;
1022
1023 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1024
Steve Antonede9ca52017-10-16 13:04:27 -07001025 std::vector<PeerConnectionInterface::IceConnectionState>
1026 ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001027 std::vector<PeerConnectionInterface::PeerConnectionState>
1028 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001029 std::vector<PeerConnectionInterface::IceGatheringState>
1030 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001031
Qingsi Wang7685e862018-06-11 20:15:46 -07001032 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1033
deadbeef1dcb1642017-03-29 21:08:16 -07001034 rtc::AsyncInvoker invoker_;
1035
Seth Hampson2f0d7022018-02-20 11:54:42 -08001036 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001037};
1038
Elad Alon99c3fe52017-10-13 16:29:40 +02001039class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1040 public:
1041 virtual ~MockRtcEventLogOutput() = default;
1042 MOCK_CONST_METHOD0(IsActive, bool());
1043 MOCK_METHOD1(Write, bool(const std::string&));
1044};
1045
Seth Hampson2f0d7022018-02-20 11:54:42 -08001046// This helper object is used for both specifying how many audio/video frames
1047// are expected to be received for a caller/callee. It provides helper functions
1048// to specify these expectations. The object initially starts in a state of no
1049// expectations.
1050class MediaExpectations {
1051 public:
1052 enum ExpectFrames {
1053 kExpectSomeFrames,
1054 kExpectNoFrames,
1055 kNoExpectation,
1056 };
1057
1058 void ExpectBidirectionalAudioAndVideo() {
1059 ExpectBidirectionalAudio();
1060 ExpectBidirectionalVideo();
1061 }
1062
1063 void ExpectBidirectionalAudio() {
1064 CallerExpectsSomeAudio();
1065 CalleeExpectsSomeAudio();
1066 }
1067
1068 void ExpectNoAudio() {
1069 CallerExpectsNoAudio();
1070 CalleeExpectsNoAudio();
1071 }
1072
1073 void ExpectBidirectionalVideo() {
1074 CallerExpectsSomeVideo();
1075 CalleeExpectsSomeVideo();
1076 }
1077
1078 void ExpectNoVideo() {
1079 CallerExpectsNoVideo();
1080 CalleeExpectsNoVideo();
1081 }
1082
1083 void CallerExpectsSomeAudioAndVideo() {
1084 CallerExpectsSomeAudio();
1085 CallerExpectsSomeVideo();
1086 }
1087
1088 void CalleeExpectsSomeAudioAndVideo() {
1089 CalleeExpectsSomeAudio();
1090 CalleeExpectsSomeVideo();
1091 }
1092
1093 // Caller's audio functions.
1094 void CallerExpectsSomeAudio(
1095 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1096 caller_audio_expectation_ = kExpectSomeFrames;
1097 caller_audio_frames_expected_ = expected_audio_frames;
1098 }
1099
1100 void CallerExpectsNoAudio() {
1101 caller_audio_expectation_ = kExpectNoFrames;
1102 caller_audio_frames_expected_ = 0;
1103 }
1104
1105 // Caller's video functions.
1106 void CallerExpectsSomeVideo(
1107 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1108 caller_video_expectation_ = kExpectSomeFrames;
1109 caller_video_frames_expected_ = expected_video_frames;
1110 }
1111
1112 void CallerExpectsNoVideo() {
1113 caller_video_expectation_ = kExpectNoFrames;
1114 caller_video_frames_expected_ = 0;
1115 }
1116
1117 // Callee's audio functions.
1118 void CalleeExpectsSomeAudio(
1119 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1120 callee_audio_expectation_ = kExpectSomeFrames;
1121 callee_audio_frames_expected_ = expected_audio_frames;
1122 }
1123
1124 void CalleeExpectsNoAudio() {
1125 callee_audio_expectation_ = kExpectNoFrames;
1126 callee_audio_frames_expected_ = 0;
1127 }
1128
1129 // Callee's video functions.
1130 void CalleeExpectsSomeVideo(
1131 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1132 callee_video_expectation_ = kExpectSomeFrames;
1133 callee_video_frames_expected_ = expected_video_frames;
1134 }
1135
1136 void CalleeExpectsNoVideo() {
1137 callee_video_expectation_ = kExpectNoFrames;
1138 callee_video_frames_expected_ = 0;
1139 }
1140
1141 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1142 ExpectFrames caller_video_expectation_ = kNoExpectation;
1143 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1144 ExpectFrames callee_video_expectation_ = kNoExpectation;
1145 int caller_audio_frames_expected_ = 0;
1146 int caller_video_frames_expected_ = 0;
1147 int callee_audio_frames_expected_ = 0;
1148 int callee_video_frames_expected_ = 0;
1149};
1150
deadbeef1dcb1642017-03-29 21:08:16 -07001151// Tests two PeerConnections connecting to each other end-to-end, using a
1152// virtual network, fake A/V capture and fake encoder/decoders. The
1153// PeerConnections share the threads/socket servers, but use separate versions
1154// of everything else (including "PeerConnectionFactory"s).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001155class PeerConnectionIntegrationBaseTest : public testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001156 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001157 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1158 : sdp_semantics_(sdp_semantics),
1159 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001160 fss_(new rtc::FirewallSocketServer(ss_.get())),
1161 network_thread_(new rtc::Thread(fss_.get())),
deadbeef1dcb1642017-03-29 21:08:16 -07001162 worker_thread_(rtc::Thread::Create()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001163 network_thread_->SetName("PCNetworkThread", this);
1164 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001165 RTC_CHECK(network_thread_->Start());
1166 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001167 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001168 }
1169
Seth Hampson2f0d7022018-02-20 11:54:42 -08001170 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001171 // The PeerConnections should deleted before the TurnCustomizers.
1172 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1173 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1174 // that the TurnCustomizer outlives the life of the PeerConnection or else
1175 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001176 if (caller_) {
1177 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001178 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001179 }
1180 if (callee_) {
1181 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001182 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001183 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001184
1185 // If turn servers were created for the test they need to be destroyed on
1186 // the network thread.
1187 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1188 turn_servers_.clear();
1189 turn_customizers_.clear();
1190 });
deadbeef1dcb1642017-03-29 21:08:16 -07001191 }
1192
1193 bool SignalingStateStable() {
1194 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1195 }
1196
deadbeef71452802017-05-07 17:21:01 -07001197 bool DtlsConnected() {
1198 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1199 // are connected. This is an important distinction. Once we have separate
1200 // ICE and DTLS state, this check needs to use the DTLS state.
1201 return (callee()->ice_connection_state() ==
1202 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1203 callee()->ice_connection_state() ==
1204 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1205 (caller()->ice_connection_state() ==
1206 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1207 caller()->ice_connection_state() ==
1208 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
1209 }
1210
Qingsi Wang7685e862018-06-11 20:15:46 -07001211 // When |event_log_factory| is null, the default implementation of the event
1212 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001213 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1214 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001215 const PeerConnectionFactory::Options* options,
1216 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001217 webrtc::PeerConnectionDependencies dependencies,
1218 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001219 RTCConfiguration modified_config;
1220 if (config) {
1221 modified_config = *config;
1222 }
Steve Anton3acffc32018-04-12 17:21:03 -07001223 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001224 if (!dependencies.cert_generator) {
1225 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001226 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001227 }
1228 std::unique_ptr<PeerConnectionWrapper> client(
1229 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001230
Niels Möllerf06f9232018-08-07 12:32:18 +02001231 if (!client->Init(options, &modified_config, std::move(dependencies),
1232 network_thread_.get(), worker_thread_.get(),
1233 std::move(event_log_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001234 return nullptr;
1235 }
1236 return client;
1237 }
1238
Qingsi Wang7685e862018-06-11 20:15:46 -07001239 std::unique_ptr<PeerConnectionWrapper>
1240 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1241 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001242 const PeerConnectionFactory::Options* options,
1243 const RTCConfiguration* config,
1244 webrtc::PeerConnectionDependencies dependencies) {
1245 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1246 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001247 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001248 std::move(dependencies),
1249 std::move(event_log_factory));
1250 }
1251
deadbeef1dcb1642017-03-29 21:08:16 -07001252 bool CreatePeerConnectionWrappers() {
1253 return CreatePeerConnectionWrappersWithConfig(
1254 PeerConnectionInterface::RTCConfiguration(),
1255 PeerConnectionInterface::RTCConfiguration());
1256 }
1257
Steve Anton3acffc32018-04-12 17:21:03 -07001258 bool CreatePeerConnectionWrappersWithSdpSemantics(
1259 SdpSemantics caller_semantics,
1260 SdpSemantics callee_semantics) {
1261 // Can't specify the sdp_semantics in the passed-in configuration since it
1262 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1263 // stored in sdp_semantics_. So get around this by modifying the instance
1264 // variable before calling CreatePeerConnectionWrapper for the caller and
1265 // callee PeerConnections.
1266 SdpSemantics original_semantics = sdp_semantics_;
1267 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001268 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001269 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1270 nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001271 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001272 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001273 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1274 nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001275 sdp_semantics_ = original_semantics;
1276 return caller_ && callee_;
1277 }
1278
deadbeef1dcb1642017-03-29 21:08:16 -07001279 bool CreatePeerConnectionWrappersWithConfig(
1280 const PeerConnectionInterface::RTCConfiguration& caller_config,
1281 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001282 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001283 "Caller", nullptr, &caller_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001284 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001285 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001286 "Callee", nullptr, &callee_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001287 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001288 return caller_ && callee_;
1289 }
1290
1291 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1292 const PeerConnectionInterface::RTCConfiguration& caller_config,
1293 webrtc::PeerConnectionDependencies caller_dependencies,
1294 const PeerConnectionInterface::RTCConfiguration& callee_config,
1295 webrtc::PeerConnectionDependencies callee_dependencies) {
1296 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001297 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001298 std::move(caller_dependencies), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001299 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001300 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001301 std::move(callee_dependencies), nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001302 return caller_ && callee_;
1303 }
1304
1305 bool CreatePeerConnectionWrappersWithOptions(
1306 const PeerConnectionFactory::Options& caller_options,
1307 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001308 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001309 "Caller", &caller_options, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001310 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001311 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001312 "Callee", &callee_options, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001313 webrtc::PeerConnectionDependencies(nullptr), nullptr);
1314 return caller_ && callee_;
1315 }
1316
1317 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1318 PeerConnectionInterface::RTCConfiguration default_config;
1319 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001320 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001321 webrtc::PeerConnectionDependencies(nullptr));
1322 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001323 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001324 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001325 return caller_ && callee_;
1326 }
1327
Seth Hampson2f0d7022018-02-20 11:54:42 -08001328 std::unique_ptr<PeerConnectionWrapper>
1329 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001330 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1331 new FakeRTCCertificateGenerator());
1332 cert_generator->use_alternate_key();
1333
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001334 webrtc::PeerConnectionDependencies dependencies(nullptr);
1335 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001336 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001337 std::move(dependencies), nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001338 }
1339
Seth Hampsonaed71642018-06-11 07:41:32 -07001340 cricket::TestTurnServer* CreateTurnServer(
1341 rtc::SocketAddress internal_address,
1342 rtc::SocketAddress external_address,
1343 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1344 const std::string& common_name = "test turn server") {
1345 rtc::Thread* thread = network_thread();
1346 std::unique_ptr<cricket::TestTurnServer> turn_server =
1347 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1348 RTC_FROM_HERE,
1349 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001350 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001351 thread, internal_address, external_address, type,
1352 /*ignore_bad_certs=*/true, common_name);
1353 });
1354 turn_servers_.push_back(std::move(turn_server));
1355 // Interactions with the turn server should be done on the network thread.
1356 return turn_servers_.back().get();
1357 }
1358
1359 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1360 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1361 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1362 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001363 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001364 turn_customizers_.push_back(std::move(turn_customizer));
1365 // Interactions with the turn customizer should be done on the network
1366 // thread.
1367 return turn_customizers_.back().get();
1368 }
1369
1370 // Checks that the function counters for a TestTurnCustomizer are greater than
1371 // 0.
1372 void ExpectTurnCustomizerCountersIncremented(
1373 cricket::TestTurnCustomizer* turn_customizer) {
1374 unsigned int allow_channel_data_counter =
1375 network_thread()->Invoke<unsigned int>(
1376 RTC_FROM_HERE, [turn_customizer] {
1377 return turn_customizer->allow_channel_data_cnt_;
1378 });
1379 EXPECT_GT(allow_channel_data_counter, 0u);
1380 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1381 RTC_FROM_HERE,
1382 [turn_customizer] { return turn_customizer->modify_cnt_; });
1383 EXPECT_GT(modify_counter, 0u);
1384 }
1385
deadbeef1dcb1642017-03-29 21:08:16 -07001386 // Once called, SDP blobs and ICE candidates will be automatically signaled
1387 // between PeerConnections.
1388 void ConnectFakeSignaling() {
1389 caller_->set_signaling_message_receiver(callee_.get());
1390 callee_->set_signaling_message_receiver(caller_.get());
1391 }
1392
Steve Antonede9ca52017-10-16 13:04:27 -07001393 // Once called, SDP blobs will be automatically signaled between
1394 // PeerConnections. Note that ICE candidates will not be signaled unless they
1395 // are in the exchanged SDP blobs.
1396 void ConnectFakeSignalingForSdpOnly() {
1397 ConnectFakeSignaling();
1398 SetSignalIceCandidates(false);
1399 }
1400
deadbeef1dcb1642017-03-29 21:08:16 -07001401 void SetSignalingDelayMs(int delay_ms) {
1402 caller_->set_signaling_delay_ms(delay_ms);
1403 callee_->set_signaling_delay_ms(delay_ms);
1404 }
1405
Steve Antonede9ca52017-10-16 13:04:27 -07001406 void SetSignalIceCandidates(bool signal) {
1407 caller_->set_signal_ice_candidates(signal);
1408 callee_->set_signal_ice_candidates(signal);
1409 }
1410
deadbeef1dcb1642017-03-29 21:08:16 -07001411 // Messages may get lost on the unreliable DataChannel, so we send multiple
1412 // times to avoid test flakiness.
1413 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1414 const std::string& data,
1415 int retries) {
1416 for (int i = 0; i < retries; ++i) {
1417 dc->Send(DataBuffer(data));
1418 }
1419 }
1420
1421 rtc::Thread* network_thread() { return network_thread_.get(); }
1422
1423 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1424
1425 PeerConnectionWrapper* caller() { return caller_.get(); }
1426
1427 // Set the |caller_| to the |wrapper| passed in and return the
1428 // original |caller_|.
1429 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1430 PeerConnectionWrapper* wrapper) {
1431 PeerConnectionWrapper* old = caller_.release();
1432 caller_.reset(wrapper);
1433 return old;
1434 }
1435
1436 PeerConnectionWrapper* callee() { return callee_.get(); }
1437
1438 // Set the |callee_| to the |wrapper| passed in and return the
1439 // original |callee_|.
1440 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1441 PeerConnectionWrapper* wrapper) {
1442 PeerConnectionWrapper* old = callee_.release();
1443 callee_.reset(wrapper);
1444 return old;
1445 }
1446
Steve Antonede9ca52017-10-16 13:04:27 -07001447 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1448
Seth Hampson2f0d7022018-02-20 11:54:42 -08001449 // Expects the provided number of new frames to be received within
1450 // kMaxWaitForFramesMs. The new expected frames are specified in
1451 // |media_expectations|. Returns false if any of the expectations were
1452 // not met.
1453 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1454 // First initialize the expected frame counts based upon the current
1455 // frame count.
1456 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1457 if (media_expectations.caller_audio_expectation_ ==
1458 MediaExpectations::kExpectSomeFrames) {
1459 total_caller_audio_frames_expected +=
1460 media_expectations.caller_audio_frames_expected_;
1461 }
1462 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001463 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001464 if (media_expectations.caller_video_expectation_ ==
1465 MediaExpectations::kExpectSomeFrames) {
1466 total_caller_video_frames_expected +=
1467 media_expectations.caller_video_frames_expected_;
1468 }
1469 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1470 if (media_expectations.callee_audio_expectation_ ==
1471 MediaExpectations::kExpectSomeFrames) {
1472 total_callee_audio_frames_expected +=
1473 media_expectations.callee_audio_frames_expected_;
1474 }
1475 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001476 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001477 if (media_expectations.callee_video_expectation_ ==
1478 MediaExpectations::kExpectSomeFrames) {
1479 total_callee_video_frames_expected +=
1480 media_expectations.callee_video_frames_expected_;
1481 }
deadbeef1dcb1642017-03-29 21:08:16 -07001482
Seth Hampson2f0d7022018-02-20 11:54:42 -08001483 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001484 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001485 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001486 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001487 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001488 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001489 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001490 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001491 total_callee_video_frames_expected,
1492 kMaxWaitForFramesMs);
1493 bool expectations_correct =
1494 caller()->audio_frames_received() >=
1495 total_caller_audio_frames_expected &&
1496 caller()->min_video_frames_received_per_track() >=
1497 total_caller_video_frames_expected &&
1498 callee()->audio_frames_received() >=
1499 total_callee_audio_frames_expected &&
1500 callee()->min_video_frames_received_per_track() >=
1501 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001502
Seth Hampson2f0d7022018-02-20 11:54:42 -08001503 // After the combined wait, print out a more detailed message upon
1504 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001505 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001506 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001507 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001508 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001509 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001510 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001511 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001512 total_callee_video_frames_expected);
1513
1514 // We want to make sure nothing unexpected was received.
1515 if (media_expectations.caller_audio_expectation_ ==
1516 MediaExpectations::kExpectNoFrames) {
1517 EXPECT_EQ(caller()->audio_frames_received(),
1518 total_caller_audio_frames_expected);
1519 if (caller()->audio_frames_received() !=
1520 total_caller_audio_frames_expected) {
1521 expectations_correct = false;
1522 }
1523 }
1524 if (media_expectations.caller_video_expectation_ ==
1525 MediaExpectations::kExpectNoFrames) {
1526 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1527 total_caller_video_frames_expected);
1528 if (caller()->min_video_frames_received_per_track() !=
1529 total_caller_video_frames_expected) {
1530 expectations_correct = false;
1531 }
1532 }
1533 if (media_expectations.callee_audio_expectation_ ==
1534 MediaExpectations::kExpectNoFrames) {
1535 EXPECT_EQ(callee()->audio_frames_received(),
1536 total_callee_audio_frames_expected);
1537 if (callee()->audio_frames_received() !=
1538 total_callee_audio_frames_expected) {
1539 expectations_correct = false;
1540 }
1541 }
1542 if (media_expectations.callee_video_expectation_ ==
1543 MediaExpectations::kExpectNoFrames) {
1544 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1545 total_callee_video_frames_expected);
1546 if (callee()->min_video_frames_received_per_track() !=
1547 total_callee_video_frames_expected) {
1548 expectations_correct = false;
1549 }
1550 }
1551 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001552 }
1553
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001554 void TestNegotiatedCipherSuite(
1555 const PeerConnectionFactory::Options& caller_options,
1556 const PeerConnectionFactory::Options& callee_options,
1557 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001558 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1559 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001560 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001561 caller()->AddAudioVideoTracks();
1562 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001563 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001564 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001565 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001566 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001567 // TODO(bugs.webrtc.org/9456): Fix it.
1568 EXPECT_EQ(1, webrtc::metrics::NumEvents(
1569 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1570 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001571 }
1572
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001573 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1574 bool remote_gcm_enabled,
1575 int expected_cipher_suite) {
1576 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001577 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1578 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001579 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001580 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1581 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001582 TestNegotiatedCipherSuite(caller_options, callee_options,
1583 expected_cipher_suite);
1584 }
1585
Seth Hampson2f0d7022018-02-20 11:54:42 -08001586 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001587 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001588
deadbeef1dcb1642017-03-29 21:08:16 -07001589 private:
1590 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001591 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001592 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001593 // |network_thread_| and |worker_thread_| are used by both
1594 // |caller_| and |callee_| so they must be destroyed
1595 // later.
1596 std::unique_ptr<rtc::Thread> network_thread_;
1597 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001598 // The turn servers and turn customizers should be accessed & deleted on the
1599 // network thread to avoid a race with the socket read/write that occurs
1600 // on the network thread.
1601 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1602 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001603 std::unique_ptr<PeerConnectionWrapper> caller_;
1604 std::unique_ptr<PeerConnectionWrapper> callee_;
1605};
1606
Seth Hampson2f0d7022018-02-20 11:54:42 -08001607class PeerConnectionIntegrationTest
1608 : public PeerConnectionIntegrationBaseTest,
1609 public ::testing::WithParamInterface<SdpSemantics> {
1610 protected:
1611 PeerConnectionIntegrationTest()
1612 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1613};
1614
1615class PeerConnectionIntegrationTestPlanB
1616 : public PeerConnectionIntegrationBaseTest {
1617 protected:
1618 PeerConnectionIntegrationTestPlanB()
1619 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1620};
1621
1622class PeerConnectionIntegrationTestUnifiedPlan
1623 : public PeerConnectionIntegrationBaseTest {
1624 protected:
1625 PeerConnectionIntegrationTestUnifiedPlan()
1626 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1627};
1628
deadbeef1dcb1642017-03-29 21:08:16 -07001629// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1630// includes testing that the callback is invoked if an observer is connected
1631// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001632TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001633 RtpReceiverObserverOnFirstPacketReceived) {
1634 ASSERT_TRUE(CreatePeerConnectionWrappers());
1635 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001636 caller()->AddAudioVideoTracks();
1637 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001638 // Start offer/answer exchange and wait for it to complete.
1639 caller()->CreateAndSetAndSignalOffer();
1640 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1641 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001642 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1643 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001644 // Wait for all "first packet received" callbacks to be fired.
1645 EXPECT_TRUE_WAIT(
1646 std::all_of(caller()->rtp_receiver_observers().begin(),
1647 caller()->rtp_receiver_observers().end(),
1648 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1649 return o->first_packet_received();
1650 }),
1651 kMaxWaitForFramesMs);
1652 EXPECT_TRUE_WAIT(
1653 std::all_of(callee()->rtp_receiver_observers().begin(),
1654 callee()->rtp_receiver_observers().end(),
1655 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1656 return o->first_packet_received();
1657 }),
1658 kMaxWaitForFramesMs);
1659 // If new observers are set after the first packet was already received, the
1660 // callback should still be invoked.
1661 caller()->ResetRtpReceiverObservers();
1662 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001663 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1664 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001665 EXPECT_TRUE(
1666 std::all_of(caller()->rtp_receiver_observers().begin(),
1667 caller()->rtp_receiver_observers().end(),
1668 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1669 return o->first_packet_received();
1670 }));
1671 EXPECT_TRUE(
1672 std::all_of(callee()->rtp_receiver_observers().begin(),
1673 callee()->rtp_receiver_observers().end(),
1674 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1675 return o->first_packet_received();
1676 }));
1677}
1678
1679class DummyDtmfObserver : public DtmfSenderObserverInterface {
1680 public:
1681 DummyDtmfObserver() : completed_(false) {}
1682
1683 // Implements DtmfSenderObserverInterface.
1684 void OnToneChange(const std::string& tone) override {
1685 tones_.push_back(tone);
1686 if (tone.empty()) {
1687 completed_ = true;
1688 }
1689 }
1690
1691 const std::vector<std::string>& tones() const { return tones_; }
1692 bool completed() const { return completed_; }
1693
1694 private:
1695 bool completed_;
1696 std::vector<std::string> tones_;
1697};
1698
1699// Assumes |sender| already has an audio track added and the offer/answer
1700// exchange is done.
1701void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1702 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001703 // We should be able to get a DTMF sender from the local sender.
1704 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1705 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1706 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001707 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001708 dtmf_sender->RegisterObserver(&observer);
1709
1710 // Test the DtmfSender object just created.
1711 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1712 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1713
1714 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1715 std::vector<std::string> tones = {"1", "a", ""};
1716 EXPECT_EQ(tones, observer.tones());
1717 dtmf_sender->UnregisterObserver();
1718 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1719}
1720
1721// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1722// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001723TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001724 ASSERT_TRUE(CreatePeerConnectionWrappers());
1725 ConnectFakeSignaling();
1726 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001727 caller()->AddAudioTrack();
1728 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001729 caller()->CreateAndSetAndSignalOffer();
1730 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001731 // DTLS must finish before the DTMF sender can be used reliably.
1732 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001733 TestDtmfFromSenderToReceiver(caller(), callee());
1734 TestDtmfFromSenderToReceiver(callee(), caller());
1735}
1736
1737// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1738// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001739TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001740 ASSERT_TRUE(CreatePeerConnectionWrappers());
1741 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001742
deadbeef1dcb1642017-03-29 21:08:16 -07001743 // Do normal offer/answer and wait for some frames to be received in each
1744 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001745 caller()->AddAudioVideoTracks();
1746 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001747 caller()->CreateAndSetAndSignalOffer();
1748 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001749 MediaExpectations media_expectations;
1750 media_expectations.ExpectBidirectionalAudioAndVideo();
1751 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001752 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1753 webrtc::kEnumCounterKeyProtocolDtls));
1754 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1755 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001756}
1757
1758// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001759TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001760 PeerConnectionInterface::RTCConfiguration sdes_config;
1761 sdes_config.enable_dtls_srtp.emplace(false);
1762 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1763 ConnectFakeSignaling();
1764
1765 // Do normal offer/answer and wait for some frames to be received in each
1766 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001767 caller()->AddAudioVideoTracks();
1768 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001769 caller()->CreateAndSetAndSignalOffer();
1770 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001771 MediaExpectations media_expectations;
1772 media_expectations.ExpectBidirectionalAudioAndVideo();
1773 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001774 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1775 webrtc::kEnumCounterKeyProtocolSdes));
1776 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1777 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001778}
1779
Steve Anton8c0f7a72017-10-03 10:03:10 -07001780// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1781// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001782TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001783 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1784 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1785 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1786 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1787 return pc->GetRemoteAudioSSLCertificate();
1788 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001789 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1790 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1791 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1792 return pc->GetRemoteAudioSSLCertChain();
1793 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001794
1795 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1796 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1797
1798 // Configure each side with a known certificate so they can be compared later.
1799 PeerConnectionInterface::RTCConfiguration caller_config;
1800 caller_config.enable_dtls_srtp.emplace(true);
1801 caller_config.certificates.push_back(caller_cert);
1802 PeerConnectionInterface::RTCConfiguration callee_config;
1803 callee_config.enable_dtls_srtp.emplace(true);
1804 callee_config.certificates.push_back(callee_cert);
1805 ASSERT_TRUE(
1806 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1807 ConnectFakeSignaling();
1808
1809 // When first initialized, there should not be a remote SSL certificate (and
1810 // calling this method should not crash).
1811 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1812 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001813 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1814 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001815
Steve Anton15324772018-01-16 10:26:49 -08001816 caller()->AddAudioTrack();
1817 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001818 caller()->CreateAndSetAndSignalOffer();
1819 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1820 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1821
1822 // Once DTLS has been connected, each side should return the other's SSL
1823 // certificate when calling GetRemoteAudioSSLCertificate.
1824
1825 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1826 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001827 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001828 caller_remote_cert->ToPEMString());
1829
1830 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1831 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001832 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001833 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001834
1835 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1836 ASSERT_TRUE(caller_remote_cert_chain);
1837 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1838 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001839 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001840 remote_cert->ToPEMString());
1841
1842 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1843 ASSERT_TRUE(callee_remote_cert_chain);
1844 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1845 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001846 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001847 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001848}
1849
deadbeef1dcb1642017-03-29 21:08:16 -07001850// This test sets up a call between two parties with a source resolution of
1851// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001852TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001853 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1854 ASSERT_TRUE(CreatePeerConnectionWrappers());
1855 ConnectFakeSignaling();
1856
Niels Möller5c7efe72018-05-11 10:34:46 +02001857 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1858 webrtc::FakePeriodicVideoSource::Config config;
1859 config.width = 1280;
1860 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001861 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001862 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1863 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001864
1865 // Do normal offer/answer and wait for at least one frame to be received in
1866 // each direction.
1867 caller()->CreateAndSetAndSignalOffer();
1868 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1869 callee()->min_video_frames_received_per_track() > 0,
1870 kMaxWaitForFramesMs);
1871
1872 // Check rendered aspect ratio.
1873 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1874 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1875 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1876 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1877}
1878
1879// This test sets up an one-way call, with media only from caller to
1880// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001881TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001882 ASSERT_TRUE(CreatePeerConnectionWrappers());
1883 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001884 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001885 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001886 MediaExpectations media_expectations;
1887 media_expectations.CalleeExpectsSomeAudioAndVideo();
1888 media_expectations.CallerExpectsNoAudio();
1889 media_expectations.CallerExpectsNoVideo();
1890 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001891}
1892
1893// This test sets up a audio call initially, with the callee rejecting video
1894// initially. Then later the callee decides to upgrade to audio/video, and
1895// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001896TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001897 ASSERT_TRUE(CreatePeerConnectionWrappers());
1898 ConnectFakeSignaling();
1899 // Initially, offer an audio/video stream from the caller, but refuse to
1900 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001901 caller()->AddAudioVideoTracks();
1902 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001903 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1904 PeerConnectionInterface::RTCOfferAnswerOptions options;
1905 options.offer_to_receive_video = 0;
1906 callee()->SetOfferAnswerOptions(options);
1907 } else {
1908 callee()->SetRemoteOfferHandler([this] {
1909 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1910 });
1911 }
deadbeef1dcb1642017-03-29 21:08:16 -07001912 // Do offer/answer and make sure audio is still received end-to-end.
1913 caller()->CreateAndSetAndSignalOffer();
1914 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001915 {
1916 MediaExpectations media_expectations;
1917 media_expectations.ExpectBidirectionalAudio();
1918 media_expectations.ExpectNoVideo();
1919 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1920 }
deadbeef1dcb1642017-03-29 21:08:16 -07001921 // Sanity check that the callee's description has a rejected video section.
1922 ASSERT_NE(nullptr, callee()->pc()->local_description());
1923 const ContentInfo* callee_video_content =
1924 GetFirstVideoContent(callee()->pc()->local_description()->description());
1925 ASSERT_NE(nullptr, callee_video_content);
1926 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001927
deadbeef1dcb1642017-03-29 21:08:16 -07001928 // Now negotiate with video and ensure negotiation succeeds, with video
1929 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001930 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001931 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1932 PeerConnectionInterface::RTCOfferAnswerOptions options;
1933 options.offer_to_receive_video = 1;
1934 callee()->SetOfferAnswerOptions(options);
1935 } else {
1936 callee()->SetRemoteOfferHandler(nullptr);
1937 caller()->SetRemoteOfferHandler([this] {
1938 // The caller creates a new transceiver to receive video on when receiving
1939 // the offer, but by default it is send only.
1940 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001941 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001942 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1943 transceivers[2]->receiver()->media_type());
1944 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1945 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1946 });
1947 }
deadbeef1dcb1642017-03-29 21:08:16 -07001948 callee()->CreateAndSetAndSignalOffer();
1949 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001950 {
1951 // Expect additional audio frames to be received after the upgrade.
1952 MediaExpectations media_expectations;
1953 media_expectations.ExpectBidirectionalAudioAndVideo();
1954 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1955 }
deadbeef1dcb1642017-03-29 21:08:16 -07001956}
1957
deadbeef4389b4d2017-09-07 09:07:36 -07001958// Simpler than the above test; just add an audio track to an established
1959// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001960TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07001961 ASSERT_TRUE(CreatePeerConnectionWrappers());
1962 ConnectFakeSignaling();
1963 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08001964 caller()->AddVideoTrack();
1965 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001966 caller()->CreateAndSetAndSignalOffer();
1967 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1968 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08001969 caller()->AddAudioTrack();
1970 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001971 caller()->CreateAndSetAndSignalOffer();
1972 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1973 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001974 MediaExpectations media_expectations;
1975 media_expectations.ExpectBidirectionalAudioAndVideo();
1976 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07001977}
1978
deadbeef1dcb1642017-03-29 21:08:16 -07001979// This test sets up a call that's transferred to a new caller with a different
1980// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001981TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07001982 ASSERT_TRUE(CreatePeerConnectionWrappers());
1983 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001984 caller()->AddAudioVideoTracks();
1985 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001986 caller()->CreateAndSetAndSignalOffer();
1987 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1988
1989 // Keep the original peer around which will still send packets to the
1990 // receiving client. These SRTP packets will be dropped.
1991 std::unique_ptr<PeerConnectionWrapper> original_peer(
1992 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08001993 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07001994 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1995 // directly above.
1996 original_peer->pc()->Close();
1997
1998 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001999 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002000 caller()->CreateAndSetAndSignalOffer();
2001 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2002 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002003 MediaExpectations media_expectations;
2004 media_expectations.ExpectBidirectionalAudioAndVideo();
2005 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002006}
2007
2008// This test sets up a call that's transferred to a new callee with a different
2009// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002010TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002011 ASSERT_TRUE(CreatePeerConnectionWrappers());
2012 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002013 caller()->AddAudioVideoTracks();
2014 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002015 caller()->CreateAndSetAndSignalOffer();
2016 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2017
2018 // Keep the original peer around which will still send packets to the
2019 // receiving client. These SRTP packets will be dropped.
2020 std::unique_ptr<PeerConnectionWrapper> original_peer(
2021 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002022 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002023 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2024 // directly above.
2025 original_peer->pc()->Close();
2026
2027 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002028 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002029 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2030 caller()->CreateAndSetAndSignalOffer();
2031 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2032 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002033 MediaExpectations media_expectations;
2034 media_expectations.ExpectBidirectionalAudioAndVideo();
2035 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002036}
2037
2038// This test sets up a non-bundled call and negotiates bundling at the same
2039// time as starting an ICE restart. When bundling is in effect in the restart,
2040// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002041TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002042 ASSERT_TRUE(CreatePeerConnectionWrappers());
2043 ConnectFakeSignaling();
2044
Steve Anton15324772018-01-16 10:26:49 -08002045 caller()->AddAudioVideoTracks();
2046 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002047 // Remove the bundle group from the SDP received by the callee.
2048 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2049 desc->RemoveGroupByName("BUNDLE");
2050 });
2051 caller()->CreateAndSetAndSignalOffer();
2052 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002053 {
2054 MediaExpectations media_expectations;
2055 media_expectations.ExpectBidirectionalAudioAndVideo();
2056 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2057 }
deadbeef1dcb1642017-03-29 21:08:16 -07002058 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2059 callee()->SetReceivedSdpMunger(nullptr);
2060 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2061 caller()->CreateAndSetAndSignalOffer();
2062 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2063
2064 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002065 {
2066 MediaExpectations media_expectations;
2067 media_expectations.ExpectBidirectionalAudioAndVideo();
2068 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2069 }
deadbeef1dcb1642017-03-29 21:08:16 -07002070}
2071
2072// Test CVO (Coordination of Video Orientation). If a video source is rotated
2073// and both peers support the CVO RTP header extension, the actual video frames
2074// don't need to be encoded in different resolutions, since the rotation is
2075// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002076TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002077 ASSERT_TRUE(CreatePeerConnectionWrappers());
2078 ConnectFakeSignaling();
2079 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002080 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002081 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002082 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002083 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2084
2085 // Wait for video frames to be received by both sides.
2086 caller()->CreateAndSetAndSignalOffer();
2087 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2088 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2089 callee()->min_video_frames_received_per_track() > 0,
2090 kMaxWaitForFramesMs);
2091
2092 // Ensure that the aspect ratio is unmodified.
2093 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2094 // not just assumed.
2095 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2096 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2097 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2098 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2099 // Ensure that the CVO bits were surfaced to the renderer.
2100 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2101 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2102}
2103
2104// Test that when the CVO extension isn't supported, video is rotated the
2105// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002106TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002107 ASSERT_TRUE(CreatePeerConnectionWrappers());
2108 ConnectFakeSignaling();
2109 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002110 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002111 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002112 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002113 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2114
2115 // Remove the CVO extension from the offered SDP.
2116 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2117 cricket::VideoContentDescription* video =
2118 GetFirstVideoContentDescription(desc);
2119 video->ClearRtpHeaderExtensions();
2120 });
2121 // Wait for video frames to be received by both sides.
2122 caller()->CreateAndSetAndSignalOffer();
2123 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2124 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2125 callee()->min_video_frames_received_per_track() > 0,
2126 kMaxWaitForFramesMs);
2127
2128 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2129 // rotation.
2130 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2131 // not just assumed.
2132 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2133 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2134 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2135 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2136 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2137 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2138 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2139}
2140
deadbeef1dcb1642017-03-29 21:08:16 -07002141// Test that if the answerer rejects the audio m= section, no audio is sent or
2142// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002143TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002144 ASSERT_TRUE(CreatePeerConnectionWrappers());
2145 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002146 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002147 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2148 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2149 // it will reject the audio m= section completely.
2150 PeerConnectionInterface::RTCOfferAnswerOptions options;
2151 options.offer_to_receive_audio = 0;
2152 callee()->SetOfferAnswerOptions(options);
2153 } else {
2154 // Stopping the audio RtpTransceiver will cause the media section to be
2155 // rejected in the answer.
2156 callee()->SetRemoteOfferHandler([this] {
2157 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2158 });
2159 }
Steve Anton15324772018-01-16 10:26:49 -08002160 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002161 // Do offer/answer and wait for successful end-to-end video frames.
2162 caller()->CreateAndSetAndSignalOffer();
2163 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002164 MediaExpectations media_expectations;
2165 media_expectations.ExpectBidirectionalVideo();
2166 media_expectations.ExpectNoAudio();
2167 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2168
deadbeef1dcb1642017-03-29 21:08:16 -07002169 // Sanity check that the callee's description has a rejected audio section.
2170 ASSERT_NE(nullptr, callee()->pc()->local_description());
2171 const ContentInfo* callee_audio_content =
2172 GetFirstAudioContent(callee()->pc()->local_description()->description());
2173 ASSERT_NE(nullptr, callee_audio_content);
2174 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002175 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2176 // The caller's transceiver should have stopped after receiving the answer.
2177 EXPECT_TRUE(caller()
2178 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2179 ->stopped());
2180 }
deadbeef1dcb1642017-03-29 21:08:16 -07002181}
2182
2183// Test that if the answerer rejects the video m= section, no video is sent or
2184// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002185TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002186 ASSERT_TRUE(CreatePeerConnectionWrappers());
2187 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002188 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002189 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2190 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2191 // it will reject the video m= section completely.
2192 PeerConnectionInterface::RTCOfferAnswerOptions options;
2193 options.offer_to_receive_video = 0;
2194 callee()->SetOfferAnswerOptions(options);
2195 } else {
2196 // Stopping the video RtpTransceiver will cause the media section to be
2197 // rejected in the answer.
2198 callee()->SetRemoteOfferHandler([this] {
2199 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2200 });
2201 }
Steve Anton15324772018-01-16 10:26:49 -08002202 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002203 // Do offer/answer and wait for successful end-to-end audio frames.
2204 caller()->CreateAndSetAndSignalOffer();
2205 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002206 MediaExpectations media_expectations;
2207 media_expectations.ExpectBidirectionalAudio();
2208 media_expectations.ExpectNoVideo();
2209 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2210
deadbeef1dcb1642017-03-29 21:08:16 -07002211 // Sanity check that the callee's description has a rejected video section.
2212 ASSERT_NE(nullptr, callee()->pc()->local_description());
2213 const ContentInfo* callee_video_content =
2214 GetFirstVideoContent(callee()->pc()->local_description()->description());
2215 ASSERT_NE(nullptr, callee_video_content);
2216 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002217 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2218 // The caller's transceiver should have stopped after receiving the answer.
2219 EXPECT_TRUE(caller()
2220 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2221 ->stopped());
2222 }
deadbeef1dcb1642017-03-29 21:08:16 -07002223}
2224
2225// Test that if the answerer rejects both audio and video m= sections, nothing
2226// bad happens.
2227// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2228// test anything but the fact that negotiation succeeds, which doesn't mean
2229// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002230TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002231 ASSERT_TRUE(CreatePeerConnectionWrappers());
2232 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002233 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002234 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2235 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2236 // will reject both audio and video m= sections.
2237 PeerConnectionInterface::RTCOfferAnswerOptions options;
2238 options.offer_to_receive_audio = 0;
2239 options.offer_to_receive_video = 0;
2240 callee()->SetOfferAnswerOptions(options);
2241 } else {
2242 callee()->SetRemoteOfferHandler([this] {
2243 // Stopping all transceivers will cause all media sections to be rejected.
2244 for (auto transceiver : callee()->pc()->GetTransceivers()) {
2245 transceiver->Stop();
2246 }
2247 });
2248 }
deadbeef1dcb1642017-03-29 21:08:16 -07002249 // Do offer/answer and wait for stable signaling state.
2250 caller()->CreateAndSetAndSignalOffer();
2251 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002252
deadbeef1dcb1642017-03-29 21:08:16 -07002253 // Sanity check that the callee's description has rejected m= sections.
2254 ASSERT_NE(nullptr, callee()->pc()->local_description());
2255 const ContentInfo* callee_audio_content =
2256 GetFirstAudioContent(callee()->pc()->local_description()->description());
2257 ASSERT_NE(nullptr, callee_audio_content);
2258 EXPECT_TRUE(callee_audio_content->rejected);
2259 const ContentInfo* callee_video_content =
2260 GetFirstVideoContent(callee()->pc()->local_description()->description());
2261 ASSERT_NE(nullptr, callee_video_content);
2262 EXPECT_TRUE(callee_video_content->rejected);
2263}
2264
2265// This test sets up an audio and video call between two parties. After the
2266// call runs for a while, the caller sends an updated offer with video being
2267// rejected. Once the re-negotiation is done, the video flow should stop and
2268// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002269TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002270 ASSERT_TRUE(CreatePeerConnectionWrappers());
2271 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002272 caller()->AddAudioVideoTracks();
2273 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002274 caller()->CreateAndSetAndSignalOffer();
2275 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002276 {
2277 MediaExpectations media_expectations;
2278 media_expectations.ExpectBidirectionalAudioAndVideo();
2279 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2280 }
deadbeef1dcb1642017-03-29 21:08:16 -07002281 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002282 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2283 caller()->SetGeneratedSdpMunger(
2284 [](cricket::SessionDescription* description) {
2285 for (cricket::ContentInfo& content : description->contents()) {
2286 if (cricket::IsVideoContent(&content)) {
2287 content.rejected = true;
2288 }
2289 }
2290 });
2291 } else {
2292 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2293 }
deadbeef1dcb1642017-03-29 21:08:16 -07002294 caller()->CreateAndSetAndSignalOffer();
2295 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2296
2297 // Sanity check that the caller's description has a rejected video section.
2298 ASSERT_NE(nullptr, caller()->pc()->local_description());
2299 const ContentInfo* caller_video_content =
2300 GetFirstVideoContent(caller()->pc()->local_description()->description());
2301 ASSERT_NE(nullptr, caller_video_content);
2302 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002303 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002304 {
2305 MediaExpectations media_expectations;
2306 media_expectations.ExpectBidirectionalAudio();
2307 media_expectations.ExpectNoVideo();
2308 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2309 }
deadbeef1dcb1642017-03-29 21:08:16 -07002310}
2311
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002312// Do one offer/answer with audio, another that disables it (rejecting the m=
2313// section), and another that re-enables it. Regression test for:
2314// bugs.webrtc.org/6023
2315TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2316 ASSERT_TRUE(CreatePeerConnectionWrappers());
2317 ConnectFakeSignaling();
2318
2319 // Add audio track, do normal offer/answer.
2320 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2321 caller()->CreateLocalAudioTrack();
2322 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2323 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2324 caller()->CreateAndSetAndSignalOffer();
2325 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2326
2327 // Remove audio track, and set offer_to_receive_audio to false to cause the
2328 // m= section to be completely disabled, not just "recvonly".
2329 caller()->pc()->RemoveTrack(sender);
2330 PeerConnectionInterface::RTCOfferAnswerOptions options;
2331 options.offer_to_receive_audio = 0;
2332 caller()->SetOfferAnswerOptions(options);
2333 caller()->CreateAndSetAndSignalOffer();
2334 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2335
2336 // Add the audio track again, expecting negotiation to succeed and frames to
2337 // flow.
2338 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2339 options.offer_to_receive_audio = 1;
2340 caller()->SetOfferAnswerOptions(options);
2341 caller()->CreateAndSetAndSignalOffer();
2342 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2343
2344 MediaExpectations media_expectations;
2345 media_expectations.CalleeExpectsSomeAudio();
2346 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2347}
2348
deadbeef1dcb1642017-03-29 21:08:16 -07002349// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2350// is needed to support legacy endpoints.
2351// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2352// add a test for an end-to-end test without MID signaling either (basically,
2353// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002354TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002355 ASSERT_TRUE(CreatePeerConnectionWrappers());
2356 ConnectFakeSignaling();
2357 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002358 caller()->AddAudioVideoTracks();
2359 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002360 // Remove SSRCs and MSIDs from the received offer SDP.
2361 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002362 caller()->CreateAndSetAndSignalOffer();
2363 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002364 MediaExpectations media_expectations;
2365 media_expectations.ExpectBidirectionalAudioAndVideo();
2366 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002367}
2368
Seth Hampson5897a6e2018-04-03 11:16:33 -07002369// Basic end-to-end test, without SSRC signaling. This means that the track
2370// was created properly and frames are delivered when the MSIDs are communicated
2371// with a=msid lines and no a=ssrc lines.
2372TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2373 EndToEndCallWithoutSsrcSignaling) {
2374 const char kStreamId[] = "streamId";
2375 ASSERT_TRUE(CreatePeerConnectionWrappers());
2376 ConnectFakeSignaling();
2377 // Add just audio tracks.
2378 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2379 callee()->AddAudioTrack();
2380
2381 // Remove SSRCs from the received offer SDP.
2382 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2383 caller()->CreateAndSetAndSignalOffer();
2384 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2385 MediaExpectations media_expectations;
2386 media_expectations.ExpectBidirectionalAudio();
2387 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2388}
2389
Steve Antondf527fd2018-04-27 15:52:03 -07002390// Tests that video flows between multiple video tracks when SSRCs are not
2391// signaled. This exercises the MID RTP header extension which is needed to
2392// demux the incoming video tracks.
2393TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2394 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2395 ASSERT_TRUE(CreatePeerConnectionWrappers());
2396 ConnectFakeSignaling();
2397 caller()->AddVideoTrack();
2398 caller()->AddVideoTrack();
2399 callee()->AddVideoTrack();
2400 callee()->AddVideoTrack();
2401
2402 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2403 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2404 caller()->CreateAndSetAndSignalOffer();
2405 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2406 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2407 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2408
2409 // Expect video to be received in both directions on both tracks.
2410 MediaExpectations media_expectations;
2411 media_expectations.ExpectBidirectionalVideo();
2412 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2413}
2414
deadbeef1dcb1642017-03-29 21:08:16 -07002415// Test that if two video tracks are sent (from caller to callee, in this test),
2416// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002417TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002418 ASSERT_TRUE(CreatePeerConnectionWrappers());
2419 ConnectFakeSignaling();
2420 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002421 caller()->AddAudioVideoTracks();
2422 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002423 caller()->CreateAndSetAndSignalOffer();
2424 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002425 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002426
2427 MediaExpectations media_expectations;
2428 media_expectations.CalleeExpectsSomeAudioAndVideo();
2429 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002430}
2431
2432static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2433 bool first = true;
2434 for (cricket::ContentInfo& content : desc->contents()) {
2435 if (first) {
2436 first = false;
2437 continue;
2438 }
2439 content.bundle_only = true;
2440 }
2441 first = true;
2442 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2443 if (first) {
2444 first = false;
2445 continue;
2446 }
2447 transport.description.ice_ufrag.clear();
2448 transport.description.ice_pwd.clear();
2449 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2450 transport.description.identity_fingerprint.reset(nullptr);
2451 }
2452}
2453
2454// Test that if applying a true "max bundle" offer, which uses ports of 0,
2455// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2456// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2457// successfully and media flows.
2458// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2459// TODO(deadbeef): Won't need this test once we start generating actual
2460// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002461TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002462 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2463 ASSERT_TRUE(CreatePeerConnectionWrappers());
2464 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002465 caller()->AddAudioVideoTracks();
2466 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002467 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2468 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2469 // but the first m= section.
2470 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2471 caller()->CreateAndSetAndSignalOffer();
2472 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002473 MediaExpectations media_expectations;
2474 media_expectations.ExpectBidirectionalAudioAndVideo();
2475 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002476}
2477
2478// Test that we can receive the audio output level from a remote audio track.
2479// TODO(deadbeef): Use a fake audio source and verify that the output level is
2480// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002481TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002482 ASSERT_TRUE(CreatePeerConnectionWrappers());
2483 ConnectFakeSignaling();
2484 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002485 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002486 caller()->CreateAndSetAndSignalOffer();
2487 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2488
2489 // Get the audio output level stats. Note that the level is not available
2490 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002491 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002492 kMaxWaitForFramesMs);
2493}
2494
2495// Test that an audio input level is reported.
2496// TODO(deadbeef): Use a fake audio source and verify that the input level is
2497// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002498TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002499 ASSERT_TRUE(CreatePeerConnectionWrappers());
2500 ConnectFakeSignaling();
2501 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002502 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002503 caller()->CreateAndSetAndSignalOffer();
2504 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2505
2506 // Get the audio input level stats. The level should be available very
2507 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002508 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002509 kMaxWaitForStatsMs);
2510}
2511
2512// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002513TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002514 ASSERT_TRUE(CreatePeerConnectionWrappers());
2515 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002516 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002517 // Do offer/answer, wait for the callee to receive some frames.
2518 caller()->CreateAndSetAndSignalOffer();
2519 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002520
2521 MediaExpectations media_expectations;
2522 media_expectations.CalleeExpectsSomeAudioAndVideo();
2523 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002524
2525 // Get a handle to the remote tracks created, so they can be used as GetStats
2526 // filters.
Steve Anton15324772018-01-16 10:26:49 -08002527 for (auto receiver : callee()->pc()->GetReceivers()) {
2528 // We received frames, so we definitely should have nonzero "received bytes"
2529 // stats at this point.
2530 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2531 0);
2532 }
deadbeef1dcb1642017-03-29 21:08:16 -07002533}
2534
2535// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002536TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002537 ASSERT_TRUE(CreatePeerConnectionWrappers());
2538 ConnectFakeSignaling();
2539 auto audio_track = caller()->CreateLocalAudioTrack();
2540 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002541 caller()->AddTrack(audio_track);
2542 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002543 // Do offer/answer, wait for the callee to receive some frames.
2544 caller()->CreateAndSetAndSignalOffer();
2545 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002546 MediaExpectations media_expectations;
2547 media_expectations.CalleeExpectsSomeAudioAndVideo();
2548 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002549
2550 // The callee received frames, so we definitely should have nonzero "sent
2551 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002552 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2553 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2554}
2555
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002556// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002557TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002558 ASSERT_TRUE(CreatePeerConnectionWrappers());
2559 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002560 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002561
Steve Anton15324772018-01-16 10:26:49 -08002562 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002563
2564 // Do offer/answer, wait for the callee to receive some frames.
2565 caller()->CreateAndSetAndSignalOffer();
2566 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2567
2568 // Get the remote audio track created on the receiver, so they can be used as
2569 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002570 auto receivers = callee()->pc()->GetReceivers();
2571 ASSERT_EQ(1u, receivers.size());
2572 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002573
2574 // Get the audio output level stats. Note that the level is not available
2575 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002576 EXPECT_TRUE_WAIT(
2577 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2578 0,
2579 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002580}
2581
deadbeefd8ad7882017-04-18 16:01:17 -07002582// Test that we can get stats (using the new stats implemnetation) for
2583// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2584// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002585TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002586 GetStatsForUnsignaledStreamWithNewStatsApi) {
2587 ASSERT_TRUE(CreatePeerConnectionWrappers());
2588 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002589 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002590 // Remove SSRCs and MSIDs from the received offer SDP.
2591 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2592 caller()->CreateAndSetAndSignalOffer();
2593 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002594 MediaExpectations media_expectations;
2595 media_expectations.CalleeExpectsSomeAudio(1);
2596 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002597
2598 // We received a frame, so we should have nonzero "bytes received" stats for
2599 // the unsignaled stream, if stats are working for it.
2600 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2601 callee()->NewGetStats();
2602 ASSERT_NE(nullptr, report);
2603 auto inbound_stream_stats =
2604 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2605 ASSERT_EQ(1U, inbound_stream_stats.size());
2606 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2607 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002608 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2609}
2610
Taylor Brandstettera4653442018-06-19 09:44:26 -07002611// Same as above but for the legacy stats implementation.
2612TEST_P(PeerConnectionIntegrationTest,
2613 GetStatsForUnsignaledStreamWithOldStatsApi) {
2614 ASSERT_TRUE(CreatePeerConnectionWrappers());
2615 ConnectFakeSignaling();
2616 caller()->AddAudioTrack();
2617 // Remove SSRCs and MSIDs from the received offer SDP.
2618 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2619 caller()->CreateAndSetAndSignalOffer();
2620 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2621
2622 // Note that, since the old stats implementation associates SSRCs with tracks
2623 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2624 // associated track ID. So we can't use the track "selector" argument.
2625 //
2626 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2627 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002628 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002629 kDefaultTimeout);
2630}
2631
zhihuangf8164932017-05-19 13:09:47 -07002632// Test that we can successfully get the media related stats (audio level
2633// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002634TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002635 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2636 ASSERT_TRUE(CreatePeerConnectionWrappers());
2637 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002638 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002639 // Remove SSRCs and MSIDs from the received offer SDP.
2640 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2641 caller()->CreateAndSetAndSignalOffer();
2642 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002643 MediaExpectations media_expectations;
2644 media_expectations.CalleeExpectsSomeAudio(1);
2645 media_expectations.CalleeExpectsSomeVideo(1);
2646 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002647
2648 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2649 callee()->NewGetStats();
2650 ASSERT_NE(nullptr, report);
2651
2652 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2653 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2654 ASSERT_GE(audio_index, 0);
2655 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002656}
2657
deadbeef4e2deab2017-09-20 13:56:21 -07002658// Helper for test below.
2659void ModifySsrcs(cricket::SessionDescription* desc) {
2660 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002661 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002662 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002663 for (uint32_t& ssrc : stream.ssrcs) {
2664 ssrc = rtc::CreateRandomId();
2665 }
2666 }
2667 }
2668}
2669
2670// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2671// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2672// This should result in two "RTCInboundRTPStreamStats", but only one
2673// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2674// being reset to 0 once the SSRC change occurs.
2675//
2676// Regression test for this bug:
2677// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2678//
2679// The bug causes the track stats to only represent one of the two streams:
2680// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2681// that the track stat counters would reset to 0 when the new stream is
2682// received, and a 50% chance that they'll stop updating (while
2683// "concealed_samples" continues increasing, due to silence being generated for
2684// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002685TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002686 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002687 ASSERT_TRUE(CreatePeerConnectionWrappers());
2688 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002689 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002690 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2691 // that doesn't signal SSRCs (from the callee's perspective).
2692 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2693 caller()->CreateAndSetAndSignalOffer();
2694 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2695 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002696 {
2697 MediaExpectations media_expectations;
2698 media_expectations.CalleeExpectsSomeAudio(50);
2699 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2700 }
deadbeef4e2deab2017-09-20 13:56:21 -07002701 // Some audio frames were received, so we should have nonzero "samples
2702 // received" for the track.
2703 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2704 callee()->NewGetStats();
2705 ASSERT_NE(nullptr, report);
2706 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2707 ASSERT_EQ(1U, track_stats.size());
2708 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2709 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2710 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2711
2712 // Create a new offer and munge it to cause the caller to use a new SSRC.
2713 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2714 caller()->CreateAndSetAndSignalOffer();
2715 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2716 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2717 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002718 {
2719 MediaExpectations media_expectations;
2720 media_expectations.CalleeExpectsSomeAudio(25);
2721 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2722 }
deadbeef4e2deab2017-09-20 13:56:21 -07002723
2724 report = callee()->NewGetStats();
2725 ASSERT_NE(nullptr, report);
2726 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2727 ASSERT_EQ(1U, track_stats.size());
2728 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2729 // The "total samples received" stat should only be greater than it was
2730 // before.
2731 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2732 // Right now, the new SSRC will cause the counters to reset to 0.
2733 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2734
2735 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002736 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002737 // good sign that we're seeing stats from the old stream that's no longer
2738 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002739 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002740 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2741 EXPECT_LT(*track_stats[0]->concealed_samples,
2742 *track_stats[0]->total_samples_received *
2743 kAcceptableConcealedSamplesPercentage);
2744
2745 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2746 // sanity check that the SSRC really changed.
2747 // TODO(deadbeef): This isn't working right now, because we're not returning
2748 // *any* stats for the inactive stream. Uncomment when the bug is completely
2749 // fixed.
2750 // auto inbound_stream_stats =
2751 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2752 // ASSERT_EQ(2U, inbound_stream_stats.size());
2753}
2754
deadbeef1dcb1642017-03-29 21:08:16 -07002755// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002756TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
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();
2762 // Do normal offer/answer and wait for some frames to be received in each
2763 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002764 caller()->AddAudioVideoTracks();
2765 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002766 caller()->CreateAndSetAndSignalOffer();
2767 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002768 MediaExpectations media_expectations;
2769 media_expectations.ExpectBidirectionalAudioAndVideo();
2770 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002771}
2772
2773// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002774TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002775 PeerConnectionFactory::Options dtls_10_options;
2776 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2777 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2778 dtls_10_options));
2779 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002780 caller()->AddAudioVideoTracks();
2781 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002782 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002783 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002784 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002785 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002786 kDefaultTimeout);
2787 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002788 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002789 // TODO(bugs.webrtc.org/9456): Fix it.
2790 EXPECT_EQ(1, webrtc::metrics::NumEvents(
2791 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2792 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002793}
2794
2795// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002796TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002797 PeerConnectionFactory::Options dtls_12_options;
2798 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2799 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2800 dtls_12_options));
2801 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002802 caller()->AddAudioVideoTracks();
2803 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002804 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002805 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002806 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002807 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002808 kDefaultTimeout);
2809 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002810 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002811 // TODO(bugs.webrtc.org/9456): Fix it.
2812 EXPECT_EQ(1, webrtc::metrics::NumEvents(
2813 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2814 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002815}
2816
2817// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2818// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002819TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002820 PeerConnectionFactory::Options caller_options;
2821 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2822 PeerConnectionFactory::Options callee_options;
2823 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2824 ASSERT_TRUE(
2825 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2826 ConnectFakeSignaling();
2827 // Do normal offer/answer and wait for some frames to be received in each
2828 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002829 caller()->AddAudioVideoTracks();
2830 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002831 caller()->CreateAndSetAndSignalOffer();
2832 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002833 MediaExpectations media_expectations;
2834 media_expectations.ExpectBidirectionalAudioAndVideo();
2835 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002836}
2837
2838// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2839// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002840TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07002841 PeerConnectionFactory::Options caller_options;
2842 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2843 PeerConnectionFactory::Options callee_options;
2844 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2845 ASSERT_TRUE(
2846 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2847 ConnectFakeSignaling();
2848 // Do normal offer/answer and wait for some frames to be received in each
2849 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002850 caller()->AddAudioVideoTracks();
2851 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002852 caller()->CreateAndSetAndSignalOffer();
2853 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002854 MediaExpectations media_expectations;
2855 media_expectations.ExpectBidirectionalAudioAndVideo();
2856 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002857}
2858
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002859// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
2860// works as expected; the cipher should only be used if enabled by both sides.
2861TEST_P(PeerConnectionIntegrationTest,
2862 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
2863 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002864 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002865 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002866 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
2867 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002868 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2869 TestNegotiatedCipherSuite(caller_options, callee_options,
2870 expected_cipher_suite);
2871}
2872
2873TEST_P(PeerConnectionIntegrationTest,
2874 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
2875 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002876 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
2877 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002878 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002879 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002880 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2881 TestNegotiatedCipherSuite(caller_options, callee_options,
2882 expected_cipher_suite);
2883}
2884
2885TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
2886 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002887 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002888 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002889 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002890 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
2891 TestNegotiatedCipherSuite(caller_options, callee_options,
2892 expected_cipher_suite);
2893}
2894
deadbeef1dcb1642017-03-29 21:08:16 -07002895// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002896TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07002897 bool local_gcm_enabled = false;
2898 bool remote_gcm_enabled = false;
2899 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2900 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2901 expected_cipher_suite);
2902}
2903
2904// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002905TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07002906 bool local_gcm_enabled = true;
2907 bool remote_gcm_enabled = true;
2908 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2909 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2910 expected_cipher_suite);
2911}
2912
2913// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002914TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002915 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2916 bool local_gcm_enabled = true;
2917 bool remote_gcm_enabled = false;
2918 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2919 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2920 expected_cipher_suite);
2921}
2922
2923// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002924TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002925 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2926 bool local_gcm_enabled = false;
2927 bool remote_gcm_enabled = true;
2928 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2929 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2930 expected_cipher_suite);
2931}
2932
deadbeef7914b8c2017-04-21 03:23:33 -07002933// Verify that media can be transmitted end-to-end when GCM crypto suites are
2934// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2935// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2936// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002937TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07002938 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002939 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07002940 ASSERT_TRUE(
2941 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2942 ConnectFakeSignaling();
2943 // Do normal offer/answer and wait for some frames to be received in each
2944 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002945 caller()->AddAudioVideoTracks();
2946 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002947 caller()->CreateAndSetAndSignalOffer();
2948 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002949 MediaExpectations media_expectations;
2950 media_expectations.ExpectBidirectionalAudioAndVideo();
2951 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07002952}
2953
deadbeef1dcb1642017-03-29 21:08:16 -07002954// This test sets up a call between two parties with audio, video and an RTP
2955// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002956TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02002957 PeerConnectionInterface::RTCConfiguration rtc_config;
2958 rtc_config.enable_rtp_data_channel = true;
2959 rtc_config.enable_dtls_srtp = false;
2960 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07002961 ConnectFakeSignaling();
2962 // Expect that data channel created on caller side will show up for callee as
2963 // well.
2964 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002965 caller()->AddAudioVideoTracks();
2966 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002967 caller()->CreateAndSetAndSignalOffer();
2968 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2969 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002970 MediaExpectations media_expectations;
2971 media_expectations.ExpectBidirectionalAudioAndVideo();
2972 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002973 ASSERT_NE(nullptr, caller()->data_channel());
2974 ASSERT_NE(nullptr, callee()->data_channel());
2975 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2976 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2977
2978 // Ensure data can be sent in both directions.
2979 std::string data = "hello world";
2980 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2981 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2982 kDefaultTimeout);
2983 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2984 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2985 kDefaultTimeout);
2986}
2987
2988// Ensure that an RTP data channel is signaled as closed for the caller when
2989// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002990TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002991 RtpDataChannelSignaledClosedInCalleeOffer) {
2992 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02002993 PeerConnectionInterface::RTCConfiguration rtc_config;
2994 rtc_config.enable_rtp_data_channel = true;
2995 rtc_config.enable_dtls_srtp = false;
2996 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07002997 ConnectFakeSignaling();
2998 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002999 caller()->AddAudioVideoTracks();
3000 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003001 caller()->CreateAndSetAndSignalOffer();
3002 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3003 ASSERT_NE(nullptr, caller()->data_channel());
3004 ASSERT_NE(nullptr, callee()->data_channel());
3005 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3006 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3007
3008 // Close the data channel on the callee, and do an updated offer/answer.
3009 callee()->data_channel()->Close();
3010 callee()->CreateAndSetAndSignalOffer();
3011 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3012 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3013 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3014}
3015
3016// Tests that data is buffered in an RTP data channel until an observer is
3017// registered for it.
3018//
3019// NOTE: RTP data channels can receive data before the underlying
3020// transport has detected that a channel is writable and thus data can be
3021// received before the data channel state changes to open. That is hard to test
3022// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003023TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003024 DataBufferedUntilRtpDataChannelObserverRegistered) {
3025 // Use fake clock and simulated network delay so that we predictably can wait
3026 // until an SCTP message has been delivered without "sleep()"ing.
3027 rtc::ScopedFakeClock fake_clock;
3028 // Some things use a time of "0" as a special value, so we need to start out
3029 // the fake clock at a nonzero time.
3030 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003031 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003032 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3033 virtual_socket_server()->UpdateDelayDistribution();
3034
Niels Möllerf06f9232018-08-07 12:32:18 +02003035 PeerConnectionInterface::RTCConfiguration rtc_config;
3036 rtc_config.enable_rtp_data_channel = true;
3037 rtc_config.enable_dtls_srtp = false;
3038 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003039 ConnectFakeSignaling();
3040 caller()->CreateDataChannel();
3041 caller()->CreateAndSetAndSignalOffer();
3042 ASSERT_TRUE(caller()->data_channel() != nullptr);
3043 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3044 kDefaultTimeout, fake_clock);
3045 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3046 kDefaultTimeout, fake_clock);
3047 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3048 callee()->data_channel()->state(), kDefaultTimeout,
3049 fake_clock);
3050
3051 // Unregister the observer which is normally automatically registered.
3052 callee()->data_channel()->UnregisterObserver();
3053 // Send data and advance fake clock until it should have been received.
3054 std::string data = "hello world";
3055 caller()->data_channel()->Send(DataBuffer(data));
3056 SIMULATED_WAIT(false, 50, fake_clock);
3057
3058 // Attach data channel and expect data to be received immediately. Note that
3059 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3060 // further, but data can be received even if the callback is asynchronous.
3061 MockDataChannelObserver new_observer(callee()->data_channel());
3062 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3063 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003064 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3065 // If this is not done a DCHECK can be hit in ports.cc, because a large
3066 // negative number is calculated for the rtt due to the global clock changing.
3067 caller()->pc()->Close();
3068 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07003069}
3070
3071// This test sets up a call between two parties with audio, video and but only
3072// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003073TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003074 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3075 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003076 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003077 rtc_config_1.enable_dtls_srtp = false;
3078 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3079 rtc_config_2.enable_dtls_srtp = false;
3080 rtc_config_2.enable_dtls_srtp = false;
3081 ASSERT_TRUE(
3082 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003083 ConnectFakeSignaling();
3084 caller()->CreateDataChannel();
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 // The caller should still have a data channel, but it should be closed, and
3090 // one should ever have been created for the callee.
3091 EXPECT_TRUE(caller()->data_channel() != nullptr);
3092 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3093 EXPECT_EQ(nullptr, callee()->data_channel());
3094}
3095
3096// This test sets up a call between two parties with audio, and video. When
3097// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003098TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003099 PeerConnectionInterface::RTCConfiguration rtc_config;
3100 rtc_config.enable_rtp_data_channel = true;
3101 rtc_config.enable_dtls_srtp = false;
3102 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003103 ConnectFakeSignaling();
3104 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003105 caller()->AddAudioVideoTracks();
3106 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003107 caller()->CreateAndSetAndSignalOffer();
3108 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3109 // Create data channel and do new offer and answer.
3110 caller()->CreateDataChannel();
3111 caller()->CreateAndSetAndSignalOffer();
3112 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3113 ASSERT_NE(nullptr, caller()->data_channel());
3114 ASSERT_NE(nullptr, callee()->data_channel());
3115 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3116 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3117 // Ensure data can be sent in both directions.
3118 std::string data = "hello world";
3119 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3120 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3121 kDefaultTimeout);
3122 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3123 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3124 kDefaultTimeout);
3125}
3126
3127#ifdef HAVE_SCTP
3128
3129// This test sets up a call between two parties with audio, video and an SCTP
3130// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003131TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003132 ASSERT_TRUE(CreatePeerConnectionWrappers());
3133 ConnectFakeSignaling();
3134 // Expect that data channel created on caller side will show up for callee as
3135 // well.
3136 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003137 caller()->AddAudioVideoTracks();
3138 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003139 caller()->CreateAndSetAndSignalOffer();
3140 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3141 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003142 MediaExpectations media_expectations;
3143 media_expectations.ExpectBidirectionalAudioAndVideo();
3144 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003145 // Caller data channel should already exist (it created one). Callee data
3146 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3147 ASSERT_NE(nullptr, caller()->data_channel());
3148 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3149 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3150 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3151
3152 // Ensure data can be sent in both directions.
3153 std::string data = "hello world";
3154 caller()->data_channel()->Send(DataBuffer(data));
3155 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3156 kDefaultTimeout);
3157 callee()->data_channel()->Send(DataBuffer(data));
3158 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3159 kDefaultTimeout);
3160}
3161
3162// Ensure that when the callee closes an SCTP data channel, the closing
3163// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003164TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003165 // Same procedure as above test.
3166 ASSERT_TRUE(CreatePeerConnectionWrappers());
3167 ConnectFakeSignaling();
3168 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003169 caller()->AddAudioVideoTracks();
3170 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003171 caller()->CreateAndSetAndSignalOffer();
3172 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3173 ASSERT_NE(nullptr, caller()->data_channel());
3174 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3175 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3176 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3177
3178 // Close the data channel on the callee side, and wait for it to reach the
3179 // "closed" state on both sides.
3180 callee()->data_channel()->Close();
3181 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3182 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3183}
3184
Seth Hampson2f0d7022018-02-20 11:54:42 -08003185TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003186 ASSERT_TRUE(CreatePeerConnectionWrappers());
3187 ConnectFakeSignaling();
3188 webrtc::DataChannelInit init;
3189 init.id = 53;
3190 init.maxRetransmits = 52;
3191 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003192 caller()->AddAudioVideoTracks();
3193 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003194 caller()->CreateAndSetAndSignalOffer();
3195 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003196 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3197 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07003198 EXPECT_EQ(init.id, callee()->data_channel()->id());
3199 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3200 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3201 EXPECT_FALSE(callee()->data_channel()->negotiated());
3202}
3203
deadbeef1dcb1642017-03-29 21:08:16 -07003204// Test usrsctp's ability to process unordered data stream, where data actually
3205// arrives out of order using simulated delays. Previously there have been some
3206// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003207TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003208 // Introduce random network delays.
3209 // Otherwise it's not a true "unordered" test.
3210 virtual_socket_server()->set_delay_mean(20);
3211 virtual_socket_server()->set_delay_stddev(5);
3212 virtual_socket_server()->UpdateDelayDistribution();
3213 // Normal procedure, but with unordered data channel config.
3214 ASSERT_TRUE(CreatePeerConnectionWrappers());
3215 ConnectFakeSignaling();
3216 webrtc::DataChannelInit init;
3217 init.ordered = false;
3218 caller()->CreateDataChannel(&init);
3219 caller()->CreateAndSetAndSignalOffer();
3220 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3221 ASSERT_NE(nullptr, caller()->data_channel());
3222 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3223 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3224 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3225
3226 static constexpr int kNumMessages = 100;
3227 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3228 static constexpr size_t kMaxMessageSize = 4096;
3229 // Create and send random messages.
3230 std::vector<std::string> sent_messages;
3231 for (int i = 0; i < kNumMessages; ++i) {
3232 size_t length =
3233 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3234 std::string message;
3235 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3236 caller()->data_channel()->Send(DataBuffer(message));
3237 callee()->data_channel()->Send(DataBuffer(message));
3238 sent_messages.push_back(message);
3239 }
3240
3241 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003242 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003243 caller()->data_observer()->received_message_count(),
3244 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003245 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003246 callee()->data_observer()->received_message_count(),
3247 kDefaultTimeout);
3248
3249 // Sort and compare to make sure none of the messages were corrupted.
3250 std::vector<std::string> caller_received_messages =
3251 caller()->data_observer()->messages();
3252 std::vector<std::string> callee_received_messages =
3253 callee()->data_observer()->messages();
3254 std::sort(sent_messages.begin(), sent_messages.end());
3255 std::sort(caller_received_messages.begin(), caller_received_messages.end());
3256 std::sort(callee_received_messages.begin(), callee_received_messages.end());
3257 EXPECT_EQ(sent_messages, caller_received_messages);
3258 EXPECT_EQ(sent_messages, callee_received_messages);
3259}
3260
3261// This test sets up a call between two parties with audio, and video. When
3262// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003263TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003264 ASSERT_TRUE(CreatePeerConnectionWrappers());
3265 ConnectFakeSignaling();
3266 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003267 caller()->AddAudioVideoTracks();
3268 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003269 caller()->CreateAndSetAndSignalOffer();
3270 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3271 // Create data channel and do new offer and answer.
3272 caller()->CreateDataChannel();
3273 caller()->CreateAndSetAndSignalOffer();
3274 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3275 // Caller data channel should already exist (it created one). Callee data
3276 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3277 ASSERT_NE(nullptr, caller()->data_channel());
3278 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3279 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3280 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3281 // Ensure data can be sent in both directions.
3282 std::string data = "hello world";
3283 caller()->data_channel()->Send(DataBuffer(data));
3284 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3285 kDefaultTimeout);
3286 callee()->data_channel()->Send(DataBuffer(data));
3287 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3288 kDefaultTimeout);
3289}
3290
deadbeef7914b8c2017-04-21 03:23:33 -07003291// Set up a connection initially just using SCTP data channels, later upgrading
3292// to audio/video, ensuring frames are received end-to-end. Effectively the
3293// inverse of the test above.
3294// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003295TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003296 ASSERT_TRUE(CreatePeerConnectionWrappers());
3297 ConnectFakeSignaling();
3298 // Do initial offer/answer with just data channel.
3299 caller()->CreateDataChannel();
3300 caller()->CreateAndSetAndSignalOffer();
3301 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3302 // Wait until data can be sent over the data channel.
3303 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3304 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3305 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3306
3307 // Do subsequent offer/answer with two-way audio and video. Audio and video
3308 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003309 caller()->AddAudioVideoTracks();
3310 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003311 caller()->CreateAndSetAndSignalOffer();
3312 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003313 MediaExpectations media_expectations;
3314 media_expectations.ExpectBidirectionalAudioAndVideo();
3315 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003316}
3317
deadbeef8b7e9ad2017-05-25 09:38:55 -07003318static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07003319 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08003320 GetFirstDataContentDescription(desc);
3321 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003322 dcd_offer->set_use_sctpmap(false);
3323 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3324}
3325
3326// Test that the data channel works when a spec-compliant SCTP m= section is
3327// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3328// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003329TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003330 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3331 ASSERT_TRUE(CreatePeerConnectionWrappers());
3332 ConnectFakeSignaling();
3333 caller()->CreateDataChannel();
3334 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3335 caller()->CreateAndSetAndSignalOffer();
3336 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3337 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3338 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3339 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3340
3341 // Ensure data can be sent in both directions.
3342 std::string data = "hello world";
3343 caller()->data_channel()->Send(DataBuffer(data));
3344 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3345 kDefaultTimeout);
3346 callee()->data_channel()->Send(DataBuffer(data));
3347 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3348 kDefaultTimeout);
3349}
3350
deadbeef1dcb1642017-03-29 21:08:16 -07003351#endif // HAVE_SCTP
3352
3353// Test that the ICE connection and gathering states eventually reach
3354// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003355TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003356 ASSERT_TRUE(CreatePeerConnectionWrappers());
3357 ConnectFakeSignaling();
3358 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003359 caller()->AddAudioVideoTracks();
3360 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003361 caller()->CreateAndSetAndSignalOffer();
3362 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3363 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3364 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3365 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3366 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3367 // After the best candidate pair is selected and all candidates are signaled,
3368 // the ICE connection state should reach "complete".
3369 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3370 // answerer/"callee" by default) only reaches "connected". When this is
3371 // fixed, this test should be updated.
3372 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3373 caller()->ice_connection_state(), kDefaultTimeout);
3374 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3375 callee()->ice_connection_state(), kDefaultTimeout);
3376}
3377
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003378// Replaces the first candidate with a static address and configures a
3379// MockAsyncResolver to return the replaced address the first time the static
3380// address is resolved. Candidates past the first will not be signaled.
3381class ReplaceFirstCandidateAddressDropOthers final
3382 : public IceCandidateReplacerInterface {
3383 public:
3384 ReplaceFirstCandidateAddressDropOthers(
3385 const SocketAddress& new_address,
3386 rtc::MockAsyncResolver* mock_async_resolver)
3387 : mock_async_resolver_(mock_async_resolver), new_address_(new_address) {
3388 RTC_DCHECK(mock_async_resolver);
3389 }
3390
3391 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3392 const webrtc::IceCandidateInterface* candidate) override {
3393 if (replaced_candidate_) {
3394 return nullptr;
3395 }
3396
3397 replaced_candidate_ = true;
3398 cricket::Candidate new_candidate(candidate->candidate());
3399 new_candidate.set_address(new_address_);
3400 EXPECT_CALL(*mock_async_resolver_, GetResolvedAddress(_, _))
3401 .WillOnce(DoAll(SetArgPointee<1>(candidate->candidate().address()),
3402 Return(true)));
3403 EXPECT_CALL(*mock_async_resolver_, Destroy(_));
3404 return webrtc::CreateIceCandidate(
3405 candidate->sdp_mid(), candidate->sdp_mline_index(), new_candidate);
3406 }
3407
3408 private:
3409 rtc::MockAsyncResolver* mock_async_resolver_;
3410 SocketAddress new_address_;
3411 bool replaced_candidate_ = false;
3412};
3413
3414// Drops all candidates before they are signaled.
3415class DropAllCandidates final : public IceCandidateReplacerInterface {
3416 public:
3417 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3418 const webrtc::IceCandidateInterface*) override {
3419 return nullptr;
3420 }
3421};
3422
3423// Replace the first caller ICE candidate IP with a fake hostname and drop the
3424// other candidates. Drop all candidates on the callee side (to avoid a prflx
3425// connection). Use a mock resolver to resolve the hostname back to the original
3426// IP on the callee side and check that the ice connection connects.
3427TEST_P(PeerConnectionIntegrationTest,
3428 IceStatesReachCompletionWithRemoteHostname) {
3429 webrtc::MockAsyncResolverFactory* callee_mock_async_resolver_factory;
3430 {
3431 auto resolver_factory =
3432 absl::make_unique<webrtc::MockAsyncResolverFactory>();
3433 callee_mock_async_resolver_factory = resolver_factory.get();
3434 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3435 callee_deps.async_resolver_factory = std::move(resolver_factory);
3436
3437 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3438 RTCConfiguration(), webrtc::PeerConnectionDependencies(nullptr),
3439 RTCConfiguration(), std::move(callee_deps)));
3440 }
3441
3442 rtc::MockAsyncResolver mock_async_resolver;
3443
3444 // This also verifies that the injected AsyncResolverFactory is used by
3445 // P2PTransportChannel.
3446 EXPECT_CALL(*callee_mock_async_resolver_factory, Create())
3447 .WillOnce(Return(&mock_async_resolver));
3448 caller()->SetLocalIceCandidateReplacer(
3449 absl::make_unique<ReplaceFirstCandidateAddressDropOthers>(
3450 SocketAddress("a.b", 10000), &mock_async_resolver));
3451 callee()->SetLocalIceCandidateReplacer(
3452 absl::make_unique<DropAllCandidates>());
3453
3454 ConnectFakeSignaling();
3455 caller()->AddAudioVideoTracks();
3456 callee()->AddAudioVideoTracks();
3457 caller()->CreateAndSetAndSignalOffer();
3458 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3459 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3460 caller()->ice_connection_state(), kDefaultTimeout);
3461 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3462 callee()->ice_connection_state(), kDefaultTimeout);
3463}
3464
Steve Antonede9ca52017-10-16 13:04:27 -07003465// Test that firewalling the ICE connection causes the clients to identify the
3466// disconnected state and then removing the firewall causes them to reconnect.
3467class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003468 : public PeerConnectionIntegrationBaseTest,
3469 public ::testing::WithParamInterface<
3470 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003471 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003472 PeerConnectionIntegrationIceStatesTest()
3473 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3474 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003475 }
3476
3477 void StartStunServer(const SocketAddress& server_address) {
3478 stun_server_.reset(
3479 cricket::TestStunServer::Create(network_thread(), server_address));
3480 }
3481
3482 bool TestIPv6() {
3483 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3484 }
3485
3486 void SetPortAllocatorFlags() {
Qingsi Wanga2d60672018-04-11 16:57:45 -07003487 network_thread()->Invoke<void>(
3488 RTC_FROM_HERE,
3489 rtc::Bind(&cricket::PortAllocator::set_flags,
3490 caller()->port_allocator(), port_allocator_flags_));
3491 network_thread()->Invoke<void>(
3492 RTC_FROM_HERE,
3493 rtc::Bind(&cricket::PortAllocator::set_flags,
3494 callee()->port_allocator(), port_allocator_flags_));
Steve Antonede9ca52017-10-16 13:04:27 -07003495 }
3496
3497 std::vector<SocketAddress> CallerAddresses() {
3498 std::vector<SocketAddress> addresses;
3499 addresses.push_back(SocketAddress("1.1.1.1", 0));
3500 if (TestIPv6()) {
3501 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3502 }
3503 return addresses;
3504 }
3505
3506 std::vector<SocketAddress> CalleeAddresses() {
3507 std::vector<SocketAddress> addresses;
3508 addresses.push_back(SocketAddress("2.2.2.2", 0));
3509 if (TestIPv6()) {
3510 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3511 }
3512 return addresses;
3513 }
3514
3515 void SetUpNetworkInterfaces() {
3516 // Remove the default interfaces added by the test infrastructure.
3517 caller()->network()->RemoveInterface(kDefaultLocalAddress);
3518 callee()->network()->RemoveInterface(kDefaultLocalAddress);
3519
3520 // Add network addresses for test.
3521 for (const auto& caller_address : CallerAddresses()) {
3522 caller()->network()->AddInterface(caller_address);
3523 }
3524 for (const auto& callee_address : CalleeAddresses()) {
3525 callee()->network()->AddInterface(callee_address);
3526 }
3527 }
3528
3529 private:
3530 uint32_t port_allocator_flags_;
3531 std::unique_ptr<cricket::TestStunServer> stun_server_;
3532};
3533
3534// Tests that the PeerConnection goes through all the ICE gathering/connection
3535// states over the duration of the call. This includes Disconnected and Failed
3536// states, induced by putting a firewall between the peers and waiting for them
3537// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003538TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
3539 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
3540 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
3541 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07003542
3543 const SocketAddress kStunServerAddress =
3544 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3545 StartStunServer(kStunServerAddress);
3546
3547 PeerConnectionInterface::RTCConfiguration config;
3548 PeerConnectionInterface::IceServer ice_stun_server;
3549 ice_stun_server.urls.push_back(
3550 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3551 kStunServerAddress.PortAsString());
3552 config.servers.push_back(ice_stun_server);
3553
3554 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3555 ConnectFakeSignaling();
3556 SetPortAllocatorFlags();
3557 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003558 caller()->AddAudioVideoTracks();
3559 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003560
3561 // Initial state before anything happens.
3562 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3563 caller()->ice_gathering_state());
3564 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3565 caller()->ice_connection_state());
3566
3567 // Start the call by creating the offer, setting it as the local description,
3568 // then sending it to the peer who will respond with an answer. This happens
3569 // asynchronously so that we can watch the states as it runs in the
3570 // background.
3571 caller()->CreateAndSetAndSignalOffer();
3572
Steve Anton83119dd2017-11-10 16:19:52 -08003573 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3574 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003575
3576 // Verify that the observer was notified of the intermediate transitions.
3577 EXPECT_THAT(caller()->ice_connection_state_history(),
3578 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3579 PeerConnectionInterface::kIceConnectionConnected,
3580 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02003581 // After the ice transport transitions from checking to connected we revert
3582 // back to new as the standard requires, as at that point the DTLS transport
3583 // is in the "new" state while no transports are "connecting", "checking",
3584 // "failed" or disconnected. This is pretty unintuitive, and we might want to
3585 // amend the spec to handle this case more gracefully.
3586 EXPECT_THAT(
3587 caller()->peer_connection_state_history(),
3588 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
3589 PeerConnectionInterface::PeerConnectionState::kNew,
3590 PeerConnectionInterface::PeerConnectionState::kConnecting,
3591 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07003592 EXPECT_THAT(caller()->ice_gathering_state_history(),
3593 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
3594 PeerConnectionInterface::kIceGatheringComplete));
3595
3596 // Block connections to/from the caller and wait for ICE to become
3597 // disconnected.
3598 for (const auto& caller_address : CallerAddresses()) {
3599 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3600 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003601 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08003602 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
3603 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003604
3605 // Let ICE re-establish by removing the firewall rules.
3606 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01003607 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08003608 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3609 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003610
3611 // According to RFC7675, if there is no response within 30 seconds then the
3612 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08003613 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07003614 constexpr int kConsentTimeout = 30000;
3615 for (const auto& caller_address : CallerAddresses()) {
3616 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3617 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003618 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08003619 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
3620 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003621}
3622
3623// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
3624// and that the statistics in the metric observers are updated correctly.
3625TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
3626 ASSERT_TRUE(CreatePeerConnectionWrappers());
3627 ConnectFakeSignaling();
3628 SetPortAllocatorFlags();
3629 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003630 caller()->AddAudioVideoTracks();
3631 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003632 caller()->CreateAndSetAndSignalOffer();
3633
3634 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3635
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003636 // TODO(bugs.webrtc.org/9456): Fix it.
3637 const int num_best_ipv4 = webrtc::metrics::NumEvents(
3638 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
3639 const int num_best_ipv6 = webrtc::metrics::NumEvents(
3640 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003641 if (TestIPv6()) {
3642 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
3643 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003644 EXPECT_EQ(0, num_best_ipv4);
3645 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003646 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003647 EXPECT_EQ(1, num_best_ipv4);
3648 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003649 }
3650
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003651 EXPECT_EQ(0, webrtc::metrics::NumEvents(
3652 "WebRTC.PeerConnection.CandidatePairType_UDP",
3653 webrtc::kIceCandidatePairHostHost));
3654 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3655 "WebRTC.PeerConnection.CandidatePairType_UDP",
3656 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07003657}
3658
3659constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
3660 cricket::PORTALLOCATOR_DISABLE_STUN |
3661 cricket::PORTALLOCATOR_DISABLE_RELAY;
3662constexpr uint32_t kFlagsIPv6NoStun =
3663 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
3664 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
3665constexpr uint32_t kFlagsIPv4Stun =
3666 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
3667
Seth Hampson2f0d7022018-02-20 11:54:42 -08003668INSTANTIATE_TEST_CASE_P(
3669 PeerConnectionIntegrationTest,
3670 PeerConnectionIntegrationIceStatesTest,
3671 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3672 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
3673 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
3674 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07003675
deadbeef1dcb1642017-03-29 21:08:16 -07003676// This test sets up a call between two parties with audio and video.
3677// During the call, the caller restarts ICE and the test verifies that
3678// new ICE candidates are generated and audio and video still can flow, and the
3679// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003680TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07003681 ASSERT_TRUE(CreatePeerConnectionWrappers());
3682 ConnectFakeSignaling();
3683 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08003684 caller()->AddAudioVideoTracks();
3685 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003686 caller()->CreateAndSetAndSignalOffer();
3687 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3688 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3689 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3690 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3691 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3692
3693 // To verify that the ICE restart actually occurs, get
3694 // ufrag/password/candidates before and after restart.
3695 // Create an SDP string of the first audio candidate for both clients.
3696 const webrtc::IceCandidateCollection* audio_candidates_caller =
3697 caller()->pc()->local_description()->candidates(0);
3698 const webrtc::IceCandidateCollection* audio_candidates_callee =
3699 callee()->pc()->local_description()->candidates(0);
3700 ASSERT_GT(audio_candidates_caller->count(), 0u);
3701 ASSERT_GT(audio_candidates_callee->count(), 0u);
3702 std::string caller_candidate_pre_restart;
3703 ASSERT_TRUE(
3704 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
3705 std::string callee_candidate_pre_restart;
3706 ASSERT_TRUE(
3707 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3708 const cricket::SessionDescription* desc =
3709 caller()->pc()->local_description()->description();
3710 std::string caller_ufrag_pre_restart =
3711 desc->transport_infos()[0].description.ice_ufrag;
3712 desc = callee()->pc()->local_description()->description();
3713 std::string callee_ufrag_pre_restart =
3714 desc->transport_infos()[0].description.ice_ufrag;
3715
3716 // Have the caller initiate an ICE restart.
3717 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3718 caller()->CreateAndSetAndSignalOffer();
3719 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3720 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3721 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3722 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3723 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3724
3725 // Grab the ufrags/candidates again.
3726 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3727 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3728 ASSERT_GT(audio_candidates_caller->count(), 0u);
3729 ASSERT_GT(audio_candidates_callee->count(), 0u);
3730 std::string caller_candidate_post_restart;
3731 ASSERT_TRUE(
3732 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3733 std::string callee_candidate_post_restart;
3734 ASSERT_TRUE(
3735 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
3736 desc = caller()->pc()->local_description()->description();
3737 std::string caller_ufrag_post_restart =
3738 desc->transport_infos()[0].description.ice_ufrag;
3739 desc = callee()->pc()->local_description()->description();
3740 std::string callee_ufrag_post_restart =
3741 desc->transport_infos()[0].description.ice_ufrag;
3742 // Sanity check that an ICE restart was actually negotiated in SDP.
3743 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
3744 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3745 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3746 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3747
3748 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003749 MediaExpectations media_expectations;
3750 media_expectations.ExpectBidirectionalAudioAndVideo();
3751 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003752}
3753
3754// Verify that audio/video can be received end-to-end when ICE renomination is
3755// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003756TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07003757 PeerConnectionInterface::RTCConfiguration config;
3758 config.enable_ice_renomination = true;
3759 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3760 ConnectFakeSignaling();
3761 // Do normal offer/answer and wait for some frames to be received in each
3762 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003763 caller()->AddAudioVideoTracks();
3764 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003765 caller()->CreateAndSetAndSignalOffer();
3766 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3767 // Sanity check that ICE renomination was actually negotiated.
3768 const cricket::SessionDescription* desc =
3769 caller()->pc()->local_description()->description();
3770 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003771 ASSERT_NE(
3772 info.description.transport_options.end(),
3773 std::find(info.description.transport_options.begin(),
3774 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003775 }
3776 desc = callee()->pc()->local_description()->description();
3777 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003778 ASSERT_NE(
3779 info.description.transport_options.end(),
3780 std::find(info.description.transport_options.begin(),
3781 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003782 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003783 MediaExpectations media_expectations;
3784 media_expectations.ExpectBidirectionalAudioAndVideo();
3785 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003786}
3787
Steve Anton6f25b092017-10-23 09:39:20 -07003788// With a max bundle policy and RTCP muxing, adding a new media description to
3789// the connection should not affect ICE at all because the new media will use
3790// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003791TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003792 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07003793 PeerConnectionInterface::RTCConfiguration config;
3794 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3795 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3796 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
3797 config, PeerConnectionInterface::RTCConfiguration()));
3798 ConnectFakeSignaling();
3799
Steve Anton15324772018-01-16 10:26:49 -08003800 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003801 caller()->CreateAndSetAndSignalOffer();
3802 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07003803 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3804 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07003805
3806 caller()->clear_ice_connection_state_history();
3807
Steve Anton15324772018-01-16 10:26:49 -08003808 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003809 caller()->CreateAndSetAndSignalOffer();
3810 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3811
3812 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
3813}
3814
deadbeef1dcb1642017-03-29 21:08:16 -07003815// This test sets up a call between two parties with audio and video. It then
3816// renegotiates setting the video m-line to "port 0", then later renegotiates
3817// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003818TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003819 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
3820 ASSERT_TRUE(CreatePeerConnectionWrappers());
3821 ConnectFakeSignaling();
3822
3823 // Do initial negotiation, only sending media from the caller. Will result in
3824 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08003825 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003826 caller()->CreateAndSetAndSignalOffer();
3827 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3828
3829 // Negotiate again, disabling the video "m=" section (the callee will set the
3830 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003831 if (sdp_semantics_ == SdpSemantics::kPlanB) {
3832 PeerConnectionInterface::RTCOfferAnswerOptions options;
3833 options.offer_to_receive_video = 0;
3834 callee()->SetOfferAnswerOptions(options);
3835 } else {
3836 callee()->SetRemoteOfferHandler([this] {
3837 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
3838 });
3839 }
deadbeef1dcb1642017-03-29 21:08:16 -07003840 caller()->CreateAndSetAndSignalOffer();
3841 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3842 // Sanity check that video "m=" section was actually rejected.
3843 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
3844 callee()->pc()->local_description()->description());
3845 ASSERT_NE(nullptr, answer_video_content);
3846 ASSERT_TRUE(answer_video_content->rejected);
3847
3848 // Enable video and do negotiation again, making sure video is received
3849 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003850 if (sdp_semantics_ == SdpSemantics::kPlanB) {
3851 PeerConnectionInterface::RTCOfferAnswerOptions options;
3852 options.offer_to_receive_video = 1;
3853 callee()->SetOfferAnswerOptions(options);
3854 } else {
3855 // The caller's transceiver is stopped, so we need to add another track.
3856 auto caller_transceiver =
3857 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
3858 EXPECT_TRUE(caller_transceiver->stopped());
3859 caller()->AddVideoTrack();
3860 }
3861 callee()->AddVideoTrack();
3862 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07003863 caller()->CreateAndSetAndSignalOffer();
3864 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003865
deadbeef1dcb1642017-03-29 21:08:16 -07003866 // Verify the caller receives frames from the newly added stream, and the
3867 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003868 MediaExpectations media_expectations;
3869 media_expectations.CalleeExpectsSomeAudio();
3870 media_expectations.ExpectBidirectionalVideo();
3871 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003872}
3873
deadbeef1dcb1642017-03-29 21:08:16 -07003874// This tests that if we negotiate after calling CreateSender but before we
3875// have a track, then set a track later, frames from the newly-set track are
3876// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003877TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07003878 MediaFlowsAfterEarlyWarmupWithCreateSender) {
3879 ASSERT_TRUE(CreatePeerConnectionWrappers());
3880 ConnectFakeSignaling();
3881 auto caller_audio_sender =
3882 caller()->pc()->CreateSender("audio", "caller_stream");
3883 auto caller_video_sender =
3884 caller()->pc()->CreateSender("video", "caller_stream");
3885 auto callee_audio_sender =
3886 callee()->pc()->CreateSender("audio", "callee_stream");
3887 auto callee_video_sender =
3888 callee()->pc()->CreateSender("video", "callee_stream");
3889 caller()->CreateAndSetAndSignalOffer();
3890 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3891 // Wait for ICE to complete, without any tracks being set.
3892 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3893 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3894 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3895 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3896 // Now set the tracks, and expect frames to immediately start flowing.
3897 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3898 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3899 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3900 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08003901 MediaExpectations media_expectations;
3902 media_expectations.ExpectBidirectionalAudioAndVideo();
3903 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3904}
3905
3906// This tests that if we negotiate after calling AddTransceiver but before we
3907// have a track, then set a track later, frames from the newly-set tracks are
3908// received end-to-end.
3909TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
3910 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
3911 ASSERT_TRUE(CreatePeerConnectionWrappers());
3912 ConnectFakeSignaling();
3913 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
3914 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
3915 auto caller_audio_sender = audio_result.MoveValue()->sender();
3916 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
3917 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
3918 auto caller_video_sender = video_result.MoveValue()->sender();
3919 callee()->SetRemoteOfferHandler([this] {
3920 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
3921 callee()->pc()->GetTransceivers()[0]->SetDirection(
3922 RtpTransceiverDirection::kSendRecv);
3923 callee()->pc()->GetTransceivers()[1]->SetDirection(
3924 RtpTransceiverDirection::kSendRecv);
3925 });
3926 caller()->CreateAndSetAndSignalOffer();
3927 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3928 // Wait for ICE to complete, without any tracks being set.
3929 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3930 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3931 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3932 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3933 // Now set the tracks, and expect frames to immediately start flowing.
3934 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
3935 auto callee_video_sender = callee()->pc()->GetSenders()[1];
3936 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3937 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3938 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3939 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
3940 MediaExpectations media_expectations;
3941 media_expectations.ExpectBidirectionalAudioAndVideo();
3942 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003943}
3944
3945// This test verifies that a remote video track can be added via AddStream,
3946// and sent end-to-end. For this particular test, it's simply echoed back
3947// from the caller to the callee, rather than being forwarded to a third
3948// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003949TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07003950 ASSERT_TRUE(CreatePeerConnectionWrappers());
3951 ConnectFakeSignaling();
3952 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08003953 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07003954 caller()->CreateAndSetAndSignalOffer();
3955 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003956 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07003957
3958 // Echo the stream back, and do a new offer/anwer (initiated by callee this
3959 // time).
3960 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
3961 callee()->CreateAndSetAndSignalOffer();
3962 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3963
Seth Hampson2f0d7022018-02-20 11:54:42 -08003964 MediaExpectations media_expectations;
3965 media_expectations.ExpectBidirectionalVideo();
3966 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003967}
3968
3969// Test that we achieve the expected end-to-end connection time, using a
3970// fake clock and simulated latency on the media and signaling paths.
3971// We use a TURN<->TURN connection because this is usually the quickest to
3972// set up initially, especially when we're confident the connection will work
3973// and can start sending media before we get a STUN response.
3974//
3975// With various optimizations enabled, here are the network delays we expect to
3976// be on the critical path:
3977// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
3978// signaling answer (with DTLS fingerprint).
3979// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
3980// using TURN<->TURN pair, and DTLS exchange is 4 packets,
3981// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003982TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07003983 rtc::ScopedFakeClock fake_clock;
3984 // Some things use a time of "0" as a special value, so we need to start out
3985 // the fake clock at a nonzero time.
3986 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003987 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003988
3989 static constexpr int media_hop_delay_ms = 50;
3990 static constexpr int signaling_trip_delay_ms = 500;
3991 // For explanation of these values, see comment above.
3992 static constexpr int required_media_hops = 9;
3993 static constexpr int required_signaling_trips = 2;
3994 // For internal delays (such as posting an event asychronously).
3995 static constexpr int allowed_internal_delay_ms = 20;
3996 static constexpr int total_connection_time_ms =
3997 media_hop_delay_ms * required_media_hops +
3998 signaling_trip_delay_ms * required_signaling_trips +
3999 allowed_internal_delay_ms;
4000
4001 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4002 3478};
4003 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4004 0};
4005 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4006 3478};
4007 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4008 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004009 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4010 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004011
Seth Hampsonaed71642018-06-11 07:41:32 -07004012 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4013 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004014 // Bypass permission check on received packets so media can be sent before
4015 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004016 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4017 turn_server_1->set_enable_permission_checks(false);
4018 });
4019 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4020 turn_server_2->set_enable_permission_checks(false);
4021 });
deadbeef1dcb1642017-03-29 21:08:16 -07004022
4023 PeerConnectionInterface::RTCConfiguration client_1_config;
4024 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4025 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4026 ice_server_1.username = "test";
4027 ice_server_1.password = "test";
4028 client_1_config.servers.push_back(ice_server_1);
4029 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4030 client_1_config.presume_writable_when_fully_relayed = true;
4031
4032 PeerConnectionInterface::RTCConfiguration client_2_config;
4033 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4034 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4035 ice_server_2.username = "test";
4036 ice_server_2.password = "test";
4037 client_2_config.servers.push_back(ice_server_2);
4038 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4039 client_2_config.presume_writable_when_fully_relayed = true;
4040
4041 ASSERT_TRUE(
4042 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4043 // Set up the simulated delays.
4044 SetSignalingDelayMs(signaling_trip_delay_ms);
4045 ConnectFakeSignaling();
4046 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4047 virtual_socket_server()->UpdateDelayDistribution();
4048
4049 // Set "offer to receive audio/video" without adding any tracks, so we just
4050 // set up ICE/DTLS with no media.
4051 PeerConnectionInterface::RTCOfferAnswerOptions options;
4052 options.offer_to_receive_audio = 1;
4053 options.offer_to_receive_video = 1;
4054 caller()->SetOfferAnswerOptions(options);
4055 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004056 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4057 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004058 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4059 // If this is not done a DCHECK can be hit in ports.cc, because a large
4060 // negative number is calculated for the rtt due to the global clock changing.
4061 caller()->pc()->Close();
4062 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07004063}
4064
Jonas Orelandbdcee282017-10-10 14:01:40 +02004065// Verify that a TurnCustomizer passed in through RTCConfiguration
4066// is actually used by the underlying TURN candidate pair.
4067// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004068TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004069 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4070 3478};
4071 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4072 0};
4073 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4074 3478};
4075 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4076 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004077 CreateTurnServer(turn_server_1_internal_address,
4078 turn_server_1_external_address);
4079 CreateTurnServer(turn_server_2_internal_address,
4080 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004081
4082 PeerConnectionInterface::RTCConfiguration client_1_config;
4083 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4084 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4085 ice_server_1.username = "test";
4086 ice_server_1.password = "test";
4087 client_1_config.servers.push_back(ice_server_1);
4088 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004089 auto* customizer1 = CreateTurnCustomizer();
4090 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004091
4092 PeerConnectionInterface::RTCConfiguration client_2_config;
4093 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4094 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4095 ice_server_2.username = "test";
4096 ice_server_2.password = "test";
4097 client_2_config.servers.push_back(ice_server_2);
4098 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004099 auto* customizer2 = CreateTurnCustomizer();
4100 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004101
4102 ASSERT_TRUE(
4103 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4104 ConnectFakeSignaling();
4105
4106 // Set "offer to receive audio/video" without adding any tracks, so we just
4107 // set up ICE/DTLS with no media.
4108 PeerConnectionInterface::RTCOfferAnswerOptions options;
4109 options.offer_to_receive_audio = 1;
4110 options.offer_to_receive_video = 1;
4111 caller()->SetOfferAnswerOptions(options);
4112 caller()->CreateAndSetAndSignalOffer();
4113 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4114
Seth Hampsonaed71642018-06-11 07:41:32 -07004115 ExpectTurnCustomizerCountersIncremented(customizer1);
4116 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004117}
4118
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004119// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4120// send media between the caller and the callee.
4121TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4122 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4123 3478};
4124 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4125
4126 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004127 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4128 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004129
4130 webrtc::PeerConnectionInterface::IceServer ice_server;
4131 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4132 ice_server.username = "test";
4133 ice_server.password = "test";
4134
4135 PeerConnectionInterface::RTCConfiguration client_1_config;
4136 client_1_config.servers.push_back(ice_server);
4137 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4138
4139 PeerConnectionInterface::RTCConfiguration client_2_config;
4140 client_2_config.servers.push_back(ice_server);
4141 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4142
4143 ASSERT_TRUE(
4144 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4145
4146 // Do normal offer/answer and wait for ICE to complete.
4147 ConnectFakeSignaling();
4148 caller()->AddAudioVideoTracks();
4149 callee()->AddAudioVideoTracks();
4150 caller()->CreateAndSetAndSignalOffer();
4151 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4152 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4153 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4154
4155 MediaExpectations media_expectations;
4156 media_expectations.ExpectBidirectionalAudioAndVideo();
4157 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4158}
4159
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004160// Verify that a SSLCertificateVerifier passed in through
4161// PeerConnectionDependencies is actually used by the underlying SSL
4162// implementation to determine whether a certificate presented by the TURN
4163// server is accepted by the client. Note that openssladapter_unittest.cc
4164// contains more detailed, lower-level tests.
4165TEST_P(PeerConnectionIntegrationTest,
4166 SSLCertificateVerifierUsedForTurnConnections) {
4167 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4168 3478};
4169 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4170
4171 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4172 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004173 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4174 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004175
4176 webrtc::PeerConnectionInterface::IceServer ice_server;
4177 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4178 ice_server.username = "test";
4179 ice_server.password = "test";
4180
4181 PeerConnectionInterface::RTCConfiguration client_1_config;
4182 client_1_config.servers.push_back(ice_server);
4183 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4184
4185 PeerConnectionInterface::RTCConfiguration client_2_config;
4186 client_2_config.servers.push_back(ice_server);
4187 // Setting the type to kRelay forces the connection to go through a TURN
4188 // server.
4189 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4190
4191 // Get a copy to the pointer so we can verify calls later.
4192 rtc::TestCertificateVerifier* client_1_cert_verifier =
4193 new rtc::TestCertificateVerifier();
4194 client_1_cert_verifier->verify_certificate_ = true;
4195 rtc::TestCertificateVerifier* client_2_cert_verifier =
4196 new rtc::TestCertificateVerifier();
4197 client_2_cert_verifier->verify_certificate_ = true;
4198
4199 // Create the dependencies with the test certificate verifier.
4200 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4201 client_1_deps.tls_cert_verifier =
4202 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4203 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4204 client_2_deps.tls_cert_verifier =
4205 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4206
4207 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4208 client_1_config, std::move(client_1_deps), client_2_config,
4209 std::move(client_2_deps)));
4210 ConnectFakeSignaling();
4211
4212 // Set "offer to receive audio/video" without adding any tracks, so we just
4213 // set up ICE/DTLS with no media.
4214 PeerConnectionInterface::RTCOfferAnswerOptions options;
4215 options.offer_to_receive_audio = 1;
4216 options.offer_to_receive_video = 1;
4217 caller()->SetOfferAnswerOptions(options);
4218 caller()->CreateAndSetAndSignalOffer();
4219 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4220
4221 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4222 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004223}
4224
4225TEST_P(PeerConnectionIntegrationTest,
4226 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4227 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4228 3478};
4229 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4230
4231 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4232 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004233 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4234 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004235
4236 webrtc::PeerConnectionInterface::IceServer ice_server;
4237 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4238 ice_server.username = "test";
4239 ice_server.password = "test";
4240
4241 PeerConnectionInterface::RTCConfiguration client_1_config;
4242 client_1_config.servers.push_back(ice_server);
4243 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4244
4245 PeerConnectionInterface::RTCConfiguration client_2_config;
4246 client_2_config.servers.push_back(ice_server);
4247 // Setting the type to kRelay forces the connection to go through a TURN
4248 // server.
4249 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4250
4251 // Get a copy to the pointer so we can verify calls later.
4252 rtc::TestCertificateVerifier* client_1_cert_verifier =
4253 new rtc::TestCertificateVerifier();
4254 client_1_cert_verifier->verify_certificate_ = false;
4255 rtc::TestCertificateVerifier* client_2_cert_verifier =
4256 new rtc::TestCertificateVerifier();
4257 client_2_cert_verifier->verify_certificate_ = false;
4258
4259 // Create the dependencies with the test certificate verifier.
4260 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4261 client_1_deps.tls_cert_verifier =
4262 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4263 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4264 client_2_deps.tls_cert_verifier =
4265 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4266
4267 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4268 client_1_config, std::move(client_1_deps), client_2_config,
4269 std::move(client_2_deps)));
4270 ConnectFakeSignaling();
4271
4272 // Set "offer to receive audio/video" without adding any tracks, so we just
4273 // set up ICE/DTLS with no media.
4274 PeerConnectionInterface::RTCOfferAnswerOptions options;
4275 options.offer_to_receive_audio = 1;
4276 options.offer_to_receive_video = 1;
4277 caller()->SetOfferAnswerOptions(options);
4278 caller()->CreateAndSetAndSignalOffer();
4279 bool wait_res = true;
4280 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4281 // properly, should be able to just wait for a state of "failed" instead of
4282 // waiting a fixed 10 seconds.
4283 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4284 ASSERT_FALSE(wait_res);
4285
4286 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4287 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004288}
4289
deadbeefc964d0b2017-04-03 10:03:35 -07004290// Test that audio and video flow end-to-end when codec names don't use the
4291// expected casing, given that they're supposed to be case insensitive. To test
4292// this, all but one codec is removed from each media description, and its
4293// casing is changed.
4294//
4295// In the past, this has regressed and caused crashes/black video, due to the
4296// fact that code at some layers was doing case-insensitive comparisons and
4297// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004298TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004299 ASSERT_TRUE(CreatePeerConnectionWrappers());
4300 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004301 caller()->AddAudioVideoTracks();
4302 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004303
4304 // Remove all but one audio/video codec (opus and VP8), and change the
4305 // casing of the caller's generated offer.
4306 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4307 cricket::AudioContentDescription* audio =
4308 GetFirstAudioContentDescription(description);
4309 ASSERT_NE(nullptr, audio);
4310 auto audio_codecs = audio->codecs();
4311 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4312 [](const cricket::AudioCodec& codec) {
4313 return codec.name != "opus";
4314 }),
4315 audio_codecs.end());
4316 ASSERT_EQ(1u, audio_codecs.size());
4317 audio_codecs[0].name = "OpUs";
4318 audio->set_codecs(audio_codecs);
4319
4320 cricket::VideoContentDescription* video =
4321 GetFirstVideoContentDescription(description);
4322 ASSERT_NE(nullptr, video);
4323 auto video_codecs = video->codecs();
4324 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4325 [](const cricket::VideoCodec& codec) {
4326 return codec.name != "VP8";
4327 }),
4328 video_codecs.end());
4329 ASSERT_EQ(1u, video_codecs.size());
4330 video_codecs[0].name = "vP8";
4331 video->set_codecs(video_codecs);
4332 });
4333
4334 caller()->CreateAndSetAndSignalOffer();
4335 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4336
4337 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004338 MediaExpectations media_expectations;
4339 media_expectations.ExpectBidirectionalAudioAndVideo();
4340 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004341}
4342
Jonas Oreland49ac5952018-09-26 16:04:32 +02004343TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004344 ASSERT_TRUE(CreatePeerConnectionWrappers());
4345 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004346 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004347 caller()->CreateAndSetAndSignalOffer();
4348 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004349 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004350 MediaExpectations media_expectations;
4351 media_expectations.CalleeExpectsSomeAudio(1);
4352 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004353 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004354 auto receiver = callee()->pc()->GetReceivers()[0];
4355 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004356 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004357 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4358 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004359 sources[0].source_id());
4360 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4361}
4362
4363TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4364 ASSERT_TRUE(CreatePeerConnectionWrappers());
4365 ConnectFakeSignaling();
4366 caller()->AddVideoTrack();
4367 caller()->CreateAndSetAndSignalOffer();
4368 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4369 // Wait for one video frame to be received by the callee.
4370 MediaExpectations media_expectations;
4371 media_expectations.CalleeExpectsSomeVideo(1);
4372 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4373 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4374 auto receiver = callee()->pc()->GetReceivers()[0];
4375 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4376 auto sources = receiver->GetSources();
4377 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4378 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4379 sources[0].source_id());
4380 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004381}
4382
deadbeef2f425aa2017-04-14 10:41:32 -07004383// Test that if a track is removed and added again with a different stream ID,
4384// the new stream ID is successfully communicated in SDP and media continues to
4385// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004386// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4387// it will not reuse a transceiver that has already been sending. After creating
4388// a new transceiver it tries to create an offer with two senders of the same
4389// track ids and it fails.
4390TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004391 ASSERT_TRUE(CreatePeerConnectionWrappers());
4392 ConnectFakeSignaling();
4393
deadbeef2f425aa2017-04-14 10:41:32 -07004394 // Add track using stream 1, do offer/answer.
4395 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4396 caller()->CreateLocalAudioTrack();
4397 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004398 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004399 caller()->CreateAndSetAndSignalOffer();
4400 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004401 {
4402 MediaExpectations media_expectations;
4403 media_expectations.CalleeExpectsSomeAudio(1);
4404 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4405 }
deadbeef2f425aa2017-04-14 10:41:32 -07004406 // Remove the sender, and create a new one with the new stream.
4407 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004408 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004409 caller()->CreateAndSetAndSignalOffer();
4410 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4411 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004412 {
4413 MediaExpectations media_expectations;
4414 media_expectations.CalleeExpectsSomeAudio();
4415 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4416 }
deadbeef2f425aa2017-04-14 10:41:32 -07004417}
4418
Seth Hampson2f0d7022018-02-20 11:54:42 -08004419TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004420 ASSERT_TRUE(CreatePeerConnectionWrappers());
4421 ConnectFakeSignaling();
4422
Karl Wiberg918f50c2018-07-05 11:40:33 +02004423 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Elad Alon99c3fe52017-10-13 16:29:40 +02004424 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
4425 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
4426 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004427 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4428 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004429
Steve Anton15324772018-01-16 10:26:49 -08004430 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004431 caller()->CreateAndSetAndSignalOffer();
4432 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4433}
4434
Steve Antonede9ca52017-10-16 13:04:27 -07004435// Test that if candidates are only signaled by applying full session
4436// descriptions (instead of using AddIceCandidate), the peers can connect to
4437// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004438TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004439 ASSERT_TRUE(CreatePeerConnectionWrappers());
4440 // Each side will signal the session descriptions but not candidates.
4441 ConnectFakeSignalingForSdpOnly();
4442
4443 // Add audio video track and exchange the initial offer/answer with media
4444 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004445 caller()->AddAudioVideoTracks();
4446 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004447 caller()->CreateAndSetAndSignalOffer();
4448
4449 // Wait for all candidates to be gathered on both the caller and callee.
4450 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4451 caller()->ice_gathering_state(), kDefaultTimeout);
4452 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4453 callee()->ice_gathering_state(), kDefaultTimeout);
4454
4455 // The candidates will now be included in the session description, so
4456 // signaling them will start the ICE connection.
4457 caller()->CreateAndSetAndSignalOffer();
4458 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4459
4460 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004461 MediaExpectations media_expectations;
4462 media_expectations.ExpectBidirectionalAudioAndVideo();
4463 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004464}
4465
henrika5f6bf242017-11-01 11:06:56 +01004466// Test that SetAudioPlayout can be used to disable audio playout from the
4467// start, then later enable it. This may be useful, for example, if the caller
4468// needs to play a local ringtone until some event occurs, after which it
4469// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004470TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004471 ASSERT_TRUE(CreatePeerConnectionWrappers());
4472 ConnectFakeSignaling();
4473
4474 // Set up audio-only call where audio playout is disabled on caller's side.
4475 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004476 caller()->AddAudioTrack();
4477 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004478 caller()->CreateAndSetAndSignalOffer();
4479 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4480
4481 // Pump messages for a second.
4482 WAIT(false, 1000);
4483 // Since audio playout is disabled, the caller shouldn't have received
4484 // anything (at the playout level, at least).
4485 EXPECT_EQ(0, caller()->audio_frames_received());
4486 // As a sanity check, make sure the callee (for which playout isn't disabled)
4487 // did still see frames on its audio level.
4488 ASSERT_GT(callee()->audio_frames_received(), 0);
4489
4490 // Enable playout again, and ensure audio starts flowing.
4491 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004492 MediaExpectations media_expectations;
4493 media_expectations.ExpectBidirectionalAudio();
4494 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004495}
4496
4497double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4498 auto report = pc->NewGetStats();
4499 auto track_stats_list =
4500 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4501 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4502 for (const auto* track_stats : track_stats_list) {
4503 if (track_stats->remote_source.is_defined() &&
4504 *track_stats->remote_source) {
4505 remote_track_stats = track_stats;
4506 break;
4507 }
4508 }
4509
4510 if (!remote_track_stats->total_audio_energy.is_defined()) {
4511 return 0.0;
4512 }
4513 return *remote_track_stats->total_audio_energy;
4514}
4515
4516// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4517// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004518TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004519 DisableAudioPlayoutStillGeneratesAudioStats) {
4520 ASSERT_TRUE(CreatePeerConnectionWrappers());
4521 ConnectFakeSignaling();
4522
4523 // Set up audio-only call where playout is disabled but audio-processing is
4524 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004525 caller()->AddAudioTrack();
4526 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004527 caller()->pc()->SetAudioPlayout(false);
4528
4529 caller()->CreateAndSetAndSignalOffer();
4530 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4531
4532 // Wait for the callee to receive audio stats.
4533 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4534}
4535
henrika4f167df2017-11-01 14:45:55 +01004536// Test that SetAudioRecording can be used to disable audio recording from the
4537// start, then later enable it. This may be useful, for example, if the caller
4538// wants to ensure that no audio resources are active before a certain state
4539// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004540TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004541 ASSERT_TRUE(CreatePeerConnectionWrappers());
4542 ConnectFakeSignaling();
4543
4544 // Set up audio-only call where audio recording is disabled on caller's side.
4545 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08004546 caller()->AddAudioTrack();
4547 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01004548 caller()->CreateAndSetAndSignalOffer();
4549 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4550
4551 // Pump messages for a second.
4552 WAIT(false, 1000);
4553 // Since caller has disabled audio recording, the callee shouldn't have
4554 // received anything.
4555 EXPECT_EQ(0, callee()->audio_frames_received());
4556 // As a sanity check, make sure the caller did still see frames on its
4557 // audio level since audio recording is enabled on the calle side.
4558 ASSERT_GT(caller()->audio_frames_received(), 0);
4559
4560 // Enable audio recording again, and ensure audio starts flowing.
4561 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004562 MediaExpectations media_expectations;
4563 media_expectations.ExpectBidirectionalAudio();
4564 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01004565}
4566
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004567// Test that after closing PeerConnections, they stop sending any packets (ICE,
4568// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004569TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004570 // Set up audio/video/data, wait for some frames to be received.
4571 ASSERT_TRUE(CreatePeerConnectionWrappers());
4572 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004573 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004574#ifdef HAVE_SCTP
4575 caller()->CreateDataChannel();
4576#endif
4577 caller()->CreateAndSetAndSignalOffer();
4578 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004579 MediaExpectations media_expectations;
4580 media_expectations.CalleeExpectsSomeAudioAndVideo();
4581 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004582 // Close PeerConnections.
4583 caller()->pc()->Close();
4584 callee()->pc()->Close();
4585 // Pump messages for a second, and ensure no new packets end up sent.
4586 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
4587 WAIT(false, 1000);
4588 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
4589 EXPECT_EQ(sent_packets_a, sent_packets_b);
4590}
4591
Steve Anton7eca0932018-03-30 15:18:41 -07004592// Test that transport stats are generated by the RTCStatsCollector for a
4593// connection that only involves data channels. This is a regression test for
4594// crbug.com/826972.
4595#ifdef HAVE_SCTP
4596TEST_P(PeerConnectionIntegrationTest,
4597 TransportStatsReportedForDataChannelOnlyConnection) {
4598 ASSERT_TRUE(CreatePeerConnectionWrappers());
4599 ConnectFakeSignaling();
4600 caller()->CreateDataChannel();
4601
4602 caller()->CreateAndSetAndSignalOffer();
4603 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4604 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
4605
4606 auto caller_report = caller()->NewGetStats();
4607 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
4608 auto callee_report = callee()->NewGetStats();
4609 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
4610}
4611#endif // HAVE_SCTP
4612
Qingsi Wang7685e862018-06-11 20:15:46 -07004613TEST_P(PeerConnectionIntegrationTest,
4614 IceEventsGeneratedAndLoggedInRtcEventLog) {
4615 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
4616 ConnectFakeSignaling();
4617 PeerConnectionInterface::RTCOfferAnswerOptions options;
4618 options.offer_to_receive_audio = 1;
4619 caller()->SetOfferAnswerOptions(options);
4620 caller()->CreateAndSetAndSignalOffer();
4621 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4622 ASSERT_NE(nullptr, caller()->event_log_factory());
4623 ASSERT_NE(nullptr, callee()->event_log_factory());
4624 webrtc::FakeRtcEventLog* caller_event_log =
4625 static_cast<webrtc::FakeRtcEventLog*>(
4626 caller()->event_log_factory()->last_log_created());
4627 webrtc::FakeRtcEventLog* callee_event_log =
4628 static_cast<webrtc::FakeRtcEventLog*>(
4629 callee()->event_log_factory()->last_log_created());
4630 ASSERT_NE(nullptr, caller_event_log);
4631 ASSERT_NE(nullptr, callee_event_log);
4632 int caller_ice_config_count = caller_event_log->GetEventCount(
4633 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4634 int caller_ice_event_count = caller_event_log->GetEventCount(
4635 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4636 int callee_ice_config_count = callee_event_log->GetEventCount(
4637 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4638 int callee_ice_event_count = callee_event_log->GetEventCount(
4639 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4640 EXPECT_LT(0, caller_ice_config_count);
4641 EXPECT_LT(0, caller_ice_event_count);
4642 EXPECT_LT(0, callee_ice_config_count);
4643 EXPECT_LT(0, callee_ice_event_count);
4644}
4645
Seth Hampson2f0d7022018-02-20 11:54:42 -08004646INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
4647 PeerConnectionIntegrationTest,
4648 Values(SdpSemantics::kPlanB,
4649 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08004650
Steve Anton74255ff2018-01-24 18:32:57 -08004651// Tests that verify interoperability between Plan B and Unified Plan
4652// PeerConnections.
4653class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004654 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08004655 public ::testing::WithParamInterface<
4656 std::tuple<SdpSemantics, SdpSemantics>> {
4657 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004658 // Setting the SdpSemantics for the base test to kDefault does not matter
4659 // because we specify not to use the test semantics when creating
4660 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08004661 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07004662 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08004663 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08004664 callee_semantics_(std::get<1>(GetParam())) {}
4665
4666 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07004667 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
4668 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08004669 }
4670
4671 const SdpSemantics caller_semantics_;
4672 const SdpSemantics callee_semantics_;
4673};
4674
4675TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
4676 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4677 ConnectFakeSignaling();
4678
4679 caller()->CreateAndSetAndSignalOffer();
4680 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4681}
4682
4683TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
4684 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4685 ConnectFakeSignaling();
4686 auto audio_sender = caller()->AddAudioTrack();
4687
4688 caller()->CreateAndSetAndSignalOffer();
4689 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4690
4691 // Verify that one audio receiver has been created on the remote and that it
4692 // has the same track ID as the sending track.
4693 auto receivers = callee()->pc()->GetReceivers();
4694 ASSERT_EQ(1u, receivers.size());
4695 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
4696 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
4697
Seth Hampson2f0d7022018-02-20 11:54:42 -08004698 MediaExpectations media_expectations;
4699 media_expectations.CalleeExpectsSomeAudio();
4700 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004701}
4702
4703TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
4704 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4705 ConnectFakeSignaling();
4706 auto video_sender = caller()->AddVideoTrack();
4707 auto audio_sender = caller()->AddAudioTrack();
4708
4709 caller()->CreateAndSetAndSignalOffer();
4710 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4711
4712 // Verify that one audio and one video receiver have been created on the
4713 // remote and that they have the same track IDs as the sending tracks.
4714 auto audio_receivers =
4715 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
4716 ASSERT_EQ(1u, audio_receivers.size());
4717 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
4718 auto video_receivers =
4719 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
4720 ASSERT_EQ(1u, video_receivers.size());
4721 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
4722
Seth Hampson2f0d7022018-02-20 11:54:42 -08004723 MediaExpectations media_expectations;
4724 media_expectations.CalleeExpectsSomeAudioAndVideo();
4725 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004726}
4727
4728TEST_P(PeerConnectionIntegrationInteropTest,
4729 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
4730 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4731 ConnectFakeSignaling();
4732 caller()->AddAudioVideoTracks();
4733 callee()->AddAudioVideoTracks();
4734
4735 caller()->CreateAndSetAndSignalOffer();
4736 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4737
Seth Hampson2f0d7022018-02-20 11:54:42 -08004738 MediaExpectations media_expectations;
4739 media_expectations.ExpectBidirectionalAudioAndVideo();
4740 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004741}
4742
4743TEST_P(PeerConnectionIntegrationInteropTest,
4744 ReverseRolesOneAudioLocalToOneVideoRemote) {
4745 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4746 ConnectFakeSignaling();
4747 caller()->AddAudioTrack();
4748 callee()->AddVideoTrack();
4749
4750 caller()->CreateAndSetAndSignalOffer();
4751 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4752
4753 // Verify that only the audio track has been negotiated.
4754 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
4755 // Might also check that the callee's NegotiationNeeded flag is set.
4756
4757 // Reverse roles.
4758 callee()->CreateAndSetAndSignalOffer();
4759 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4760
Seth Hampson2f0d7022018-02-20 11:54:42 -08004761 MediaExpectations media_expectations;
4762 media_expectations.CallerExpectsSomeVideo();
4763 media_expectations.CalleeExpectsSomeAudio();
4764 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004765}
4766
Steve Antonba42e992018-04-09 14:10:01 -07004767INSTANTIATE_TEST_CASE_P(
4768 PeerConnectionIntegrationTest,
4769 PeerConnectionIntegrationInteropTest,
4770 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4771 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
4772
4773// Test that if the Unified Plan side offers two video tracks then the Plan B
4774// side will only see the first one and ignore the second.
4775TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07004776 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
4777 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08004778 ConnectFakeSignaling();
4779 auto first_sender = caller()->AddVideoTrack();
4780 caller()->AddVideoTrack();
4781
4782 caller()->CreateAndSetAndSignalOffer();
4783 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4784
4785 // Verify that there is only one receiver and it corresponds to the first
4786 // added track.
4787 auto receivers = callee()->pc()->GetReceivers();
4788 ASSERT_EQ(1u, receivers.size());
4789 EXPECT_TRUE(receivers[0]->track()->enabled());
4790 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
4791
Seth Hampson2f0d7022018-02-20 11:54:42 -08004792 MediaExpectations media_expectations;
4793 media_expectations.CalleeExpectsSomeVideo();
4794 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004795}
4796
deadbeef1dcb1642017-03-29 21:08:16 -07004797} // namespace
4798
4799#endif // if !defined(THREAD_SANITIZER)