blob: d9fa1d5abdf9dfe039cf98e46a4d898d1e1cfc62 [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"
Anders Carlsson67537952018-05-03 11:28:29 +020031#include "api/video_codecs/builtin_video_decoder_factory.h"
32#include "api/video_codecs/builtin_video_encoder_factory.h"
33#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070034#include "call/call.h"
35#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
36#include "logging/rtc_event_log/rtc_event_log_factory_interface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "media/engine/fakewebrtcvideoengine.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070038#include "media/engine/webrtcmediaengine.h"
39#include "modules/audio_processing/include/audio_processing.h"
Zach Stein6fcdc2f2018-08-23 16:25:55 -070040#include "p2p/base/mockasyncresolver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "p2p/base/p2pconstants.h"
42#include "p2p/base/portinterface.h"
Steve Antonede9ca52017-10-16 13:04:27 -070043#include "p2p/base/teststunserver.h"
Jonas Orelandbdcee282017-10-10 14:01:40 +020044#include "p2p/base/testturncustomizer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "p2p/base/testturnserver.h"
46#include "p2p/client/basicportallocator.h"
47#include "pc/dtmfsender.h"
48#include "pc/localaudiosource.h"
49#include "pc/mediasession.h"
50#include "pc/peerconnection.h"
51#include "pc/peerconnectionfactory.h"
Seth Hampson2f0d7022018-02-20 11:54:42 -080052#include "pc/rtpmediautils.h"
Steve Anton4ab68ee2017-12-19 14:26:11 -080053#include "pc/sessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "pc/test/fakeaudiocapturemodule.h"
Niels Möller0f405822018-05-17 09:16:41 +020055#include "pc/test/fakeperiodicvideotracksource.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020056#include "pc/test/fakertccertificategenerator.h"
57#include "pc/test/fakevideotrackrenderer.h"
58#include "pc/test/mockpeerconnectionobservers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "rtc_base/fakenetwork.h"
Steve Antonede9ca52017-10-16 13:04:27 -070060#include "rtc_base/firewallsocketserver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020061#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020062#include "rtc_base/numerics/safe_conversions.h"
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070063#include "rtc_base/testcertificateverifier.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020064#include "rtc_base/virtualsocketserver.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070065#include "system_wrappers/include/metrics_default.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020066#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070067
68using cricket::ContentInfo;
69using cricket::FakeWebRtcVideoDecoder;
70using cricket::FakeWebRtcVideoDecoderFactory;
71using cricket::FakeWebRtcVideoEncoder;
72using cricket::FakeWebRtcVideoEncoderFactory;
73using cricket::MediaContentDescription;
Steve Antondf527fd2018-04-27 15:52:03 -070074using cricket::StreamParams;
Steve Antonede9ca52017-10-16 13:04:27 -070075using rtc::SocketAddress;
Seth Hampson2f0d7022018-02-20 11:54:42 -080076using ::testing::Combine;
Steve Antonede9ca52017-10-16 13:04:27 -070077using ::testing::ElementsAre;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070078using ::testing::Return;
79using ::testing::SetArgPointee;
Steve Antonede9ca52017-10-16 13:04:27 -070080using ::testing::Values;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070081using ::testing::_;
deadbeef1dcb1642017-03-29 21:08:16 -070082using webrtc::DataBuffer;
83using webrtc::DataChannelInterface;
84using webrtc::DtmfSender;
85using webrtc::DtmfSenderInterface;
86using webrtc::DtmfSenderObserverInterface;
Steve Anton15324772018-01-16 10:26:49 -080087using webrtc::FakeVideoTrackRenderer;
deadbeef1dcb1642017-03-29 21:08:16 -070088using webrtc::MediaStreamInterface;
89using webrtc::MediaStreamTrackInterface;
90using webrtc::MockCreateSessionDescriptionObserver;
91using webrtc::MockDataChannelObserver;
92using webrtc::MockSetSessionDescriptionObserver;
93using webrtc::MockStatsObserver;
94using webrtc::ObserverInterface;
Steve Anton8c0f7a72017-10-03 10:03:10 -070095using webrtc::PeerConnection;
deadbeef1dcb1642017-03-29 21:08:16 -070096using webrtc::PeerConnectionInterface;
Steve Anton74255ff2018-01-24 18:32:57 -080097using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070098using webrtc::PeerConnectionFactory;
Steve Anton8c0f7a72017-10-03 10:03:10 -070099using webrtc::PeerConnectionProxy;
Steve Anton15324772018-01-16 10:26:49 -0800100using webrtc::RTCErrorType;
Steve Anton7eca0932018-03-30 15:18:41 -0700101using webrtc::RTCTransportStats;
Steve Anton74255ff2018-01-24 18:32:57 -0800102using webrtc::RtpSenderInterface;
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100103using webrtc::RtpReceiverInterface;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800104using webrtc::RtpSenderInterface;
105using webrtc::RtpTransceiverDirection;
106using webrtc::RtpTransceiverInit;
107using webrtc::RtpTransceiverInterface;
Steve Antond3679212018-01-17 17:41:02 -0800108using webrtc::SdpSemantics;
Steve Antona3a92c22017-12-07 10:27:41 -0800109using webrtc::SdpType;
deadbeef1dcb1642017-03-29 21:08:16 -0700110using webrtc::SessionDescriptionInterface;
111using webrtc::StreamCollectionInterface;
Steve Anton15324772018-01-16 10:26:49 -0800112using webrtc::VideoTrackInterface;
deadbeef1dcb1642017-03-29 21:08:16 -0700113
114namespace {
115
116static const int kDefaultTimeout = 10000;
117static const int kMaxWaitForStatsMs = 3000;
118static const int kMaxWaitForActivationMs = 5000;
119static const int kMaxWaitForFramesMs = 10000;
120// Default number of audio/video frames to wait for before considering a test
121// successful.
122static const int kDefaultExpectedAudioFrameCount = 3;
123static const int kDefaultExpectedVideoFrameCount = 3;
124
deadbeef1dcb1642017-03-29 21:08:16 -0700125static const char kDataChannelLabel[] = "data_channel";
126
127// SRTP cipher name negotiated by the tests. This must be updated if the
128// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700129static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700130static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
131
Steve Antonede9ca52017-10-16 13:04:27 -0700132static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
133
deadbeef1dcb1642017-03-29 21:08:16 -0700134// Helper function for constructing offer/answer options to initiate an ICE
135// restart.
136PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
137 PeerConnectionInterface::RTCOfferAnswerOptions options;
138 options.ice_restart = true;
139 return options;
140}
141
deadbeefd8ad7882017-04-18 16:01:17 -0700142// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
143// attribute from received SDP, simulating a legacy endpoint.
144void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
145 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800146 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700147 }
148 desc->set_msid_supported(false);
149}
150
Seth Hampson5897a6e2018-04-03 11:16:33 -0700151// Removes all stream information besides the stream ids, simulating an
152// endpoint that only signals a=msid lines to convey stream_ids.
153void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
154 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700155 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700156 std::vector<std::string> stream_ids;
157 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700158 const StreamParams& first_stream =
159 content.media_description()->streams()[0];
160 track_id = first_stream.id;
161 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700162 }
163 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700164 StreamParams new_stream;
165 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700166 new_stream.set_stream_ids(stream_ids);
167 content.media_description()->AddStream(new_stream);
168 }
169}
170
zhihuangf8164932017-05-19 13:09:47 -0700171int FindFirstMediaStatsIndexByKind(
172 const std::string& kind,
173 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
174 media_stats_vec) {
175 for (size_t i = 0; i < media_stats_vec.size(); i++) {
176 if (media_stats_vec[i]->kind.ValueToString() == kind) {
177 return i;
178 }
179 }
180 return -1;
181}
182
deadbeef1dcb1642017-03-29 21:08:16 -0700183class SignalingMessageReceiver {
184 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800185 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700186 virtual void ReceiveIceMessage(const std::string& sdp_mid,
187 int sdp_mline_index,
188 const std::string& msg) = 0;
189
190 protected:
191 SignalingMessageReceiver() {}
192 virtual ~SignalingMessageReceiver() {}
193};
194
195class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
196 public:
197 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
198 : expected_media_type_(media_type) {}
199
200 void OnFirstPacketReceived(cricket::MediaType media_type) override {
201 ASSERT_EQ(expected_media_type_, media_type);
202 first_packet_received_ = true;
203 }
204
205 bool first_packet_received() const { return first_packet_received_; }
206
207 virtual ~MockRtpReceiverObserver() {}
208
209 private:
210 bool first_packet_received_ = false;
211 cricket::MediaType expected_media_type_;
212};
213
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700214// Used by PeerConnectionWrapper::OnIceCandidate to allow a test to modify an
215// ICE candidate before it is signaled.
216class IceCandidateReplacerInterface {
217 public:
218 virtual ~IceCandidateReplacerInterface() = default;
219 // Return nullptr to drop the candidate (it won't be signaled to the other
220 // side).
221 virtual std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
222 const webrtc::IceCandidateInterface*) = 0;
223};
224
deadbeef1dcb1642017-03-29 21:08:16 -0700225// Helper class that wraps a peer connection, observes it, and can accept
226// signaling messages from another wrapper.
227//
228// Uses a fake network, fake A/V capture, and optionally fake
229// encoders/decoders, though they aren't used by default since they don't
230// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700231// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800232// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700233class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800234 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700235 public:
236 // Different factory methods for convenience.
237 // TODO(deadbeef): Could use the pattern of:
238 //
239 // PeerConnectionWrapper =
240 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
241 //
242 // To reduce some code duplication.
243 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
244 const std::string& debug_name,
245 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
246 rtc::Thread* network_thread,
247 rtc::Thread* worker_thread) {
248 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700249 webrtc::PeerConnectionDependencies dependencies(nullptr);
250 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200251 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
252 worker_thread, nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700253 delete client;
254 return nullptr;
255 }
256 return client;
257 }
258
deadbeef2f425aa2017-04-14 10:41:32 -0700259 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
260 return peer_connection_factory_.get();
261 }
262
deadbeef1dcb1642017-03-29 21:08:16 -0700263 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
264
265 // If a signaling message receiver is set (via ConnectFakeSignaling), this
266 // will set the whole offer/answer exchange in motion. Just need to wait for
267 // the signaling state to reach "stable".
268 void CreateAndSetAndSignalOffer() {
269 auto offer = CreateOffer();
270 ASSERT_NE(nullptr, offer);
271 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
272 }
273
274 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
275 // when a remote offer is received (via fake signaling) and an answer is
276 // generated. By default, uses default options.
277 void SetOfferAnswerOptions(
278 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
279 offer_answer_options_ = options;
280 }
281
282 // Set a callback to be invoked when SDP is received via the fake signaling
283 // channel, which provides an opportunity to munge (modify) the SDP. This is
284 // used to test SDP being applied that a PeerConnection would normally not
285 // generate, but a non-JSEP endpoint might.
286 void SetReceivedSdpMunger(
287 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100288 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700289 }
290
deadbeefc964d0b2017-04-03 10:03:35 -0700291 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700292 // generated.
293 void SetGeneratedSdpMunger(
294 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100295 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700296 }
297
Seth Hampson2f0d7022018-02-20 11:54:42 -0800298 // Set a callback to be invoked when a remote offer is received via the fake
299 // signaling channel. This provides an opportunity to change the
300 // PeerConnection state before an answer is created and sent to the caller.
301 void SetRemoteOfferHandler(std::function<void()> handler) {
302 remote_offer_handler_ = std::move(handler);
303 }
304
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700305 void SetLocalIceCandidateReplacer(
306 std::unique_ptr<IceCandidateReplacerInterface> replacer) {
307 local_ice_candidate_replacer_ = std::move(replacer);
308 }
309
Steve Antonede9ca52017-10-16 13:04:27 -0700310 // Every ICE connection state in order that has been seen by the observer.
311 std::vector<PeerConnectionInterface::IceConnectionState>
312 ice_connection_state_history() const {
313 return ice_connection_state_history_;
314 }
Steve Anton6f25b092017-10-23 09:39:20 -0700315 void clear_ice_connection_state_history() {
316 ice_connection_state_history_.clear();
317 }
Steve Antonede9ca52017-10-16 13:04:27 -0700318
319 // Every ICE gathering state in order that has been seen by the observer.
320 std::vector<PeerConnectionInterface::IceGatheringState>
321 ice_gathering_state_history() const {
322 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700323 }
324
Steve Anton15324772018-01-16 10:26:49 -0800325 void AddAudioVideoTracks() {
326 AddAudioTrack();
327 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700328 }
329
Steve Anton74255ff2018-01-24 18:32:57 -0800330 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
331 return AddTrack(CreateLocalAudioTrack());
332 }
deadbeef1dcb1642017-03-29 21:08:16 -0700333
Steve Anton74255ff2018-01-24 18:32:57 -0800334 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
335 return AddTrack(CreateLocalVideoTrack());
336 }
deadbeef1dcb1642017-03-29 21:08:16 -0700337
338 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200339 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700340 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200341 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700342 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200343 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700344 // TODO(perkj): Test audio source when it is implemented. Currently audio
345 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700346 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700347 source);
348 }
349
350 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Niels Möller5c7efe72018-05-11 10:34:46 +0200351 return CreateLocalVideoTrackInternal(
352 webrtc::FakePeriodicVideoSource::Config());
deadbeef1dcb1642017-03-29 21:08:16 -0700353 }
354
355 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200356 CreateLocalVideoTrackWithConfig(
357 webrtc::FakePeriodicVideoSource::Config config) {
358 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700359 }
360
361 rtc::scoped_refptr<webrtc::VideoTrackInterface>
362 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200363 webrtc::FakePeriodicVideoSource::Config config;
364 config.rotation = rotation;
365 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700366 }
367
Steve Anton74255ff2018-01-24 18:32:57 -0800368 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
369 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800370 const std::vector<std::string>& stream_ids = {}) {
371 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800372 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800373 return result.MoveValue();
374 }
375
376 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
377 cricket::MediaType media_type) {
378 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
379 for (auto receiver : pc()->GetReceivers()) {
380 if (receiver->media_type() == media_type) {
381 receivers.push_back(receiver);
382 }
383 }
384 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700385 }
386
Seth Hampson2f0d7022018-02-20 11:54:42 -0800387 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
388 cricket::MediaType media_type) {
389 for (auto transceiver : pc()->GetTransceivers()) {
390 if (transceiver->receiver()->media_type() == media_type) {
391 return transceiver;
392 }
393 }
394 return nullptr;
395 }
396
deadbeef1dcb1642017-03-29 21:08:16 -0700397 bool SignalingStateStable() {
398 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
399 }
400
401 void CreateDataChannel() { CreateDataChannel(nullptr); }
402
403 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700404 CreateDataChannel(kDataChannelLabel, init);
405 }
406
407 void CreateDataChannel(const std::string& label,
408 const webrtc::DataChannelInit* init) {
409 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700410 ASSERT_TRUE(data_channel_.get() != nullptr);
411 data_observer_.reset(new MockDataChannelObserver(data_channel_));
412 }
413
414 DataChannelInterface* data_channel() { return data_channel_; }
415 const MockDataChannelObserver* data_observer() const {
416 return data_observer_.get();
417 }
418
419 int audio_frames_received() const {
420 return fake_audio_capture_module_->frames_received();
421 }
422
423 // Takes minimum of video frames received for each track.
424 //
425 // Can be used like:
426 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
427 //
428 // To ensure that all video tracks received at least a certain number of
429 // frames.
430 int min_video_frames_received_per_track() const {
431 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200432 if (fake_video_renderers_.empty()) {
433 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700434 }
deadbeef1dcb1642017-03-29 21:08:16 -0700435
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200436 for (const auto& pair : fake_video_renderers_) {
437 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700438 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200439 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700440 }
441
442 // Returns a MockStatsObserver in a state after stats gathering finished,
443 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700444 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700445 webrtc::MediaStreamTrackInterface* track) {
446 rtc::scoped_refptr<MockStatsObserver> observer(
447 new rtc::RefCountedObject<MockStatsObserver>());
448 EXPECT_TRUE(peer_connection_->GetStats(
449 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
450 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
451 return observer;
452 }
453
454 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700455 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
456 return OldGetStatsForTrack(nullptr);
457 }
458
459 // Synchronously gets stats and returns them. If it times out, fails the test
460 // and returns null.
461 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
462 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
463 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
464 peer_connection_->GetStats(callback);
465 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
466 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700467 }
468
469 int rendered_width() {
470 EXPECT_FALSE(fake_video_renderers_.empty());
471 return fake_video_renderers_.empty()
472 ? 0
473 : fake_video_renderers_.begin()->second->width();
474 }
475
476 int rendered_height() {
477 EXPECT_FALSE(fake_video_renderers_.empty());
478 return fake_video_renderers_.empty()
479 ? 0
480 : fake_video_renderers_.begin()->second->height();
481 }
482
483 double rendered_aspect_ratio() {
484 if (rendered_height() == 0) {
485 return 0.0;
486 }
487 return static_cast<double>(rendered_width()) / rendered_height();
488 }
489
490 webrtc::VideoRotation rendered_rotation() {
491 EXPECT_FALSE(fake_video_renderers_.empty());
492 return fake_video_renderers_.empty()
493 ? webrtc::kVideoRotation_0
494 : fake_video_renderers_.begin()->second->rotation();
495 }
496
497 int local_rendered_width() {
498 return local_video_renderer_ ? local_video_renderer_->width() : 0;
499 }
500
501 int local_rendered_height() {
502 return local_video_renderer_ ? local_video_renderer_->height() : 0;
503 }
504
505 double local_rendered_aspect_ratio() {
506 if (local_rendered_height() == 0) {
507 return 0.0;
508 }
509 return static_cast<double>(local_rendered_width()) /
510 local_rendered_height();
511 }
512
513 size_t number_of_remote_streams() {
514 if (!pc()) {
515 return 0;
516 }
517 return pc()->remote_streams()->count();
518 }
519
520 StreamCollectionInterface* remote_streams() const {
521 if (!pc()) {
522 ADD_FAILURE();
523 return nullptr;
524 }
525 return pc()->remote_streams();
526 }
527
528 StreamCollectionInterface* local_streams() {
529 if (!pc()) {
530 ADD_FAILURE();
531 return nullptr;
532 }
533 return pc()->local_streams();
534 }
535
536 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
537 return pc()->signaling_state();
538 }
539
540 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
541 return pc()->ice_connection_state();
542 }
543
544 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
545 return pc()->ice_gathering_state();
546 }
547
548 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
549 // GetReceivers. They're updated automatically when a remote offer/answer
550 // from the fake signaling channel is applied, or when
551 // ResetRtpReceiverObservers below is called.
552 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
553 rtp_receiver_observers() {
554 return rtp_receiver_observers_;
555 }
556
557 void ResetRtpReceiverObservers() {
558 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100559 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
560 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700561 std::unique_ptr<MockRtpReceiverObserver> observer(
562 new MockRtpReceiverObserver(receiver->media_type()));
563 receiver->SetObserver(observer.get());
564 rtp_receiver_observers_.push_back(std::move(observer));
565 }
566 }
567
Steve Antonede9ca52017-10-16 13:04:27 -0700568 rtc::FakeNetworkManager* network() const {
569 return fake_network_manager_.get();
570 }
571 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
572
Qingsi Wang7685e862018-06-11 20:15:46 -0700573 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
574 return event_log_factory_;
575 }
576
deadbeef1dcb1642017-03-29 21:08:16 -0700577 private:
578 explicit PeerConnectionWrapper(const std::string& debug_name)
579 : debug_name_(debug_name) {}
580
Niels Möllerf06f9232018-08-07 12:32:18 +0200581 bool Init(const PeerConnectionFactory::Options* options,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700582 const PeerConnectionInterface::RTCConfiguration* config,
583 webrtc::PeerConnectionDependencies dependencies,
584 rtc::Thread* network_thread,
Qingsi Wang7685e862018-06-11 20:15:46 -0700585 rtc::Thread* worker_thread,
586 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700587 // There's an error in this test code if Init ends up being called twice.
588 RTC_DCHECK(!peer_connection_);
589 RTC_DCHECK(!peer_connection_factory_);
590
591 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700592 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700593
594 std::unique_ptr<cricket::PortAllocator> port_allocator(
595 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700596 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700597 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
598 if (!fake_audio_capture_module_) {
599 return false;
600 }
deadbeef1dcb1642017-03-29 21:08:16 -0700601 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700602
603 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
604 pc_factory_dependencies.network_thread = network_thread;
605 pc_factory_dependencies.worker_thread = worker_thread;
606 pc_factory_dependencies.signaling_thread = signaling_thread;
607 pc_factory_dependencies.media_engine =
608 cricket::WebRtcMediaEngineFactory::Create(
609 rtc::scoped_refptr<webrtc::AudioDeviceModule>(
610 fake_audio_capture_module_),
611 webrtc::CreateBuiltinAudioEncoderFactory(),
612 webrtc::CreateBuiltinAudioDecoderFactory(),
613 webrtc::CreateBuiltinVideoEncoderFactory(),
614 webrtc::CreateBuiltinVideoDecoderFactory(), nullptr,
615 webrtc::AudioProcessingBuilder().Create());
616 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
617 if (event_log_factory) {
618 event_log_factory_ = event_log_factory.get();
619 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
620 } else {
621 pc_factory_dependencies.event_log_factory =
622 webrtc::CreateRtcEventLogFactory();
623 }
624 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
625 std::move(pc_factory_dependencies));
626
deadbeef1dcb1642017-03-29 21:08:16 -0700627 if (!peer_connection_factory_) {
628 return false;
629 }
630 if (options) {
631 peer_connection_factory_->SetOptions(*options);
632 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800633 if (config) {
634 sdp_semantics_ = config->sdp_semantics;
635 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700636
637 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200638 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700639 return peer_connection_.get() != nullptr;
640 }
641
642 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700643 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700644 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700645 PeerConnectionInterface::RTCConfiguration modified_config;
646 // If |config| is null, this will result in a default configuration being
647 // used.
648 if (config) {
649 modified_config = *config;
650 }
651 // Disable resolution adaptation; we don't want it interfering with the
652 // test results.
653 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
654 // ratios and not specific resolutions, is this even necessary?
655 modified_config.set_cpu_adaptation(false);
656
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700657 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700658 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700659 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700660 }
661
662 void set_signaling_message_receiver(
663 SignalingMessageReceiver* signaling_message_receiver) {
664 signaling_message_receiver_ = signaling_message_receiver;
665 }
666
667 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
668
Steve Antonede9ca52017-10-16 13:04:27 -0700669 void set_signal_ice_candidates(bool signal) {
670 signal_ice_candidates_ = signal;
671 }
672
deadbeef1dcb1642017-03-29 21:08:16 -0700673 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200674 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700675 // Set max frame rate to 10fps to reduce the risk of test flakiness.
676 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200677 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700678
Niels Möller5c7efe72018-05-11 10:34:46 +0200679 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200680 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
681 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700682 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200683 peer_connection_factory_->CreateVideoTrack(
684 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700685 if (!local_video_renderer_) {
686 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
687 }
688 return track;
689 }
690
691 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100692 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800693 std::unique_ptr<SessionDescriptionInterface> desc =
694 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700695 if (received_sdp_munger_) {
696 received_sdp_munger_(desc->description());
697 }
698
699 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
700 // Setting a remote description may have changed the number of receivers,
701 // so reset the receiver observers.
702 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800703 if (remote_offer_handler_) {
704 remote_offer_handler_();
705 }
deadbeef1dcb1642017-03-29 21:08:16 -0700706 auto answer = CreateAnswer();
707 ASSERT_NE(nullptr, answer);
708 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
709 }
710
711 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100712 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800713 std::unique_ptr<SessionDescriptionInterface> desc =
714 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700715 if (received_sdp_munger_) {
716 received_sdp_munger_(desc->description());
717 }
718
719 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
720 // Set the RtpReceiverObserver after receivers are created.
721 ResetRtpReceiverObservers();
722 }
723
724 // Returns null on failure.
725 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
726 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
727 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
728 pc()->CreateOffer(observer, offer_answer_options_);
729 return WaitForDescriptionFromObserver(observer);
730 }
731
732 // Returns null on failure.
733 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
734 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
735 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
736 pc()->CreateAnswer(observer, offer_answer_options_);
737 return WaitForDescriptionFromObserver(observer);
738 }
739
740 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100741 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700742 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
743 if (!observer->result()) {
744 return nullptr;
745 }
746 auto description = observer->MoveDescription();
747 if (generated_sdp_munger_) {
748 generated_sdp_munger_(description->description());
749 }
750 return description;
751 }
752
753 // Setting the local description and sending the SDP message over the fake
754 // signaling channel are combined into the same method because the SDP
755 // message needs to be sent as soon as SetLocalDescription finishes, without
756 // waiting for the observer to be called. This ensures that ICE candidates
757 // don't outrace the description.
758 bool SetLocalDescriptionAndSendSdpMessage(
759 std::unique_ptr<SessionDescriptionInterface> desc) {
760 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
761 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100762 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800763 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700764 std::string sdp;
765 EXPECT_TRUE(desc->ToString(&sdp));
766 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800767 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
768 RemoveUnusedVideoRenderers();
769 }
deadbeef1dcb1642017-03-29 21:08:16 -0700770 // As mentioned above, we need to send the message immediately after
771 // SetLocalDescription.
772 SendSdpMessage(type, sdp);
773 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
774 return true;
775 }
776
777 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
778 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
779 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100780 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700781 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800782 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
783 RemoveUnusedVideoRenderers();
784 }
deadbeef1dcb1642017-03-29 21:08:16 -0700785 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
786 return observer->result();
787 }
788
Seth Hampson2f0d7022018-02-20 11:54:42 -0800789 // This is a work around to remove unused fake_video_renderers from
790 // transceivers that have either stopped or are no longer receiving.
791 void RemoveUnusedVideoRenderers() {
792 auto transceivers = pc()->GetTransceivers();
793 for (auto& transceiver : transceivers) {
794 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
795 continue;
796 }
797 // Remove fake video renderers from any stopped transceivers.
798 if (transceiver->stopped()) {
799 auto it =
800 fake_video_renderers_.find(transceiver->receiver()->track()->id());
801 if (it != fake_video_renderers_.end()) {
802 fake_video_renderers_.erase(it);
803 }
804 }
805 // Remove fake video renderers from any transceivers that are no longer
806 // receiving.
807 if ((transceiver->current_direction() &&
808 !webrtc::RtpTransceiverDirectionHasRecv(
809 *transceiver->current_direction()))) {
810 auto it =
811 fake_video_renderers_.find(transceiver->receiver()->track()->id());
812 if (it != fake_video_renderers_.end()) {
813 fake_video_renderers_.erase(it);
814 }
815 }
816 }
817 }
818
deadbeef1dcb1642017-03-29 21:08:16 -0700819 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
820 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800821 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700822 if (signaling_delay_ms_ == 0) {
823 RelaySdpMessageIfReceiverExists(type, msg);
824 } else {
825 invoker_.AsyncInvokeDelayed<void>(
826 RTC_FROM_HERE, rtc::Thread::Current(),
827 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
828 this, type, msg),
829 signaling_delay_ms_);
830 }
831 }
832
Steve Antona3a92c22017-12-07 10:27:41 -0800833 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700834 if (signaling_message_receiver_) {
835 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
836 }
837 }
838
839 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
840 // default).
841 void SendIceMessage(const std::string& sdp_mid,
842 int sdp_mline_index,
843 const std::string& msg) {
844 if (signaling_delay_ms_ == 0) {
845 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
846 } else {
847 invoker_.AsyncInvokeDelayed<void>(
848 RTC_FROM_HERE, rtc::Thread::Current(),
849 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
850 this, sdp_mid, sdp_mline_index, msg),
851 signaling_delay_ms_);
852 }
853 }
854
855 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
856 int sdp_mline_index,
857 const std::string& msg) {
858 if (signaling_message_receiver_) {
859 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
860 msg);
861 }
862 }
863
864 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800865 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
866 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700867 HandleIncomingOffer(msg);
868 } else {
869 HandleIncomingAnswer(msg);
870 }
871 }
872
873 void ReceiveIceMessage(const std::string& sdp_mid,
874 int sdp_mline_index,
875 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100876 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700877 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
878 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
879 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
880 }
881
882 // PeerConnectionObserver callbacks.
883 void OnSignalingChange(
884 webrtc::PeerConnectionInterface::SignalingState new_state) override {
885 EXPECT_EQ(pc()->signaling_state(), new_state);
886 }
Steve Anton15324772018-01-16 10:26:49 -0800887 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
888 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
889 streams) override {
890 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
891 rtc::scoped_refptr<VideoTrackInterface> video_track(
892 static_cast<VideoTrackInterface*>(receiver->track().get()));
893 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700894 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800895 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200896 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700897 }
898 }
Steve Anton15324772018-01-16 10:26:49 -0800899 void OnRemoveTrack(
900 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
901 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
902 auto it = fake_video_renderers_.find(receiver->track()->id());
903 RTC_DCHECK(it != fake_video_renderers_.end());
904 fake_video_renderers_.erase(it);
905 }
906 }
deadbeef1dcb1642017-03-29 21:08:16 -0700907 void OnRenegotiationNeeded() override {}
908 void OnIceConnectionChange(
909 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
910 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700911 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700912 }
913 void OnIceGatheringChange(
914 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700915 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700916 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700917 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700918 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceIceCandidate(
919 const webrtc::IceCandidateInterface* candidate) {
920 std::string candidate_string;
921 candidate->ToString(&candidate_string);
922
923 auto owned_candidate =
924 local_ice_candidate_replacer_->ReplaceCandidate(candidate);
925 if (!owned_candidate) {
926 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer dropped \""
927 << candidate_string << "\"";
928 return nullptr;
929 }
930 std::string owned_candidate_string;
931 owned_candidate->ToString(&owned_candidate_string);
932 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer changed \""
933 << candidate_string << "\" to \"" << owned_candidate_string
934 << "\"";
935 return owned_candidate;
936 }
deadbeef1dcb1642017-03-29 21:08:16 -0700937 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100938 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700939
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700940 const webrtc::IceCandidateInterface* new_candidate = candidate;
941 std::unique_ptr<webrtc::IceCandidateInterface> owned_candidate;
942 if (local_ice_candidate_replacer_) {
943 owned_candidate = ReplaceIceCandidate(candidate);
944 if (!owned_candidate) {
945 return; // The candidate was dropped.
946 }
947 new_candidate = owned_candidate.get();
948 }
949
deadbeef1dcb1642017-03-29 21:08:16 -0700950 std::string ice_sdp;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700951 EXPECT_TRUE(new_candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700952 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700953 // Remote party may be deleted.
954 return;
955 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700956 SendIceMessage(new_candidate->sdp_mid(), new_candidate->sdp_mline_index(),
957 ice_sdp);
deadbeef1dcb1642017-03-29 21:08:16 -0700958 }
959 void OnDataChannel(
960 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100961 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700962 data_channel_ = data_channel;
963 data_observer_.reset(new MockDataChannelObserver(data_channel));
964 }
965
deadbeef1dcb1642017-03-29 21:08:16 -0700966 std::string debug_name_;
967
968 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
969
970 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
971 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
972 peer_connection_factory_;
973
Steve Antonede9ca52017-10-16 13:04:27 -0700974 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700975 // Needed to keep track of number of frames sent.
976 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
977 // Needed to keep track of number of frames received.
978 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
979 fake_video_renderers_;
980 // Needed to ensure frames aren't received for removed tracks.
981 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
982 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -0700983
984 // For remote peer communication.
985 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
986 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -0700987 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -0700988
Niels Möller5c7efe72018-05-11 10:34:46 +0200989 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -0700990 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +0200991 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
992 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -0700993 // |local_video_renderer_| attached to the first created local video track.
994 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
995
Seth Hampson2f0d7022018-02-20 11:54:42 -0800996 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -0700997 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
998 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
999 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001000 std::function<void()> remote_offer_handler_;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07001001 std::unique_ptr<IceCandidateReplacerInterface> local_ice_candidate_replacer_;
deadbeef1dcb1642017-03-29 21:08:16 -07001002 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1003 std::unique_ptr<MockDataChannelObserver> data_observer_;
1004
1005 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1006
Steve Antonede9ca52017-10-16 13:04:27 -07001007 std::vector<PeerConnectionInterface::IceConnectionState>
1008 ice_connection_state_history_;
1009 std::vector<PeerConnectionInterface::IceGatheringState>
1010 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001011
Qingsi Wang7685e862018-06-11 20:15:46 -07001012 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1013
deadbeef1dcb1642017-03-29 21:08:16 -07001014 rtc::AsyncInvoker invoker_;
1015
Seth Hampson2f0d7022018-02-20 11:54:42 -08001016 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001017};
1018
Elad Alon99c3fe52017-10-13 16:29:40 +02001019class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1020 public:
1021 virtual ~MockRtcEventLogOutput() = default;
1022 MOCK_CONST_METHOD0(IsActive, bool());
1023 MOCK_METHOD1(Write, bool(const std::string&));
1024};
1025
Seth Hampson2f0d7022018-02-20 11:54:42 -08001026// This helper object is used for both specifying how many audio/video frames
1027// are expected to be received for a caller/callee. It provides helper functions
1028// to specify these expectations. The object initially starts in a state of no
1029// expectations.
1030class MediaExpectations {
1031 public:
1032 enum ExpectFrames {
1033 kExpectSomeFrames,
1034 kExpectNoFrames,
1035 kNoExpectation,
1036 };
1037
1038 void ExpectBidirectionalAudioAndVideo() {
1039 ExpectBidirectionalAudio();
1040 ExpectBidirectionalVideo();
1041 }
1042
1043 void ExpectBidirectionalAudio() {
1044 CallerExpectsSomeAudio();
1045 CalleeExpectsSomeAudio();
1046 }
1047
1048 void ExpectNoAudio() {
1049 CallerExpectsNoAudio();
1050 CalleeExpectsNoAudio();
1051 }
1052
1053 void ExpectBidirectionalVideo() {
1054 CallerExpectsSomeVideo();
1055 CalleeExpectsSomeVideo();
1056 }
1057
1058 void ExpectNoVideo() {
1059 CallerExpectsNoVideo();
1060 CalleeExpectsNoVideo();
1061 }
1062
1063 void CallerExpectsSomeAudioAndVideo() {
1064 CallerExpectsSomeAudio();
1065 CallerExpectsSomeVideo();
1066 }
1067
1068 void CalleeExpectsSomeAudioAndVideo() {
1069 CalleeExpectsSomeAudio();
1070 CalleeExpectsSomeVideo();
1071 }
1072
1073 // Caller's audio functions.
1074 void CallerExpectsSomeAudio(
1075 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1076 caller_audio_expectation_ = kExpectSomeFrames;
1077 caller_audio_frames_expected_ = expected_audio_frames;
1078 }
1079
1080 void CallerExpectsNoAudio() {
1081 caller_audio_expectation_ = kExpectNoFrames;
1082 caller_audio_frames_expected_ = 0;
1083 }
1084
1085 // Caller's video functions.
1086 void CallerExpectsSomeVideo(
1087 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1088 caller_video_expectation_ = kExpectSomeFrames;
1089 caller_video_frames_expected_ = expected_video_frames;
1090 }
1091
1092 void CallerExpectsNoVideo() {
1093 caller_video_expectation_ = kExpectNoFrames;
1094 caller_video_frames_expected_ = 0;
1095 }
1096
1097 // Callee's audio functions.
1098 void CalleeExpectsSomeAudio(
1099 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1100 callee_audio_expectation_ = kExpectSomeFrames;
1101 callee_audio_frames_expected_ = expected_audio_frames;
1102 }
1103
1104 void CalleeExpectsNoAudio() {
1105 callee_audio_expectation_ = kExpectNoFrames;
1106 callee_audio_frames_expected_ = 0;
1107 }
1108
1109 // Callee's video functions.
1110 void CalleeExpectsSomeVideo(
1111 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1112 callee_video_expectation_ = kExpectSomeFrames;
1113 callee_video_frames_expected_ = expected_video_frames;
1114 }
1115
1116 void CalleeExpectsNoVideo() {
1117 callee_video_expectation_ = kExpectNoFrames;
1118 callee_video_frames_expected_ = 0;
1119 }
1120
1121 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1122 ExpectFrames caller_video_expectation_ = kNoExpectation;
1123 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1124 ExpectFrames callee_video_expectation_ = kNoExpectation;
1125 int caller_audio_frames_expected_ = 0;
1126 int caller_video_frames_expected_ = 0;
1127 int callee_audio_frames_expected_ = 0;
1128 int callee_video_frames_expected_ = 0;
1129};
1130
deadbeef1dcb1642017-03-29 21:08:16 -07001131// Tests two PeerConnections connecting to each other end-to-end, using a
1132// virtual network, fake A/V capture and fake encoder/decoders. The
1133// PeerConnections share the threads/socket servers, but use separate versions
1134// of everything else (including "PeerConnectionFactory"s).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001135class PeerConnectionIntegrationBaseTest : public testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001136 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001137 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1138 : sdp_semantics_(sdp_semantics),
1139 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001140 fss_(new rtc::FirewallSocketServer(ss_.get())),
1141 network_thread_(new rtc::Thread(fss_.get())),
deadbeef1dcb1642017-03-29 21:08:16 -07001142 worker_thread_(rtc::Thread::Create()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001143 network_thread_->SetName("PCNetworkThread", this);
1144 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001145 RTC_CHECK(network_thread_->Start());
1146 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001147 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001148 }
1149
Seth Hampson2f0d7022018-02-20 11:54:42 -08001150 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001151 // The PeerConnections should deleted before the TurnCustomizers.
1152 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1153 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1154 // that the TurnCustomizer outlives the life of the PeerConnection or else
1155 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001156 if (caller_) {
1157 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001158 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001159 }
1160 if (callee_) {
1161 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001162 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001163 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001164
1165 // If turn servers were created for the test they need to be destroyed on
1166 // the network thread.
1167 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1168 turn_servers_.clear();
1169 turn_customizers_.clear();
1170 });
deadbeef1dcb1642017-03-29 21:08:16 -07001171 }
1172
1173 bool SignalingStateStable() {
1174 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1175 }
1176
deadbeef71452802017-05-07 17:21:01 -07001177 bool DtlsConnected() {
1178 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1179 // are connected. This is an important distinction. Once we have separate
1180 // ICE and DTLS state, this check needs to use the DTLS state.
1181 return (callee()->ice_connection_state() ==
1182 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1183 callee()->ice_connection_state() ==
1184 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1185 (caller()->ice_connection_state() ==
1186 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1187 caller()->ice_connection_state() ==
1188 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
1189 }
1190
Qingsi Wang7685e862018-06-11 20:15:46 -07001191 // When |event_log_factory| is null, the default implementation of the event
1192 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001193 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1194 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001195 const PeerConnectionFactory::Options* options,
1196 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001197 webrtc::PeerConnectionDependencies dependencies,
1198 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001199 RTCConfiguration modified_config;
1200 if (config) {
1201 modified_config = *config;
1202 }
Steve Anton3acffc32018-04-12 17:21:03 -07001203 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001204 if (!dependencies.cert_generator) {
1205 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001206 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001207 }
1208 std::unique_ptr<PeerConnectionWrapper> client(
1209 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001210
Niels Möllerf06f9232018-08-07 12:32:18 +02001211 if (!client->Init(options, &modified_config, std::move(dependencies),
1212 network_thread_.get(), worker_thread_.get(),
1213 std::move(event_log_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001214 return nullptr;
1215 }
1216 return client;
1217 }
1218
Qingsi Wang7685e862018-06-11 20:15:46 -07001219 std::unique_ptr<PeerConnectionWrapper>
1220 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1221 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001222 const PeerConnectionFactory::Options* options,
1223 const RTCConfiguration* config,
1224 webrtc::PeerConnectionDependencies dependencies) {
1225 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1226 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001227 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001228 std::move(dependencies),
1229 std::move(event_log_factory));
1230 }
1231
deadbeef1dcb1642017-03-29 21:08:16 -07001232 bool CreatePeerConnectionWrappers() {
1233 return CreatePeerConnectionWrappersWithConfig(
1234 PeerConnectionInterface::RTCConfiguration(),
1235 PeerConnectionInterface::RTCConfiguration());
1236 }
1237
Steve Anton3acffc32018-04-12 17:21:03 -07001238 bool CreatePeerConnectionWrappersWithSdpSemantics(
1239 SdpSemantics caller_semantics,
1240 SdpSemantics callee_semantics) {
1241 // Can't specify the sdp_semantics in the passed-in configuration since it
1242 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1243 // stored in sdp_semantics_. So get around this by modifying the instance
1244 // variable before calling CreatePeerConnectionWrapper for the caller and
1245 // callee PeerConnections.
1246 SdpSemantics original_semantics = sdp_semantics_;
1247 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001248 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001249 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1250 nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001251 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001252 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001253 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1254 nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001255 sdp_semantics_ = original_semantics;
1256 return caller_ && callee_;
1257 }
1258
deadbeef1dcb1642017-03-29 21:08:16 -07001259 bool CreatePeerConnectionWrappersWithConfig(
1260 const PeerConnectionInterface::RTCConfiguration& caller_config,
1261 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001262 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001263 "Caller", nullptr, &caller_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001264 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001265 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001266 "Callee", nullptr, &callee_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001267 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001268 return caller_ && callee_;
1269 }
1270
1271 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1272 const PeerConnectionInterface::RTCConfiguration& caller_config,
1273 webrtc::PeerConnectionDependencies caller_dependencies,
1274 const PeerConnectionInterface::RTCConfiguration& callee_config,
1275 webrtc::PeerConnectionDependencies callee_dependencies) {
1276 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001277 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001278 std::move(caller_dependencies), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001279 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001280 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001281 std::move(callee_dependencies), nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001282 return caller_ && callee_;
1283 }
1284
1285 bool CreatePeerConnectionWrappersWithOptions(
1286 const PeerConnectionFactory::Options& caller_options,
1287 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001288 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001289 "Caller", &caller_options, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001290 webrtc::PeerConnectionDependencies(nullptr), nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001291 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001292 "Callee", &callee_options, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001293 webrtc::PeerConnectionDependencies(nullptr), nullptr);
1294 return caller_ && callee_;
1295 }
1296
1297 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1298 PeerConnectionInterface::RTCConfiguration default_config;
1299 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001300 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001301 webrtc::PeerConnectionDependencies(nullptr));
1302 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001303 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001304 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001305 return caller_ && callee_;
1306 }
1307
Seth Hampson2f0d7022018-02-20 11:54:42 -08001308 std::unique_ptr<PeerConnectionWrapper>
1309 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001310 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1311 new FakeRTCCertificateGenerator());
1312 cert_generator->use_alternate_key();
1313
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001314 webrtc::PeerConnectionDependencies dependencies(nullptr);
1315 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001316 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -07001317 std::move(dependencies), nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001318 }
1319
Seth Hampsonaed71642018-06-11 07:41:32 -07001320 cricket::TestTurnServer* CreateTurnServer(
1321 rtc::SocketAddress internal_address,
1322 rtc::SocketAddress external_address,
1323 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1324 const std::string& common_name = "test turn server") {
1325 rtc::Thread* thread = network_thread();
1326 std::unique_ptr<cricket::TestTurnServer> turn_server =
1327 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1328 RTC_FROM_HERE,
1329 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001330 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001331 thread, internal_address, external_address, type,
1332 /*ignore_bad_certs=*/true, common_name);
1333 });
1334 turn_servers_.push_back(std::move(turn_server));
1335 // Interactions with the turn server should be done on the network thread.
1336 return turn_servers_.back().get();
1337 }
1338
1339 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1340 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1341 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1342 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001343 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001344 turn_customizers_.push_back(std::move(turn_customizer));
1345 // Interactions with the turn customizer should be done on the network
1346 // thread.
1347 return turn_customizers_.back().get();
1348 }
1349
1350 // Checks that the function counters for a TestTurnCustomizer are greater than
1351 // 0.
1352 void ExpectTurnCustomizerCountersIncremented(
1353 cricket::TestTurnCustomizer* turn_customizer) {
1354 unsigned int allow_channel_data_counter =
1355 network_thread()->Invoke<unsigned int>(
1356 RTC_FROM_HERE, [turn_customizer] {
1357 return turn_customizer->allow_channel_data_cnt_;
1358 });
1359 EXPECT_GT(allow_channel_data_counter, 0u);
1360 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1361 RTC_FROM_HERE,
1362 [turn_customizer] { return turn_customizer->modify_cnt_; });
1363 EXPECT_GT(modify_counter, 0u);
1364 }
1365
deadbeef1dcb1642017-03-29 21:08:16 -07001366 // Once called, SDP blobs and ICE candidates will be automatically signaled
1367 // between PeerConnections.
1368 void ConnectFakeSignaling() {
1369 caller_->set_signaling_message_receiver(callee_.get());
1370 callee_->set_signaling_message_receiver(caller_.get());
1371 }
1372
Steve Antonede9ca52017-10-16 13:04:27 -07001373 // Once called, SDP blobs will be automatically signaled between
1374 // PeerConnections. Note that ICE candidates will not be signaled unless they
1375 // are in the exchanged SDP blobs.
1376 void ConnectFakeSignalingForSdpOnly() {
1377 ConnectFakeSignaling();
1378 SetSignalIceCandidates(false);
1379 }
1380
deadbeef1dcb1642017-03-29 21:08:16 -07001381 void SetSignalingDelayMs(int delay_ms) {
1382 caller_->set_signaling_delay_ms(delay_ms);
1383 callee_->set_signaling_delay_ms(delay_ms);
1384 }
1385
Steve Antonede9ca52017-10-16 13:04:27 -07001386 void SetSignalIceCandidates(bool signal) {
1387 caller_->set_signal_ice_candidates(signal);
1388 callee_->set_signal_ice_candidates(signal);
1389 }
1390
deadbeef1dcb1642017-03-29 21:08:16 -07001391 // Messages may get lost on the unreliable DataChannel, so we send multiple
1392 // times to avoid test flakiness.
1393 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1394 const std::string& data,
1395 int retries) {
1396 for (int i = 0; i < retries; ++i) {
1397 dc->Send(DataBuffer(data));
1398 }
1399 }
1400
1401 rtc::Thread* network_thread() { return network_thread_.get(); }
1402
1403 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1404
1405 PeerConnectionWrapper* caller() { return caller_.get(); }
1406
1407 // Set the |caller_| to the |wrapper| passed in and return the
1408 // original |caller_|.
1409 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1410 PeerConnectionWrapper* wrapper) {
1411 PeerConnectionWrapper* old = caller_.release();
1412 caller_.reset(wrapper);
1413 return old;
1414 }
1415
1416 PeerConnectionWrapper* callee() { return callee_.get(); }
1417
1418 // Set the |callee_| to the |wrapper| passed in and return the
1419 // original |callee_|.
1420 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1421 PeerConnectionWrapper* wrapper) {
1422 PeerConnectionWrapper* old = callee_.release();
1423 callee_.reset(wrapper);
1424 return old;
1425 }
1426
Steve Antonede9ca52017-10-16 13:04:27 -07001427 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1428
Seth Hampson2f0d7022018-02-20 11:54:42 -08001429 // Expects the provided number of new frames to be received within
1430 // kMaxWaitForFramesMs. The new expected frames are specified in
1431 // |media_expectations|. Returns false if any of the expectations were
1432 // not met.
1433 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1434 // First initialize the expected frame counts based upon the current
1435 // frame count.
1436 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1437 if (media_expectations.caller_audio_expectation_ ==
1438 MediaExpectations::kExpectSomeFrames) {
1439 total_caller_audio_frames_expected +=
1440 media_expectations.caller_audio_frames_expected_;
1441 }
1442 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001443 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001444 if (media_expectations.caller_video_expectation_ ==
1445 MediaExpectations::kExpectSomeFrames) {
1446 total_caller_video_frames_expected +=
1447 media_expectations.caller_video_frames_expected_;
1448 }
1449 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1450 if (media_expectations.callee_audio_expectation_ ==
1451 MediaExpectations::kExpectSomeFrames) {
1452 total_callee_audio_frames_expected +=
1453 media_expectations.callee_audio_frames_expected_;
1454 }
1455 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001456 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001457 if (media_expectations.callee_video_expectation_ ==
1458 MediaExpectations::kExpectSomeFrames) {
1459 total_callee_video_frames_expected +=
1460 media_expectations.callee_video_frames_expected_;
1461 }
deadbeef1dcb1642017-03-29 21:08:16 -07001462
Seth Hampson2f0d7022018-02-20 11:54:42 -08001463 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001464 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001465 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001466 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001467 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001468 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001469 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001470 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001471 total_callee_video_frames_expected,
1472 kMaxWaitForFramesMs);
1473 bool expectations_correct =
1474 caller()->audio_frames_received() >=
1475 total_caller_audio_frames_expected &&
1476 caller()->min_video_frames_received_per_track() >=
1477 total_caller_video_frames_expected &&
1478 callee()->audio_frames_received() >=
1479 total_callee_audio_frames_expected &&
1480 callee()->min_video_frames_received_per_track() >=
1481 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001482
Seth Hampson2f0d7022018-02-20 11:54:42 -08001483 // After the combined wait, print out a more detailed message upon
1484 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001485 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001486 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001487 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001488 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001489 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001490 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001491 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001492 total_callee_video_frames_expected);
1493
1494 // We want to make sure nothing unexpected was received.
1495 if (media_expectations.caller_audio_expectation_ ==
1496 MediaExpectations::kExpectNoFrames) {
1497 EXPECT_EQ(caller()->audio_frames_received(),
1498 total_caller_audio_frames_expected);
1499 if (caller()->audio_frames_received() !=
1500 total_caller_audio_frames_expected) {
1501 expectations_correct = false;
1502 }
1503 }
1504 if (media_expectations.caller_video_expectation_ ==
1505 MediaExpectations::kExpectNoFrames) {
1506 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1507 total_caller_video_frames_expected);
1508 if (caller()->min_video_frames_received_per_track() !=
1509 total_caller_video_frames_expected) {
1510 expectations_correct = false;
1511 }
1512 }
1513 if (media_expectations.callee_audio_expectation_ ==
1514 MediaExpectations::kExpectNoFrames) {
1515 EXPECT_EQ(callee()->audio_frames_received(),
1516 total_callee_audio_frames_expected);
1517 if (callee()->audio_frames_received() !=
1518 total_callee_audio_frames_expected) {
1519 expectations_correct = false;
1520 }
1521 }
1522 if (media_expectations.callee_video_expectation_ ==
1523 MediaExpectations::kExpectNoFrames) {
1524 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1525 total_callee_video_frames_expected);
1526 if (callee()->min_video_frames_received_per_track() !=
1527 total_callee_video_frames_expected) {
1528 expectations_correct = false;
1529 }
1530 }
1531 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001532 }
1533
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001534 void TestNegotiatedCipherSuite(
1535 const PeerConnectionFactory::Options& caller_options,
1536 const PeerConnectionFactory::Options& callee_options,
1537 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001538 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1539 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001540 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001541 caller()->AddAudioVideoTracks();
1542 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001543 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001544 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001545 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001546 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001547 // TODO(bugs.webrtc.org/9456): Fix it.
1548 EXPECT_EQ(1, webrtc::metrics::NumEvents(
1549 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1550 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001551 }
1552
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001553 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1554 bool remote_gcm_enabled,
1555 int expected_cipher_suite) {
1556 PeerConnectionFactory::Options caller_options;
1557 caller_options.crypto_options.enable_gcm_crypto_suites = local_gcm_enabled;
1558 PeerConnectionFactory::Options callee_options;
1559 callee_options.crypto_options.enable_gcm_crypto_suites = remote_gcm_enabled;
1560 TestNegotiatedCipherSuite(caller_options, callee_options,
1561 expected_cipher_suite);
1562 }
1563
Seth Hampson2f0d7022018-02-20 11:54:42 -08001564 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001565 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001566
deadbeef1dcb1642017-03-29 21:08:16 -07001567 private:
1568 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001569 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001570 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001571 // |network_thread_| and |worker_thread_| are used by both
1572 // |caller_| and |callee_| so they must be destroyed
1573 // later.
1574 std::unique_ptr<rtc::Thread> network_thread_;
1575 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001576 // The turn servers and turn customizers should be accessed & deleted on the
1577 // network thread to avoid a race with the socket read/write that occurs
1578 // on the network thread.
1579 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1580 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001581 std::unique_ptr<PeerConnectionWrapper> caller_;
1582 std::unique_ptr<PeerConnectionWrapper> callee_;
1583};
1584
Seth Hampson2f0d7022018-02-20 11:54:42 -08001585class PeerConnectionIntegrationTest
1586 : public PeerConnectionIntegrationBaseTest,
1587 public ::testing::WithParamInterface<SdpSemantics> {
1588 protected:
1589 PeerConnectionIntegrationTest()
1590 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1591};
1592
1593class PeerConnectionIntegrationTestPlanB
1594 : public PeerConnectionIntegrationBaseTest {
1595 protected:
1596 PeerConnectionIntegrationTestPlanB()
1597 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1598};
1599
1600class PeerConnectionIntegrationTestUnifiedPlan
1601 : public PeerConnectionIntegrationBaseTest {
1602 protected:
1603 PeerConnectionIntegrationTestUnifiedPlan()
1604 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1605};
1606
deadbeef1dcb1642017-03-29 21:08:16 -07001607// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1608// includes testing that the callback is invoked if an observer is connected
1609// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001610TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001611 RtpReceiverObserverOnFirstPacketReceived) {
1612 ASSERT_TRUE(CreatePeerConnectionWrappers());
1613 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001614 caller()->AddAudioVideoTracks();
1615 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001616 // Start offer/answer exchange and wait for it to complete.
1617 caller()->CreateAndSetAndSignalOffer();
1618 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1619 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001620 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1621 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001622 // Wait for all "first packet received" callbacks to be fired.
1623 EXPECT_TRUE_WAIT(
1624 std::all_of(caller()->rtp_receiver_observers().begin(),
1625 caller()->rtp_receiver_observers().end(),
1626 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1627 return o->first_packet_received();
1628 }),
1629 kMaxWaitForFramesMs);
1630 EXPECT_TRUE_WAIT(
1631 std::all_of(callee()->rtp_receiver_observers().begin(),
1632 callee()->rtp_receiver_observers().end(),
1633 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1634 return o->first_packet_received();
1635 }),
1636 kMaxWaitForFramesMs);
1637 // If new observers are set after the first packet was already received, the
1638 // callback should still be invoked.
1639 caller()->ResetRtpReceiverObservers();
1640 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001641 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1642 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001643 EXPECT_TRUE(
1644 std::all_of(caller()->rtp_receiver_observers().begin(),
1645 caller()->rtp_receiver_observers().end(),
1646 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1647 return o->first_packet_received();
1648 }));
1649 EXPECT_TRUE(
1650 std::all_of(callee()->rtp_receiver_observers().begin(),
1651 callee()->rtp_receiver_observers().end(),
1652 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1653 return o->first_packet_received();
1654 }));
1655}
1656
1657class DummyDtmfObserver : public DtmfSenderObserverInterface {
1658 public:
1659 DummyDtmfObserver() : completed_(false) {}
1660
1661 // Implements DtmfSenderObserverInterface.
1662 void OnToneChange(const std::string& tone) override {
1663 tones_.push_back(tone);
1664 if (tone.empty()) {
1665 completed_ = true;
1666 }
1667 }
1668
1669 const std::vector<std::string>& tones() const { return tones_; }
1670 bool completed() const { return completed_; }
1671
1672 private:
1673 bool completed_;
1674 std::vector<std::string> tones_;
1675};
1676
1677// Assumes |sender| already has an audio track added and the offer/answer
1678// exchange is done.
1679void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1680 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001681 // We should be able to get a DTMF sender from the local sender.
1682 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1683 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1684 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001685 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001686 dtmf_sender->RegisterObserver(&observer);
1687
1688 // Test the DtmfSender object just created.
1689 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1690 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1691
1692 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1693 std::vector<std::string> tones = {"1", "a", ""};
1694 EXPECT_EQ(tones, observer.tones());
1695 dtmf_sender->UnregisterObserver();
1696 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1697}
1698
1699// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1700// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001701TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001702 ASSERT_TRUE(CreatePeerConnectionWrappers());
1703 ConnectFakeSignaling();
1704 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001705 caller()->AddAudioTrack();
1706 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001707 caller()->CreateAndSetAndSignalOffer();
1708 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001709 // DTLS must finish before the DTMF sender can be used reliably.
1710 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001711 TestDtmfFromSenderToReceiver(caller(), callee());
1712 TestDtmfFromSenderToReceiver(callee(), caller());
1713}
1714
1715// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1716// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001717TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001718 ASSERT_TRUE(CreatePeerConnectionWrappers());
1719 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001720
deadbeef1dcb1642017-03-29 21:08:16 -07001721 // Do normal offer/answer and wait for some frames to be received in each
1722 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001723 caller()->AddAudioVideoTracks();
1724 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001725 caller()->CreateAndSetAndSignalOffer();
1726 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001727 MediaExpectations media_expectations;
1728 media_expectations.ExpectBidirectionalAudioAndVideo();
1729 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001730 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1731 webrtc::kEnumCounterKeyProtocolDtls));
1732 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1733 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001734}
1735
1736// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001737TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001738 PeerConnectionInterface::RTCConfiguration sdes_config;
1739 sdes_config.enable_dtls_srtp.emplace(false);
1740 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1741 ConnectFakeSignaling();
1742
1743 // 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::kEnumCounterKeyProtocolSdes));
1754 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1755 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001756}
1757
Steve Anton8c0f7a72017-10-03 10:03:10 -07001758// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1759// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001760TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001761 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1762 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1763 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1764 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1765 return pc->GetRemoteAudioSSLCertificate();
1766 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001767 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1768 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1769 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1770 return pc->GetRemoteAudioSSLCertChain();
1771 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001772
1773 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1774 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1775
1776 // Configure each side with a known certificate so they can be compared later.
1777 PeerConnectionInterface::RTCConfiguration caller_config;
1778 caller_config.enable_dtls_srtp.emplace(true);
1779 caller_config.certificates.push_back(caller_cert);
1780 PeerConnectionInterface::RTCConfiguration callee_config;
1781 callee_config.enable_dtls_srtp.emplace(true);
1782 callee_config.certificates.push_back(callee_cert);
1783 ASSERT_TRUE(
1784 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1785 ConnectFakeSignaling();
1786
1787 // When first initialized, there should not be a remote SSL certificate (and
1788 // calling this method should not crash).
1789 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1790 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001791 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1792 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001793
Steve Anton15324772018-01-16 10:26:49 -08001794 caller()->AddAudioTrack();
1795 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001796 caller()->CreateAndSetAndSignalOffer();
1797 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1798 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1799
1800 // Once DTLS has been connected, each side should return the other's SSL
1801 // certificate when calling GetRemoteAudioSSLCertificate.
1802
1803 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1804 ASSERT_TRUE(caller_remote_cert);
1805 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1806 caller_remote_cert->ToPEMString());
1807
1808 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1809 ASSERT_TRUE(callee_remote_cert);
1810 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1811 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001812
1813 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1814 ASSERT_TRUE(caller_remote_cert_chain);
1815 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1816 auto remote_cert = &caller_remote_cert_chain->Get(0);
1817 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1818 remote_cert->ToPEMString());
1819
1820 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1821 ASSERT_TRUE(callee_remote_cert_chain);
1822 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1823 remote_cert = &callee_remote_cert_chain->Get(0);
1824 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1825 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001826}
1827
deadbeef1dcb1642017-03-29 21:08:16 -07001828// This test sets up a call between two parties with a source resolution of
1829// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001830TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001831 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1832 ASSERT_TRUE(CreatePeerConnectionWrappers());
1833 ConnectFakeSignaling();
1834
Niels Möller5c7efe72018-05-11 10:34:46 +02001835 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1836 webrtc::FakePeriodicVideoSource::Config config;
1837 config.width = 1280;
1838 config.height = 720;
1839 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1840 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001841
1842 // Do normal offer/answer and wait for at least one frame to be received in
1843 // each direction.
1844 caller()->CreateAndSetAndSignalOffer();
1845 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1846 callee()->min_video_frames_received_per_track() > 0,
1847 kMaxWaitForFramesMs);
1848
1849 // Check rendered aspect ratio.
1850 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1851 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1852 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1853 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1854}
1855
1856// This test sets up an one-way call, with media only from caller to
1857// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001858TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001859 ASSERT_TRUE(CreatePeerConnectionWrappers());
1860 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001861 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001862 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001863 MediaExpectations media_expectations;
1864 media_expectations.CalleeExpectsSomeAudioAndVideo();
1865 media_expectations.CallerExpectsNoAudio();
1866 media_expectations.CallerExpectsNoVideo();
1867 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001868}
1869
1870// This test sets up a audio call initially, with the callee rejecting video
1871// initially. Then later the callee decides to upgrade to audio/video, and
1872// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001873TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001874 ASSERT_TRUE(CreatePeerConnectionWrappers());
1875 ConnectFakeSignaling();
1876 // Initially, offer an audio/video stream from the caller, but refuse to
1877 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001878 caller()->AddAudioVideoTracks();
1879 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001880 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1881 PeerConnectionInterface::RTCOfferAnswerOptions options;
1882 options.offer_to_receive_video = 0;
1883 callee()->SetOfferAnswerOptions(options);
1884 } else {
1885 callee()->SetRemoteOfferHandler([this] {
1886 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1887 });
1888 }
deadbeef1dcb1642017-03-29 21:08:16 -07001889 // Do offer/answer and make sure audio is still received end-to-end.
1890 caller()->CreateAndSetAndSignalOffer();
1891 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001892 {
1893 MediaExpectations media_expectations;
1894 media_expectations.ExpectBidirectionalAudio();
1895 media_expectations.ExpectNoVideo();
1896 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1897 }
deadbeef1dcb1642017-03-29 21:08:16 -07001898 // Sanity check that the callee's description has a rejected video section.
1899 ASSERT_NE(nullptr, callee()->pc()->local_description());
1900 const ContentInfo* callee_video_content =
1901 GetFirstVideoContent(callee()->pc()->local_description()->description());
1902 ASSERT_NE(nullptr, callee_video_content);
1903 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001904
deadbeef1dcb1642017-03-29 21:08:16 -07001905 // Now negotiate with video and ensure negotiation succeeds, with video
1906 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001907 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001908 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1909 PeerConnectionInterface::RTCOfferAnswerOptions options;
1910 options.offer_to_receive_video = 1;
1911 callee()->SetOfferAnswerOptions(options);
1912 } else {
1913 callee()->SetRemoteOfferHandler(nullptr);
1914 caller()->SetRemoteOfferHandler([this] {
1915 // The caller creates a new transceiver to receive video on when receiving
1916 // the offer, but by default it is send only.
1917 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001918 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001919 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1920 transceivers[2]->receiver()->media_type());
1921 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1922 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1923 });
1924 }
deadbeef1dcb1642017-03-29 21:08:16 -07001925 callee()->CreateAndSetAndSignalOffer();
1926 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001927 {
1928 // Expect additional audio frames to be received after the upgrade.
1929 MediaExpectations media_expectations;
1930 media_expectations.ExpectBidirectionalAudioAndVideo();
1931 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1932 }
deadbeef1dcb1642017-03-29 21:08:16 -07001933}
1934
deadbeef4389b4d2017-09-07 09:07:36 -07001935// Simpler than the above test; just add an audio track to an established
1936// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001937TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07001938 ASSERT_TRUE(CreatePeerConnectionWrappers());
1939 ConnectFakeSignaling();
1940 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08001941 caller()->AddVideoTrack();
1942 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001943 caller()->CreateAndSetAndSignalOffer();
1944 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1945 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08001946 caller()->AddAudioTrack();
1947 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001948 caller()->CreateAndSetAndSignalOffer();
1949 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1950 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001951 MediaExpectations media_expectations;
1952 media_expectations.ExpectBidirectionalAudioAndVideo();
1953 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07001954}
1955
deadbeef1dcb1642017-03-29 21:08:16 -07001956// This test sets up a call that's transferred to a new caller with a different
1957// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001958TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07001959 ASSERT_TRUE(CreatePeerConnectionWrappers());
1960 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001961 caller()->AddAudioVideoTracks();
1962 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001963 caller()->CreateAndSetAndSignalOffer();
1964 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1965
1966 // Keep the original peer around which will still send packets to the
1967 // receiving client. These SRTP packets will be dropped.
1968 std::unique_ptr<PeerConnectionWrapper> original_peer(
1969 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08001970 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07001971 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1972 // directly above.
1973 original_peer->pc()->Close();
1974
1975 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001976 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001977 caller()->CreateAndSetAndSignalOffer();
1978 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1979 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001980 MediaExpectations media_expectations;
1981 media_expectations.ExpectBidirectionalAudioAndVideo();
1982 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001983}
1984
1985// This test sets up a call that's transferred to a new callee with a different
1986// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001987TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07001988 ASSERT_TRUE(CreatePeerConnectionWrappers());
1989 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001990 caller()->AddAudioVideoTracks();
1991 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001992 caller()->CreateAndSetAndSignalOffer();
1993 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1994
1995 // Keep the original peer around which will still send packets to the
1996 // receiving client. These SRTP packets will be dropped.
1997 std::unique_ptr<PeerConnectionWrapper> original_peer(
1998 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08001999 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002000 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2001 // directly above.
2002 original_peer->pc()->Close();
2003
2004 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002005 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002006 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2007 caller()->CreateAndSetAndSignalOffer();
2008 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2009 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002010 MediaExpectations media_expectations;
2011 media_expectations.ExpectBidirectionalAudioAndVideo();
2012 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002013}
2014
2015// This test sets up a non-bundled call and negotiates bundling at the same
2016// time as starting an ICE restart. When bundling is in effect in the restart,
2017// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002018TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002019 ASSERT_TRUE(CreatePeerConnectionWrappers());
2020 ConnectFakeSignaling();
2021
Steve Anton15324772018-01-16 10:26:49 -08002022 caller()->AddAudioVideoTracks();
2023 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002024 // Remove the bundle group from the SDP received by the callee.
2025 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2026 desc->RemoveGroupByName("BUNDLE");
2027 });
2028 caller()->CreateAndSetAndSignalOffer();
2029 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002030 {
2031 MediaExpectations media_expectations;
2032 media_expectations.ExpectBidirectionalAudioAndVideo();
2033 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2034 }
deadbeef1dcb1642017-03-29 21:08:16 -07002035 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2036 callee()->SetReceivedSdpMunger(nullptr);
2037 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2038 caller()->CreateAndSetAndSignalOffer();
2039 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2040
2041 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002042 {
2043 MediaExpectations media_expectations;
2044 media_expectations.ExpectBidirectionalAudioAndVideo();
2045 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2046 }
deadbeef1dcb1642017-03-29 21:08:16 -07002047}
2048
2049// Test CVO (Coordination of Video Orientation). If a video source is rotated
2050// and both peers support the CVO RTP header extension, the actual video frames
2051// don't need to be encoded in different resolutions, since the rotation is
2052// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002053TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002054 ASSERT_TRUE(CreatePeerConnectionWrappers());
2055 ConnectFakeSignaling();
2056 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002057 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002058 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002059 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002060 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2061
2062 // Wait for video frames to be received by both sides.
2063 caller()->CreateAndSetAndSignalOffer();
2064 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2065 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2066 callee()->min_video_frames_received_per_track() > 0,
2067 kMaxWaitForFramesMs);
2068
2069 // Ensure that the aspect ratio is unmodified.
2070 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2071 // not just assumed.
2072 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2073 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2074 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2075 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2076 // Ensure that the CVO bits were surfaced to the renderer.
2077 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2078 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2079}
2080
2081// Test that when the CVO extension isn't supported, video is rotated the
2082// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002083TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002084 ASSERT_TRUE(CreatePeerConnectionWrappers());
2085 ConnectFakeSignaling();
2086 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002087 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002088 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002089 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002090 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2091
2092 // Remove the CVO extension from the offered SDP.
2093 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2094 cricket::VideoContentDescription* video =
2095 GetFirstVideoContentDescription(desc);
2096 video->ClearRtpHeaderExtensions();
2097 });
2098 // Wait for video frames to be received by both sides.
2099 caller()->CreateAndSetAndSignalOffer();
2100 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2101 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2102 callee()->min_video_frames_received_per_track() > 0,
2103 kMaxWaitForFramesMs);
2104
2105 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2106 // rotation.
2107 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2108 // not just assumed.
2109 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2110 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2111 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2112 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2113 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2114 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2115 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2116}
2117
deadbeef1dcb1642017-03-29 21:08:16 -07002118// Test that if the answerer rejects the audio m= section, no audio is sent or
2119// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002120TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002121 ASSERT_TRUE(CreatePeerConnectionWrappers());
2122 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002123 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002124 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2125 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2126 // it will reject the audio m= section completely.
2127 PeerConnectionInterface::RTCOfferAnswerOptions options;
2128 options.offer_to_receive_audio = 0;
2129 callee()->SetOfferAnswerOptions(options);
2130 } else {
2131 // Stopping the audio RtpTransceiver will cause the media section to be
2132 // rejected in the answer.
2133 callee()->SetRemoteOfferHandler([this] {
2134 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2135 });
2136 }
Steve Anton15324772018-01-16 10:26:49 -08002137 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002138 // Do offer/answer and wait for successful end-to-end video frames.
2139 caller()->CreateAndSetAndSignalOffer();
2140 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002141 MediaExpectations media_expectations;
2142 media_expectations.ExpectBidirectionalVideo();
2143 media_expectations.ExpectNoAudio();
2144 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2145
deadbeef1dcb1642017-03-29 21:08:16 -07002146 // Sanity check that the callee's description has a rejected audio section.
2147 ASSERT_NE(nullptr, callee()->pc()->local_description());
2148 const ContentInfo* callee_audio_content =
2149 GetFirstAudioContent(callee()->pc()->local_description()->description());
2150 ASSERT_NE(nullptr, callee_audio_content);
2151 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002152 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2153 // The caller's transceiver should have stopped after receiving the answer.
2154 EXPECT_TRUE(caller()
2155 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2156 ->stopped());
2157 }
deadbeef1dcb1642017-03-29 21:08:16 -07002158}
2159
2160// Test that if the answerer rejects the video m= section, no video is sent or
2161// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002162TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002163 ASSERT_TRUE(CreatePeerConnectionWrappers());
2164 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002165 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002166 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2167 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2168 // it will reject the video m= section completely.
2169 PeerConnectionInterface::RTCOfferAnswerOptions options;
2170 options.offer_to_receive_video = 0;
2171 callee()->SetOfferAnswerOptions(options);
2172 } else {
2173 // Stopping the video RtpTransceiver will cause the media section to be
2174 // rejected in the answer.
2175 callee()->SetRemoteOfferHandler([this] {
2176 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2177 });
2178 }
Steve Anton15324772018-01-16 10:26:49 -08002179 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002180 // Do offer/answer and wait for successful end-to-end audio frames.
2181 caller()->CreateAndSetAndSignalOffer();
2182 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002183 MediaExpectations media_expectations;
2184 media_expectations.ExpectBidirectionalAudio();
2185 media_expectations.ExpectNoVideo();
2186 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2187
deadbeef1dcb1642017-03-29 21:08:16 -07002188 // Sanity check that the callee's description has a rejected video section.
2189 ASSERT_NE(nullptr, callee()->pc()->local_description());
2190 const ContentInfo* callee_video_content =
2191 GetFirstVideoContent(callee()->pc()->local_description()->description());
2192 ASSERT_NE(nullptr, callee_video_content);
2193 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002194 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2195 // The caller's transceiver should have stopped after receiving the answer.
2196 EXPECT_TRUE(caller()
2197 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2198 ->stopped());
2199 }
deadbeef1dcb1642017-03-29 21:08:16 -07002200}
2201
2202// Test that if the answerer rejects both audio and video m= sections, nothing
2203// bad happens.
2204// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2205// test anything but the fact that negotiation succeeds, which doesn't mean
2206// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002207TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002208 ASSERT_TRUE(CreatePeerConnectionWrappers());
2209 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002210 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002211 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2212 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2213 // will reject both audio and video m= sections.
2214 PeerConnectionInterface::RTCOfferAnswerOptions options;
2215 options.offer_to_receive_audio = 0;
2216 options.offer_to_receive_video = 0;
2217 callee()->SetOfferAnswerOptions(options);
2218 } else {
2219 callee()->SetRemoteOfferHandler([this] {
2220 // Stopping all transceivers will cause all media sections to be rejected.
2221 for (auto transceiver : callee()->pc()->GetTransceivers()) {
2222 transceiver->Stop();
2223 }
2224 });
2225 }
deadbeef1dcb1642017-03-29 21:08:16 -07002226 // Do offer/answer and wait for stable signaling state.
2227 caller()->CreateAndSetAndSignalOffer();
2228 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002229
deadbeef1dcb1642017-03-29 21:08:16 -07002230 // Sanity check that the callee's description has rejected m= sections.
2231 ASSERT_NE(nullptr, callee()->pc()->local_description());
2232 const ContentInfo* callee_audio_content =
2233 GetFirstAudioContent(callee()->pc()->local_description()->description());
2234 ASSERT_NE(nullptr, callee_audio_content);
2235 EXPECT_TRUE(callee_audio_content->rejected);
2236 const ContentInfo* callee_video_content =
2237 GetFirstVideoContent(callee()->pc()->local_description()->description());
2238 ASSERT_NE(nullptr, callee_video_content);
2239 EXPECT_TRUE(callee_video_content->rejected);
2240}
2241
2242// This test sets up an audio and video call between two parties. After the
2243// call runs for a while, the caller sends an updated offer with video being
2244// rejected. Once the re-negotiation is done, the video flow should stop and
2245// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002246TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002247 ASSERT_TRUE(CreatePeerConnectionWrappers());
2248 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002249 caller()->AddAudioVideoTracks();
2250 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002251 caller()->CreateAndSetAndSignalOffer();
2252 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002253 {
2254 MediaExpectations media_expectations;
2255 media_expectations.ExpectBidirectionalAudioAndVideo();
2256 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2257 }
deadbeef1dcb1642017-03-29 21:08:16 -07002258 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002259 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2260 caller()->SetGeneratedSdpMunger(
2261 [](cricket::SessionDescription* description) {
2262 for (cricket::ContentInfo& content : description->contents()) {
2263 if (cricket::IsVideoContent(&content)) {
2264 content.rejected = true;
2265 }
2266 }
2267 });
2268 } else {
2269 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2270 }
deadbeef1dcb1642017-03-29 21:08:16 -07002271 caller()->CreateAndSetAndSignalOffer();
2272 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2273
2274 // Sanity check that the caller's description has a rejected video section.
2275 ASSERT_NE(nullptr, caller()->pc()->local_description());
2276 const ContentInfo* caller_video_content =
2277 GetFirstVideoContent(caller()->pc()->local_description()->description());
2278 ASSERT_NE(nullptr, caller_video_content);
2279 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002280 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002281 {
2282 MediaExpectations media_expectations;
2283 media_expectations.ExpectBidirectionalAudio();
2284 media_expectations.ExpectNoVideo();
2285 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2286 }
deadbeef1dcb1642017-03-29 21:08:16 -07002287}
2288
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002289// Do one offer/answer with audio, another that disables it (rejecting the m=
2290// section), and another that re-enables it. Regression test for:
2291// bugs.webrtc.org/6023
2292TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2293 ASSERT_TRUE(CreatePeerConnectionWrappers());
2294 ConnectFakeSignaling();
2295
2296 // Add audio track, do normal offer/answer.
2297 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2298 caller()->CreateLocalAudioTrack();
2299 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2300 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2301 caller()->CreateAndSetAndSignalOffer();
2302 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2303
2304 // Remove audio track, and set offer_to_receive_audio to false to cause the
2305 // m= section to be completely disabled, not just "recvonly".
2306 caller()->pc()->RemoveTrack(sender);
2307 PeerConnectionInterface::RTCOfferAnswerOptions options;
2308 options.offer_to_receive_audio = 0;
2309 caller()->SetOfferAnswerOptions(options);
2310 caller()->CreateAndSetAndSignalOffer();
2311 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2312
2313 // Add the audio track again, expecting negotiation to succeed and frames to
2314 // flow.
2315 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2316 options.offer_to_receive_audio = 1;
2317 caller()->SetOfferAnswerOptions(options);
2318 caller()->CreateAndSetAndSignalOffer();
2319 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2320
2321 MediaExpectations media_expectations;
2322 media_expectations.CalleeExpectsSomeAudio();
2323 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2324}
2325
deadbeef1dcb1642017-03-29 21:08:16 -07002326// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2327// is needed to support legacy endpoints.
2328// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2329// add a test for an end-to-end test without MID signaling either (basically,
2330// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002331TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002332 ASSERT_TRUE(CreatePeerConnectionWrappers());
2333 ConnectFakeSignaling();
2334 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002335 caller()->AddAudioVideoTracks();
2336 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002337 // Remove SSRCs and MSIDs from the received offer SDP.
2338 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002339 caller()->CreateAndSetAndSignalOffer();
2340 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002341 MediaExpectations media_expectations;
2342 media_expectations.ExpectBidirectionalAudioAndVideo();
2343 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002344}
2345
Seth Hampson5897a6e2018-04-03 11:16:33 -07002346// Basic end-to-end test, without SSRC signaling. This means that the track
2347// was created properly and frames are delivered when the MSIDs are communicated
2348// with a=msid lines and no a=ssrc lines.
2349TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2350 EndToEndCallWithoutSsrcSignaling) {
2351 const char kStreamId[] = "streamId";
2352 ASSERT_TRUE(CreatePeerConnectionWrappers());
2353 ConnectFakeSignaling();
2354 // Add just audio tracks.
2355 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2356 callee()->AddAudioTrack();
2357
2358 // Remove SSRCs from the received offer SDP.
2359 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2360 caller()->CreateAndSetAndSignalOffer();
2361 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2362 MediaExpectations media_expectations;
2363 media_expectations.ExpectBidirectionalAudio();
2364 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2365}
2366
Steve Antondf527fd2018-04-27 15:52:03 -07002367// Tests that video flows between multiple video tracks when SSRCs are not
2368// signaled. This exercises the MID RTP header extension which is needed to
2369// demux the incoming video tracks.
2370TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2371 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2372 ASSERT_TRUE(CreatePeerConnectionWrappers());
2373 ConnectFakeSignaling();
2374 caller()->AddVideoTrack();
2375 caller()->AddVideoTrack();
2376 callee()->AddVideoTrack();
2377 callee()->AddVideoTrack();
2378
2379 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2380 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2381 caller()->CreateAndSetAndSignalOffer();
2382 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2383 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2384 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2385
2386 // Expect video to be received in both directions on both tracks.
2387 MediaExpectations media_expectations;
2388 media_expectations.ExpectBidirectionalVideo();
2389 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2390}
2391
deadbeef1dcb1642017-03-29 21:08:16 -07002392// Test that if two video tracks are sent (from caller to callee, in this test),
2393// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002394TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002395 ASSERT_TRUE(CreatePeerConnectionWrappers());
2396 ConnectFakeSignaling();
2397 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002398 caller()->AddAudioVideoTracks();
2399 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002400 caller()->CreateAndSetAndSignalOffer();
2401 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002402 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002403
2404 MediaExpectations media_expectations;
2405 media_expectations.CalleeExpectsSomeAudioAndVideo();
2406 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002407}
2408
2409static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2410 bool first = true;
2411 for (cricket::ContentInfo& content : desc->contents()) {
2412 if (first) {
2413 first = false;
2414 continue;
2415 }
2416 content.bundle_only = true;
2417 }
2418 first = true;
2419 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2420 if (first) {
2421 first = false;
2422 continue;
2423 }
2424 transport.description.ice_ufrag.clear();
2425 transport.description.ice_pwd.clear();
2426 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2427 transport.description.identity_fingerprint.reset(nullptr);
2428 }
2429}
2430
2431// Test that if applying a true "max bundle" offer, which uses ports of 0,
2432// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2433// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2434// successfully and media flows.
2435// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2436// TODO(deadbeef): Won't need this test once we start generating actual
2437// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002438TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002439 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2440 ASSERT_TRUE(CreatePeerConnectionWrappers());
2441 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002442 caller()->AddAudioVideoTracks();
2443 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002444 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2445 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2446 // but the first m= section.
2447 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2448 caller()->CreateAndSetAndSignalOffer();
2449 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002450 MediaExpectations media_expectations;
2451 media_expectations.ExpectBidirectionalAudioAndVideo();
2452 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002453}
2454
2455// Test that we can receive the audio output level from a remote audio track.
2456// TODO(deadbeef): Use a fake audio source and verify that the output level is
2457// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002458TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002459 ASSERT_TRUE(CreatePeerConnectionWrappers());
2460 ConnectFakeSignaling();
2461 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002462 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002463 caller()->CreateAndSetAndSignalOffer();
2464 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2465
2466 // Get the audio output level stats. Note that the level is not available
2467 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002468 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002469 kMaxWaitForFramesMs);
2470}
2471
2472// Test that an audio input level is reported.
2473// TODO(deadbeef): Use a fake audio source and verify that the input level is
2474// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002475TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002476 ASSERT_TRUE(CreatePeerConnectionWrappers());
2477 ConnectFakeSignaling();
2478 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002479 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002480 caller()->CreateAndSetAndSignalOffer();
2481 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2482
2483 // Get the audio input level stats. The level should be available very
2484 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002485 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002486 kMaxWaitForStatsMs);
2487}
2488
2489// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002490TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002491 ASSERT_TRUE(CreatePeerConnectionWrappers());
2492 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002493 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002494 // Do offer/answer, wait for the callee to receive some frames.
2495 caller()->CreateAndSetAndSignalOffer();
2496 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002497
2498 MediaExpectations media_expectations;
2499 media_expectations.CalleeExpectsSomeAudioAndVideo();
2500 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002501
2502 // Get a handle to the remote tracks created, so they can be used as GetStats
2503 // filters.
Steve Anton15324772018-01-16 10:26:49 -08002504 for (auto receiver : callee()->pc()->GetReceivers()) {
2505 // We received frames, so we definitely should have nonzero "received bytes"
2506 // stats at this point.
2507 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2508 0);
2509 }
deadbeef1dcb1642017-03-29 21:08:16 -07002510}
2511
2512// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002513TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002514 ASSERT_TRUE(CreatePeerConnectionWrappers());
2515 ConnectFakeSignaling();
2516 auto audio_track = caller()->CreateLocalAudioTrack();
2517 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002518 caller()->AddTrack(audio_track);
2519 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002520 // Do offer/answer, wait for the callee to receive some frames.
2521 caller()->CreateAndSetAndSignalOffer();
2522 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002523 MediaExpectations media_expectations;
2524 media_expectations.CalleeExpectsSomeAudioAndVideo();
2525 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002526
2527 // The callee received frames, so we definitely should have nonzero "sent
2528 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002529 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2530 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2531}
2532
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002533// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002534TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002535 ASSERT_TRUE(CreatePeerConnectionWrappers());
2536 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002537 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002538
Steve Anton15324772018-01-16 10:26:49 -08002539 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002540
2541 // Do offer/answer, wait for the callee to receive some frames.
2542 caller()->CreateAndSetAndSignalOffer();
2543 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2544
2545 // Get the remote audio track created on the receiver, so they can be used as
2546 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002547 auto receivers = callee()->pc()->GetReceivers();
2548 ASSERT_EQ(1u, receivers.size());
2549 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002550
2551 // Get the audio output level stats. Note that the level is not available
2552 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002553 EXPECT_TRUE_WAIT(
2554 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2555 0,
2556 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002557}
2558
deadbeefd8ad7882017-04-18 16:01:17 -07002559// Test that we can get stats (using the new stats implemnetation) for
2560// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2561// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002562TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002563 GetStatsForUnsignaledStreamWithNewStatsApi) {
2564 ASSERT_TRUE(CreatePeerConnectionWrappers());
2565 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002566 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002567 // Remove SSRCs and MSIDs from the received offer SDP.
2568 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2569 caller()->CreateAndSetAndSignalOffer();
2570 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002571 MediaExpectations media_expectations;
2572 media_expectations.CalleeExpectsSomeAudio(1);
2573 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002574
2575 // We received a frame, so we should have nonzero "bytes received" stats for
2576 // the unsignaled stream, if stats are working for it.
2577 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2578 callee()->NewGetStats();
2579 ASSERT_NE(nullptr, report);
2580 auto inbound_stream_stats =
2581 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2582 ASSERT_EQ(1U, inbound_stream_stats.size());
2583 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2584 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002585 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2586}
2587
Taylor Brandstettera4653442018-06-19 09:44:26 -07002588// Same as above but for the legacy stats implementation.
2589TEST_P(PeerConnectionIntegrationTest,
2590 GetStatsForUnsignaledStreamWithOldStatsApi) {
2591 ASSERT_TRUE(CreatePeerConnectionWrappers());
2592 ConnectFakeSignaling();
2593 caller()->AddAudioTrack();
2594 // Remove SSRCs and MSIDs from the received offer SDP.
2595 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2596 caller()->CreateAndSetAndSignalOffer();
2597 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2598
2599 // Note that, since the old stats implementation associates SSRCs with tracks
2600 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2601 // associated track ID. So we can't use the track "selector" argument.
2602 //
2603 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2604 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002605 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002606 kDefaultTimeout);
2607}
2608
zhihuangf8164932017-05-19 13:09:47 -07002609// Test that we can successfully get the media related stats (audio level
2610// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002611TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002612 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2613 ASSERT_TRUE(CreatePeerConnectionWrappers());
2614 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002615 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002616 // Remove SSRCs and MSIDs from the received offer SDP.
2617 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2618 caller()->CreateAndSetAndSignalOffer();
2619 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002620 MediaExpectations media_expectations;
2621 media_expectations.CalleeExpectsSomeAudio(1);
2622 media_expectations.CalleeExpectsSomeVideo(1);
2623 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002624
2625 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2626 callee()->NewGetStats();
2627 ASSERT_NE(nullptr, report);
2628
2629 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2630 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2631 ASSERT_GE(audio_index, 0);
2632 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002633}
2634
deadbeef4e2deab2017-09-20 13:56:21 -07002635// Helper for test below.
2636void ModifySsrcs(cricket::SessionDescription* desc) {
2637 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002638 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002639 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002640 for (uint32_t& ssrc : stream.ssrcs) {
2641 ssrc = rtc::CreateRandomId();
2642 }
2643 }
2644 }
2645}
2646
2647// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2648// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2649// This should result in two "RTCInboundRTPStreamStats", but only one
2650// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2651// being reset to 0 once the SSRC change occurs.
2652//
2653// Regression test for this bug:
2654// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2655//
2656// The bug causes the track stats to only represent one of the two streams:
2657// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2658// that the track stat counters would reset to 0 when the new stream is
2659// received, and a 50% chance that they'll stop updating (while
2660// "concealed_samples" continues increasing, due to silence being generated for
2661// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002662TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002663 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002664 ASSERT_TRUE(CreatePeerConnectionWrappers());
2665 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002666 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002667 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2668 // that doesn't signal SSRCs (from the callee's perspective).
2669 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2670 caller()->CreateAndSetAndSignalOffer();
2671 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2672 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002673 {
2674 MediaExpectations media_expectations;
2675 media_expectations.CalleeExpectsSomeAudio(50);
2676 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2677 }
deadbeef4e2deab2017-09-20 13:56:21 -07002678 // Some audio frames were received, so we should have nonzero "samples
2679 // received" for the track.
2680 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2681 callee()->NewGetStats();
2682 ASSERT_NE(nullptr, report);
2683 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2684 ASSERT_EQ(1U, track_stats.size());
2685 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2686 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2687 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2688
2689 // Create a new offer and munge it to cause the caller to use a new SSRC.
2690 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2691 caller()->CreateAndSetAndSignalOffer();
2692 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2693 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2694 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002695 {
2696 MediaExpectations media_expectations;
2697 media_expectations.CalleeExpectsSomeAudio(25);
2698 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2699 }
deadbeef4e2deab2017-09-20 13:56:21 -07002700
2701 report = callee()->NewGetStats();
2702 ASSERT_NE(nullptr, report);
2703 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2704 ASSERT_EQ(1U, track_stats.size());
2705 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2706 // The "total samples received" stat should only be greater than it was
2707 // before.
2708 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2709 // Right now, the new SSRC will cause the counters to reset to 0.
2710 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2711
2712 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002713 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002714 // good sign that we're seeing stats from the old stream that's no longer
2715 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002716 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002717 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2718 EXPECT_LT(*track_stats[0]->concealed_samples,
2719 *track_stats[0]->total_samples_received *
2720 kAcceptableConcealedSamplesPercentage);
2721
2722 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2723 // sanity check that the SSRC really changed.
2724 // TODO(deadbeef): This isn't working right now, because we're not returning
2725 // *any* stats for the inactive stream. Uncomment when the bug is completely
2726 // fixed.
2727 // auto inbound_stream_stats =
2728 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2729 // ASSERT_EQ(2U, inbound_stream_stats.size());
2730}
2731
deadbeef1dcb1642017-03-29 21:08:16 -07002732// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002733TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002734 PeerConnectionFactory::Options dtls_10_options;
2735 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2736 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2737 dtls_10_options));
2738 ConnectFakeSignaling();
2739 // Do normal offer/answer and wait for some frames to be received in each
2740 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002741 caller()->AddAudioVideoTracks();
2742 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002743 caller()->CreateAndSetAndSignalOffer();
2744 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002745 MediaExpectations media_expectations;
2746 media_expectations.ExpectBidirectionalAudioAndVideo();
2747 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002748}
2749
2750// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002751TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002752 PeerConnectionFactory::Options dtls_10_options;
2753 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2754 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2755 dtls_10_options));
2756 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002757 caller()->AddAudioVideoTracks();
2758 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002759 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002760 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002761 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002762 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002763 kDefaultTimeout);
2764 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002765 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002766 // TODO(bugs.webrtc.org/9456): Fix it.
2767 EXPECT_EQ(1, webrtc::metrics::NumEvents(
2768 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2769 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002770}
2771
2772// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002773TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002774 PeerConnectionFactory::Options dtls_12_options;
2775 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2776 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2777 dtls_12_options));
2778 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002779 caller()->AddAudioVideoTracks();
2780 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002781 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002782 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002783 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002784 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002785 kDefaultTimeout);
2786 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002787 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002788 // TODO(bugs.webrtc.org/9456): Fix it.
2789 EXPECT_EQ(1, webrtc::metrics::NumEvents(
2790 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2791 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002792}
2793
2794// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2795// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002796TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002797 PeerConnectionFactory::Options caller_options;
2798 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2799 PeerConnectionFactory::Options callee_options;
2800 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2801 ASSERT_TRUE(
2802 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2803 ConnectFakeSignaling();
2804 // Do normal offer/answer and wait for some frames to be received in each
2805 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002806 caller()->AddAudioVideoTracks();
2807 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002808 caller()->CreateAndSetAndSignalOffer();
2809 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002810 MediaExpectations media_expectations;
2811 media_expectations.ExpectBidirectionalAudioAndVideo();
2812 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002813}
2814
2815// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2816// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002817TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07002818 PeerConnectionFactory::Options caller_options;
2819 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2820 PeerConnectionFactory::Options callee_options;
2821 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2822 ASSERT_TRUE(
2823 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2824 ConnectFakeSignaling();
2825 // Do normal offer/answer and wait for some frames to be received in each
2826 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002827 caller()->AddAudioVideoTracks();
2828 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002829 caller()->CreateAndSetAndSignalOffer();
2830 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002831 MediaExpectations media_expectations;
2832 media_expectations.ExpectBidirectionalAudioAndVideo();
2833 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002834}
2835
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002836// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
2837// works as expected; the cipher should only be used if enabled by both sides.
2838TEST_P(PeerConnectionIntegrationTest,
2839 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
2840 PeerConnectionFactory::Options caller_options;
2841 caller_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = true;
2842 PeerConnectionFactory::Options callee_options;
2843 callee_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = false;
2844 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2845 TestNegotiatedCipherSuite(caller_options, callee_options,
2846 expected_cipher_suite);
2847}
2848
2849TEST_P(PeerConnectionIntegrationTest,
2850 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
2851 PeerConnectionFactory::Options caller_options;
2852 caller_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = false;
2853 PeerConnectionFactory::Options callee_options;
2854 callee_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = true;
2855 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2856 TestNegotiatedCipherSuite(caller_options, callee_options,
2857 expected_cipher_suite);
2858}
2859
2860TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
2861 PeerConnectionFactory::Options caller_options;
2862 caller_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = true;
2863 PeerConnectionFactory::Options callee_options;
2864 callee_options.crypto_options.enable_aes128_sha1_32_crypto_cipher = true;
2865 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
2866 TestNegotiatedCipherSuite(caller_options, callee_options,
2867 expected_cipher_suite);
2868}
2869
deadbeef1dcb1642017-03-29 21:08:16 -07002870// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002871TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07002872 bool local_gcm_enabled = false;
2873 bool remote_gcm_enabled = false;
2874 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2875 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2876 expected_cipher_suite);
2877}
2878
2879// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002880TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07002881 bool local_gcm_enabled = true;
2882 bool remote_gcm_enabled = true;
2883 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2884 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2885 expected_cipher_suite);
2886}
2887
2888// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002889TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002890 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2891 bool local_gcm_enabled = true;
2892 bool remote_gcm_enabled = false;
2893 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2894 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2895 expected_cipher_suite);
2896}
2897
2898// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002899TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002900 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2901 bool local_gcm_enabled = false;
2902 bool remote_gcm_enabled = true;
2903 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2904 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2905 expected_cipher_suite);
2906}
2907
deadbeef7914b8c2017-04-21 03:23:33 -07002908// Verify that media can be transmitted end-to-end when GCM crypto suites are
2909// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2910// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2911// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002912TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07002913 PeerConnectionFactory::Options gcm_options;
2914 gcm_options.crypto_options.enable_gcm_crypto_suites = true;
2915 ASSERT_TRUE(
2916 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2917 ConnectFakeSignaling();
2918 // Do normal offer/answer and wait for some frames to be received in each
2919 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002920 caller()->AddAudioVideoTracks();
2921 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002922 caller()->CreateAndSetAndSignalOffer();
2923 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002924 MediaExpectations media_expectations;
2925 media_expectations.ExpectBidirectionalAudioAndVideo();
2926 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07002927}
2928
deadbeef1dcb1642017-03-29 21:08:16 -07002929// This test sets up a call between two parties with audio, video and an RTP
2930// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002931TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02002932 PeerConnectionInterface::RTCConfiguration rtc_config;
2933 rtc_config.enable_rtp_data_channel = true;
2934 rtc_config.enable_dtls_srtp = false;
2935 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07002936 ConnectFakeSignaling();
2937 // Expect that data channel created on caller side will show up for callee as
2938 // well.
2939 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002940 caller()->AddAudioVideoTracks();
2941 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002942 caller()->CreateAndSetAndSignalOffer();
2943 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2944 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002945 MediaExpectations media_expectations;
2946 media_expectations.ExpectBidirectionalAudioAndVideo();
2947 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002948 ASSERT_NE(nullptr, caller()->data_channel());
2949 ASSERT_NE(nullptr, callee()->data_channel());
2950 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2951 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2952
2953 // Ensure data can be sent in both directions.
2954 std::string data = "hello world";
2955 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2956 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2957 kDefaultTimeout);
2958 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2959 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2960 kDefaultTimeout);
2961}
2962
2963// Ensure that an RTP data channel is signaled as closed for the caller when
2964// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002965TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002966 RtpDataChannelSignaledClosedInCalleeOffer) {
2967 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02002968 PeerConnectionInterface::RTCConfiguration rtc_config;
2969 rtc_config.enable_rtp_data_channel = true;
2970 rtc_config.enable_dtls_srtp = false;
2971 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07002972 ConnectFakeSignaling();
2973 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002974 caller()->AddAudioVideoTracks();
2975 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002976 caller()->CreateAndSetAndSignalOffer();
2977 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2978 ASSERT_NE(nullptr, caller()->data_channel());
2979 ASSERT_NE(nullptr, callee()->data_channel());
2980 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2981 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2982
2983 // Close the data channel on the callee, and do an updated offer/answer.
2984 callee()->data_channel()->Close();
2985 callee()->CreateAndSetAndSignalOffer();
2986 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2987 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2988 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2989}
2990
2991// Tests that data is buffered in an RTP data channel until an observer is
2992// registered for it.
2993//
2994// NOTE: RTP data channels can receive data before the underlying
2995// transport has detected that a channel is writable and thus data can be
2996// received before the data channel state changes to open. That is hard to test
2997// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002998TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002999 DataBufferedUntilRtpDataChannelObserverRegistered) {
3000 // Use fake clock and simulated network delay so that we predictably can wait
3001 // until an SCTP message has been delivered without "sleep()"ing.
3002 rtc::ScopedFakeClock fake_clock;
3003 // Some things use a time of "0" as a special value, so we need to start out
3004 // the fake clock at a nonzero time.
3005 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003006 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003007 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3008 virtual_socket_server()->UpdateDelayDistribution();
3009
Niels Möllerf06f9232018-08-07 12:32:18 +02003010 PeerConnectionInterface::RTCConfiguration rtc_config;
3011 rtc_config.enable_rtp_data_channel = true;
3012 rtc_config.enable_dtls_srtp = false;
3013 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003014 ConnectFakeSignaling();
3015 caller()->CreateDataChannel();
3016 caller()->CreateAndSetAndSignalOffer();
3017 ASSERT_TRUE(caller()->data_channel() != nullptr);
3018 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3019 kDefaultTimeout, fake_clock);
3020 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3021 kDefaultTimeout, fake_clock);
3022 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3023 callee()->data_channel()->state(), kDefaultTimeout,
3024 fake_clock);
3025
3026 // Unregister the observer which is normally automatically registered.
3027 callee()->data_channel()->UnregisterObserver();
3028 // Send data and advance fake clock until it should have been received.
3029 std::string data = "hello world";
3030 caller()->data_channel()->Send(DataBuffer(data));
3031 SIMULATED_WAIT(false, 50, fake_clock);
3032
3033 // Attach data channel and expect data to be received immediately. Note that
3034 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3035 // further, but data can be received even if the callback is asynchronous.
3036 MockDataChannelObserver new_observer(callee()->data_channel());
3037 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3038 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003039 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3040 // If this is not done a DCHECK can be hit in ports.cc, because a large
3041 // negative number is calculated for the rtt due to the global clock changing.
3042 caller()->pc()->Close();
3043 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07003044}
3045
3046// This test sets up a call between two parties with audio, video and but only
3047// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003048TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003049 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3050 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003051 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003052 rtc_config_1.enable_dtls_srtp = false;
3053 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3054 rtc_config_2.enable_dtls_srtp = false;
3055 rtc_config_2.enable_dtls_srtp = false;
3056 ASSERT_TRUE(
3057 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003058 ConnectFakeSignaling();
3059 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003060 caller()->AddAudioVideoTracks();
3061 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003062 caller()->CreateAndSetAndSignalOffer();
3063 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3064 // The caller should still have a data channel, but it should be closed, and
3065 // one should ever have been created for the callee.
3066 EXPECT_TRUE(caller()->data_channel() != nullptr);
3067 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3068 EXPECT_EQ(nullptr, callee()->data_channel());
3069}
3070
3071// This test sets up a call between two parties with audio, and video. When
3072// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003073TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003074 PeerConnectionInterface::RTCConfiguration rtc_config;
3075 rtc_config.enable_rtp_data_channel = true;
3076 rtc_config.enable_dtls_srtp = false;
3077 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003078 ConnectFakeSignaling();
3079 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003080 caller()->AddAudioVideoTracks();
3081 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003082 caller()->CreateAndSetAndSignalOffer();
3083 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3084 // Create data channel and do new offer and answer.
3085 caller()->CreateDataChannel();
3086 caller()->CreateAndSetAndSignalOffer();
3087 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3088 ASSERT_NE(nullptr, caller()->data_channel());
3089 ASSERT_NE(nullptr, callee()->data_channel());
3090 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3091 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3092 // Ensure data can be sent in both directions.
3093 std::string data = "hello world";
3094 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3095 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3096 kDefaultTimeout);
3097 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3098 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3099 kDefaultTimeout);
3100}
3101
3102#ifdef HAVE_SCTP
3103
3104// This test sets up a call between two parties with audio, video and an SCTP
3105// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003106TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003107 ASSERT_TRUE(CreatePeerConnectionWrappers());
3108 ConnectFakeSignaling();
3109 // Expect that data channel created on caller side will show up for callee as
3110 // well.
3111 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003112 caller()->AddAudioVideoTracks();
3113 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003114 caller()->CreateAndSetAndSignalOffer();
3115 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3116 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003117 MediaExpectations media_expectations;
3118 media_expectations.ExpectBidirectionalAudioAndVideo();
3119 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003120 // Caller data channel should already exist (it created one). Callee data
3121 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3122 ASSERT_NE(nullptr, caller()->data_channel());
3123 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3124 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3125 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3126
3127 // Ensure data can be sent in both directions.
3128 std::string data = "hello world";
3129 caller()->data_channel()->Send(DataBuffer(data));
3130 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3131 kDefaultTimeout);
3132 callee()->data_channel()->Send(DataBuffer(data));
3133 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3134 kDefaultTimeout);
3135}
3136
3137// Ensure that when the callee closes an SCTP data channel, the closing
3138// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003139TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003140 // Same procedure as above test.
3141 ASSERT_TRUE(CreatePeerConnectionWrappers());
3142 ConnectFakeSignaling();
3143 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003144 caller()->AddAudioVideoTracks();
3145 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003146 caller()->CreateAndSetAndSignalOffer();
3147 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3148 ASSERT_NE(nullptr, caller()->data_channel());
3149 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3150 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3151 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3152
3153 // Close the data channel on the callee side, and wait for it to reach the
3154 // "closed" state on both sides.
3155 callee()->data_channel()->Close();
3156 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3157 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3158}
3159
Seth Hampson2f0d7022018-02-20 11:54:42 -08003160TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003161 ASSERT_TRUE(CreatePeerConnectionWrappers());
3162 ConnectFakeSignaling();
3163 webrtc::DataChannelInit init;
3164 init.id = 53;
3165 init.maxRetransmits = 52;
3166 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003167 caller()->AddAudioVideoTracks();
3168 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003169 caller()->CreateAndSetAndSignalOffer();
3170 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003171 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3172 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07003173 EXPECT_EQ(init.id, callee()->data_channel()->id());
3174 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3175 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3176 EXPECT_FALSE(callee()->data_channel()->negotiated());
3177}
3178
deadbeef1dcb1642017-03-29 21:08:16 -07003179// Test usrsctp's ability to process unordered data stream, where data actually
3180// arrives out of order using simulated delays. Previously there have been some
3181// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003182TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003183 // Introduce random network delays.
3184 // Otherwise it's not a true "unordered" test.
3185 virtual_socket_server()->set_delay_mean(20);
3186 virtual_socket_server()->set_delay_stddev(5);
3187 virtual_socket_server()->UpdateDelayDistribution();
3188 // Normal procedure, but with unordered data channel config.
3189 ASSERT_TRUE(CreatePeerConnectionWrappers());
3190 ConnectFakeSignaling();
3191 webrtc::DataChannelInit init;
3192 init.ordered = false;
3193 caller()->CreateDataChannel(&init);
3194 caller()->CreateAndSetAndSignalOffer();
3195 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3196 ASSERT_NE(nullptr, caller()->data_channel());
3197 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3198 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3199 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3200
3201 static constexpr int kNumMessages = 100;
3202 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3203 static constexpr size_t kMaxMessageSize = 4096;
3204 // Create and send random messages.
3205 std::vector<std::string> sent_messages;
3206 for (int i = 0; i < kNumMessages; ++i) {
3207 size_t length =
3208 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3209 std::string message;
3210 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3211 caller()->data_channel()->Send(DataBuffer(message));
3212 callee()->data_channel()->Send(DataBuffer(message));
3213 sent_messages.push_back(message);
3214 }
3215
3216 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003217 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003218 caller()->data_observer()->received_message_count(),
3219 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003220 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003221 callee()->data_observer()->received_message_count(),
3222 kDefaultTimeout);
3223
3224 // Sort and compare to make sure none of the messages were corrupted.
3225 std::vector<std::string> caller_received_messages =
3226 caller()->data_observer()->messages();
3227 std::vector<std::string> callee_received_messages =
3228 callee()->data_observer()->messages();
3229 std::sort(sent_messages.begin(), sent_messages.end());
3230 std::sort(caller_received_messages.begin(), caller_received_messages.end());
3231 std::sort(callee_received_messages.begin(), callee_received_messages.end());
3232 EXPECT_EQ(sent_messages, caller_received_messages);
3233 EXPECT_EQ(sent_messages, callee_received_messages);
3234}
3235
3236// This test sets up a call between two parties with audio, and video. When
3237// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003238TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003239 ASSERT_TRUE(CreatePeerConnectionWrappers());
3240 ConnectFakeSignaling();
3241 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003242 caller()->AddAudioVideoTracks();
3243 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003244 caller()->CreateAndSetAndSignalOffer();
3245 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3246 // Create data channel and do new offer and answer.
3247 caller()->CreateDataChannel();
3248 caller()->CreateAndSetAndSignalOffer();
3249 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3250 // Caller data channel should already exist (it created one). Callee data
3251 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3252 ASSERT_NE(nullptr, caller()->data_channel());
3253 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3254 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3255 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3256 // Ensure data can be sent in both directions.
3257 std::string data = "hello world";
3258 caller()->data_channel()->Send(DataBuffer(data));
3259 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3260 kDefaultTimeout);
3261 callee()->data_channel()->Send(DataBuffer(data));
3262 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3263 kDefaultTimeout);
3264}
3265
deadbeef7914b8c2017-04-21 03:23:33 -07003266// Set up a connection initially just using SCTP data channels, later upgrading
3267// to audio/video, ensuring frames are received end-to-end. Effectively the
3268// inverse of the test above.
3269// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003270TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003271 ASSERT_TRUE(CreatePeerConnectionWrappers());
3272 ConnectFakeSignaling();
3273 // Do initial offer/answer with just data channel.
3274 caller()->CreateDataChannel();
3275 caller()->CreateAndSetAndSignalOffer();
3276 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3277 // Wait until data can be sent over the data channel.
3278 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3279 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3280 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3281
3282 // Do subsequent offer/answer with two-way audio and video. Audio and video
3283 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003284 caller()->AddAudioVideoTracks();
3285 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003286 caller()->CreateAndSetAndSignalOffer();
3287 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003288 MediaExpectations media_expectations;
3289 media_expectations.ExpectBidirectionalAudioAndVideo();
3290 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003291}
3292
deadbeef8b7e9ad2017-05-25 09:38:55 -07003293static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07003294 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08003295 GetFirstDataContentDescription(desc);
3296 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003297 dcd_offer->set_use_sctpmap(false);
3298 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3299}
3300
3301// Test that the data channel works when a spec-compliant SCTP m= section is
3302// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3303// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003304TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003305 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3306 ASSERT_TRUE(CreatePeerConnectionWrappers());
3307 ConnectFakeSignaling();
3308 caller()->CreateDataChannel();
3309 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3310 caller()->CreateAndSetAndSignalOffer();
3311 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3312 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3313 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3314 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3315
3316 // Ensure data can be sent in both directions.
3317 std::string data = "hello world";
3318 caller()->data_channel()->Send(DataBuffer(data));
3319 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3320 kDefaultTimeout);
3321 callee()->data_channel()->Send(DataBuffer(data));
3322 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3323 kDefaultTimeout);
3324}
3325
deadbeef1dcb1642017-03-29 21:08:16 -07003326#endif // HAVE_SCTP
3327
3328// Test that the ICE connection and gathering states eventually reach
3329// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003330TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003331 ASSERT_TRUE(CreatePeerConnectionWrappers());
3332 ConnectFakeSignaling();
3333 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003334 caller()->AddAudioVideoTracks();
3335 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003336 caller()->CreateAndSetAndSignalOffer();
3337 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3338 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3339 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3340 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3341 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3342 // After the best candidate pair is selected and all candidates are signaled,
3343 // the ICE connection state should reach "complete".
3344 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3345 // answerer/"callee" by default) only reaches "connected". When this is
3346 // fixed, this test should be updated.
3347 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3348 caller()->ice_connection_state(), kDefaultTimeout);
3349 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3350 callee()->ice_connection_state(), kDefaultTimeout);
3351}
3352
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003353// Replaces the first candidate with a static address and configures a
3354// MockAsyncResolver to return the replaced address the first time the static
3355// address is resolved. Candidates past the first will not be signaled.
3356class ReplaceFirstCandidateAddressDropOthers final
3357 : public IceCandidateReplacerInterface {
3358 public:
3359 ReplaceFirstCandidateAddressDropOthers(
3360 const SocketAddress& new_address,
3361 rtc::MockAsyncResolver* mock_async_resolver)
3362 : mock_async_resolver_(mock_async_resolver), new_address_(new_address) {
3363 RTC_DCHECK(mock_async_resolver);
3364 }
3365
3366 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3367 const webrtc::IceCandidateInterface* candidate) override {
3368 if (replaced_candidate_) {
3369 return nullptr;
3370 }
3371
3372 replaced_candidate_ = true;
3373 cricket::Candidate new_candidate(candidate->candidate());
3374 new_candidate.set_address(new_address_);
3375 EXPECT_CALL(*mock_async_resolver_, GetResolvedAddress(_, _))
3376 .WillOnce(DoAll(SetArgPointee<1>(candidate->candidate().address()),
3377 Return(true)));
3378 EXPECT_CALL(*mock_async_resolver_, Destroy(_));
3379 return webrtc::CreateIceCandidate(
3380 candidate->sdp_mid(), candidate->sdp_mline_index(), new_candidate);
3381 }
3382
3383 private:
3384 rtc::MockAsyncResolver* mock_async_resolver_;
3385 SocketAddress new_address_;
3386 bool replaced_candidate_ = false;
3387};
3388
3389// Drops all candidates before they are signaled.
3390class DropAllCandidates final : public IceCandidateReplacerInterface {
3391 public:
3392 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3393 const webrtc::IceCandidateInterface*) override {
3394 return nullptr;
3395 }
3396};
3397
3398// Replace the first caller ICE candidate IP with a fake hostname and drop the
3399// other candidates. Drop all candidates on the callee side (to avoid a prflx
3400// connection). Use a mock resolver to resolve the hostname back to the original
3401// IP on the callee side and check that the ice connection connects.
3402TEST_P(PeerConnectionIntegrationTest,
3403 IceStatesReachCompletionWithRemoteHostname) {
3404 webrtc::MockAsyncResolverFactory* callee_mock_async_resolver_factory;
3405 {
3406 auto resolver_factory =
3407 absl::make_unique<webrtc::MockAsyncResolverFactory>();
3408 callee_mock_async_resolver_factory = resolver_factory.get();
3409 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3410 callee_deps.async_resolver_factory = std::move(resolver_factory);
3411
3412 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3413 RTCConfiguration(), webrtc::PeerConnectionDependencies(nullptr),
3414 RTCConfiguration(), std::move(callee_deps)));
3415 }
3416
3417 rtc::MockAsyncResolver mock_async_resolver;
3418
3419 // This also verifies that the injected AsyncResolverFactory is used by
3420 // P2PTransportChannel.
3421 EXPECT_CALL(*callee_mock_async_resolver_factory, Create())
3422 .WillOnce(Return(&mock_async_resolver));
3423 caller()->SetLocalIceCandidateReplacer(
3424 absl::make_unique<ReplaceFirstCandidateAddressDropOthers>(
3425 SocketAddress("a.b", 10000), &mock_async_resolver));
3426 callee()->SetLocalIceCandidateReplacer(
3427 absl::make_unique<DropAllCandidates>());
3428
3429 ConnectFakeSignaling();
3430 caller()->AddAudioVideoTracks();
3431 callee()->AddAudioVideoTracks();
3432 caller()->CreateAndSetAndSignalOffer();
3433 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3434 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3435 caller()->ice_connection_state(), kDefaultTimeout);
3436 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3437 callee()->ice_connection_state(), kDefaultTimeout);
3438}
3439
Steve Antonede9ca52017-10-16 13:04:27 -07003440// Test that firewalling the ICE connection causes the clients to identify the
3441// disconnected state and then removing the firewall causes them to reconnect.
3442class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003443 : public PeerConnectionIntegrationBaseTest,
3444 public ::testing::WithParamInterface<
3445 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003446 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003447 PeerConnectionIntegrationIceStatesTest()
3448 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3449 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003450 }
3451
3452 void StartStunServer(const SocketAddress& server_address) {
3453 stun_server_.reset(
3454 cricket::TestStunServer::Create(network_thread(), server_address));
3455 }
3456
3457 bool TestIPv6() {
3458 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3459 }
3460
3461 void SetPortAllocatorFlags() {
Qingsi Wanga2d60672018-04-11 16:57:45 -07003462 network_thread()->Invoke<void>(
3463 RTC_FROM_HERE,
3464 rtc::Bind(&cricket::PortAllocator::set_flags,
3465 caller()->port_allocator(), port_allocator_flags_));
3466 network_thread()->Invoke<void>(
3467 RTC_FROM_HERE,
3468 rtc::Bind(&cricket::PortAllocator::set_flags,
3469 callee()->port_allocator(), port_allocator_flags_));
Steve Antonede9ca52017-10-16 13:04:27 -07003470 }
3471
3472 std::vector<SocketAddress> CallerAddresses() {
3473 std::vector<SocketAddress> addresses;
3474 addresses.push_back(SocketAddress("1.1.1.1", 0));
3475 if (TestIPv6()) {
3476 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3477 }
3478 return addresses;
3479 }
3480
3481 std::vector<SocketAddress> CalleeAddresses() {
3482 std::vector<SocketAddress> addresses;
3483 addresses.push_back(SocketAddress("2.2.2.2", 0));
3484 if (TestIPv6()) {
3485 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3486 }
3487 return addresses;
3488 }
3489
3490 void SetUpNetworkInterfaces() {
3491 // Remove the default interfaces added by the test infrastructure.
3492 caller()->network()->RemoveInterface(kDefaultLocalAddress);
3493 callee()->network()->RemoveInterface(kDefaultLocalAddress);
3494
3495 // Add network addresses for test.
3496 for (const auto& caller_address : CallerAddresses()) {
3497 caller()->network()->AddInterface(caller_address);
3498 }
3499 for (const auto& callee_address : CalleeAddresses()) {
3500 callee()->network()->AddInterface(callee_address);
3501 }
3502 }
3503
3504 private:
3505 uint32_t port_allocator_flags_;
3506 std::unique_ptr<cricket::TestStunServer> stun_server_;
3507};
3508
3509// Tests that the PeerConnection goes through all the ICE gathering/connection
3510// states over the duration of the call. This includes Disconnected and Failed
3511// states, induced by putting a firewall between the peers and waiting for them
3512// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003513TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
3514 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
3515 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
3516 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07003517
3518 const SocketAddress kStunServerAddress =
3519 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3520 StartStunServer(kStunServerAddress);
3521
3522 PeerConnectionInterface::RTCConfiguration config;
3523 PeerConnectionInterface::IceServer ice_stun_server;
3524 ice_stun_server.urls.push_back(
3525 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3526 kStunServerAddress.PortAsString());
3527 config.servers.push_back(ice_stun_server);
3528
3529 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3530 ConnectFakeSignaling();
3531 SetPortAllocatorFlags();
3532 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003533 caller()->AddAudioVideoTracks();
3534 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003535
3536 // Initial state before anything happens.
3537 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3538 caller()->ice_gathering_state());
3539 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3540 caller()->ice_connection_state());
3541
3542 // Start the call by creating the offer, setting it as the local description,
3543 // then sending it to the peer who will respond with an answer. This happens
3544 // asynchronously so that we can watch the states as it runs in the
3545 // background.
3546 caller()->CreateAndSetAndSignalOffer();
3547
Steve Anton83119dd2017-11-10 16:19:52 -08003548 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3549 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003550
3551 // Verify that the observer was notified of the intermediate transitions.
3552 EXPECT_THAT(caller()->ice_connection_state_history(),
3553 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3554 PeerConnectionInterface::kIceConnectionConnected,
3555 PeerConnectionInterface::kIceConnectionCompleted));
3556 EXPECT_THAT(caller()->ice_gathering_state_history(),
3557 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
3558 PeerConnectionInterface::kIceGatheringComplete));
3559
3560 // Block connections to/from the caller and wait for ICE to become
3561 // disconnected.
3562 for (const auto& caller_address : CallerAddresses()) {
3563 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3564 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003565 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08003566 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
3567 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003568
3569 // Let ICE re-establish by removing the firewall rules.
3570 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01003571 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08003572 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3573 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003574
3575 // According to RFC7675, if there is no response within 30 seconds then the
3576 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08003577 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07003578 constexpr int kConsentTimeout = 30000;
3579 for (const auto& caller_address : CallerAddresses()) {
3580 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3581 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003582 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08003583 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
3584 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003585}
3586
3587// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
3588// and that the statistics in the metric observers are updated correctly.
3589TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
3590 ASSERT_TRUE(CreatePeerConnectionWrappers());
3591 ConnectFakeSignaling();
3592 SetPortAllocatorFlags();
3593 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003594 caller()->AddAudioVideoTracks();
3595 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003596 caller()->CreateAndSetAndSignalOffer();
3597
3598 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3599
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003600 // TODO(bugs.webrtc.org/9456): Fix it.
3601 const int num_best_ipv4 = webrtc::metrics::NumEvents(
3602 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
3603 const int num_best_ipv6 = webrtc::metrics::NumEvents(
3604 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003605 if (TestIPv6()) {
3606 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
3607 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003608 EXPECT_EQ(0, num_best_ipv4);
3609 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003610 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003611 EXPECT_EQ(1, num_best_ipv4);
3612 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003613 }
3614
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003615 EXPECT_EQ(0, webrtc::metrics::NumEvents(
3616 "WebRTC.PeerConnection.CandidatePairType_UDP",
3617 webrtc::kIceCandidatePairHostHost));
3618 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3619 "WebRTC.PeerConnection.CandidatePairType_UDP",
3620 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07003621}
3622
3623constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
3624 cricket::PORTALLOCATOR_DISABLE_STUN |
3625 cricket::PORTALLOCATOR_DISABLE_RELAY;
3626constexpr uint32_t kFlagsIPv6NoStun =
3627 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
3628 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
3629constexpr uint32_t kFlagsIPv4Stun =
3630 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
3631
Seth Hampson2f0d7022018-02-20 11:54:42 -08003632INSTANTIATE_TEST_CASE_P(
3633 PeerConnectionIntegrationTest,
3634 PeerConnectionIntegrationIceStatesTest,
3635 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3636 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
3637 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
3638 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07003639
deadbeef1dcb1642017-03-29 21:08:16 -07003640// This test sets up a call between two parties with audio and video.
3641// During the call, the caller restarts ICE and the test verifies that
3642// new ICE candidates are generated and audio and video still can flow, and the
3643// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003644TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07003645 ASSERT_TRUE(CreatePeerConnectionWrappers());
3646 ConnectFakeSignaling();
3647 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08003648 caller()->AddAudioVideoTracks();
3649 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003650 caller()->CreateAndSetAndSignalOffer();
3651 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3652 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3653 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3654 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3655 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3656
3657 // To verify that the ICE restart actually occurs, get
3658 // ufrag/password/candidates before and after restart.
3659 // Create an SDP string of the first audio candidate for both clients.
3660 const webrtc::IceCandidateCollection* audio_candidates_caller =
3661 caller()->pc()->local_description()->candidates(0);
3662 const webrtc::IceCandidateCollection* audio_candidates_callee =
3663 callee()->pc()->local_description()->candidates(0);
3664 ASSERT_GT(audio_candidates_caller->count(), 0u);
3665 ASSERT_GT(audio_candidates_callee->count(), 0u);
3666 std::string caller_candidate_pre_restart;
3667 ASSERT_TRUE(
3668 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
3669 std::string callee_candidate_pre_restart;
3670 ASSERT_TRUE(
3671 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3672 const cricket::SessionDescription* desc =
3673 caller()->pc()->local_description()->description();
3674 std::string caller_ufrag_pre_restart =
3675 desc->transport_infos()[0].description.ice_ufrag;
3676 desc = callee()->pc()->local_description()->description();
3677 std::string callee_ufrag_pre_restart =
3678 desc->transport_infos()[0].description.ice_ufrag;
3679
3680 // Have the caller initiate an ICE restart.
3681 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3682 caller()->CreateAndSetAndSignalOffer();
3683 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3684 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3685 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3686 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3687 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3688
3689 // Grab the ufrags/candidates again.
3690 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3691 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3692 ASSERT_GT(audio_candidates_caller->count(), 0u);
3693 ASSERT_GT(audio_candidates_callee->count(), 0u);
3694 std::string caller_candidate_post_restart;
3695 ASSERT_TRUE(
3696 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3697 std::string callee_candidate_post_restart;
3698 ASSERT_TRUE(
3699 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
3700 desc = caller()->pc()->local_description()->description();
3701 std::string caller_ufrag_post_restart =
3702 desc->transport_infos()[0].description.ice_ufrag;
3703 desc = callee()->pc()->local_description()->description();
3704 std::string callee_ufrag_post_restart =
3705 desc->transport_infos()[0].description.ice_ufrag;
3706 // Sanity check that an ICE restart was actually negotiated in SDP.
3707 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
3708 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3709 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3710 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3711
3712 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003713 MediaExpectations media_expectations;
3714 media_expectations.ExpectBidirectionalAudioAndVideo();
3715 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003716}
3717
3718// Verify that audio/video can be received end-to-end when ICE renomination is
3719// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003720TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07003721 PeerConnectionInterface::RTCConfiguration config;
3722 config.enable_ice_renomination = true;
3723 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3724 ConnectFakeSignaling();
3725 // Do normal offer/answer and wait for some frames to be received in each
3726 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003727 caller()->AddAudioVideoTracks();
3728 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003729 caller()->CreateAndSetAndSignalOffer();
3730 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3731 // Sanity check that ICE renomination was actually negotiated.
3732 const cricket::SessionDescription* desc =
3733 caller()->pc()->local_description()->description();
3734 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003735 ASSERT_NE(
3736 info.description.transport_options.end(),
3737 std::find(info.description.transport_options.begin(),
3738 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003739 }
3740 desc = callee()->pc()->local_description()->description();
3741 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003742 ASSERT_NE(
3743 info.description.transport_options.end(),
3744 std::find(info.description.transport_options.begin(),
3745 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003746 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003747 MediaExpectations media_expectations;
3748 media_expectations.ExpectBidirectionalAudioAndVideo();
3749 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003750}
3751
Steve Anton6f25b092017-10-23 09:39:20 -07003752// With a max bundle policy and RTCP muxing, adding a new media description to
3753// the connection should not affect ICE at all because the new media will use
3754// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003755TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003756 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07003757 PeerConnectionInterface::RTCConfiguration config;
3758 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3759 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3760 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
3761 config, PeerConnectionInterface::RTCConfiguration()));
3762 ConnectFakeSignaling();
3763
Steve Anton15324772018-01-16 10:26:49 -08003764 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003765 caller()->CreateAndSetAndSignalOffer();
3766 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07003767 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3768 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07003769
3770 caller()->clear_ice_connection_state_history();
3771
Steve Anton15324772018-01-16 10:26:49 -08003772 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003773 caller()->CreateAndSetAndSignalOffer();
3774 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3775
3776 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
3777}
3778
deadbeef1dcb1642017-03-29 21:08:16 -07003779// This test sets up a call between two parties with audio and video. It then
3780// renegotiates setting the video m-line to "port 0", then later renegotiates
3781// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003782TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003783 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
3784 ASSERT_TRUE(CreatePeerConnectionWrappers());
3785 ConnectFakeSignaling();
3786
3787 // Do initial negotiation, only sending media from the caller. Will result in
3788 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08003789 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003790 caller()->CreateAndSetAndSignalOffer();
3791 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3792
3793 // Negotiate again, disabling the video "m=" section (the callee will set the
3794 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003795 if (sdp_semantics_ == SdpSemantics::kPlanB) {
3796 PeerConnectionInterface::RTCOfferAnswerOptions options;
3797 options.offer_to_receive_video = 0;
3798 callee()->SetOfferAnswerOptions(options);
3799 } else {
3800 callee()->SetRemoteOfferHandler([this] {
3801 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
3802 });
3803 }
deadbeef1dcb1642017-03-29 21:08:16 -07003804 caller()->CreateAndSetAndSignalOffer();
3805 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3806 // Sanity check that video "m=" section was actually rejected.
3807 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
3808 callee()->pc()->local_description()->description());
3809 ASSERT_NE(nullptr, answer_video_content);
3810 ASSERT_TRUE(answer_video_content->rejected);
3811
3812 // Enable video and do negotiation again, making sure video is received
3813 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003814 if (sdp_semantics_ == SdpSemantics::kPlanB) {
3815 PeerConnectionInterface::RTCOfferAnswerOptions options;
3816 options.offer_to_receive_video = 1;
3817 callee()->SetOfferAnswerOptions(options);
3818 } else {
3819 // The caller's transceiver is stopped, so we need to add another track.
3820 auto caller_transceiver =
3821 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
3822 EXPECT_TRUE(caller_transceiver->stopped());
3823 caller()->AddVideoTrack();
3824 }
3825 callee()->AddVideoTrack();
3826 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07003827 caller()->CreateAndSetAndSignalOffer();
3828 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003829
deadbeef1dcb1642017-03-29 21:08:16 -07003830 // Verify the caller receives frames from the newly added stream, and the
3831 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003832 MediaExpectations media_expectations;
3833 media_expectations.CalleeExpectsSomeAudio();
3834 media_expectations.ExpectBidirectionalVideo();
3835 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003836}
3837
deadbeef1dcb1642017-03-29 21:08:16 -07003838// This tests that if we negotiate after calling CreateSender but before we
3839// have a track, then set a track later, frames from the newly-set track are
3840// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003841TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07003842 MediaFlowsAfterEarlyWarmupWithCreateSender) {
3843 ASSERT_TRUE(CreatePeerConnectionWrappers());
3844 ConnectFakeSignaling();
3845 auto caller_audio_sender =
3846 caller()->pc()->CreateSender("audio", "caller_stream");
3847 auto caller_video_sender =
3848 caller()->pc()->CreateSender("video", "caller_stream");
3849 auto callee_audio_sender =
3850 callee()->pc()->CreateSender("audio", "callee_stream");
3851 auto callee_video_sender =
3852 callee()->pc()->CreateSender("video", "callee_stream");
3853 caller()->CreateAndSetAndSignalOffer();
3854 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3855 // Wait for ICE to complete, without any tracks being set.
3856 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3857 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3858 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3859 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3860 // Now set the tracks, and expect frames to immediately start flowing.
3861 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3862 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3863 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3864 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08003865 MediaExpectations media_expectations;
3866 media_expectations.ExpectBidirectionalAudioAndVideo();
3867 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3868}
3869
3870// This tests that if we negotiate after calling AddTransceiver but before we
3871// have a track, then set a track later, frames from the newly-set tracks are
3872// received end-to-end.
3873TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
3874 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
3875 ASSERT_TRUE(CreatePeerConnectionWrappers());
3876 ConnectFakeSignaling();
3877 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
3878 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
3879 auto caller_audio_sender = audio_result.MoveValue()->sender();
3880 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
3881 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
3882 auto caller_video_sender = video_result.MoveValue()->sender();
3883 callee()->SetRemoteOfferHandler([this] {
3884 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
3885 callee()->pc()->GetTransceivers()[0]->SetDirection(
3886 RtpTransceiverDirection::kSendRecv);
3887 callee()->pc()->GetTransceivers()[1]->SetDirection(
3888 RtpTransceiverDirection::kSendRecv);
3889 });
3890 caller()->CreateAndSetAndSignalOffer();
3891 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3892 // Wait for ICE to complete, without any tracks being set.
3893 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3894 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3895 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3896 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3897 // Now set the tracks, and expect frames to immediately start flowing.
3898 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
3899 auto callee_video_sender = callee()->pc()->GetSenders()[1];
3900 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3901 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3902 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3903 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
3904 MediaExpectations media_expectations;
3905 media_expectations.ExpectBidirectionalAudioAndVideo();
3906 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003907}
3908
3909// This test verifies that a remote video track can be added via AddStream,
3910// and sent end-to-end. For this particular test, it's simply echoed back
3911// from the caller to the callee, rather than being forwarded to a third
3912// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003913TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07003914 ASSERT_TRUE(CreatePeerConnectionWrappers());
3915 ConnectFakeSignaling();
3916 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08003917 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07003918 caller()->CreateAndSetAndSignalOffer();
3919 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003920 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07003921
3922 // Echo the stream back, and do a new offer/anwer (initiated by callee this
3923 // time).
3924 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
3925 callee()->CreateAndSetAndSignalOffer();
3926 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3927
Seth Hampson2f0d7022018-02-20 11:54:42 -08003928 MediaExpectations media_expectations;
3929 media_expectations.ExpectBidirectionalVideo();
3930 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003931}
3932
3933// Test that we achieve the expected end-to-end connection time, using a
3934// fake clock and simulated latency on the media and signaling paths.
3935// We use a TURN<->TURN connection because this is usually the quickest to
3936// set up initially, especially when we're confident the connection will work
3937// and can start sending media before we get a STUN response.
3938//
3939// With various optimizations enabled, here are the network delays we expect to
3940// be on the critical path:
3941// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
3942// signaling answer (with DTLS fingerprint).
3943// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
3944// using TURN<->TURN pair, and DTLS exchange is 4 packets,
3945// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003946TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07003947 rtc::ScopedFakeClock fake_clock;
3948 // Some things use a time of "0" as a special value, so we need to start out
3949 // the fake clock at a nonzero time.
3950 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003951 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003952
3953 static constexpr int media_hop_delay_ms = 50;
3954 static constexpr int signaling_trip_delay_ms = 500;
3955 // For explanation of these values, see comment above.
3956 static constexpr int required_media_hops = 9;
3957 static constexpr int required_signaling_trips = 2;
3958 // For internal delays (such as posting an event asychronously).
3959 static constexpr int allowed_internal_delay_ms = 20;
3960 static constexpr int total_connection_time_ms =
3961 media_hop_delay_ms * required_media_hops +
3962 signaling_trip_delay_ms * required_signaling_trips +
3963 allowed_internal_delay_ms;
3964
3965 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3966 3478};
3967 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3968 0};
3969 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3970 3478};
3971 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3972 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07003973 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
3974 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02003975
Seth Hampsonaed71642018-06-11 07:41:32 -07003976 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
3977 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07003978 // Bypass permission check on received packets so media can be sent before
3979 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07003980 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
3981 turn_server_1->set_enable_permission_checks(false);
3982 });
3983 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
3984 turn_server_2->set_enable_permission_checks(false);
3985 });
deadbeef1dcb1642017-03-29 21:08:16 -07003986
3987 PeerConnectionInterface::RTCConfiguration client_1_config;
3988 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3989 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3990 ice_server_1.username = "test";
3991 ice_server_1.password = "test";
3992 client_1_config.servers.push_back(ice_server_1);
3993 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3994 client_1_config.presume_writable_when_fully_relayed = true;
3995
3996 PeerConnectionInterface::RTCConfiguration client_2_config;
3997 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3998 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3999 ice_server_2.username = "test";
4000 ice_server_2.password = "test";
4001 client_2_config.servers.push_back(ice_server_2);
4002 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4003 client_2_config.presume_writable_when_fully_relayed = true;
4004
4005 ASSERT_TRUE(
4006 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4007 // Set up the simulated delays.
4008 SetSignalingDelayMs(signaling_trip_delay_ms);
4009 ConnectFakeSignaling();
4010 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4011 virtual_socket_server()->UpdateDelayDistribution();
4012
4013 // Set "offer to receive audio/video" without adding any tracks, so we just
4014 // set up ICE/DTLS with no media.
4015 PeerConnectionInterface::RTCOfferAnswerOptions options;
4016 options.offer_to_receive_audio = 1;
4017 options.offer_to_receive_video = 1;
4018 caller()->SetOfferAnswerOptions(options);
4019 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004020 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4021 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004022 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4023 // If this is not done a DCHECK can be hit in ports.cc, because a large
4024 // negative number is calculated for the rtt due to the global clock changing.
4025 caller()->pc()->Close();
4026 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07004027}
4028
Jonas Orelandbdcee282017-10-10 14:01:40 +02004029// Verify that a TurnCustomizer passed in through RTCConfiguration
4030// is actually used by the underlying TURN candidate pair.
4031// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004032TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004033 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4034 3478};
4035 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4036 0};
4037 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4038 3478};
4039 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4040 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004041 CreateTurnServer(turn_server_1_internal_address,
4042 turn_server_1_external_address);
4043 CreateTurnServer(turn_server_2_internal_address,
4044 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004045
4046 PeerConnectionInterface::RTCConfiguration client_1_config;
4047 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4048 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4049 ice_server_1.username = "test";
4050 ice_server_1.password = "test";
4051 client_1_config.servers.push_back(ice_server_1);
4052 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004053 auto* customizer1 = CreateTurnCustomizer();
4054 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004055
4056 PeerConnectionInterface::RTCConfiguration client_2_config;
4057 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4058 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4059 ice_server_2.username = "test";
4060 ice_server_2.password = "test";
4061 client_2_config.servers.push_back(ice_server_2);
4062 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004063 auto* customizer2 = CreateTurnCustomizer();
4064 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004065
4066 ASSERT_TRUE(
4067 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4068 ConnectFakeSignaling();
4069
4070 // Set "offer to receive audio/video" without adding any tracks, so we just
4071 // set up ICE/DTLS with no media.
4072 PeerConnectionInterface::RTCOfferAnswerOptions options;
4073 options.offer_to_receive_audio = 1;
4074 options.offer_to_receive_video = 1;
4075 caller()->SetOfferAnswerOptions(options);
4076 caller()->CreateAndSetAndSignalOffer();
4077 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4078
Seth Hampsonaed71642018-06-11 07:41:32 -07004079 ExpectTurnCustomizerCountersIncremented(customizer1);
4080 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004081}
4082
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004083// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4084// send media between the caller and the callee.
4085TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4086 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4087 3478};
4088 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4089
4090 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004091 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4092 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004093
4094 webrtc::PeerConnectionInterface::IceServer ice_server;
4095 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4096 ice_server.username = "test";
4097 ice_server.password = "test";
4098
4099 PeerConnectionInterface::RTCConfiguration client_1_config;
4100 client_1_config.servers.push_back(ice_server);
4101 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4102
4103 PeerConnectionInterface::RTCConfiguration client_2_config;
4104 client_2_config.servers.push_back(ice_server);
4105 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4106
4107 ASSERT_TRUE(
4108 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4109
4110 // Do normal offer/answer and wait for ICE to complete.
4111 ConnectFakeSignaling();
4112 caller()->AddAudioVideoTracks();
4113 callee()->AddAudioVideoTracks();
4114 caller()->CreateAndSetAndSignalOffer();
4115 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4116 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4117 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4118
4119 MediaExpectations media_expectations;
4120 media_expectations.ExpectBidirectionalAudioAndVideo();
4121 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4122}
4123
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004124// Verify that a SSLCertificateVerifier passed in through
4125// PeerConnectionDependencies is actually used by the underlying SSL
4126// implementation to determine whether a certificate presented by the TURN
4127// server is accepted by the client. Note that openssladapter_unittest.cc
4128// contains more detailed, lower-level tests.
4129TEST_P(PeerConnectionIntegrationTest,
4130 SSLCertificateVerifierUsedForTurnConnections) {
4131 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4132 3478};
4133 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4134
4135 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4136 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004137 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4138 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004139
4140 webrtc::PeerConnectionInterface::IceServer ice_server;
4141 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4142 ice_server.username = "test";
4143 ice_server.password = "test";
4144
4145 PeerConnectionInterface::RTCConfiguration client_1_config;
4146 client_1_config.servers.push_back(ice_server);
4147 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4148
4149 PeerConnectionInterface::RTCConfiguration client_2_config;
4150 client_2_config.servers.push_back(ice_server);
4151 // Setting the type to kRelay forces the connection to go through a TURN
4152 // server.
4153 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4154
4155 // Get a copy to the pointer so we can verify calls later.
4156 rtc::TestCertificateVerifier* client_1_cert_verifier =
4157 new rtc::TestCertificateVerifier();
4158 client_1_cert_verifier->verify_certificate_ = true;
4159 rtc::TestCertificateVerifier* client_2_cert_verifier =
4160 new rtc::TestCertificateVerifier();
4161 client_2_cert_verifier->verify_certificate_ = true;
4162
4163 // Create the dependencies with the test certificate verifier.
4164 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4165 client_1_deps.tls_cert_verifier =
4166 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4167 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4168 client_2_deps.tls_cert_verifier =
4169 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4170
4171 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4172 client_1_config, std::move(client_1_deps), client_2_config,
4173 std::move(client_2_deps)));
4174 ConnectFakeSignaling();
4175
4176 // Set "offer to receive audio/video" without adding any tracks, so we just
4177 // set up ICE/DTLS with no media.
4178 PeerConnectionInterface::RTCOfferAnswerOptions options;
4179 options.offer_to_receive_audio = 1;
4180 options.offer_to_receive_video = 1;
4181 caller()->SetOfferAnswerOptions(options);
4182 caller()->CreateAndSetAndSignalOffer();
4183 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4184
4185 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4186 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004187}
4188
4189TEST_P(PeerConnectionIntegrationTest,
4190 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4191 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4192 3478};
4193 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4194
4195 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4196 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004197 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4198 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004199
4200 webrtc::PeerConnectionInterface::IceServer ice_server;
4201 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4202 ice_server.username = "test";
4203 ice_server.password = "test";
4204
4205 PeerConnectionInterface::RTCConfiguration client_1_config;
4206 client_1_config.servers.push_back(ice_server);
4207 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4208
4209 PeerConnectionInterface::RTCConfiguration client_2_config;
4210 client_2_config.servers.push_back(ice_server);
4211 // Setting the type to kRelay forces the connection to go through a TURN
4212 // server.
4213 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4214
4215 // Get a copy to the pointer so we can verify calls later.
4216 rtc::TestCertificateVerifier* client_1_cert_verifier =
4217 new rtc::TestCertificateVerifier();
4218 client_1_cert_verifier->verify_certificate_ = false;
4219 rtc::TestCertificateVerifier* client_2_cert_verifier =
4220 new rtc::TestCertificateVerifier();
4221 client_2_cert_verifier->verify_certificate_ = false;
4222
4223 // Create the dependencies with the test certificate verifier.
4224 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4225 client_1_deps.tls_cert_verifier =
4226 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4227 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4228 client_2_deps.tls_cert_verifier =
4229 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4230
4231 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4232 client_1_config, std::move(client_1_deps), client_2_config,
4233 std::move(client_2_deps)));
4234 ConnectFakeSignaling();
4235
4236 // Set "offer to receive audio/video" without adding any tracks, so we just
4237 // set up ICE/DTLS with no media.
4238 PeerConnectionInterface::RTCOfferAnswerOptions options;
4239 options.offer_to_receive_audio = 1;
4240 options.offer_to_receive_video = 1;
4241 caller()->SetOfferAnswerOptions(options);
4242 caller()->CreateAndSetAndSignalOffer();
4243 bool wait_res = true;
4244 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4245 // properly, should be able to just wait for a state of "failed" instead of
4246 // waiting a fixed 10 seconds.
4247 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4248 ASSERT_FALSE(wait_res);
4249
4250 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4251 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004252}
4253
deadbeefc964d0b2017-04-03 10:03:35 -07004254// Test that audio and video flow end-to-end when codec names don't use the
4255// expected casing, given that they're supposed to be case insensitive. To test
4256// this, all but one codec is removed from each media description, and its
4257// casing is changed.
4258//
4259// In the past, this has regressed and caused crashes/black video, due to the
4260// fact that code at some layers was doing case-insensitive comparisons and
4261// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004262TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004263 ASSERT_TRUE(CreatePeerConnectionWrappers());
4264 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004265 caller()->AddAudioVideoTracks();
4266 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004267
4268 // Remove all but one audio/video codec (opus and VP8), and change the
4269 // casing of the caller's generated offer.
4270 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4271 cricket::AudioContentDescription* audio =
4272 GetFirstAudioContentDescription(description);
4273 ASSERT_NE(nullptr, audio);
4274 auto audio_codecs = audio->codecs();
4275 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4276 [](const cricket::AudioCodec& codec) {
4277 return codec.name != "opus";
4278 }),
4279 audio_codecs.end());
4280 ASSERT_EQ(1u, audio_codecs.size());
4281 audio_codecs[0].name = "OpUs";
4282 audio->set_codecs(audio_codecs);
4283
4284 cricket::VideoContentDescription* video =
4285 GetFirstVideoContentDescription(description);
4286 ASSERT_NE(nullptr, video);
4287 auto video_codecs = video->codecs();
4288 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4289 [](const cricket::VideoCodec& codec) {
4290 return codec.name != "VP8";
4291 }),
4292 video_codecs.end());
4293 ASSERT_EQ(1u, video_codecs.size());
4294 video_codecs[0].name = "vP8";
4295 video->set_codecs(video_codecs);
4296 });
4297
4298 caller()->CreateAndSetAndSignalOffer();
4299 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4300
4301 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004302 MediaExpectations media_expectations;
4303 media_expectations.ExpectBidirectionalAudioAndVideo();
4304 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004305}
4306
Seth Hampson2f0d7022018-02-20 11:54:42 -08004307TEST_P(PeerConnectionIntegrationTest, GetSources) {
hbos8d609f62017-04-10 07:39:05 -07004308 ASSERT_TRUE(CreatePeerConnectionWrappers());
4309 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004310 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004311 caller()->CreateAndSetAndSignalOffer();
4312 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004313 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004314 MediaExpectations media_expectations;
4315 media_expectations.CalleeExpectsSomeAudio(1);
4316 ASSERT_TRUE(ExpectNewFrames(media_expectations));
hbos8d609f62017-04-10 07:39:05 -07004317 ASSERT_GT(callee()->pc()->GetReceivers().size(), 0u);
4318 auto receiver = callee()->pc()->GetReceivers()[0];
4319 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
4320
4321 auto contributing_sources = receiver->GetSources();
4322 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4323 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4324 contributing_sources[0].source_id());
4325}
4326
deadbeef2f425aa2017-04-14 10:41:32 -07004327// Test that if a track is removed and added again with a different stream ID,
4328// the new stream ID is successfully communicated in SDP and media continues to
4329// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004330// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4331// it will not reuse a transceiver that has already been sending. After creating
4332// a new transceiver it tries to create an offer with two senders of the same
4333// track ids and it fails.
4334TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004335 ASSERT_TRUE(CreatePeerConnectionWrappers());
4336 ConnectFakeSignaling();
4337
deadbeef2f425aa2017-04-14 10:41:32 -07004338 // Add track using stream 1, do offer/answer.
4339 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4340 caller()->CreateLocalAudioTrack();
4341 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004342 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004343 caller()->CreateAndSetAndSignalOffer();
4344 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004345 {
4346 MediaExpectations media_expectations;
4347 media_expectations.CalleeExpectsSomeAudio(1);
4348 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4349 }
deadbeef2f425aa2017-04-14 10:41:32 -07004350 // Remove the sender, and create a new one with the new stream.
4351 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004352 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004353 caller()->CreateAndSetAndSignalOffer();
4354 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4355 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004356 {
4357 MediaExpectations media_expectations;
4358 media_expectations.CalleeExpectsSomeAudio();
4359 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4360 }
deadbeef2f425aa2017-04-14 10:41:32 -07004361}
4362
Seth Hampson2f0d7022018-02-20 11:54:42 -08004363TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004364 ASSERT_TRUE(CreatePeerConnectionWrappers());
4365 ConnectFakeSignaling();
4366
Karl Wiberg918f50c2018-07-05 11:40:33 +02004367 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Elad Alon99c3fe52017-10-13 16:29:40 +02004368 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
4369 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
4370 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004371 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4372 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004373
Steve Anton15324772018-01-16 10:26:49 -08004374 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004375 caller()->CreateAndSetAndSignalOffer();
4376 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4377}
4378
Steve Antonede9ca52017-10-16 13:04:27 -07004379// Test that if candidates are only signaled by applying full session
4380// descriptions (instead of using AddIceCandidate), the peers can connect to
4381// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004382TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004383 ASSERT_TRUE(CreatePeerConnectionWrappers());
4384 // Each side will signal the session descriptions but not candidates.
4385 ConnectFakeSignalingForSdpOnly();
4386
4387 // Add audio video track and exchange the initial offer/answer with media
4388 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004389 caller()->AddAudioVideoTracks();
4390 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004391 caller()->CreateAndSetAndSignalOffer();
4392
4393 // Wait for all candidates to be gathered on both the caller and callee.
4394 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4395 caller()->ice_gathering_state(), kDefaultTimeout);
4396 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4397 callee()->ice_gathering_state(), kDefaultTimeout);
4398
4399 // The candidates will now be included in the session description, so
4400 // signaling them will start the ICE connection.
4401 caller()->CreateAndSetAndSignalOffer();
4402 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4403
4404 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004405 MediaExpectations media_expectations;
4406 media_expectations.ExpectBidirectionalAudioAndVideo();
4407 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004408}
4409
henrika5f6bf242017-11-01 11:06:56 +01004410// Test that SetAudioPlayout can be used to disable audio playout from the
4411// start, then later enable it. This may be useful, for example, if the caller
4412// needs to play a local ringtone until some event occurs, after which it
4413// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004414TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004415 ASSERT_TRUE(CreatePeerConnectionWrappers());
4416 ConnectFakeSignaling();
4417
4418 // Set up audio-only call where audio playout is disabled on caller's side.
4419 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004420 caller()->AddAudioTrack();
4421 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004422 caller()->CreateAndSetAndSignalOffer();
4423 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4424
4425 // Pump messages for a second.
4426 WAIT(false, 1000);
4427 // Since audio playout is disabled, the caller shouldn't have received
4428 // anything (at the playout level, at least).
4429 EXPECT_EQ(0, caller()->audio_frames_received());
4430 // As a sanity check, make sure the callee (for which playout isn't disabled)
4431 // did still see frames on its audio level.
4432 ASSERT_GT(callee()->audio_frames_received(), 0);
4433
4434 // Enable playout again, and ensure audio starts flowing.
4435 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004436 MediaExpectations media_expectations;
4437 media_expectations.ExpectBidirectionalAudio();
4438 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004439}
4440
4441double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4442 auto report = pc->NewGetStats();
4443 auto track_stats_list =
4444 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4445 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4446 for (const auto* track_stats : track_stats_list) {
4447 if (track_stats->remote_source.is_defined() &&
4448 *track_stats->remote_source) {
4449 remote_track_stats = track_stats;
4450 break;
4451 }
4452 }
4453
4454 if (!remote_track_stats->total_audio_energy.is_defined()) {
4455 return 0.0;
4456 }
4457 return *remote_track_stats->total_audio_energy;
4458}
4459
4460// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4461// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004462TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004463 DisableAudioPlayoutStillGeneratesAudioStats) {
4464 ASSERT_TRUE(CreatePeerConnectionWrappers());
4465 ConnectFakeSignaling();
4466
4467 // Set up audio-only call where playout is disabled but audio-processing is
4468 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004469 caller()->AddAudioTrack();
4470 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004471 caller()->pc()->SetAudioPlayout(false);
4472
4473 caller()->CreateAndSetAndSignalOffer();
4474 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4475
4476 // Wait for the callee to receive audio stats.
4477 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4478}
4479
henrika4f167df2017-11-01 14:45:55 +01004480// Test that SetAudioRecording can be used to disable audio recording from the
4481// start, then later enable it. This may be useful, for example, if the caller
4482// wants to ensure that no audio resources are active before a certain state
4483// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004484TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004485 ASSERT_TRUE(CreatePeerConnectionWrappers());
4486 ConnectFakeSignaling();
4487
4488 // Set up audio-only call where audio recording is disabled on caller's side.
4489 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08004490 caller()->AddAudioTrack();
4491 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01004492 caller()->CreateAndSetAndSignalOffer();
4493 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4494
4495 // Pump messages for a second.
4496 WAIT(false, 1000);
4497 // Since caller has disabled audio recording, the callee shouldn't have
4498 // received anything.
4499 EXPECT_EQ(0, callee()->audio_frames_received());
4500 // As a sanity check, make sure the caller did still see frames on its
4501 // audio level since audio recording is enabled on the calle side.
4502 ASSERT_GT(caller()->audio_frames_received(), 0);
4503
4504 // Enable audio recording again, and ensure audio starts flowing.
4505 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004506 MediaExpectations media_expectations;
4507 media_expectations.ExpectBidirectionalAudio();
4508 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01004509}
4510
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004511// Test that after closing PeerConnections, they stop sending any packets (ICE,
4512// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004513TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004514 // Set up audio/video/data, wait for some frames to be received.
4515 ASSERT_TRUE(CreatePeerConnectionWrappers());
4516 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004517 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004518#ifdef HAVE_SCTP
4519 caller()->CreateDataChannel();
4520#endif
4521 caller()->CreateAndSetAndSignalOffer();
4522 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004523 MediaExpectations media_expectations;
4524 media_expectations.CalleeExpectsSomeAudioAndVideo();
4525 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004526 // Close PeerConnections.
4527 caller()->pc()->Close();
4528 callee()->pc()->Close();
4529 // Pump messages for a second, and ensure no new packets end up sent.
4530 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
4531 WAIT(false, 1000);
4532 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
4533 EXPECT_EQ(sent_packets_a, sent_packets_b);
4534}
4535
Steve Anton7eca0932018-03-30 15:18:41 -07004536// Test that transport stats are generated by the RTCStatsCollector for a
4537// connection that only involves data channels. This is a regression test for
4538// crbug.com/826972.
4539#ifdef HAVE_SCTP
4540TEST_P(PeerConnectionIntegrationTest,
4541 TransportStatsReportedForDataChannelOnlyConnection) {
4542 ASSERT_TRUE(CreatePeerConnectionWrappers());
4543 ConnectFakeSignaling();
4544 caller()->CreateDataChannel();
4545
4546 caller()->CreateAndSetAndSignalOffer();
4547 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4548 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
4549
4550 auto caller_report = caller()->NewGetStats();
4551 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
4552 auto callee_report = callee()->NewGetStats();
4553 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
4554}
4555#endif // HAVE_SCTP
4556
Qingsi Wang7685e862018-06-11 20:15:46 -07004557TEST_P(PeerConnectionIntegrationTest,
4558 IceEventsGeneratedAndLoggedInRtcEventLog) {
4559 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
4560 ConnectFakeSignaling();
4561 PeerConnectionInterface::RTCOfferAnswerOptions options;
4562 options.offer_to_receive_audio = 1;
4563 caller()->SetOfferAnswerOptions(options);
4564 caller()->CreateAndSetAndSignalOffer();
4565 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4566 ASSERT_NE(nullptr, caller()->event_log_factory());
4567 ASSERT_NE(nullptr, callee()->event_log_factory());
4568 webrtc::FakeRtcEventLog* caller_event_log =
4569 static_cast<webrtc::FakeRtcEventLog*>(
4570 caller()->event_log_factory()->last_log_created());
4571 webrtc::FakeRtcEventLog* callee_event_log =
4572 static_cast<webrtc::FakeRtcEventLog*>(
4573 callee()->event_log_factory()->last_log_created());
4574 ASSERT_NE(nullptr, caller_event_log);
4575 ASSERT_NE(nullptr, callee_event_log);
4576 int caller_ice_config_count = caller_event_log->GetEventCount(
4577 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4578 int caller_ice_event_count = caller_event_log->GetEventCount(
4579 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4580 int callee_ice_config_count = callee_event_log->GetEventCount(
4581 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4582 int callee_ice_event_count = callee_event_log->GetEventCount(
4583 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4584 EXPECT_LT(0, caller_ice_config_count);
4585 EXPECT_LT(0, caller_ice_event_count);
4586 EXPECT_LT(0, callee_ice_config_count);
4587 EXPECT_LT(0, callee_ice_event_count);
4588}
4589
Seth Hampson2f0d7022018-02-20 11:54:42 -08004590INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
4591 PeerConnectionIntegrationTest,
4592 Values(SdpSemantics::kPlanB,
4593 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08004594
Steve Anton74255ff2018-01-24 18:32:57 -08004595// Tests that verify interoperability between Plan B and Unified Plan
4596// PeerConnections.
4597class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004598 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08004599 public ::testing::WithParamInterface<
4600 std::tuple<SdpSemantics, SdpSemantics>> {
4601 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004602 // Setting the SdpSemantics for the base test to kDefault does not matter
4603 // because we specify not to use the test semantics when creating
4604 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08004605 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07004606 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08004607 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08004608 callee_semantics_(std::get<1>(GetParam())) {}
4609
4610 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07004611 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
4612 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08004613 }
4614
4615 const SdpSemantics caller_semantics_;
4616 const SdpSemantics callee_semantics_;
4617};
4618
4619TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
4620 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4621 ConnectFakeSignaling();
4622
4623 caller()->CreateAndSetAndSignalOffer();
4624 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4625}
4626
4627TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
4628 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4629 ConnectFakeSignaling();
4630 auto audio_sender = caller()->AddAudioTrack();
4631
4632 caller()->CreateAndSetAndSignalOffer();
4633 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4634
4635 // Verify that one audio receiver has been created on the remote and that it
4636 // has the same track ID as the sending track.
4637 auto receivers = callee()->pc()->GetReceivers();
4638 ASSERT_EQ(1u, receivers.size());
4639 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
4640 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
4641
Seth Hampson2f0d7022018-02-20 11:54:42 -08004642 MediaExpectations media_expectations;
4643 media_expectations.CalleeExpectsSomeAudio();
4644 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004645}
4646
4647TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
4648 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4649 ConnectFakeSignaling();
4650 auto video_sender = caller()->AddVideoTrack();
4651 auto audio_sender = caller()->AddAudioTrack();
4652
4653 caller()->CreateAndSetAndSignalOffer();
4654 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4655
4656 // Verify that one audio and one video receiver have been created on the
4657 // remote and that they have the same track IDs as the sending tracks.
4658 auto audio_receivers =
4659 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
4660 ASSERT_EQ(1u, audio_receivers.size());
4661 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
4662 auto video_receivers =
4663 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
4664 ASSERT_EQ(1u, video_receivers.size());
4665 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
4666
Seth Hampson2f0d7022018-02-20 11:54:42 -08004667 MediaExpectations media_expectations;
4668 media_expectations.CalleeExpectsSomeAudioAndVideo();
4669 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004670}
4671
4672TEST_P(PeerConnectionIntegrationInteropTest,
4673 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
4674 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4675 ConnectFakeSignaling();
4676 caller()->AddAudioVideoTracks();
4677 callee()->AddAudioVideoTracks();
4678
4679 caller()->CreateAndSetAndSignalOffer();
4680 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4681
Seth Hampson2f0d7022018-02-20 11:54:42 -08004682 MediaExpectations media_expectations;
4683 media_expectations.ExpectBidirectionalAudioAndVideo();
4684 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004685}
4686
4687TEST_P(PeerConnectionIntegrationInteropTest,
4688 ReverseRolesOneAudioLocalToOneVideoRemote) {
4689 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4690 ConnectFakeSignaling();
4691 caller()->AddAudioTrack();
4692 callee()->AddVideoTrack();
4693
4694 caller()->CreateAndSetAndSignalOffer();
4695 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4696
4697 // Verify that only the audio track has been negotiated.
4698 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
4699 // Might also check that the callee's NegotiationNeeded flag is set.
4700
4701 // Reverse roles.
4702 callee()->CreateAndSetAndSignalOffer();
4703 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4704
Seth Hampson2f0d7022018-02-20 11:54:42 -08004705 MediaExpectations media_expectations;
4706 media_expectations.CallerExpectsSomeVideo();
4707 media_expectations.CalleeExpectsSomeAudio();
4708 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004709}
4710
Steve Antonba42e992018-04-09 14:10:01 -07004711INSTANTIATE_TEST_CASE_P(
4712 PeerConnectionIntegrationTest,
4713 PeerConnectionIntegrationInteropTest,
4714 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4715 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
4716
4717// Test that if the Unified Plan side offers two video tracks then the Plan B
4718// side will only see the first one and ignore the second.
4719TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07004720 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
4721 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08004722 ConnectFakeSignaling();
4723 auto first_sender = caller()->AddVideoTrack();
4724 caller()->AddVideoTrack();
4725
4726 caller()->CreateAndSetAndSignalOffer();
4727 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4728
4729 // Verify that there is only one receiver and it corresponds to the first
4730 // added track.
4731 auto receivers = callee()->pc()->GetReceivers();
4732 ASSERT_EQ(1u, receivers.size());
4733 EXPECT_TRUE(receivers[0]->track()->enabled());
4734 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
4735
Seth Hampson2f0d7022018-02-20 11:54:42 -08004736 MediaExpectations media_expectations;
4737 media_expectations.CalleeExpectsSomeVideo();
4738 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004739}
4740
deadbeef1dcb1642017-03-29 21:08:16 -07004741} // namespace
4742
4743#endif // if !defined(THREAD_SANITIZER)