blob: fda34fe2635bda53dc42f759e409097c85939d70 [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"
Bjorn Mellem175aa2e2018-11-08 11:23:22 -080031#include "api/test/loopback_media_transport.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020032#include "api/umametrics.h"
Anders Carlsson67537952018-05-03 11:28:29 +020033#include "api/video_codecs/builtin_video_decoder_factory.h"
34#include "api/video_codecs/builtin_video_encoder_factory.h"
35#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070036#include "call/call.h"
37#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
38#include "logging/rtc_event_log/rtc_event_log_factory_interface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "media/engine/fakewebrtcvideoengine.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070040#include "media/engine/webrtcmediaengine.h"
41#include "modules/audio_processing/include/audio_processing.h"
Zach Stein6fcdc2f2018-08-23 16:25:55 -070042#include "p2p/base/mockasyncresolver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "p2p/base/p2pconstants.h"
44#include "p2p/base/portinterface.h"
Steve Antonede9ca52017-10-16 13:04:27 -070045#include "p2p/base/teststunserver.h"
Jonas Orelandbdcee282017-10-10 14:01:40 +020046#include "p2p/base/testturncustomizer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "p2p/base/testturnserver.h"
48#include "p2p/client/basicportallocator.h"
49#include "pc/dtmfsender.h"
50#include "pc/localaudiosource.h"
51#include "pc/mediasession.h"
52#include "pc/peerconnection.h"
53#include "pc/peerconnectionfactory.h"
Seth Hampson2f0d7022018-02-20 11:54:42 -080054#include "pc/rtpmediautils.h"
Steve Anton4ab68ee2017-12-19 14:26:11 -080055#include "pc/sessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020056#include "pc/test/fakeaudiocapturemodule.h"
Niels Möller0f405822018-05-17 09:16:41 +020057#include "pc/test/fakeperiodicvideotracksource.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020058#include "pc/test/fakertccertificategenerator.h"
59#include "pc/test/fakevideotrackrenderer.h"
60#include "pc/test/mockpeerconnectionobservers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020061#include "rtc_base/fakenetwork.h"
Steve Antonede9ca52017-10-16 13:04:27 -070062#include "rtc_base/firewallsocketserver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020063#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020064#include "rtc_base/numerics/safe_conversions.h"
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070065#include "rtc_base/testcertificateverifier.h"
Johannes Kron965e7942018-09-13 15:36:20 +020066#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020067#include "rtc_base/virtualsocketserver.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020068#include "system_wrappers/include/metrics.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020069#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070070
71using cricket::ContentInfo;
72using cricket::FakeWebRtcVideoDecoder;
73using cricket::FakeWebRtcVideoDecoderFactory;
74using cricket::FakeWebRtcVideoEncoder;
75using cricket::FakeWebRtcVideoEncoderFactory;
76using cricket::MediaContentDescription;
Steve Antondf527fd2018-04-27 15:52:03 -070077using cricket::StreamParams;
Steve Antonede9ca52017-10-16 13:04:27 -070078using rtc::SocketAddress;
Seth Hampson2f0d7022018-02-20 11:54:42 -080079using ::testing::Combine;
Steve Antonede9ca52017-10-16 13:04:27 -070080using ::testing::ElementsAre;
Steve Antona41959e2018-11-28 11:15:33 -080081using ::testing::UnorderedElementsAreArray;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070082using ::testing::Return;
83using ::testing::SetArgPointee;
Steve Antonede9ca52017-10-16 13:04:27 -070084using ::testing::Values;
Steve Antonffa6ce42018-11-30 09:26:08 -080085using ::testing::UnorderedElementsAreArray;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070086using ::testing::_;
deadbeef1dcb1642017-03-29 21:08:16 -070087using webrtc::DataBuffer;
88using webrtc::DataChannelInterface;
89using webrtc::DtmfSender;
90using webrtc::DtmfSenderInterface;
91using webrtc::DtmfSenderObserverInterface;
Steve Anton15324772018-01-16 10:26:49 -080092using webrtc::FakeVideoTrackRenderer;
deadbeef1dcb1642017-03-29 21:08:16 -070093using webrtc::MediaStreamInterface;
94using webrtc::MediaStreamTrackInterface;
95using webrtc::MockCreateSessionDescriptionObserver;
96using webrtc::MockDataChannelObserver;
97using webrtc::MockSetSessionDescriptionObserver;
98using webrtc::MockStatsObserver;
99using webrtc::ObserverInterface;
Steve Anton8c0f7a72017-10-03 10:03:10 -0700100using webrtc::PeerConnection;
deadbeef1dcb1642017-03-29 21:08:16 -0700101using webrtc::PeerConnectionInterface;
Steve Anton74255ff2018-01-24 18:32:57 -0800102using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -0700103using webrtc::PeerConnectionFactory;
Steve Anton8c0f7a72017-10-03 10:03:10 -0700104using webrtc::PeerConnectionProxy;
Steve Anton15324772018-01-16 10:26:49 -0800105using webrtc::RTCErrorType;
Steve Anton7eca0932018-03-30 15:18:41 -0700106using webrtc::RTCTransportStats;
Steve Anton74255ff2018-01-24 18:32:57 -0800107using webrtc::RtpSenderInterface;
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100108using webrtc::RtpReceiverInterface;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800109using webrtc::RtpSenderInterface;
110using webrtc::RtpTransceiverDirection;
111using webrtc::RtpTransceiverInit;
112using webrtc::RtpTransceiverInterface;
Steve Antond3679212018-01-17 17:41:02 -0800113using webrtc::SdpSemantics;
Steve Antona3a92c22017-12-07 10:27:41 -0800114using webrtc::SdpType;
deadbeef1dcb1642017-03-29 21:08:16 -0700115using webrtc::SessionDescriptionInterface;
116using webrtc::StreamCollectionInterface;
Steve Anton15324772018-01-16 10:26:49 -0800117using webrtc::VideoTrackInterface;
deadbeef1dcb1642017-03-29 21:08:16 -0700118
119namespace {
120
121static const int kDefaultTimeout = 10000;
122static const int kMaxWaitForStatsMs = 3000;
123static const int kMaxWaitForActivationMs = 5000;
124static const int kMaxWaitForFramesMs = 10000;
125// Default number of audio/video frames to wait for before considering a test
126// successful.
127static const int kDefaultExpectedAudioFrameCount = 3;
128static const int kDefaultExpectedVideoFrameCount = 3;
129
deadbeef1dcb1642017-03-29 21:08:16 -0700130static const char kDataChannelLabel[] = "data_channel";
131
132// SRTP cipher name negotiated by the tests. This must be updated if the
133// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700134static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700135static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
136
Steve Antonede9ca52017-10-16 13:04:27 -0700137static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
138
deadbeef1dcb1642017-03-29 21:08:16 -0700139// Helper function for constructing offer/answer options to initiate an ICE
140// restart.
141PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
142 PeerConnectionInterface::RTCOfferAnswerOptions options;
143 options.ice_restart = true;
144 return options;
145}
146
deadbeefd8ad7882017-04-18 16:01:17 -0700147// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
148// attribute from received SDP, simulating a legacy endpoint.
149void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
150 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800151 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700152 }
153 desc->set_msid_supported(false);
Henrik Boström5b147782018-12-04 11:25:05 +0100154 desc->set_msid_signaling(0);
deadbeefd8ad7882017-04-18 16:01:17 -0700155}
156
Seth Hampson5897a6e2018-04-03 11:16:33 -0700157// Removes all stream information besides the stream ids, simulating an
158// endpoint that only signals a=msid lines to convey stream_ids.
159void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
160 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700161 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700162 std::vector<std::string> stream_ids;
163 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700164 const StreamParams& first_stream =
165 content.media_description()->streams()[0];
166 track_id = first_stream.id;
167 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700168 }
169 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700170 StreamParams new_stream;
171 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700172 new_stream.set_stream_ids(stream_ids);
173 content.media_description()->AddStream(new_stream);
174 }
175}
176
zhihuangf8164932017-05-19 13:09:47 -0700177int FindFirstMediaStatsIndexByKind(
178 const std::string& kind,
179 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
180 media_stats_vec) {
181 for (size_t i = 0; i < media_stats_vec.size(); i++) {
182 if (media_stats_vec[i]->kind.ValueToString() == kind) {
183 return i;
184 }
185 }
186 return -1;
187}
188
deadbeef1dcb1642017-03-29 21:08:16 -0700189class SignalingMessageReceiver {
190 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800191 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700192 virtual void ReceiveIceMessage(const std::string& sdp_mid,
193 int sdp_mline_index,
194 const std::string& msg) = 0;
195
196 protected:
197 SignalingMessageReceiver() {}
198 virtual ~SignalingMessageReceiver() {}
199};
200
201class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
202 public:
203 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
204 : expected_media_type_(media_type) {}
205
206 void OnFirstPacketReceived(cricket::MediaType media_type) override {
207 ASSERT_EQ(expected_media_type_, media_type);
208 first_packet_received_ = true;
209 }
210
211 bool first_packet_received() const { return first_packet_received_; }
212
213 virtual ~MockRtpReceiverObserver() {}
214
215 private:
216 bool first_packet_received_ = false;
217 cricket::MediaType expected_media_type_;
218};
219
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700220// Used by PeerConnectionWrapper::OnIceCandidate to allow a test to modify an
221// ICE candidate before it is signaled.
222class IceCandidateReplacerInterface {
223 public:
224 virtual ~IceCandidateReplacerInterface() = default;
225 // Return nullptr to drop the candidate (it won't be signaled to the other
226 // side).
227 virtual std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
228 const webrtc::IceCandidateInterface*) = 0;
229};
230
deadbeef1dcb1642017-03-29 21:08:16 -0700231// Helper class that wraps a peer connection, observes it, and can accept
232// signaling messages from another wrapper.
233//
234// Uses a fake network, fake A/V capture, and optionally fake
235// encoders/decoders, though they aren't used by default since they don't
236// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700237// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800238// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700239class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800240 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700241 public:
242 // Different factory methods for convenience.
243 // TODO(deadbeef): Could use the pattern of:
244 //
245 // PeerConnectionWrapper =
246 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
247 //
248 // To reduce some code duplication.
249 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
250 const std::string& debug_name,
251 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
252 rtc::Thread* network_thread,
253 rtc::Thread* worker_thread) {
254 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700255 webrtc::PeerConnectionDependencies dependencies(nullptr);
256 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200257 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800258 worker_thread, nullptr,
259 /*media_transport_factory=*/nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700260 delete client;
261 return nullptr;
262 }
263 return client;
264 }
265
deadbeef2f425aa2017-04-14 10:41:32 -0700266 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
267 return peer_connection_factory_.get();
268 }
269
deadbeef1dcb1642017-03-29 21:08:16 -0700270 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
271
272 // If a signaling message receiver is set (via ConnectFakeSignaling), this
273 // will set the whole offer/answer exchange in motion. Just need to wait for
274 // the signaling state to reach "stable".
275 void CreateAndSetAndSignalOffer() {
276 auto offer = CreateOffer();
277 ASSERT_NE(nullptr, offer);
278 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
279 }
280
281 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
282 // when a remote offer is received (via fake signaling) and an answer is
283 // generated. By default, uses default options.
284 void SetOfferAnswerOptions(
285 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
286 offer_answer_options_ = options;
287 }
288
289 // Set a callback to be invoked when SDP is received via the fake signaling
290 // channel, which provides an opportunity to munge (modify) the SDP. This is
291 // used to test SDP being applied that a PeerConnection would normally not
292 // generate, but a non-JSEP endpoint might.
293 void SetReceivedSdpMunger(
294 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100295 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700296 }
297
deadbeefc964d0b2017-04-03 10:03:35 -0700298 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700299 // generated.
300 void SetGeneratedSdpMunger(
301 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100302 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700303 }
304
Seth Hampson2f0d7022018-02-20 11:54:42 -0800305 // Set a callback to be invoked when a remote offer is received via the fake
306 // signaling channel. This provides an opportunity to change the
307 // PeerConnection state before an answer is created and sent to the caller.
308 void SetRemoteOfferHandler(std::function<void()> handler) {
309 remote_offer_handler_ = std::move(handler);
310 }
311
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700312 void SetLocalIceCandidateReplacer(
313 std::unique_ptr<IceCandidateReplacerInterface> replacer) {
314 local_ice_candidate_replacer_ = std::move(replacer);
315 }
316
Steve Antonede9ca52017-10-16 13:04:27 -0700317 // Every ICE connection state in order that has been seen by the observer.
318 std::vector<PeerConnectionInterface::IceConnectionState>
319 ice_connection_state_history() const {
320 return ice_connection_state_history_;
321 }
Steve Anton6f25b092017-10-23 09:39:20 -0700322 void clear_ice_connection_state_history() {
323 ice_connection_state_history_.clear();
324 }
Steve Antonede9ca52017-10-16 13:04:27 -0700325
Jonas Olsson635474e2018-10-18 15:58:17 +0200326 // Every PeerConnection state in order that has been seen by the observer.
327 std::vector<PeerConnectionInterface::PeerConnectionState>
328 peer_connection_state_history() const {
329 return peer_connection_state_history_;
330 }
331
Steve Antonede9ca52017-10-16 13:04:27 -0700332 // Every ICE gathering state in order that has been seen by the observer.
333 std::vector<PeerConnectionInterface::IceGatheringState>
334 ice_gathering_state_history() const {
335 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700336 }
337
Steve Anton15324772018-01-16 10:26:49 -0800338 void AddAudioVideoTracks() {
339 AddAudioTrack();
340 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700341 }
342
Steve Anton74255ff2018-01-24 18:32:57 -0800343 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
344 return AddTrack(CreateLocalAudioTrack());
345 }
deadbeef1dcb1642017-03-29 21:08:16 -0700346
Steve Anton74255ff2018-01-24 18:32:57 -0800347 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
348 return AddTrack(CreateLocalVideoTrack());
349 }
deadbeef1dcb1642017-03-29 21:08:16 -0700350
351 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200352 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700353 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200354 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700355 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200356 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700357 // TODO(perkj): Test audio source when it is implemented. Currently audio
358 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700359 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700360 source);
361 }
362
363 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200364 webrtc::FakePeriodicVideoSource::Config config;
365 config.timestamp_offset_ms = rtc::TimeMillis();
366 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700367 }
368
369 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200370 CreateLocalVideoTrackWithConfig(
371 webrtc::FakePeriodicVideoSource::Config config) {
372 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700373 }
374
375 rtc::scoped_refptr<webrtc::VideoTrackInterface>
376 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200377 webrtc::FakePeriodicVideoSource::Config config;
378 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200379 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200380 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700381 }
382
Steve Anton74255ff2018-01-24 18:32:57 -0800383 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
384 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800385 const std::vector<std::string>& stream_ids = {}) {
386 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800387 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800388 return result.MoveValue();
389 }
390
391 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
392 cricket::MediaType media_type) {
393 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
394 for (auto receiver : pc()->GetReceivers()) {
395 if (receiver->media_type() == media_type) {
396 receivers.push_back(receiver);
397 }
398 }
399 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700400 }
401
Seth Hampson2f0d7022018-02-20 11:54:42 -0800402 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
403 cricket::MediaType media_type) {
404 for (auto transceiver : pc()->GetTransceivers()) {
405 if (transceiver->receiver()->media_type() == media_type) {
406 return transceiver;
407 }
408 }
409 return nullptr;
410 }
411
deadbeef1dcb1642017-03-29 21:08:16 -0700412 bool SignalingStateStable() {
413 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
414 }
415
416 void CreateDataChannel() { CreateDataChannel(nullptr); }
417
418 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700419 CreateDataChannel(kDataChannelLabel, init);
420 }
421
422 void CreateDataChannel(const std::string& label,
423 const webrtc::DataChannelInit* init) {
424 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700425 ASSERT_TRUE(data_channel_.get() != nullptr);
426 data_observer_.reset(new MockDataChannelObserver(data_channel_));
427 }
428
429 DataChannelInterface* data_channel() { return data_channel_; }
430 const MockDataChannelObserver* data_observer() const {
431 return data_observer_.get();
432 }
433
434 int audio_frames_received() const {
435 return fake_audio_capture_module_->frames_received();
436 }
437
438 // Takes minimum of video frames received for each track.
439 //
440 // Can be used like:
441 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
442 //
443 // To ensure that all video tracks received at least a certain number of
444 // frames.
445 int min_video_frames_received_per_track() const {
446 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200447 if (fake_video_renderers_.empty()) {
448 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700449 }
deadbeef1dcb1642017-03-29 21:08:16 -0700450
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200451 for (const auto& pair : fake_video_renderers_) {
452 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700453 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200454 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700455 }
456
457 // Returns a MockStatsObserver in a state after stats gathering finished,
458 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700459 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700460 webrtc::MediaStreamTrackInterface* track) {
461 rtc::scoped_refptr<MockStatsObserver> observer(
462 new rtc::RefCountedObject<MockStatsObserver>());
463 EXPECT_TRUE(peer_connection_->GetStats(
464 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
465 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
466 return observer;
467 }
468
469 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700470 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
471 return OldGetStatsForTrack(nullptr);
472 }
473
474 // Synchronously gets stats and returns them. If it times out, fails the test
475 // and returns null.
476 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
477 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
478 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
479 peer_connection_->GetStats(callback);
480 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
481 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700482 }
483
484 int rendered_width() {
485 EXPECT_FALSE(fake_video_renderers_.empty());
486 return fake_video_renderers_.empty()
487 ? 0
488 : fake_video_renderers_.begin()->second->width();
489 }
490
491 int rendered_height() {
492 EXPECT_FALSE(fake_video_renderers_.empty());
493 return fake_video_renderers_.empty()
494 ? 0
495 : fake_video_renderers_.begin()->second->height();
496 }
497
498 double rendered_aspect_ratio() {
499 if (rendered_height() == 0) {
500 return 0.0;
501 }
502 return static_cast<double>(rendered_width()) / rendered_height();
503 }
504
505 webrtc::VideoRotation rendered_rotation() {
506 EXPECT_FALSE(fake_video_renderers_.empty());
507 return fake_video_renderers_.empty()
508 ? webrtc::kVideoRotation_0
509 : fake_video_renderers_.begin()->second->rotation();
510 }
511
512 int local_rendered_width() {
513 return local_video_renderer_ ? local_video_renderer_->width() : 0;
514 }
515
516 int local_rendered_height() {
517 return local_video_renderer_ ? local_video_renderer_->height() : 0;
518 }
519
520 double local_rendered_aspect_ratio() {
521 if (local_rendered_height() == 0) {
522 return 0.0;
523 }
524 return static_cast<double>(local_rendered_width()) /
525 local_rendered_height();
526 }
527
528 size_t number_of_remote_streams() {
529 if (!pc()) {
530 return 0;
531 }
532 return pc()->remote_streams()->count();
533 }
534
535 StreamCollectionInterface* remote_streams() const {
536 if (!pc()) {
537 ADD_FAILURE();
538 return nullptr;
539 }
540 return pc()->remote_streams();
541 }
542
543 StreamCollectionInterface* local_streams() {
544 if (!pc()) {
545 ADD_FAILURE();
546 return nullptr;
547 }
548 return pc()->local_streams();
549 }
550
551 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
552 return pc()->signaling_state();
553 }
554
555 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
556 return pc()->ice_connection_state();
557 }
558
559 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
560 return pc()->ice_gathering_state();
561 }
562
563 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
564 // GetReceivers. They're updated automatically when a remote offer/answer
565 // from the fake signaling channel is applied, or when
566 // ResetRtpReceiverObservers below is called.
567 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
568 rtp_receiver_observers() {
569 return rtp_receiver_observers_;
570 }
571
572 void ResetRtpReceiverObservers() {
573 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100574 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
575 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700576 std::unique_ptr<MockRtpReceiverObserver> observer(
577 new MockRtpReceiverObserver(receiver->media_type()));
578 receiver->SetObserver(observer.get());
579 rtp_receiver_observers_.push_back(std::move(observer));
580 }
581 }
582
Steve Antonede9ca52017-10-16 13:04:27 -0700583 rtc::FakeNetworkManager* network() const {
584 return fake_network_manager_.get();
585 }
586 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
587
Qingsi Wang7685e862018-06-11 20:15:46 -0700588 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
589 return event_log_factory_;
590 }
591
deadbeef1dcb1642017-03-29 21:08:16 -0700592 private:
593 explicit PeerConnectionWrapper(const std::string& debug_name)
594 : debug_name_(debug_name) {}
595
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800596 bool Init(
597 const PeerConnectionFactory::Options* options,
598 const PeerConnectionInterface::RTCConfiguration* config,
599 webrtc::PeerConnectionDependencies dependencies,
600 rtc::Thread* network_thread,
601 rtc::Thread* worker_thread,
602 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
603 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700604 // There's an error in this test code if Init ends up being called twice.
605 RTC_DCHECK(!peer_connection_);
606 RTC_DCHECK(!peer_connection_factory_);
607
608 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700609 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700610
611 std::unique_ptr<cricket::PortAllocator> port_allocator(
612 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700613 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700614 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
615 if (!fake_audio_capture_module_) {
616 return false;
617 }
deadbeef1dcb1642017-03-29 21:08:16 -0700618 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700619
620 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
621 pc_factory_dependencies.network_thread = network_thread;
622 pc_factory_dependencies.worker_thread = worker_thread;
623 pc_factory_dependencies.signaling_thread = signaling_thread;
624 pc_factory_dependencies.media_engine =
625 cricket::WebRtcMediaEngineFactory::Create(
626 rtc::scoped_refptr<webrtc::AudioDeviceModule>(
627 fake_audio_capture_module_),
628 webrtc::CreateBuiltinAudioEncoderFactory(),
629 webrtc::CreateBuiltinAudioDecoderFactory(),
630 webrtc::CreateBuiltinVideoEncoderFactory(),
Qingsi Wang59844ce2018-11-01 04:45:53 +0000631 webrtc::CreateBuiltinVideoDecoderFactory(), nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -0700632 webrtc::AudioProcessingBuilder().Create());
633 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
634 if (event_log_factory) {
635 event_log_factory_ = event_log_factory.get();
636 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
637 } else {
638 pc_factory_dependencies.event_log_factory =
639 webrtc::CreateRtcEventLogFactory();
640 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800641 if (media_transport_factory) {
642 pc_factory_dependencies.media_transport_factory =
643 std::move(media_transport_factory);
644 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700645 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
646 std::move(pc_factory_dependencies));
647
deadbeef1dcb1642017-03-29 21:08:16 -0700648 if (!peer_connection_factory_) {
649 return false;
650 }
651 if (options) {
652 peer_connection_factory_->SetOptions(*options);
653 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800654 if (config) {
655 sdp_semantics_ = config->sdp_semantics;
656 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700657
658 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200659 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700660 return peer_connection_.get() != nullptr;
661 }
662
663 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700664 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700665 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700666 PeerConnectionInterface::RTCConfiguration modified_config;
667 // If |config| is null, this will result in a default configuration being
668 // used.
669 if (config) {
670 modified_config = *config;
671 }
672 // Disable resolution adaptation; we don't want it interfering with the
673 // test results.
674 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
675 // ratios and not specific resolutions, is this even necessary?
676 modified_config.set_cpu_adaptation(false);
677
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700678 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700679 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700680 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700681 }
682
683 void set_signaling_message_receiver(
684 SignalingMessageReceiver* signaling_message_receiver) {
685 signaling_message_receiver_ = signaling_message_receiver;
686 }
687
688 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
689
Steve Antonede9ca52017-10-16 13:04:27 -0700690 void set_signal_ice_candidates(bool signal) {
691 signal_ice_candidates_ = signal;
692 }
693
deadbeef1dcb1642017-03-29 21:08:16 -0700694 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200695 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700696 // Set max frame rate to 10fps to reduce the risk of test flakiness.
697 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200698 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700699
Niels Möller5c7efe72018-05-11 10:34:46 +0200700 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200701 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
702 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700703 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200704 peer_connection_factory_->CreateVideoTrack(
705 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700706 if (!local_video_renderer_) {
707 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
708 }
709 return track;
710 }
711
712 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100713 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800714 std::unique_ptr<SessionDescriptionInterface> desc =
715 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700716 if (received_sdp_munger_) {
717 received_sdp_munger_(desc->description());
718 }
719
720 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
721 // Setting a remote description may have changed the number of receivers,
722 // so reset the receiver observers.
723 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800724 if (remote_offer_handler_) {
725 remote_offer_handler_();
726 }
deadbeef1dcb1642017-03-29 21:08:16 -0700727 auto answer = CreateAnswer();
728 ASSERT_NE(nullptr, answer);
729 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
730 }
731
732 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100733 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800734 std::unique_ptr<SessionDescriptionInterface> desc =
735 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700736 if (received_sdp_munger_) {
737 received_sdp_munger_(desc->description());
738 }
739
740 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
741 // Set the RtpReceiverObserver after receivers are created.
742 ResetRtpReceiverObservers();
743 }
744
745 // Returns null on failure.
746 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
747 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
748 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
749 pc()->CreateOffer(observer, offer_answer_options_);
750 return WaitForDescriptionFromObserver(observer);
751 }
752
753 // Returns null on failure.
754 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
755 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
756 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
757 pc()->CreateAnswer(observer, offer_answer_options_);
758 return WaitForDescriptionFromObserver(observer);
759 }
760
761 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100762 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700763 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
764 if (!observer->result()) {
765 return nullptr;
766 }
767 auto description = observer->MoveDescription();
768 if (generated_sdp_munger_) {
769 generated_sdp_munger_(description->description());
770 }
771 return description;
772 }
773
774 // Setting the local description and sending the SDP message over the fake
775 // signaling channel are combined into the same method because the SDP
776 // message needs to be sent as soon as SetLocalDescription finishes, without
777 // waiting for the observer to be called. This ensures that ICE candidates
778 // don't outrace the description.
779 bool SetLocalDescriptionAndSendSdpMessage(
780 std::unique_ptr<SessionDescriptionInterface> desc) {
781 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
782 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100783 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800784 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700785 std::string sdp;
786 EXPECT_TRUE(desc->ToString(&sdp));
787 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800788 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
789 RemoveUnusedVideoRenderers();
790 }
deadbeef1dcb1642017-03-29 21:08:16 -0700791 // As mentioned above, we need to send the message immediately after
792 // SetLocalDescription.
793 SendSdpMessage(type, sdp);
794 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
795 return true;
796 }
797
798 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
799 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
800 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100801 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700802 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800803 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
804 RemoveUnusedVideoRenderers();
805 }
deadbeef1dcb1642017-03-29 21:08:16 -0700806 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
807 return observer->result();
808 }
809
Seth Hampson2f0d7022018-02-20 11:54:42 -0800810 // This is a work around to remove unused fake_video_renderers from
811 // transceivers that have either stopped or are no longer receiving.
812 void RemoveUnusedVideoRenderers() {
813 auto transceivers = pc()->GetTransceivers();
814 for (auto& transceiver : transceivers) {
815 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
816 continue;
817 }
818 // Remove fake video renderers from any stopped transceivers.
819 if (transceiver->stopped()) {
820 auto it =
821 fake_video_renderers_.find(transceiver->receiver()->track()->id());
822 if (it != fake_video_renderers_.end()) {
823 fake_video_renderers_.erase(it);
824 }
825 }
826 // Remove fake video renderers from any transceivers that are no longer
827 // receiving.
828 if ((transceiver->current_direction() &&
829 !webrtc::RtpTransceiverDirectionHasRecv(
830 *transceiver->current_direction()))) {
831 auto it =
832 fake_video_renderers_.find(transceiver->receiver()->track()->id());
833 if (it != fake_video_renderers_.end()) {
834 fake_video_renderers_.erase(it);
835 }
836 }
837 }
838 }
839
deadbeef1dcb1642017-03-29 21:08:16 -0700840 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
841 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800842 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700843 if (signaling_delay_ms_ == 0) {
844 RelaySdpMessageIfReceiverExists(type, msg);
845 } else {
846 invoker_.AsyncInvokeDelayed<void>(
847 RTC_FROM_HERE, rtc::Thread::Current(),
848 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
849 this, type, msg),
850 signaling_delay_ms_);
851 }
852 }
853
Steve Antona3a92c22017-12-07 10:27:41 -0800854 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700855 if (signaling_message_receiver_) {
856 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
857 }
858 }
859
860 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
861 // default).
862 void SendIceMessage(const std::string& sdp_mid,
863 int sdp_mline_index,
864 const std::string& msg) {
865 if (signaling_delay_ms_ == 0) {
866 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
867 } else {
868 invoker_.AsyncInvokeDelayed<void>(
869 RTC_FROM_HERE, rtc::Thread::Current(),
870 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
871 this, sdp_mid, sdp_mline_index, msg),
872 signaling_delay_ms_);
873 }
874 }
875
876 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
877 int sdp_mline_index,
878 const std::string& msg) {
879 if (signaling_message_receiver_) {
880 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
881 msg);
882 }
883 }
884
885 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800886 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
887 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700888 HandleIncomingOffer(msg);
889 } else {
890 HandleIncomingAnswer(msg);
891 }
892 }
893
894 void ReceiveIceMessage(const std::string& sdp_mid,
895 int sdp_mline_index,
896 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100897 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700898 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
899 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
900 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
901 }
902
903 // PeerConnectionObserver callbacks.
904 void OnSignalingChange(
905 webrtc::PeerConnectionInterface::SignalingState new_state) override {
906 EXPECT_EQ(pc()->signaling_state(), new_state);
907 }
Steve Anton15324772018-01-16 10:26:49 -0800908 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
909 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
910 streams) override {
911 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
912 rtc::scoped_refptr<VideoTrackInterface> video_track(
913 static_cast<VideoTrackInterface*>(receiver->track().get()));
914 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700915 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800916 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200917 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700918 }
919 }
Steve Anton15324772018-01-16 10:26:49 -0800920 void OnRemoveTrack(
921 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
922 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
923 auto it = fake_video_renderers_.find(receiver->track()->id());
924 RTC_DCHECK(it != fake_video_renderers_.end());
925 fake_video_renderers_.erase(it);
926 }
927 }
deadbeef1dcb1642017-03-29 21:08:16 -0700928 void OnRenegotiationNeeded() override {}
929 void OnIceConnectionChange(
930 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
931 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700932 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700933 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200934 void OnConnectionChange(
935 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
936 peer_connection_state_history_.push_back(new_state);
937 }
938
deadbeef1dcb1642017-03-29 21:08:16 -0700939 void OnIceGatheringChange(
940 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700941 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700942 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700943 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700944 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceIceCandidate(
945 const webrtc::IceCandidateInterface* candidate) {
946 std::string candidate_string;
947 candidate->ToString(&candidate_string);
948
949 auto owned_candidate =
950 local_ice_candidate_replacer_->ReplaceCandidate(candidate);
951 if (!owned_candidate) {
952 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer dropped \""
953 << candidate_string << "\"";
954 return nullptr;
955 }
956 std::string owned_candidate_string;
957 owned_candidate->ToString(&owned_candidate_string);
958 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer changed \""
959 << candidate_string << "\" to \"" << owned_candidate_string
960 << "\"";
961 return owned_candidate;
962 }
deadbeef1dcb1642017-03-29 21:08:16 -0700963 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100964 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700965
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700966 const webrtc::IceCandidateInterface* new_candidate = candidate;
967 std::unique_ptr<webrtc::IceCandidateInterface> owned_candidate;
968 if (local_ice_candidate_replacer_) {
969 owned_candidate = ReplaceIceCandidate(candidate);
970 if (!owned_candidate) {
971 return; // The candidate was dropped.
972 }
973 new_candidate = owned_candidate.get();
974 }
975
deadbeef1dcb1642017-03-29 21:08:16 -0700976 std::string ice_sdp;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700977 EXPECT_TRUE(new_candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700978 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700979 // Remote party may be deleted.
980 return;
981 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700982 SendIceMessage(new_candidate->sdp_mid(), new_candidate->sdp_mline_index(),
983 ice_sdp);
deadbeef1dcb1642017-03-29 21:08:16 -0700984 }
985 void OnDataChannel(
986 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100987 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700988 data_channel_ = data_channel;
989 data_observer_.reset(new MockDataChannelObserver(data_channel));
990 }
991
deadbeef1dcb1642017-03-29 21:08:16 -0700992 std::string debug_name_;
993
994 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
995
996 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
997 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
998 peer_connection_factory_;
999
Steve Antonede9ca52017-10-16 13:04:27 -07001000 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -07001001 // Needed to keep track of number of frames sent.
1002 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1003 // Needed to keep track of number of frames received.
1004 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1005 fake_video_renderers_;
1006 // Needed to ensure frames aren't received for removed tracks.
1007 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1008 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001009
1010 // For remote peer communication.
1011 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1012 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001013 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -07001014
Niels Möller5c7efe72018-05-11 10:34:46 +02001015 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001016 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001017 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1018 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001019 // |local_video_renderer_| attached to the first created local video track.
1020 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1021
Seth Hampson2f0d7022018-02-20 11:54:42 -08001022 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001023 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1024 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1025 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001026 std::function<void()> remote_offer_handler_;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07001027 std::unique_ptr<IceCandidateReplacerInterface> local_ice_candidate_replacer_;
deadbeef1dcb1642017-03-29 21:08:16 -07001028 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1029 std::unique_ptr<MockDataChannelObserver> data_observer_;
1030
1031 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1032
Steve Antonede9ca52017-10-16 13:04:27 -07001033 std::vector<PeerConnectionInterface::IceConnectionState>
1034 ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001035 std::vector<PeerConnectionInterface::PeerConnectionState>
1036 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001037 std::vector<PeerConnectionInterface::IceGatheringState>
1038 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001039
Qingsi Wang7685e862018-06-11 20:15:46 -07001040 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1041
deadbeef1dcb1642017-03-29 21:08:16 -07001042 rtc::AsyncInvoker invoker_;
1043
Seth Hampson2f0d7022018-02-20 11:54:42 -08001044 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001045};
1046
Elad Alon99c3fe52017-10-13 16:29:40 +02001047class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1048 public:
1049 virtual ~MockRtcEventLogOutput() = default;
1050 MOCK_CONST_METHOD0(IsActive, bool());
1051 MOCK_METHOD1(Write, bool(const std::string&));
1052};
1053
Seth Hampson2f0d7022018-02-20 11:54:42 -08001054// This helper object is used for both specifying how many audio/video frames
1055// are expected to be received for a caller/callee. It provides helper functions
1056// to specify these expectations. The object initially starts in a state of no
1057// expectations.
1058class MediaExpectations {
1059 public:
1060 enum ExpectFrames {
1061 kExpectSomeFrames,
1062 kExpectNoFrames,
1063 kNoExpectation,
1064 };
1065
1066 void ExpectBidirectionalAudioAndVideo() {
1067 ExpectBidirectionalAudio();
1068 ExpectBidirectionalVideo();
1069 }
1070
1071 void ExpectBidirectionalAudio() {
1072 CallerExpectsSomeAudio();
1073 CalleeExpectsSomeAudio();
1074 }
1075
1076 void ExpectNoAudio() {
1077 CallerExpectsNoAudio();
1078 CalleeExpectsNoAudio();
1079 }
1080
1081 void ExpectBidirectionalVideo() {
1082 CallerExpectsSomeVideo();
1083 CalleeExpectsSomeVideo();
1084 }
1085
1086 void ExpectNoVideo() {
1087 CallerExpectsNoVideo();
1088 CalleeExpectsNoVideo();
1089 }
1090
1091 void CallerExpectsSomeAudioAndVideo() {
1092 CallerExpectsSomeAudio();
1093 CallerExpectsSomeVideo();
1094 }
1095
1096 void CalleeExpectsSomeAudioAndVideo() {
1097 CalleeExpectsSomeAudio();
1098 CalleeExpectsSomeVideo();
1099 }
1100
1101 // Caller's audio functions.
1102 void CallerExpectsSomeAudio(
1103 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1104 caller_audio_expectation_ = kExpectSomeFrames;
1105 caller_audio_frames_expected_ = expected_audio_frames;
1106 }
1107
1108 void CallerExpectsNoAudio() {
1109 caller_audio_expectation_ = kExpectNoFrames;
1110 caller_audio_frames_expected_ = 0;
1111 }
1112
1113 // Caller's video functions.
1114 void CallerExpectsSomeVideo(
1115 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1116 caller_video_expectation_ = kExpectSomeFrames;
1117 caller_video_frames_expected_ = expected_video_frames;
1118 }
1119
1120 void CallerExpectsNoVideo() {
1121 caller_video_expectation_ = kExpectNoFrames;
1122 caller_video_frames_expected_ = 0;
1123 }
1124
1125 // Callee's audio functions.
1126 void CalleeExpectsSomeAudio(
1127 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1128 callee_audio_expectation_ = kExpectSomeFrames;
1129 callee_audio_frames_expected_ = expected_audio_frames;
1130 }
1131
1132 void CalleeExpectsNoAudio() {
1133 callee_audio_expectation_ = kExpectNoFrames;
1134 callee_audio_frames_expected_ = 0;
1135 }
1136
1137 // Callee's video functions.
1138 void CalleeExpectsSomeVideo(
1139 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1140 callee_video_expectation_ = kExpectSomeFrames;
1141 callee_video_frames_expected_ = expected_video_frames;
1142 }
1143
1144 void CalleeExpectsNoVideo() {
1145 callee_video_expectation_ = kExpectNoFrames;
1146 callee_video_frames_expected_ = 0;
1147 }
1148
1149 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1150 ExpectFrames caller_video_expectation_ = kNoExpectation;
1151 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1152 ExpectFrames callee_video_expectation_ = kNoExpectation;
1153 int caller_audio_frames_expected_ = 0;
1154 int caller_video_frames_expected_ = 0;
1155 int callee_audio_frames_expected_ = 0;
1156 int callee_video_frames_expected_ = 0;
1157};
1158
deadbeef1dcb1642017-03-29 21:08:16 -07001159// Tests two PeerConnections connecting to each other end-to-end, using a
1160// virtual network, fake A/V capture and fake encoder/decoders. The
1161// PeerConnections share the threads/socket servers, but use separate versions
1162// of everything else (including "PeerConnectionFactory"s).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001163class PeerConnectionIntegrationBaseTest : public testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001164 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001165 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1166 : sdp_semantics_(sdp_semantics),
1167 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001168 fss_(new rtc::FirewallSocketServer(ss_.get())),
1169 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001170 worker_thread_(rtc::Thread::Create()),
1171 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001172 network_thread_->SetName("PCNetworkThread", this);
1173 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001174 RTC_CHECK(network_thread_->Start());
1175 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001176 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001177 }
1178
Seth Hampson2f0d7022018-02-20 11:54:42 -08001179 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001180 // The PeerConnections should deleted before the TurnCustomizers.
1181 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1182 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1183 // that the TurnCustomizer outlives the life of the PeerConnection or else
1184 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001185 if (caller_) {
1186 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001187 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001188 }
1189 if (callee_) {
1190 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001191 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001192 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001193
1194 // If turn servers were created for the test they need to be destroyed on
1195 // the network thread.
1196 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1197 turn_servers_.clear();
1198 turn_customizers_.clear();
1199 });
deadbeef1dcb1642017-03-29 21:08:16 -07001200 }
1201
1202 bool SignalingStateStable() {
1203 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1204 }
1205
deadbeef71452802017-05-07 17:21:01 -07001206 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001207 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1208 // are connected. This is an important distinction. Once we have separate
1209 // ICE and DTLS state, this check needs to use the DTLS state.
1210 return (callee()->ice_connection_state() ==
1211 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1212 callee()->ice_connection_state() ==
1213 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1214 (caller()->ice_connection_state() ==
1215 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1216 caller()->ice_connection_state() ==
1217 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001218 }
1219
Qingsi Wang7685e862018-06-11 20:15:46 -07001220 // When |event_log_factory| is null, the default implementation of the event
1221 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001222 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1223 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001224 const PeerConnectionFactory::Options* options,
1225 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001226 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001227 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1228 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001229 RTCConfiguration modified_config;
1230 if (config) {
1231 modified_config = *config;
1232 }
Steve Anton3acffc32018-04-12 17:21:03 -07001233 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001234 if (!dependencies.cert_generator) {
1235 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001236 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001237 }
1238 std::unique_ptr<PeerConnectionWrapper> client(
1239 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001240
Niels Möllerf06f9232018-08-07 12:32:18 +02001241 if (!client->Init(options, &modified_config, std::move(dependencies),
1242 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001243 std::move(event_log_factory),
1244 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001245 return nullptr;
1246 }
1247 return client;
1248 }
1249
Qingsi Wang7685e862018-06-11 20:15:46 -07001250 std::unique_ptr<PeerConnectionWrapper>
1251 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1252 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001253 const PeerConnectionFactory::Options* options,
1254 const RTCConfiguration* config,
1255 webrtc::PeerConnectionDependencies dependencies) {
1256 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1257 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001258 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001259 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001260 std::move(event_log_factory),
1261 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001262 }
1263
deadbeef1dcb1642017-03-29 21:08:16 -07001264 bool CreatePeerConnectionWrappers() {
1265 return CreatePeerConnectionWrappersWithConfig(
1266 PeerConnectionInterface::RTCConfiguration(),
1267 PeerConnectionInterface::RTCConfiguration());
1268 }
1269
Steve Anton3acffc32018-04-12 17:21:03 -07001270 bool CreatePeerConnectionWrappersWithSdpSemantics(
1271 SdpSemantics caller_semantics,
1272 SdpSemantics callee_semantics) {
1273 // Can't specify the sdp_semantics in the passed-in configuration since it
1274 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1275 // stored in sdp_semantics_. So get around this by modifying the instance
1276 // variable before calling CreatePeerConnectionWrapper for the caller and
1277 // callee PeerConnections.
1278 SdpSemantics original_semantics = sdp_semantics_;
1279 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001280 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001281 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001282 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001283 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001284 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001285 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001286 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001287 sdp_semantics_ = original_semantics;
1288 return caller_ && callee_;
1289 }
1290
deadbeef1dcb1642017-03-29 21:08:16 -07001291 bool CreatePeerConnectionWrappersWithConfig(
1292 const PeerConnectionInterface::RTCConfiguration& caller_config,
1293 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001294 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001295 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001296 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1297 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001298 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001299 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001300 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1301 /*media_transport_factory=*/nullptr);
1302 return caller_ && callee_;
1303 }
1304
1305 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1306 const PeerConnectionInterface::RTCConfiguration& caller_config,
1307 const PeerConnectionInterface::RTCConfiguration& callee_config,
1308 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1309 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1310 caller_ =
1311 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1312 webrtc::PeerConnectionDependencies(nullptr),
1313 nullptr, std::move(caller_factory));
1314 callee_ =
1315 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1316 webrtc::PeerConnectionDependencies(nullptr),
1317 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001318 return caller_ && callee_;
1319 }
1320
1321 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1322 const PeerConnectionInterface::RTCConfiguration& caller_config,
1323 webrtc::PeerConnectionDependencies caller_dependencies,
1324 const PeerConnectionInterface::RTCConfiguration& callee_config,
1325 webrtc::PeerConnectionDependencies callee_dependencies) {
1326 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001327 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001328 std::move(caller_dependencies), nullptr,
1329 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001330 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001331 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001332 std::move(callee_dependencies), nullptr,
1333 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001334 return caller_ && callee_;
1335 }
1336
1337 bool CreatePeerConnectionWrappersWithOptions(
1338 const PeerConnectionFactory::Options& caller_options,
1339 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001340 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001341 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001342 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1343 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001344 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001345 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001346 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1347 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001348 return caller_ && callee_;
1349 }
1350
1351 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1352 PeerConnectionInterface::RTCConfiguration default_config;
1353 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001354 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001355 webrtc::PeerConnectionDependencies(nullptr));
1356 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001357 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001358 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001359 return caller_ && callee_;
1360 }
1361
Seth Hampson2f0d7022018-02-20 11:54:42 -08001362 std::unique_ptr<PeerConnectionWrapper>
1363 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001364 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1365 new FakeRTCCertificateGenerator());
1366 cert_generator->use_alternate_key();
1367
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001368 webrtc::PeerConnectionDependencies dependencies(nullptr);
1369 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001370 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001371 std::move(dependencies), nullptr,
1372 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001373 }
1374
Seth Hampsonaed71642018-06-11 07:41:32 -07001375 cricket::TestTurnServer* CreateTurnServer(
1376 rtc::SocketAddress internal_address,
1377 rtc::SocketAddress external_address,
1378 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1379 const std::string& common_name = "test turn server") {
1380 rtc::Thread* thread = network_thread();
1381 std::unique_ptr<cricket::TestTurnServer> turn_server =
1382 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1383 RTC_FROM_HERE,
1384 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001385 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001386 thread, internal_address, external_address, type,
1387 /*ignore_bad_certs=*/true, common_name);
1388 });
1389 turn_servers_.push_back(std::move(turn_server));
1390 // Interactions with the turn server should be done on the network thread.
1391 return turn_servers_.back().get();
1392 }
1393
1394 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1395 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1396 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1397 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001398 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001399 turn_customizers_.push_back(std::move(turn_customizer));
1400 // Interactions with the turn customizer should be done on the network
1401 // thread.
1402 return turn_customizers_.back().get();
1403 }
1404
1405 // Checks that the function counters for a TestTurnCustomizer are greater than
1406 // 0.
1407 void ExpectTurnCustomizerCountersIncremented(
1408 cricket::TestTurnCustomizer* turn_customizer) {
1409 unsigned int allow_channel_data_counter =
1410 network_thread()->Invoke<unsigned int>(
1411 RTC_FROM_HERE, [turn_customizer] {
1412 return turn_customizer->allow_channel_data_cnt_;
1413 });
1414 EXPECT_GT(allow_channel_data_counter, 0u);
1415 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1416 RTC_FROM_HERE,
1417 [turn_customizer] { return turn_customizer->modify_cnt_; });
1418 EXPECT_GT(modify_counter, 0u);
1419 }
1420
deadbeef1dcb1642017-03-29 21:08:16 -07001421 // Once called, SDP blobs and ICE candidates will be automatically signaled
1422 // between PeerConnections.
1423 void ConnectFakeSignaling() {
1424 caller_->set_signaling_message_receiver(callee_.get());
1425 callee_->set_signaling_message_receiver(caller_.get());
1426 }
1427
Steve Antonede9ca52017-10-16 13:04:27 -07001428 // Once called, SDP blobs will be automatically signaled between
1429 // PeerConnections. Note that ICE candidates will not be signaled unless they
1430 // are in the exchanged SDP blobs.
1431 void ConnectFakeSignalingForSdpOnly() {
1432 ConnectFakeSignaling();
1433 SetSignalIceCandidates(false);
1434 }
1435
deadbeef1dcb1642017-03-29 21:08:16 -07001436 void SetSignalingDelayMs(int delay_ms) {
1437 caller_->set_signaling_delay_ms(delay_ms);
1438 callee_->set_signaling_delay_ms(delay_ms);
1439 }
1440
Steve Antonede9ca52017-10-16 13:04:27 -07001441 void SetSignalIceCandidates(bool signal) {
1442 caller_->set_signal_ice_candidates(signal);
1443 callee_->set_signal_ice_candidates(signal);
1444 }
1445
deadbeef1dcb1642017-03-29 21:08:16 -07001446 // Messages may get lost on the unreliable DataChannel, so we send multiple
1447 // times to avoid test flakiness.
1448 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1449 const std::string& data,
1450 int retries) {
1451 for (int i = 0; i < retries; ++i) {
1452 dc->Send(DataBuffer(data));
1453 }
1454 }
1455
1456 rtc::Thread* network_thread() { return network_thread_.get(); }
1457
1458 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1459
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001460 webrtc::MediaTransportPair* loopback_media_transports() {
1461 return &loopback_media_transports_;
1462 }
1463
deadbeef1dcb1642017-03-29 21:08:16 -07001464 PeerConnectionWrapper* caller() { return caller_.get(); }
1465
1466 // Set the |caller_| to the |wrapper| passed in and return the
1467 // original |caller_|.
1468 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1469 PeerConnectionWrapper* wrapper) {
1470 PeerConnectionWrapper* old = caller_.release();
1471 caller_.reset(wrapper);
1472 return old;
1473 }
1474
1475 PeerConnectionWrapper* callee() { return callee_.get(); }
1476
1477 // Set the |callee_| to the |wrapper| passed in and return the
1478 // original |callee_|.
1479 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1480 PeerConnectionWrapper* wrapper) {
1481 PeerConnectionWrapper* old = callee_.release();
1482 callee_.reset(wrapper);
1483 return old;
1484 }
1485
Steve Antonede9ca52017-10-16 13:04:27 -07001486 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1487
Seth Hampson2f0d7022018-02-20 11:54:42 -08001488 // Expects the provided number of new frames to be received within
1489 // kMaxWaitForFramesMs. The new expected frames are specified in
1490 // |media_expectations|. Returns false if any of the expectations were
1491 // not met.
1492 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1493 // First initialize the expected frame counts based upon the current
1494 // frame count.
1495 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1496 if (media_expectations.caller_audio_expectation_ ==
1497 MediaExpectations::kExpectSomeFrames) {
1498 total_caller_audio_frames_expected +=
1499 media_expectations.caller_audio_frames_expected_;
1500 }
1501 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001502 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001503 if (media_expectations.caller_video_expectation_ ==
1504 MediaExpectations::kExpectSomeFrames) {
1505 total_caller_video_frames_expected +=
1506 media_expectations.caller_video_frames_expected_;
1507 }
1508 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1509 if (media_expectations.callee_audio_expectation_ ==
1510 MediaExpectations::kExpectSomeFrames) {
1511 total_callee_audio_frames_expected +=
1512 media_expectations.callee_audio_frames_expected_;
1513 }
1514 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001515 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001516 if (media_expectations.callee_video_expectation_ ==
1517 MediaExpectations::kExpectSomeFrames) {
1518 total_callee_video_frames_expected +=
1519 media_expectations.callee_video_frames_expected_;
1520 }
deadbeef1dcb1642017-03-29 21:08:16 -07001521
Seth Hampson2f0d7022018-02-20 11:54:42 -08001522 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001523 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001524 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001525 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001526 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001527 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001528 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001529 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001530 total_callee_video_frames_expected,
1531 kMaxWaitForFramesMs);
1532 bool expectations_correct =
1533 caller()->audio_frames_received() >=
1534 total_caller_audio_frames_expected &&
1535 caller()->min_video_frames_received_per_track() >=
1536 total_caller_video_frames_expected &&
1537 callee()->audio_frames_received() >=
1538 total_callee_audio_frames_expected &&
1539 callee()->min_video_frames_received_per_track() >=
1540 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001541
Seth Hampson2f0d7022018-02-20 11:54:42 -08001542 // After the combined wait, print out a more detailed message upon
1543 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001544 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001545 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001546 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001547 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001548 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001549 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001550 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001551 total_callee_video_frames_expected);
1552
1553 // We want to make sure nothing unexpected was received.
1554 if (media_expectations.caller_audio_expectation_ ==
1555 MediaExpectations::kExpectNoFrames) {
1556 EXPECT_EQ(caller()->audio_frames_received(),
1557 total_caller_audio_frames_expected);
1558 if (caller()->audio_frames_received() !=
1559 total_caller_audio_frames_expected) {
1560 expectations_correct = false;
1561 }
1562 }
1563 if (media_expectations.caller_video_expectation_ ==
1564 MediaExpectations::kExpectNoFrames) {
1565 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1566 total_caller_video_frames_expected);
1567 if (caller()->min_video_frames_received_per_track() !=
1568 total_caller_video_frames_expected) {
1569 expectations_correct = false;
1570 }
1571 }
1572 if (media_expectations.callee_audio_expectation_ ==
1573 MediaExpectations::kExpectNoFrames) {
1574 EXPECT_EQ(callee()->audio_frames_received(),
1575 total_callee_audio_frames_expected);
1576 if (callee()->audio_frames_received() !=
1577 total_callee_audio_frames_expected) {
1578 expectations_correct = false;
1579 }
1580 }
1581 if (media_expectations.callee_video_expectation_ ==
1582 MediaExpectations::kExpectNoFrames) {
1583 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1584 total_callee_video_frames_expected);
1585 if (callee()->min_video_frames_received_per_track() !=
1586 total_callee_video_frames_expected) {
1587 expectations_correct = false;
1588 }
1589 }
1590 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001591 }
1592
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001593 void TestNegotiatedCipherSuite(
1594 const PeerConnectionFactory::Options& caller_options,
1595 const PeerConnectionFactory::Options& callee_options,
1596 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001597 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1598 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001599 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001600 caller()->AddAudioVideoTracks();
1601 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001602 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001603 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001604 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001605 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001606 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001607 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001608 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1609 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001610 }
1611
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001612 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1613 bool remote_gcm_enabled,
1614 int expected_cipher_suite) {
1615 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001616 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1617 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001618 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001619 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1620 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001621 TestNegotiatedCipherSuite(caller_options, callee_options,
1622 expected_cipher_suite);
1623 }
1624
Seth Hampson2f0d7022018-02-20 11:54:42 -08001625 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001626 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001627
deadbeef1dcb1642017-03-29 21:08:16 -07001628 private:
1629 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001630 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001631 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001632 // |network_thread_| and |worker_thread_| are used by both
1633 // |caller_| and |callee_| so they must be destroyed
1634 // later.
1635 std::unique_ptr<rtc::Thread> network_thread_;
1636 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001637 // The turn servers and turn customizers should be accessed & deleted on the
1638 // network thread to avoid a race with the socket read/write that occurs
1639 // on the network thread.
1640 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1641 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001642 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001643 std::unique_ptr<PeerConnectionWrapper> caller_;
1644 std::unique_ptr<PeerConnectionWrapper> callee_;
1645};
1646
Seth Hampson2f0d7022018-02-20 11:54:42 -08001647class PeerConnectionIntegrationTest
1648 : public PeerConnectionIntegrationBaseTest,
1649 public ::testing::WithParamInterface<SdpSemantics> {
1650 protected:
1651 PeerConnectionIntegrationTest()
1652 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1653};
1654
1655class PeerConnectionIntegrationTestPlanB
1656 : public PeerConnectionIntegrationBaseTest {
1657 protected:
1658 PeerConnectionIntegrationTestPlanB()
1659 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1660};
1661
1662class PeerConnectionIntegrationTestUnifiedPlan
1663 : public PeerConnectionIntegrationBaseTest {
1664 protected:
1665 PeerConnectionIntegrationTestUnifiedPlan()
1666 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1667};
1668
deadbeef1dcb1642017-03-29 21:08:16 -07001669// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1670// includes testing that the callback is invoked if an observer is connected
1671// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001672TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001673 RtpReceiverObserverOnFirstPacketReceived) {
1674 ASSERT_TRUE(CreatePeerConnectionWrappers());
1675 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001676 caller()->AddAudioVideoTracks();
1677 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001678 // Start offer/answer exchange and wait for it to complete.
1679 caller()->CreateAndSetAndSignalOffer();
1680 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1681 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001682 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1683 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001684 // Wait for all "first packet received" callbacks to be fired.
1685 EXPECT_TRUE_WAIT(
1686 std::all_of(caller()->rtp_receiver_observers().begin(),
1687 caller()->rtp_receiver_observers().end(),
1688 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1689 return o->first_packet_received();
1690 }),
1691 kMaxWaitForFramesMs);
1692 EXPECT_TRUE_WAIT(
1693 std::all_of(callee()->rtp_receiver_observers().begin(),
1694 callee()->rtp_receiver_observers().end(),
1695 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1696 return o->first_packet_received();
1697 }),
1698 kMaxWaitForFramesMs);
1699 // If new observers are set after the first packet was already received, the
1700 // callback should still be invoked.
1701 caller()->ResetRtpReceiverObservers();
1702 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001703 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1704 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001705 EXPECT_TRUE(
1706 std::all_of(caller()->rtp_receiver_observers().begin(),
1707 caller()->rtp_receiver_observers().end(),
1708 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1709 return o->first_packet_received();
1710 }));
1711 EXPECT_TRUE(
1712 std::all_of(callee()->rtp_receiver_observers().begin(),
1713 callee()->rtp_receiver_observers().end(),
1714 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1715 return o->first_packet_received();
1716 }));
1717}
1718
1719class DummyDtmfObserver : public DtmfSenderObserverInterface {
1720 public:
1721 DummyDtmfObserver() : completed_(false) {}
1722
1723 // Implements DtmfSenderObserverInterface.
1724 void OnToneChange(const std::string& tone) override {
1725 tones_.push_back(tone);
1726 if (tone.empty()) {
1727 completed_ = true;
1728 }
1729 }
1730
1731 const std::vector<std::string>& tones() const { return tones_; }
1732 bool completed() const { return completed_; }
1733
1734 private:
1735 bool completed_;
1736 std::vector<std::string> tones_;
1737};
1738
1739// Assumes |sender| already has an audio track added and the offer/answer
1740// exchange is done.
1741void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1742 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001743 // We should be able to get a DTMF sender from the local sender.
1744 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1745 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1746 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001747 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001748 dtmf_sender->RegisterObserver(&observer);
1749
1750 // Test the DtmfSender object just created.
1751 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1752 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1753
1754 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1755 std::vector<std::string> tones = {"1", "a", ""};
1756 EXPECT_EQ(tones, observer.tones());
1757 dtmf_sender->UnregisterObserver();
1758 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1759}
1760
1761// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1762// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001763TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001764 ASSERT_TRUE(CreatePeerConnectionWrappers());
1765 ConnectFakeSignaling();
1766 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001767 caller()->AddAudioTrack();
1768 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001769 caller()->CreateAndSetAndSignalOffer();
1770 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001771 // DTLS must finish before the DTMF sender can be used reliably.
1772 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001773 TestDtmfFromSenderToReceiver(caller(), callee());
1774 TestDtmfFromSenderToReceiver(callee(), caller());
1775}
1776
1777// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1778// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001779TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001780 ASSERT_TRUE(CreatePeerConnectionWrappers());
1781 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001782
deadbeef1dcb1642017-03-29 21:08:16 -07001783 // Do normal offer/answer and wait for some frames to be received in each
1784 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001785 caller()->AddAudioVideoTracks();
1786 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001787 caller()->CreateAndSetAndSignalOffer();
1788 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001789 MediaExpectations media_expectations;
1790 media_expectations.ExpectBidirectionalAudioAndVideo();
1791 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001792 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1793 webrtc::kEnumCounterKeyProtocolDtls));
1794 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1795 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001796}
1797
1798// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001799TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001800 PeerConnectionInterface::RTCConfiguration sdes_config;
1801 sdes_config.enable_dtls_srtp.emplace(false);
1802 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1803 ConnectFakeSignaling();
1804
1805 // Do normal offer/answer and wait for some frames to be received in each
1806 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001807 caller()->AddAudioVideoTracks();
1808 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001809 caller()->CreateAndSetAndSignalOffer();
1810 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001811 MediaExpectations media_expectations;
1812 media_expectations.ExpectBidirectionalAudioAndVideo();
1813 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001814 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1815 webrtc::kEnumCounterKeyProtocolSdes));
1816 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1817 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001818}
1819
Steve Anton8c0f7a72017-10-03 10:03:10 -07001820// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1821// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001822TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001823 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1824 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1825 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1826 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1827 return pc->GetRemoteAudioSSLCertificate();
1828 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001829 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1830 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1831 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1832 return pc->GetRemoteAudioSSLCertChain();
1833 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001834
1835 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1836 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1837
1838 // Configure each side with a known certificate so they can be compared later.
1839 PeerConnectionInterface::RTCConfiguration caller_config;
1840 caller_config.enable_dtls_srtp.emplace(true);
1841 caller_config.certificates.push_back(caller_cert);
1842 PeerConnectionInterface::RTCConfiguration callee_config;
1843 callee_config.enable_dtls_srtp.emplace(true);
1844 callee_config.certificates.push_back(callee_cert);
1845 ASSERT_TRUE(
1846 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1847 ConnectFakeSignaling();
1848
1849 // When first initialized, there should not be a remote SSL certificate (and
1850 // calling this method should not crash).
1851 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1852 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001853 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1854 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001855
Steve Anton15324772018-01-16 10:26:49 -08001856 caller()->AddAudioTrack();
1857 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001858 caller()->CreateAndSetAndSignalOffer();
1859 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1860 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1861
1862 // Once DTLS has been connected, each side should return the other's SSL
1863 // certificate when calling GetRemoteAudioSSLCertificate.
1864
1865 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1866 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001867 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001868 caller_remote_cert->ToPEMString());
1869
1870 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1871 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001872 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001873 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001874
1875 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1876 ASSERT_TRUE(caller_remote_cert_chain);
1877 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1878 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001879 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001880 remote_cert->ToPEMString());
1881
1882 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1883 ASSERT_TRUE(callee_remote_cert_chain);
1884 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1885 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001886 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001887 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001888}
1889
deadbeef1dcb1642017-03-29 21:08:16 -07001890// This test sets up a call between two parties with a source resolution of
1891// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001892TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001893 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1894 ASSERT_TRUE(CreatePeerConnectionWrappers());
1895 ConnectFakeSignaling();
1896
Niels Möller5c7efe72018-05-11 10:34:46 +02001897 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1898 webrtc::FakePeriodicVideoSource::Config config;
1899 config.width = 1280;
1900 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001901 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001902 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1903 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001904
1905 // Do normal offer/answer and wait for at least one frame to be received in
1906 // each direction.
1907 caller()->CreateAndSetAndSignalOffer();
1908 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1909 callee()->min_video_frames_received_per_track() > 0,
1910 kMaxWaitForFramesMs);
1911
1912 // Check rendered aspect ratio.
1913 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1914 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1915 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1916 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1917}
1918
1919// This test sets up an one-way call, with media only from caller to
1920// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001921TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001922 ASSERT_TRUE(CreatePeerConnectionWrappers());
1923 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001924 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001925 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001926 MediaExpectations media_expectations;
1927 media_expectations.CalleeExpectsSomeAudioAndVideo();
1928 media_expectations.CallerExpectsNoAudio();
1929 media_expectations.CallerExpectsNoVideo();
1930 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001931}
1932
1933// This test sets up a audio call initially, with the callee rejecting video
1934// initially. Then later the callee decides to upgrade to audio/video, and
1935// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001936TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001937 ASSERT_TRUE(CreatePeerConnectionWrappers());
1938 ConnectFakeSignaling();
1939 // Initially, offer an audio/video stream from the caller, but refuse to
1940 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001941 caller()->AddAudioVideoTracks();
1942 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001943 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1944 PeerConnectionInterface::RTCOfferAnswerOptions options;
1945 options.offer_to_receive_video = 0;
1946 callee()->SetOfferAnswerOptions(options);
1947 } else {
1948 callee()->SetRemoteOfferHandler([this] {
1949 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1950 });
1951 }
deadbeef1dcb1642017-03-29 21:08:16 -07001952 // Do offer/answer and make sure audio is still received end-to-end.
1953 caller()->CreateAndSetAndSignalOffer();
1954 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001955 {
1956 MediaExpectations media_expectations;
1957 media_expectations.ExpectBidirectionalAudio();
1958 media_expectations.ExpectNoVideo();
1959 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1960 }
deadbeef1dcb1642017-03-29 21:08:16 -07001961 // Sanity check that the callee's description has a rejected video section.
1962 ASSERT_NE(nullptr, callee()->pc()->local_description());
1963 const ContentInfo* callee_video_content =
1964 GetFirstVideoContent(callee()->pc()->local_description()->description());
1965 ASSERT_NE(nullptr, callee_video_content);
1966 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001967
deadbeef1dcb1642017-03-29 21:08:16 -07001968 // Now negotiate with video and ensure negotiation succeeds, with video
1969 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001970 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001971 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1972 PeerConnectionInterface::RTCOfferAnswerOptions options;
1973 options.offer_to_receive_video = 1;
1974 callee()->SetOfferAnswerOptions(options);
1975 } else {
1976 callee()->SetRemoteOfferHandler(nullptr);
1977 caller()->SetRemoteOfferHandler([this] {
1978 // The caller creates a new transceiver to receive video on when receiving
1979 // the offer, but by default it is send only.
1980 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001981 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001982 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1983 transceivers[2]->receiver()->media_type());
1984 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1985 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1986 });
1987 }
deadbeef1dcb1642017-03-29 21:08:16 -07001988 callee()->CreateAndSetAndSignalOffer();
1989 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001990 {
1991 // Expect additional audio frames to be received after the upgrade.
1992 MediaExpectations media_expectations;
1993 media_expectations.ExpectBidirectionalAudioAndVideo();
1994 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1995 }
deadbeef1dcb1642017-03-29 21:08:16 -07001996}
1997
deadbeef4389b4d2017-09-07 09:07:36 -07001998// Simpler than the above test; just add an audio track to an established
1999// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002000TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002001 ASSERT_TRUE(CreatePeerConnectionWrappers());
2002 ConnectFakeSignaling();
2003 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002004 caller()->AddVideoTrack();
2005 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002006 caller()->CreateAndSetAndSignalOffer();
2007 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2008 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002009 caller()->AddAudioTrack();
2010 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002011 caller()->CreateAndSetAndSignalOffer();
2012 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2013 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002014 MediaExpectations media_expectations;
2015 media_expectations.ExpectBidirectionalAudioAndVideo();
2016 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002017}
2018
deadbeef1dcb1642017-03-29 21:08:16 -07002019// This test sets up a call that's transferred to a new caller with a different
2020// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002021TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002022 ASSERT_TRUE(CreatePeerConnectionWrappers());
2023 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002024 caller()->AddAudioVideoTracks();
2025 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002026 caller()->CreateAndSetAndSignalOffer();
2027 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2028
2029 // Keep the original peer around which will still send packets to the
2030 // receiving client. These SRTP packets will be dropped.
2031 std::unique_ptr<PeerConnectionWrapper> original_peer(
2032 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002033 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002034 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2035 // directly above.
2036 original_peer->pc()->Close();
2037
2038 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002039 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002040 caller()->CreateAndSetAndSignalOffer();
2041 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2042 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002043 MediaExpectations media_expectations;
2044 media_expectations.ExpectBidirectionalAudioAndVideo();
2045 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002046}
2047
2048// This test sets up a call that's transferred to a new callee with a different
2049// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002050TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002051 ASSERT_TRUE(CreatePeerConnectionWrappers());
2052 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002053 caller()->AddAudioVideoTracks();
2054 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002055 caller()->CreateAndSetAndSignalOffer();
2056 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2057
2058 // Keep the original peer around which will still send packets to the
2059 // receiving client. These SRTP packets will be dropped.
2060 std::unique_ptr<PeerConnectionWrapper> original_peer(
2061 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002062 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002063 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2064 // directly above.
2065 original_peer->pc()->Close();
2066
2067 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002068 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002069 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2070 caller()->CreateAndSetAndSignalOffer();
2071 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2072 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002073 MediaExpectations media_expectations;
2074 media_expectations.ExpectBidirectionalAudioAndVideo();
2075 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002076}
2077
2078// This test sets up a non-bundled call and negotiates bundling at the same
2079// time as starting an ICE restart. When bundling is in effect in the restart,
2080// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002081TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002082 ASSERT_TRUE(CreatePeerConnectionWrappers());
2083 ConnectFakeSignaling();
2084
Steve Anton15324772018-01-16 10:26:49 -08002085 caller()->AddAudioVideoTracks();
2086 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002087 // Remove the bundle group from the SDP received by the callee.
2088 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2089 desc->RemoveGroupByName("BUNDLE");
2090 });
2091 caller()->CreateAndSetAndSignalOffer();
2092 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002093 {
2094 MediaExpectations media_expectations;
2095 media_expectations.ExpectBidirectionalAudioAndVideo();
2096 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2097 }
deadbeef1dcb1642017-03-29 21:08:16 -07002098 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2099 callee()->SetReceivedSdpMunger(nullptr);
2100 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2101 caller()->CreateAndSetAndSignalOffer();
2102 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2103
2104 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002105 {
2106 MediaExpectations media_expectations;
2107 media_expectations.ExpectBidirectionalAudioAndVideo();
2108 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2109 }
deadbeef1dcb1642017-03-29 21:08:16 -07002110}
2111
2112// Test CVO (Coordination of Video Orientation). If a video source is rotated
2113// and both peers support the CVO RTP header extension, the actual video frames
2114// don't need to be encoded in different resolutions, since the rotation is
2115// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002116TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002117 ASSERT_TRUE(CreatePeerConnectionWrappers());
2118 ConnectFakeSignaling();
2119 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002120 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002121 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002122 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002123 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2124
2125 // Wait for video frames to be received by both sides.
2126 caller()->CreateAndSetAndSignalOffer();
2127 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2128 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2129 callee()->min_video_frames_received_per_track() > 0,
2130 kMaxWaitForFramesMs);
2131
2132 // Ensure that the aspect ratio is unmodified.
2133 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2134 // not just assumed.
2135 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2136 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2137 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2138 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2139 // Ensure that the CVO bits were surfaced to the renderer.
2140 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2141 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2142}
2143
2144// Test that when the CVO extension isn't supported, video is rotated the
2145// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002146TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002147 ASSERT_TRUE(CreatePeerConnectionWrappers());
2148 ConnectFakeSignaling();
2149 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002150 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002151 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002152 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002153 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2154
2155 // Remove the CVO extension from the offered SDP.
2156 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2157 cricket::VideoContentDescription* video =
2158 GetFirstVideoContentDescription(desc);
2159 video->ClearRtpHeaderExtensions();
2160 });
2161 // Wait for video frames to be received by both sides.
2162 caller()->CreateAndSetAndSignalOffer();
2163 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2164 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2165 callee()->min_video_frames_received_per_track() > 0,
2166 kMaxWaitForFramesMs);
2167
2168 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2169 // rotation.
2170 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2171 // not just assumed.
2172 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2173 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2174 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2175 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2176 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2177 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2178 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2179}
2180
deadbeef1dcb1642017-03-29 21:08:16 -07002181// Test that if the answerer rejects the audio m= section, no audio is sent or
2182// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002183TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002184 ASSERT_TRUE(CreatePeerConnectionWrappers());
2185 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002186 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002187 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2188 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2189 // it will reject the audio m= section completely.
2190 PeerConnectionInterface::RTCOfferAnswerOptions options;
2191 options.offer_to_receive_audio = 0;
2192 callee()->SetOfferAnswerOptions(options);
2193 } else {
2194 // Stopping the audio RtpTransceiver will cause the media section to be
2195 // rejected in the answer.
2196 callee()->SetRemoteOfferHandler([this] {
2197 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2198 });
2199 }
Steve Anton15324772018-01-16 10:26:49 -08002200 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002201 // Do offer/answer and wait for successful end-to-end video frames.
2202 caller()->CreateAndSetAndSignalOffer();
2203 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002204 MediaExpectations media_expectations;
2205 media_expectations.ExpectBidirectionalVideo();
2206 media_expectations.ExpectNoAudio();
2207 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2208
deadbeef1dcb1642017-03-29 21:08:16 -07002209 // Sanity check that the callee's description has a rejected audio section.
2210 ASSERT_NE(nullptr, callee()->pc()->local_description());
2211 const ContentInfo* callee_audio_content =
2212 GetFirstAudioContent(callee()->pc()->local_description()->description());
2213 ASSERT_NE(nullptr, callee_audio_content);
2214 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002215 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2216 // The caller's transceiver should have stopped after receiving the answer.
2217 EXPECT_TRUE(caller()
2218 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2219 ->stopped());
2220 }
deadbeef1dcb1642017-03-29 21:08:16 -07002221}
2222
2223// Test that if the answerer rejects the video m= section, no video is sent or
2224// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002225TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002226 ASSERT_TRUE(CreatePeerConnectionWrappers());
2227 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002228 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002229 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2230 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2231 // it will reject the video m= section completely.
2232 PeerConnectionInterface::RTCOfferAnswerOptions options;
2233 options.offer_to_receive_video = 0;
2234 callee()->SetOfferAnswerOptions(options);
2235 } else {
2236 // Stopping the video RtpTransceiver will cause the media section to be
2237 // rejected in the answer.
2238 callee()->SetRemoteOfferHandler([this] {
2239 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2240 });
2241 }
Steve Anton15324772018-01-16 10:26:49 -08002242 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002243 // Do offer/answer and wait for successful end-to-end audio frames.
2244 caller()->CreateAndSetAndSignalOffer();
2245 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002246 MediaExpectations media_expectations;
2247 media_expectations.ExpectBidirectionalAudio();
2248 media_expectations.ExpectNoVideo();
2249 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2250
deadbeef1dcb1642017-03-29 21:08:16 -07002251 // Sanity check that the callee's description has a rejected video section.
2252 ASSERT_NE(nullptr, callee()->pc()->local_description());
2253 const ContentInfo* callee_video_content =
2254 GetFirstVideoContent(callee()->pc()->local_description()->description());
2255 ASSERT_NE(nullptr, callee_video_content);
2256 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002257 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2258 // The caller's transceiver should have stopped after receiving the answer.
2259 EXPECT_TRUE(caller()
2260 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2261 ->stopped());
2262 }
deadbeef1dcb1642017-03-29 21:08:16 -07002263}
2264
2265// Test that if the answerer rejects both audio and video m= sections, nothing
2266// bad happens.
2267// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2268// test anything but the fact that negotiation succeeds, which doesn't mean
2269// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002270TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002271 ASSERT_TRUE(CreatePeerConnectionWrappers());
2272 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002273 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002274 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2275 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2276 // will reject both audio and video m= sections.
2277 PeerConnectionInterface::RTCOfferAnswerOptions options;
2278 options.offer_to_receive_audio = 0;
2279 options.offer_to_receive_video = 0;
2280 callee()->SetOfferAnswerOptions(options);
2281 } else {
2282 callee()->SetRemoteOfferHandler([this] {
2283 // Stopping all transceivers will cause all media sections to be rejected.
2284 for (auto transceiver : callee()->pc()->GetTransceivers()) {
2285 transceiver->Stop();
2286 }
2287 });
2288 }
deadbeef1dcb1642017-03-29 21:08:16 -07002289 // Do offer/answer and wait for stable signaling state.
2290 caller()->CreateAndSetAndSignalOffer();
2291 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002292
deadbeef1dcb1642017-03-29 21:08:16 -07002293 // Sanity check that the callee's description has rejected m= sections.
2294 ASSERT_NE(nullptr, callee()->pc()->local_description());
2295 const ContentInfo* callee_audio_content =
2296 GetFirstAudioContent(callee()->pc()->local_description()->description());
2297 ASSERT_NE(nullptr, callee_audio_content);
2298 EXPECT_TRUE(callee_audio_content->rejected);
2299 const ContentInfo* callee_video_content =
2300 GetFirstVideoContent(callee()->pc()->local_description()->description());
2301 ASSERT_NE(nullptr, callee_video_content);
2302 EXPECT_TRUE(callee_video_content->rejected);
2303}
2304
2305// This test sets up an audio and video call between two parties. After the
2306// call runs for a while, the caller sends an updated offer with video being
2307// rejected. Once the re-negotiation is done, the video flow should stop and
2308// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002309TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002310 ASSERT_TRUE(CreatePeerConnectionWrappers());
2311 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002312 caller()->AddAudioVideoTracks();
2313 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002314 caller()->CreateAndSetAndSignalOffer();
2315 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002316 {
2317 MediaExpectations media_expectations;
2318 media_expectations.ExpectBidirectionalAudioAndVideo();
2319 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2320 }
deadbeef1dcb1642017-03-29 21:08:16 -07002321 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002322 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2323 caller()->SetGeneratedSdpMunger(
2324 [](cricket::SessionDescription* description) {
2325 for (cricket::ContentInfo& content : description->contents()) {
2326 if (cricket::IsVideoContent(&content)) {
2327 content.rejected = true;
2328 }
2329 }
2330 });
2331 } else {
2332 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2333 }
deadbeef1dcb1642017-03-29 21:08:16 -07002334 caller()->CreateAndSetAndSignalOffer();
2335 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2336
2337 // Sanity check that the caller's description has a rejected video section.
2338 ASSERT_NE(nullptr, caller()->pc()->local_description());
2339 const ContentInfo* caller_video_content =
2340 GetFirstVideoContent(caller()->pc()->local_description()->description());
2341 ASSERT_NE(nullptr, caller_video_content);
2342 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002343 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002344 {
2345 MediaExpectations media_expectations;
2346 media_expectations.ExpectBidirectionalAudio();
2347 media_expectations.ExpectNoVideo();
2348 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2349 }
deadbeef1dcb1642017-03-29 21:08:16 -07002350}
2351
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002352// Do one offer/answer with audio, another that disables it (rejecting the m=
2353// section), and another that re-enables it. Regression test for:
2354// bugs.webrtc.org/6023
2355TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2356 ASSERT_TRUE(CreatePeerConnectionWrappers());
2357 ConnectFakeSignaling();
2358
2359 // Add audio track, do normal offer/answer.
2360 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2361 caller()->CreateLocalAudioTrack();
2362 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2363 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2364 caller()->CreateAndSetAndSignalOffer();
2365 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2366
2367 // Remove audio track, and set offer_to_receive_audio to false to cause the
2368 // m= section to be completely disabled, not just "recvonly".
2369 caller()->pc()->RemoveTrack(sender);
2370 PeerConnectionInterface::RTCOfferAnswerOptions options;
2371 options.offer_to_receive_audio = 0;
2372 caller()->SetOfferAnswerOptions(options);
2373 caller()->CreateAndSetAndSignalOffer();
2374 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2375
2376 // Add the audio track again, expecting negotiation to succeed and frames to
2377 // flow.
2378 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2379 options.offer_to_receive_audio = 1;
2380 caller()->SetOfferAnswerOptions(options);
2381 caller()->CreateAndSetAndSignalOffer();
2382 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2383
2384 MediaExpectations media_expectations;
2385 media_expectations.CalleeExpectsSomeAudio();
2386 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2387}
2388
deadbeef1dcb1642017-03-29 21:08:16 -07002389// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2390// is needed to support legacy endpoints.
2391// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2392// add a test for an end-to-end test without MID signaling either (basically,
2393// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002394TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002395 ASSERT_TRUE(CreatePeerConnectionWrappers());
2396 ConnectFakeSignaling();
2397 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002398 caller()->AddAudioVideoTracks();
2399 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002400 // Remove SSRCs and MSIDs from the received offer SDP.
2401 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002402 caller()->CreateAndSetAndSignalOffer();
2403 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002404 MediaExpectations media_expectations;
2405 media_expectations.ExpectBidirectionalAudioAndVideo();
2406 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002407}
2408
Seth Hampson5897a6e2018-04-03 11:16:33 -07002409// Basic end-to-end test, without SSRC signaling. This means that the track
2410// was created properly and frames are delivered when the MSIDs are communicated
2411// with a=msid lines and no a=ssrc lines.
2412TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2413 EndToEndCallWithoutSsrcSignaling) {
2414 const char kStreamId[] = "streamId";
2415 ASSERT_TRUE(CreatePeerConnectionWrappers());
2416 ConnectFakeSignaling();
2417 // Add just audio tracks.
2418 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2419 callee()->AddAudioTrack();
2420
2421 // Remove SSRCs from the received offer SDP.
2422 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2423 caller()->CreateAndSetAndSignalOffer();
2424 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2425 MediaExpectations media_expectations;
2426 media_expectations.ExpectBidirectionalAudio();
2427 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2428}
2429
Steve Antondf527fd2018-04-27 15:52:03 -07002430// Tests that video flows between multiple video tracks when SSRCs are not
2431// signaled. This exercises the MID RTP header extension which is needed to
2432// demux the incoming video tracks.
2433TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2434 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2435 ASSERT_TRUE(CreatePeerConnectionWrappers());
2436 ConnectFakeSignaling();
2437 caller()->AddVideoTrack();
2438 caller()->AddVideoTrack();
2439 callee()->AddVideoTrack();
2440 callee()->AddVideoTrack();
2441
2442 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2443 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2444 caller()->CreateAndSetAndSignalOffer();
2445 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2446 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2447 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2448
2449 // Expect video to be received in both directions on both tracks.
2450 MediaExpectations media_expectations;
2451 media_expectations.ExpectBidirectionalVideo();
2452 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2453}
2454
Henrik Boström5b147782018-12-04 11:25:05 +01002455TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2456 ASSERT_TRUE(CreatePeerConnectionWrappers());
2457 ConnectFakeSignaling();
2458 caller()->AddAudioTrack();
2459 caller()->AddVideoTrack();
2460 caller()->CreateAndSetAndSignalOffer();
2461 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2462 auto callee_receivers = callee()->pc()->GetReceivers();
2463 ASSERT_EQ(2u, callee_receivers.size());
2464 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2465 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2466}
2467
2468TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2469 ASSERT_TRUE(CreatePeerConnectionWrappers());
2470 ConnectFakeSignaling();
2471 caller()->AddAudioTrack();
2472 caller()->AddVideoTrack();
2473 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2474 caller()->CreateAndSetAndSignalOffer();
2475 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2476 auto callee_receivers = callee()->pc()->GetReceivers();
2477 ASSERT_EQ(2u, callee_receivers.size());
2478 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2479 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2480 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2481 callee_receivers[1]->stream_ids()[0]);
2482 EXPECT_EQ(callee_receivers[0]->streams()[0],
2483 callee_receivers[1]->streams()[0]);
2484}
2485
deadbeef1dcb1642017-03-29 21:08:16 -07002486// Test that if two video tracks are sent (from caller to callee, in this test),
2487// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002488TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002489 ASSERT_TRUE(CreatePeerConnectionWrappers());
2490 ConnectFakeSignaling();
2491 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002492 caller()->AddAudioVideoTracks();
2493 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002494 caller()->CreateAndSetAndSignalOffer();
2495 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002496 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
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
2503static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2504 bool first = true;
2505 for (cricket::ContentInfo& content : desc->contents()) {
2506 if (first) {
2507 first = false;
2508 continue;
2509 }
2510 content.bundle_only = true;
2511 }
2512 first = true;
2513 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2514 if (first) {
2515 first = false;
2516 continue;
2517 }
2518 transport.description.ice_ufrag.clear();
2519 transport.description.ice_pwd.clear();
2520 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2521 transport.description.identity_fingerprint.reset(nullptr);
2522 }
2523}
2524
2525// Test that if applying a true "max bundle" offer, which uses ports of 0,
2526// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2527// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2528// successfully and media flows.
2529// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2530// TODO(deadbeef): Won't need this test once we start generating actual
2531// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002532TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002533 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2534 ASSERT_TRUE(CreatePeerConnectionWrappers());
2535 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002536 caller()->AddAudioVideoTracks();
2537 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002538 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2539 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2540 // but the first m= section.
2541 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2542 caller()->CreateAndSetAndSignalOffer();
2543 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002544 MediaExpectations media_expectations;
2545 media_expectations.ExpectBidirectionalAudioAndVideo();
2546 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002547}
2548
2549// Test that we can receive the audio output level from a remote audio track.
2550// TODO(deadbeef): Use a fake audio source and verify that the output level is
2551// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002552TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002553 ASSERT_TRUE(CreatePeerConnectionWrappers());
2554 ConnectFakeSignaling();
2555 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002556 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002557 caller()->CreateAndSetAndSignalOffer();
2558 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2559
2560 // Get the audio output level stats. Note that the level is not available
2561 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002562 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002563 kMaxWaitForFramesMs);
2564}
2565
2566// Test that an audio input level is reported.
2567// TODO(deadbeef): Use a fake audio source and verify that the input level is
2568// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002569TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002570 ASSERT_TRUE(CreatePeerConnectionWrappers());
2571 ConnectFakeSignaling();
2572 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002573 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002574 caller()->CreateAndSetAndSignalOffer();
2575 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2576
2577 // Get the audio input level stats. The level should be available very
2578 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002579 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002580 kMaxWaitForStatsMs);
2581}
2582
2583// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002584TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002585 ASSERT_TRUE(CreatePeerConnectionWrappers());
2586 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002587 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002588 // Do offer/answer, wait for the callee to receive some frames.
2589 caller()->CreateAndSetAndSignalOffer();
2590 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002591
2592 MediaExpectations media_expectations;
2593 media_expectations.CalleeExpectsSomeAudioAndVideo();
2594 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002595
2596 // Get a handle to the remote tracks created, so they can be used as GetStats
2597 // filters.
Steve Anton15324772018-01-16 10:26:49 -08002598 for (auto receiver : callee()->pc()->GetReceivers()) {
2599 // We received frames, so we definitely should have nonzero "received bytes"
2600 // stats at this point.
2601 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2602 0);
2603 }
deadbeef1dcb1642017-03-29 21:08:16 -07002604}
2605
2606// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002607TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002608 ASSERT_TRUE(CreatePeerConnectionWrappers());
2609 ConnectFakeSignaling();
2610 auto audio_track = caller()->CreateLocalAudioTrack();
2611 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002612 caller()->AddTrack(audio_track);
2613 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002614 // Do offer/answer, wait for the callee to receive some frames.
2615 caller()->CreateAndSetAndSignalOffer();
2616 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002617 MediaExpectations media_expectations;
2618 media_expectations.CalleeExpectsSomeAudioAndVideo();
2619 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002620
2621 // The callee received frames, so we definitely should have nonzero "sent
2622 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002623 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2624 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2625}
2626
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002627// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002628TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002629 ASSERT_TRUE(CreatePeerConnectionWrappers());
2630 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002631 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002632
Steve Anton15324772018-01-16 10:26:49 -08002633 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002634
2635 // Do offer/answer, wait for the callee to receive some frames.
2636 caller()->CreateAndSetAndSignalOffer();
2637 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2638
2639 // Get the remote audio track created on the receiver, so they can be used as
2640 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002641 auto receivers = callee()->pc()->GetReceivers();
2642 ASSERT_EQ(1u, receivers.size());
2643 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002644
2645 // Get the audio output level stats. Note that the level is not available
2646 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002647 EXPECT_TRUE_WAIT(
2648 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2649 0,
2650 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002651}
2652
Steve Antona41959e2018-11-28 11:15:33 -08002653// Test that the track ID is associated with all local and remote SSRC stats
2654// using the old GetStats() and more than 1 audio and more than 1 video track.
2655// This is a regression test for crbug.com/906988
2656TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2657 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2658 ASSERT_TRUE(CreatePeerConnectionWrappers());
2659 ConnectFakeSignaling();
2660 auto audio_sender_1 = caller()->AddAudioTrack();
2661 auto video_sender_1 = caller()->AddVideoTrack();
2662 auto audio_sender_2 = caller()->AddAudioTrack();
2663 auto video_sender_2 = caller()->AddVideoTrack();
2664 caller()->CreateAndSetAndSignalOffer();
2665 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2666
2667 MediaExpectations media_expectations;
2668 media_expectations.CalleeExpectsSomeAudioAndVideo();
2669 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2670
2671 std::vector<std::string> track_ids = {
2672 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2673 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2674
2675 auto caller_stats = caller()->OldGetStats();
2676 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2677 auto callee_stats = callee()->OldGetStats();
2678 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2679}
2680
Steve Antonffa6ce42018-11-30 09:26:08 -08002681// Test that the new GetStats() returns stats for all outgoing/incoming streams
2682// with the correct track IDs if there are more than one audio and more than one
2683// video senders/receivers.
2684TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2685 ASSERT_TRUE(CreatePeerConnectionWrappers());
2686 ConnectFakeSignaling();
2687 auto audio_sender_1 = caller()->AddAudioTrack();
2688 auto video_sender_1 = caller()->AddVideoTrack();
2689 auto audio_sender_2 = caller()->AddAudioTrack();
2690 auto video_sender_2 = caller()->AddVideoTrack();
2691 caller()->CreateAndSetAndSignalOffer();
2692 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2693
2694 MediaExpectations media_expectations;
2695 media_expectations.CalleeExpectsSomeAudioAndVideo();
2696 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2697
2698 std::vector<std::string> track_ids = {
2699 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2700 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2701
2702 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2703 caller()->NewGetStats();
2704 ASSERT_TRUE(caller_report);
2705 auto outbound_stream_stats =
2706 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2707 ASSERT_EQ(4u, outbound_stream_stats.size());
2708 std::vector<std::string> outbound_track_ids;
2709 for (const auto& stat : outbound_stream_stats) {
2710 ASSERT_TRUE(stat->bytes_sent.is_defined());
2711 EXPECT_LT(0u, *stat->bytes_sent);
2712 ASSERT_TRUE(stat->track_id.is_defined());
2713 const auto* track_stat =
2714 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2715 ASSERT_TRUE(track_stat);
2716 outbound_track_ids.push_back(*track_stat->track_identifier);
2717 }
2718 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2719
2720 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2721 callee()->NewGetStats();
2722 ASSERT_TRUE(callee_report);
2723 auto inbound_stream_stats =
2724 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2725 ASSERT_EQ(4u, inbound_stream_stats.size());
2726 std::vector<std::string> inbound_track_ids;
2727 for (const auto& stat : inbound_stream_stats) {
2728 ASSERT_TRUE(stat->bytes_received.is_defined());
2729 EXPECT_LT(0u, *stat->bytes_received);
2730 ASSERT_TRUE(stat->track_id.is_defined());
2731 const auto* track_stat =
2732 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2733 ASSERT_TRUE(track_stat);
2734 inbound_track_ids.push_back(*track_stat->track_identifier);
2735 }
2736 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2737}
2738
2739// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002740// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2741// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002742TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002743 GetStatsForUnsignaledStreamWithNewStatsApi) {
2744 ASSERT_TRUE(CreatePeerConnectionWrappers());
2745 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002746 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002747 // Remove SSRCs and MSIDs from the received offer SDP.
2748 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2749 caller()->CreateAndSetAndSignalOffer();
2750 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002751 MediaExpectations media_expectations;
2752 media_expectations.CalleeExpectsSomeAudio(1);
2753 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002754
2755 // We received a frame, so we should have nonzero "bytes received" stats for
2756 // the unsignaled stream, if stats are working for it.
2757 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2758 callee()->NewGetStats();
2759 ASSERT_NE(nullptr, report);
2760 auto inbound_stream_stats =
2761 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2762 ASSERT_EQ(1U, inbound_stream_stats.size());
2763 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2764 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002765 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2766}
2767
Taylor Brandstettera4653442018-06-19 09:44:26 -07002768// Same as above but for the legacy stats implementation.
2769TEST_P(PeerConnectionIntegrationTest,
2770 GetStatsForUnsignaledStreamWithOldStatsApi) {
2771 ASSERT_TRUE(CreatePeerConnectionWrappers());
2772 ConnectFakeSignaling();
2773 caller()->AddAudioTrack();
2774 // Remove SSRCs and MSIDs from the received offer SDP.
2775 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2776 caller()->CreateAndSetAndSignalOffer();
2777 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2778
2779 // Note that, since the old stats implementation associates SSRCs with tracks
2780 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2781 // associated track ID. So we can't use the track "selector" argument.
2782 //
2783 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2784 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002785 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002786 kDefaultTimeout);
2787}
2788
zhihuangf8164932017-05-19 13:09:47 -07002789// Test that we can successfully get the media related stats (audio level
2790// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002791TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002792 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2793 ASSERT_TRUE(CreatePeerConnectionWrappers());
2794 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002795 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002796 // Remove SSRCs and MSIDs from the received offer SDP.
2797 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2798 caller()->CreateAndSetAndSignalOffer();
2799 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002800 MediaExpectations media_expectations;
2801 media_expectations.CalleeExpectsSomeAudio(1);
2802 media_expectations.CalleeExpectsSomeVideo(1);
2803 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002804
2805 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2806 callee()->NewGetStats();
2807 ASSERT_NE(nullptr, report);
2808
2809 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2810 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2811 ASSERT_GE(audio_index, 0);
2812 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002813}
2814
deadbeef4e2deab2017-09-20 13:56:21 -07002815// Helper for test below.
2816void ModifySsrcs(cricket::SessionDescription* desc) {
2817 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002818 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002819 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002820 for (uint32_t& ssrc : stream.ssrcs) {
2821 ssrc = rtc::CreateRandomId();
2822 }
2823 }
2824 }
2825}
2826
2827// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2828// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2829// This should result in two "RTCInboundRTPStreamStats", but only one
2830// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2831// being reset to 0 once the SSRC change occurs.
2832//
2833// Regression test for this bug:
2834// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2835//
2836// The bug causes the track stats to only represent one of the two streams:
2837// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2838// that the track stat counters would reset to 0 when the new stream is
2839// received, and a 50% chance that they'll stop updating (while
2840// "concealed_samples" continues increasing, due to silence being generated for
2841// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002842TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002843 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002844 ASSERT_TRUE(CreatePeerConnectionWrappers());
2845 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002846 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002847 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2848 // that doesn't signal SSRCs (from the callee's perspective).
2849 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2850 caller()->CreateAndSetAndSignalOffer();
2851 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2852 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002853 {
2854 MediaExpectations media_expectations;
2855 media_expectations.CalleeExpectsSomeAudio(50);
2856 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2857 }
deadbeef4e2deab2017-09-20 13:56:21 -07002858 // Some audio frames were received, so we should have nonzero "samples
2859 // received" for the track.
2860 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2861 callee()->NewGetStats();
2862 ASSERT_NE(nullptr, report);
2863 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2864 ASSERT_EQ(1U, track_stats.size());
2865 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2866 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2867 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2868
2869 // Create a new offer and munge it to cause the caller to use a new SSRC.
2870 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2871 caller()->CreateAndSetAndSignalOffer();
2872 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2873 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2874 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002875 {
2876 MediaExpectations media_expectations;
2877 media_expectations.CalleeExpectsSomeAudio(25);
2878 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2879 }
deadbeef4e2deab2017-09-20 13:56:21 -07002880
2881 report = callee()->NewGetStats();
2882 ASSERT_NE(nullptr, report);
2883 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2884 ASSERT_EQ(1U, track_stats.size());
2885 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2886 // The "total samples received" stat should only be greater than it was
2887 // before.
2888 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2889 // Right now, the new SSRC will cause the counters to reset to 0.
2890 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2891
2892 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002893 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002894 // good sign that we're seeing stats from the old stream that's no longer
2895 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002896 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002897 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2898 EXPECT_LT(*track_stats[0]->concealed_samples,
2899 *track_stats[0]->total_samples_received *
2900 kAcceptableConcealedSamplesPercentage);
2901
2902 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2903 // sanity check that the SSRC really changed.
2904 // TODO(deadbeef): This isn't working right now, because we're not returning
2905 // *any* stats for the inactive stream. Uncomment when the bug is completely
2906 // fixed.
2907 // auto inbound_stream_stats =
2908 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2909 // ASSERT_EQ(2U, inbound_stream_stats.size());
2910}
2911
deadbeef1dcb1642017-03-29 21:08:16 -07002912// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002913TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002914 PeerConnectionFactory::Options dtls_10_options;
2915 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2916 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2917 dtls_10_options));
2918 ConnectFakeSignaling();
2919 // Do normal offer/answer and wait for some frames to be received in each
2920 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002921 caller()->AddAudioVideoTracks();
2922 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002923 caller()->CreateAndSetAndSignalOffer();
2924 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002925 MediaExpectations media_expectations;
2926 media_expectations.ExpectBidirectionalAudioAndVideo();
2927 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002928}
2929
2930// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002931TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002932 PeerConnectionFactory::Options dtls_10_options;
2933 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2934 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2935 dtls_10_options));
2936 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002937 caller()->AddAudioVideoTracks();
2938 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002939 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002940 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002941 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002942 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002943 kDefaultTimeout);
2944 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002945 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002946 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002947 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002948 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2949 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002950}
2951
2952// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002953TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002954 PeerConnectionFactory::Options dtls_12_options;
2955 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2956 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2957 dtls_12_options));
2958 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002959 caller()->AddAudioVideoTracks();
2960 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002961 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002962 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002963 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002964 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002965 kDefaultTimeout);
2966 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002967 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002968 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002969 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002970 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2971 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002972}
2973
2974// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2975// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002976TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002977 PeerConnectionFactory::Options caller_options;
2978 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2979 PeerConnectionFactory::Options callee_options;
2980 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2981 ASSERT_TRUE(
2982 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2983 ConnectFakeSignaling();
2984 // Do normal offer/answer and wait for some frames to be received in each
2985 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002986 caller()->AddAudioVideoTracks();
2987 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002988 caller()->CreateAndSetAndSignalOffer();
2989 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002990 MediaExpectations media_expectations;
2991 media_expectations.ExpectBidirectionalAudioAndVideo();
2992 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002993}
2994
2995// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2996// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002997TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07002998 PeerConnectionFactory::Options caller_options;
2999 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3000 PeerConnectionFactory::Options callee_options;
3001 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3002 ASSERT_TRUE(
3003 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3004 ConnectFakeSignaling();
3005 // Do normal offer/answer and wait for some frames to be received in each
3006 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003007 caller()->AddAudioVideoTracks();
3008 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003009 caller()->CreateAndSetAndSignalOffer();
3010 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003011 MediaExpectations media_expectations;
3012 media_expectations.ExpectBidirectionalAudioAndVideo();
3013 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003014}
3015
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003016// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3017// works as expected; the cipher should only be used if enabled by both sides.
3018TEST_P(PeerConnectionIntegrationTest,
3019 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3020 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003021 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003022 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003023 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3024 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003025 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3026 TestNegotiatedCipherSuite(caller_options, callee_options,
3027 expected_cipher_suite);
3028}
3029
3030TEST_P(PeerConnectionIntegrationTest,
3031 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3032 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003033 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3034 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003035 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003036 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003037 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3038 TestNegotiatedCipherSuite(caller_options, callee_options,
3039 expected_cipher_suite);
3040}
3041
3042TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3043 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003044 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003045 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003046 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003047 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3048 TestNegotiatedCipherSuite(caller_options, callee_options,
3049 expected_cipher_suite);
3050}
3051
deadbeef1dcb1642017-03-29 21:08:16 -07003052// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003053TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003054 bool local_gcm_enabled = false;
3055 bool remote_gcm_enabled = false;
3056 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3057 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3058 expected_cipher_suite);
3059}
3060
3061// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003062TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003063 bool local_gcm_enabled = true;
3064 bool remote_gcm_enabled = true;
3065 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3066 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3067 expected_cipher_suite);
3068}
3069
3070// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003071TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003072 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
3073 bool local_gcm_enabled = true;
3074 bool remote_gcm_enabled = false;
3075 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3076 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3077 expected_cipher_suite);
3078}
3079
3080// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003081TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003082 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
3083 bool local_gcm_enabled = false;
3084 bool remote_gcm_enabled = true;
3085 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3086 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3087 expected_cipher_suite);
3088}
3089
deadbeef7914b8c2017-04-21 03:23:33 -07003090// Verify that media can be transmitted end-to-end when GCM crypto suites are
3091// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3092// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3093// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003094TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003095 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003096 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07003097 ASSERT_TRUE(
3098 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3099 ConnectFakeSignaling();
3100 // Do normal offer/answer and wait for some frames to be received in each
3101 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003102 caller()->AddAudioVideoTracks();
3103 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003104 caller()->CreateAndSetAndSignalOffer();
3105 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003106 MediaExpectations media_expectations;
3107 media_expectations.ExpectBidirectionalAudioAndVideo();
3108 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003109}
3110
deadbeef1dcb1642017-03-29 21:08:16 -07003111// This test sets up a call between two parties with audio, video and an RTP
3112// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003113TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003114 PeerConnectionInterface::RTCConfiguration rtc_config;
3115 rtc_config.enable_rtp_data_channel = true;
3116 rtc_config.enable_dtls_srtp = false;
3117 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003118 ConnectFakeSignaling();
3119 // Expect that data channel created on caller side will show up for callee as
3120 // well.
3121 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003122 caller()->AddAudioVideoTracks();
3123 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003124 caller()->CreateAndSetAndSignalOffer();
3125 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3126 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003127 MediaExpectations media_expectations;
3128 media_expectations.ExpectBidirectionalAudioAndVideo();
3129 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003130 ASSERT_NE(nullptr, caller()->data_channel());
3131 ASSERT_NE(nullptr, callee()->data_channel());
3132 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3133 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3134
3135 // Ensure data can be sent in both directions.
3136 std::string data = "hello world";
3137 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3138 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3139 kDefaultTimeout);
3140 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3141 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3142 kDefaultTimeout);
3143}
3144
3145// Ensure that an RTP data channel is signaled as closed for the caller when
3146// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003147TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003148 RtpDataChannelSignaledClosedInCalleeOffer) {
3149 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003150 PeerConnectionInterface::RTCConfiguration rtc_config;
3151 rtc_config.enable_rtp_data_channel = true;
3152 rtc_config.enable_dtls_srtp = false;
3153 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003154 ConnectFakeSignaling();
3155 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003156 caller()->AddAudioVideoTracks();
3157 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003158 caller()->CreateAndSetAndSignalOffer();
3159 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3160 ASSERT_NE(nullptr, caller()->data_channel());
3161 ASSERT_NE(nullptr, callee()->data_channel());
3162 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3163 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3164
3165 // Close the data channel on the callee, and do an updated offer/answer.
3166 callee()->data_channel()->Close();
3167 callee()->CreateAndSetAndSignalOffer();
3168 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3169 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3170 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3171}
3172
3173// Tests that data is buffered in an RTP data channel until an observer is
3174// registered for it.
3175//
3176// NOTE: RTP data channels can receive data before the underlying
3177// transport has detected that a channel is writable and thus data can be
3178// received before the data channel state changes to open. That is hard to test
3179// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003180TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003181 DataBufferedUntilRtpDataChannelObserverRegistered) {
3182 // Use fake clock and simulated network delay so that we predictably can wait
3183 // until an SCTP message has been delivered without "sleep()"ing.
3184 rtc::ScopedFakeClock fake_clock;
3185 // Some things use a time of "0" as a special value, so we need to start out
3186 // the fake clock at a nonzero time.
3187 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003188 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003189 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3190 virtual_socket_server()->UpdateDelayDistribution();
3191
Niels Möllerf06f9232018-08-07 12:32:18 +02003192 PeerConnectionInterface::RTCConfiguration rtc_config;
3193 rtc_config.enable_rtp_data_channel = true;
3194 rtc_config.enable_dtls_srtp = false;
3195 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003196 ConnectFakeSignaling();
3197 caller()->CreateDataChannel();
3198 caller()->CreateAndSetAndSignalOffer();
3199 ASSERT_TRUE(caller()->data_channel() != nullptr);
3200 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3201 kDefaultTimeout, fake_clock);
3202 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3203 kDefaultTimeout, fake_clock);
3204 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3205 callee()->data_channel()->state(), kDefaultTimeout,
3206 fake_clock);
3207
3208 // Unregister the observer which is normally automatically registered.
3209 callee()->data_channel()->UnregisterObserver();
3210 // Send data and advance fake clock until it should have been received.
3211 std::string data = "hello world";
3212 caller()->data_channel()->Send(DataBuffer(data));
3213 SIMULATED_WAIT(false, 50, fake_clock);
3214
3215 // Attach data channel and expect data to be received immediately. Note that
3216 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3217 // further, but data can be received even if the callback is asynchronous.
3218 MockDataChannelObserver new_observer(callee()->data_channel());
3219 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3220 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003221 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3222 // If this is not done a DCHECK can be hit in ports.cc, because a large
3223 // negative number is calculated for the rtt due to the global clock changing.
3224 caller()->pc()->Close();
3225 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07003226}
3227
3228// This test sets up a call between two parties with audio, video and but only
3229// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003230TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003231 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3232 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003233 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003234 rtc_config_1.enable_dtls_srtp = false;
3235 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3236 rtc_config_2.enable_dtls_srtp = false;
3237 rtc_config_2.enable_dtls_srtp = false;
3238 ASSERT_TRUE(
3239 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003240 ConnectFakeSignaling();
3241 caller()->CreateDataChannel();
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 // The caller should still have a data channel, but it should be closed, and
3247 // one should ever have been created for the callee.
3248 EXPECT_TRUE(caller()->data_channel() != nullptr);
3249 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3250 EXPECT_EQ(nullptr, callee()->data_channel());
3251}
3252
3253// This test sets up a call between two parties with audio, and video. When
3254// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003255TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003256 PeerConnectionInterface::RTCConfiguration rtc_config;
3257 rtc_config.enable_rtp_data_channel = true;
3258 rtc_config.enable_dtls_srtp = false;
3259 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003260 ConnectFakeSignaling();
3261 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003262 caller()->AddAudioVideoTracks();
3263 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003264 caller()->CreateAndSetAndSignalOffer();
3265 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3266 // Create data channel and do new offer and answer.
3267 caller()->CreateDataChannel();
3268 caller()->CreateAndSetAndSignalOffer();
3269 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3270 ASSERT_NE(nullptr, caller()->data_channel());
3271 ASSERT_NE(nullptr, callee()->data_channel());
3272 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3273 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3274 // Ensure data can be sent in both directions.
3275 std::string data = "hello world";
3276 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3277 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3278 kDefaultTimeout);
3279 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3280 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3281 kDefaultTimeout);
3282}
3283
3284#ifdef HAVE_SCTP
3285
3286// This test sets up a call between two parties with audio, video and an SCTP
3287// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003288TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003289 ASSERT_TRUE(CreatePeerConnectionWrappers());
3290 ConnectFakeSignaling();
3291 // Expect that data channel created on caller side will show up for callee as
3292 // well.
3293 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003294 caller()->AddAudioVideoTracks();
3295 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003296 caller()->CreateAndSetAndSignalOffer();
3297 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3298 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003299 MediaExpectations media_expectations;
3300 media_expectations.ExpectBidirectionalAudioAndVideo();
3301 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003302 // Caller data channel should already exist (it created one). Callee data
3303 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3304 ASSERT_NE(nullptr, caller()->data_channel());
3305 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3306 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3307 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3308
3309 // Ensure data can be sent in both directions.
3310 std::string data = "hello world";
3311 caller()->data_channel()->Send(DataBuffer(data));
3312 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3313 kDefaultTimeout);
3314 callee()->data_channel()->Send(DataBuffer(data));
3315 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3316 kDefaultTimeout);
3317}
3318
3319// Ensure that when the callee closes an SCTP data channel, the closing
3320// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003321TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003322 // Same procedure as above test.
3323 ASSERT_TRUE(CreatePeerConnectionWrappers());
3324 ConnectFakeSignaling();
3325 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003326 caller()->AddAudioVideoTracks();
3327 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003328 caller()->CreateAndSetAndSignalOffer();
3329 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3330 ASSERT_NE(nullptr, caller()->data_channel());
3331 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3332 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3333 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3334
3335 // Close the data channel on the callee side, and wait for it to reach the
3336 // "closed" state on both sides.
3337 callee()->data_channel()->Close();
3338 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3339 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3340}
3341
Seth Hampson2f0d7022018-02-20 11:54:42 -08003342TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003343 ASSERT_TRUE(CreatePeerConnectionWrappers());
3344 ConnectFakeSignaling();
3345 webrtc::DataChannelInit init;
3346 init.id = 53;
3347 init.maxRetransmits = 52;
3348 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003349 caller()->AddAudioVideoTracks();
3350 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003351 caller()->CreateAndSetAndSignalOffer();
3352 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003353 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3354 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07003355 EXPECT_EQ(init.id, callee()->data_channel()->id());
3356 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3357 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3358 EXPECT_FALSE(callee()->data_channel()->negotiated());
3359}
3360
deadbeef1dcb1642017-03-29 21:08:16 -07003361// Test usrsctp's ability to process unordered data stream, where data actually
3362// arrives out of order using simulated delays. Previously there have been some
3363// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003364TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003365 // Introduce random network delays.
3366 // Otherwise it's not a true "unordered" test.
3367 virtual_socket_server()->set_delay_mean(20);
3368 virtual_socket_server()->set_delay_stddev(5);
3369 virtual_socket_server()->UpdateDelayDistribution();
3370 // Normal procedure, but with unordered data channel config.
3371 ASSERT_TRUE(CreatePeerConnectionWrappers());
3372 ConnectFakeSignaling();
3373 webrtc::DataChannelInit init;
3374 init.ordered = false;
3375 caller()->CreateDataChannel(&init);
3376 caller()->CreateAndSetAndSignalOffer();
3377 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3378 ASSERT_NE(nullptr, caller()->data_channel());
3379 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3380 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3381 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3382
3383 static constexpr int kNumMessages = 100;
3384 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3385 static constexpr size_t kMaxMessageSize = 4096;
3386 // Create and send random messages.
3387 std::vector<std::string> sent_messages;
3388 for (int i = 0; i < kNumMessages; ++i) {
3389 size_t length =
3390 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3391 std::string message;
3392 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3393 caller()->data_channel()->Send(DataBuffer(message));
3394 callee()->data_channel()->Send(DataBuffer(message));
3395 sent_messages.push_back(message);
3396 }
3397
3398 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003399 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003400 caller()->data_observer()->received_message_count(),
3401 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003402 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003403 callee()->data_observer()->received_message_count(),
3404 kDefaultTimeout);
3405
3406 // Sort and compare to make sure none of the messages were corrupted.
3407 std::vector<std::string> caller_received_messages =
3408 caller()->data_observer()->messages();
3409 std::vector<std::string> callee_received_messages =
3410 callee()->data_observer()->messages();
3411 std::sort(sent_messages.begin(), sent_messages.end());
3412 std::sort(caller_received_messages.begin(), caller_received_messages.end());
3413 std::sort(callee_received_messages.begin(), callee_received_messages.end());
3414 EXPECT_EQ(sent_messages, caller_received_messages);
3415 EXPECT_EQ(sent_messages, callee_received_messages);
3416}
3417
3418// This test sets up a call between two parties with audio, and video. When
3419// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003420TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003421 ASSERT_TRUE(CreatePeerConnectionWrappers());
3422 ConnectFakeSignaling();
3423 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003424 caller()->AddAudioVideoTracks();
3425 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003426 caller()->CreateAndSetAndSignalOffer();
3427 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3428 // Create data channel and do new offer and answer.
3429 caller()->CreateDataChannel();
3430 caller()->CreateAndSetAndSignalOffer();
3431 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3432 // Caller data channel should already exist (it created one). Callee data
3433 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3434 ASSERT_NE(nullptr, caller()->data_channel());
3435 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3436 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3437 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3438 // Ensure data can be sent in both directions.
3439 std::string data = "hello world";
3440 caller()->data_channel()->Send(DataBuffer(data));
3441 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3442 kDefaultTimeout);
3443 callee()->data_channel()->Send(DataBuffer(data));
3444 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3445 kDefaultTimeout);
3446}
3447
deadbeef7914b8c2017-04-21 03:23:33 -07003448// Set up a connection initially just using SCTP data channels, later upgrading
3449// to audio/video, ensuring frames are received end-to-end. Effectively the
3450// inverse of the test above.
3451// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003452TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003453 ASSERT_TRUE(CreatePeerConnectionWrappers());
3454 ConnectFakeSignaling();
3455 // Do initial offer/answer with just data channel.
3456 caller()->CreateDataChannel();
3457 caller()->CreateAndSetAndSignalOffer();
3458 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3459 // Wait until data can be sent over the data channel.
3460 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3461 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3462 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3463
3464 // Do subsequent offer/answer with two-way audio and video. Audio and video
3465 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003466 caller()->AddAudioVideoTracks();
3467 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003468 caller()->CreateAndSetAndSignalOffer();
3469 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003470 MediaExpectations media_expectations;
3471 media_expectations.ExpectBidirectionalAudioAndVideo();
3472 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003473}
3474
deadbeef8b7e9ad2017-05-25 09:38:55 -07003475static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07003476 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08003477 GetFirstDataContentDescription(desc);
3478 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003479 dcd_offer->set_use_sctpmap(false);
3480 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3481}
3482
3483// Test that the data channel works when a spec-compliant SCTP m= section is
3484// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3485// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003486TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003487 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3488 ASSERT_TRUE(CreatePeerConnectionWrappers());
3489 ConnectFakeSignaling();
3490 caller()->CreateDataChannel();
3491 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3492 caller()->CreateAndSetAndSignalOffer();
3493 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3494 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3495 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3496 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3497
3498 // Ensure data can be sent in both directions.
3499 std::string data = "hello world";
3500 caller()->data_channel()->Send(DataBuffer(data));
3501 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3502 kDefaultTimeout);
3503 callee()->data_channel()->Send(DataBuffer(data));
3504 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3505 kDefaultTimeout);
3506}
3507
deadbeef1dcb1642017-03-29 21:08:16 -07003508#endif // HAVE_SCTP
3509
Bjorn Mellema2eb0a72018-11-09 10:13:51 -08003510// This test sets up a call between two parties with a media transport data
3511// channel.
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003512TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
3513 PeerConnectionInterface::RTCConfiguration rtc_config;
3514 rtc_config.use_media_transport_for_data_channels = true;
3515 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3516 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3517 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3518 loopback_media_transports()->second_factory()));
3519 ConnectFakeSignaling();
3520
3521 // Expect that data channel created on caller side will show up for callee as
3522 // well.
3523 caller()->CreateDataChannel();
3524 caller()->CreateAndSetAndSignalOffer();
3525 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3526
3527 // Ensure that the media transport is ready.
3528 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3529 loopback_media_transports()->FlushAsyncInvokes();
3530
3531 // Caller data channel should already exist (it created one). Callee data
3532 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3533 ASSERT_NE(nullptr, caller()->data_channel());
3534 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3535 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3536 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3537
3538 // Ensure data can be sent in both directions.
3539 std::string data = "hello world";
3540 caller()->data_channel()->Send(DataBuffer(data));
3541 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3542 kDefaultTimeout);
3543 callee()->data_channel()->Send(DataBuffer(data));
3544 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3545 kDefaultTimeout);
3546}
3547
3548// Ensure that when the callee closes a media transport data channel, the
3549// closing procedure results in the data channel being closed for the caller
3550// as well.
3551TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
3552 PeerConnectionInterface::RTCConfiguration rtc_config;
3553 rtc_config.use_media_transport_for_data_channels = true;
3554 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3555 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3556 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3557 loopback_media_transports()->second_factory()));
3558 ConnectFakeSignaling();
3559
3560 // Create a data channel on the caller and signal it to the callee.
3561 caller()->CreateDataChannel();
3562 caller()->CreateAndSetAndSignalOffer();
3563 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3564
3565 // Ensure that the media transport is ready.
3566 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3567 loopback_media_transports()->FlushAsyncInvokes();
3568
3569 // Data channels exist and open on both ends of the connection.
3570 ASSERT_NE(nullptr, caller()->data_channel());
3571 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3572 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3573 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3574
3575 // Close the data channel on the callee side, and wait for it to reach the
3576 // "closed" state on both sides.
3577 callee()->data_channel()->Close();
3578 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3579 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3580}
3581
3582TEST_P(PeerConnectionIntegrationTest,
3583 MediaTransportDataChannelConfigSentToOtherSide) {
3584 PeerConnectionInterface::RTCConfiguration rtc_config;
3585 rtc_config.use_media_transport_for_data_channels = true;
3586 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3587 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3588 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3589 loopback_media_transports()->second_factory()));
3590 ConnectFakeSignaling();
3591
3592 // Create a data channel with a non-default configuration and signal it to the
3593 // callee.
3594 webrtc::DataChannelInit init;
3595 init.id = 53;
3596 init.maxRetransmits = 52;
3597 caller()->CreateDataChannel("data-channel", &init);
3598 caller()->CreateAndSetAndSignalOffer();
3599 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3600
3601 // Ensure that the media transport is ready.
3602 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3603 loopback_media_transports()->FlushAsyncInvokes();
3604
3605 // Ensure that the data channel exists on the callee with the correct
3606 // configuration.
3607 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3608 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3609 EXPECT_EQ(init.id, callee()->data_channel()->id());
3610 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3611 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3612 EXPECT_FALSE(callee()->data_channel()->negotiated());
3613}
3614
Niels Möllerc68d2822018-11-20 14:52:05 +01003615TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
3616 PeerConnectionInterface::RTCConfiguration rtc_config;
3617 rtc_config.use_media_transport = true;
3618 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3619 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3620 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3621 loopback_media_transports()->second_factory()));
3622 ConnectFakeSignaling();
3623
3624 caller()->AddAudioTrack();
3625 callee()->AddAudioTrack();
3626 // Start offer/answer exchange and wait for it to complete.
3627 caller()->CreateAndSetAndSignalOffer();
3628 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3629
3630 // Ensure that the media transport is ready.
3631 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3632 loopback_media_transports()->FlushAsyncInvokes();
3633
3634 MediaExpectations media_expectations;
3635 media_expectations.ExpectBidirectionalAudio();
3636 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3637
3638 webrtc::MediaTransportPair::Stats first_stats =
3639 loopback_media_transports()->FirstStats();
3640 webrtc::MediaTransportPair::Stats second_stats =
3641 loopback_media_transports()->SecondStats();
3642
3643 EXPECT_GT(first_stats.received_audio_frames, 0);
3644 EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
3645
3646 EXPECT_GT(second_stats.received_audio_frames, 0);
3647 EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
3648}
3649
deadbeef1dcb1642017-03-29 21:08:16 -07003650// Test that the ICE connection and gathering states eventually reach
3651// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003652TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003653 ASSERT_TRUE(CreatePeerConnectionWrappers());
3654 ConnectFakeSignaling();
3655 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003656 caller()->AddAudioVideoTracks();
3657 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003658 caller()->CreateAndSetAndSignalOffer();
3659 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3660 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3661 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3662 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3663 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3664 // After the best candidate pair is selected and all candidates are signaled,
3665 // the ICE connection state should reach "complete".
3666 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3667 // answerer/"callee" by default) only reaches "connected". When this is
3668 // fixed, this test should be updated.
3669 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3670 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003671 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3672 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003673}
3674
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003675// Replaces the first candidate with a static address and configures a
3676// MockAsyncResolver to return the replaced address the first time the static
3677// address is resolved. Candidates past the first will not be signaled.
3678class ReplaceFirstCandidateAddressDropOthers final
3679 : public IceCandidateReplacerInterface {
3680 public:
3681 ReplaceFirstCandidateAddressDropOthers(
3682 const SocketAddress& new_address,
3683 rtc::MockAsyncResolver* mock_async_resolver)
3684 : mock_async_resolver_(mock_async_resolver), new_address_(new_address) {
3685 RTC_DCHECK(mock_async_resolver);
3686 }
3687
3688 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3689 const webrtc::IceCandidateInterface* candidate) override {
3690 if (replaced_candidate_) {
3691 return nullptr;
3692 }
3693
3694 replaced_candidate_ = true;
3695 cricket::Candidate new_candidate(candidate->candidate());
3696 new_candidate.set_address(new_address_);
3697 EXPECT_CALL(*mock_async_resolver_, GetResolvedAddress(_, _))
3698 .WillOnce(DoAll(SetArgPointee<1>(candidate->candidate().address()),
3699 Return(true)));
3700 EXPECT_CALL(*mock_async_resolver_, Destroy(_));
3701 return webrtc::CreateIceCandidate(
3702 candidate->sdp_mid(), candidate->sdp_mline_index(), new_candidate);
3703 }
3704
3705 private:
3706 rtc::MockAsyncResolver* mock_async_resolver_;
3707 SocketAddress new_address_;
3708 bool replaced_candidate_ = false;
3709};
3710
3711// Drops all candidates before they are signaled.
3712class DropAllCandidates final : public IceCandidateReplacerInterface {
3713 public:
3714 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3715 const webrtc::IceCandidateInterface*) override {
3716 return nullptr;
3717 }
3718};
3719
3720// Replace the first caller ICE candidate IP with a fake hostname and drop the
3721// other candidates. Drop all candidates on the callee side (to avoid a prflx
3722// connection). Use a mock resolver to resolve the hostname back to the original
3723// IP on the callee side and check that the ice connection connects.
3724TEST_P(PeerConnectionIntegrationTest,
3725 IceStatesReachCompletionWithRemoteHostname) {
3726 webrtc::MockAsyncResolverFactory* callee_mock_async_resolver_factory;
3727 {
3728 auto resolver_factory =
3729 absl::make_unique<webrtc::MockAsyncResolverFactory>();
3730 callee_mock_async_resolver_factory = resolver_factory.get();
3731 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3732 callee_deps.async_resolver_factory = std::move(resolver_factory);
3733
3734 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3735 RTCConfiguration(), webrtc::PeerConnectionDependencies(nullptr),
3736 RTCConfiguration(), std::move(callee_deps)));
3737 }
3738
3739 rtc::MockAsyncResolver mock_async_resolver;
3740
3741 // This also verifies that the injected AsyncResolverFactory is used by
3742 // P2PTransportChannel.
3743 EXPECT_CALL(*callee_mock_async_resolver_factory, Create())
3744 .WillOnce(Return(&mock_async_resolver));
3745 caller()->SetLocalIceCandidateReplacer(
3746 absl::make_unique<ReplaceFirstCandidateAddressDropOthers>(
3747 SocketAddress("a.b", 10000), &mock_async_resolver));
3748 callee()->SetLocalIceCandidateReplacer(
3749 absl::make_unique<DropAllCandidates>());
3750
3751 ConnectFakeSignaling();
3752 caller()->AddAudioVideoTracks();
3753 callee()->AddAudioVideoTracks();
3754 caller()->CreateAndSetAndSignalOffer();
3755 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3756 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3757 caller()->ice_connection_state(), kDefaultTimeout);
3758 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3759 callee()->ice_connection_state(), kDefaultTimeout);
3760}
3761
Steve Antonede9ca52017-10-16 13:04:27 -07003762// Test that firewalling the ICE connection causes the clients to identify the
3763// disconnected state and then removing the firewall causes them to reconnect.
3764class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003765 : public PeerConnectionIntegrationBaseTest,
3766 public ::testing::WithParamInterface<
3767 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003768 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003769 PeerConnectionIntegrationIceStatesTest()
3770 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3771 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003772 }
3773
3774 void StartStunServer(const SocketAddress& server_address) {
3775 stun_server_.reset(
3776 cricket::TestStunServer::Create(network_thread(), server_address));
3777 }
3778
3779 bool TestIPv6() {
3780 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3781 }
3782
3783 void SetPortAllocatorFlags() {
Qingsi Wanga2d60672018-04-11 16:57:45 -07003784 network_thread()->Invoke<void>(
3785 RTC_FROM_HERE,
3786 rtc::Bind(&cricket::PortAllocator::set_flags,
3787 caller()->port_allocator(), port_allocator_flags_));
3788 network_thread()->Invoke<void>(
3789 RTC_FROM_HERE,
3790 rtc::Bind(&cricket::PortAllocator::set_flags,
3791 callee()->port_allocator(), port_allocator_flags_));
Steve Antonede9ca52017-10-16 13:04:27 -07003792 }
3793
3794 std::vector<SocketAddress> CallerAddresses() {
3795 std::vector<SocketAddress> addresses;
3796 addresses.push_back(SocketAddress("1.1.1.1", 0));
3797 if (TestIPv6()) {
3798 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3799 }
3800 return addresses;
3801 }
3802
3803 std::vector<SocketAddress> CalleeAddresses() {
3804 std::vector<SocketAddress> addresses;
3805 addresses.push_back(SocketAddress("2.2.2.2", 0));
3806 if (TestIPv6()) {
3807 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3808 }
3809 return addresses;
3810 }
3811
3812 void SetUpNetworkInterfaces() {
3813 // Remove the default interfaces added by the test infrastructure.
3814 caller()->network()->RemoveInterface(kDefaultLocalAddress);
3815 callee()->network()->RemoveInterface(kDefaultLocalAddress);
3816
3817 // Add network addresses for test.
3818 for (const auto& caller_address : CallerAddresses()) {
3819 caller()->network()->AddInterface(caller_address);
3820 }
3821 for (const auto& callee_address : CalleeAddresses()) {
3822 callee()->network()->AddInterface(callee_address);
3823 }
3824 }
3825
3826 private:
3827 uint32_t port_allocator_flags_;
3828 std::unique_ptr<cricket::TestStunServer> stun_server_;
3829};
3830
3831// Tests that the PeerConnection goes through all the ICE gathering/connection
3832// states over the duration of the call. This includes Disconnected and Failed
3833// states, induced by putting a firewall between the peers and waiting for them
3834// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003835TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
3836 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
3837 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
3838 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07003839
3840 const SocketAddress kStunServerAddress =
3841 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3842 StartStunServer(kStunServerAddress);
3843
3844 PeerConnectionInterface::RTCConfiguration config;
3845 PeerConnectionInterface::IceServer ice_stun_server;
3846 ice_stun_server.urls.push_back(
3847 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3848 kStunServerAddress.PortAsString());
3849 config.servers.push_back(ice_stun_server);
3850
3851 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3852 ConnectFakeSignaling();
3853 SetPortAllocatorFlags();
3854 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003855 caller()->AddAudioVideoTracks();
3856 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003857
3858 // Initial state before anything happens.
3859 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3860 caller()->ice_gathering_state());
3861 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3862 caller()->ice_connection_state());
3863
3864 // Start the call by creating the offer, setting it as the local description,
3865 // then sending it to the peer who will respond with an answer. This happens
3866 // asynchronously so that we can watch the states as it runs in the
3867 // background.
3868 caller()->CreateAndSetAndSignalOffer();
3869
Steve Anton83119dd2017-11-10 16:19:52 -08003870 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3871 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003872
3873 // Verify that the observer was notified of the intermediate transitions.
3874 EXPECT_THAT(caller()->ice_connection_state_history(),
3875 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3876 PeerConnectionInterface::kIceConnectionConnected,
3877 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02003878 // After the ice transport transitions from checking to connected we revert
3879 // back to new as the standard requires, as at that point the DTLS transport
3880 // is in the "new" state while no transports are "connecting", "checking",
3881 // "failed" or disconnected. This is pretty unintuitive, and we might want to
3882 // amend the spec to handle this case more gracefully.
3883 EXPECT_THAT(
3884 caller()->peer_connection_state_history(),
3885 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02003886 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07003887 EXPECT_THAT(caller()->ice_gathering_state_history(),
3888 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
3889 PeerConnectionInterface::kIceGatheringComplete));
3890
3891 // Block connections to/from the caller and wait for ICE to become
3892 // disconnected.
3893 for (const auto& caller_address : CallerAddresses()) {
3894 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3895 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003896 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08003897 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
3898 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003899
3900 // Let ICE re-establish by removing the firewall rules.
3901 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01003902 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08003903 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3904 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003905
3906 // According to RFC7675, if there is no response within 30 seconds then the
3907 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08003908 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07003909 constexpr int kConsentTimeout = 30000;
3910 for (const auto& caller_address : CallerAddresses()) {
3911 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3912 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003913 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08003914 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
3915 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003916}
3917
3918// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
3919// and that the statistics in the metric observers are updated correctly.
3920TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
3921 ASSERT_TRUE(CreatePeerConnectionWrappers());
3922 ConnectFakeSignaling();
3923 SetPortAllocatorFlags();
3924 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003925 caller()->AddAudioVideoTracks();
3926 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003927 caller()->CreateAndSetAndSignalOffer();
3928
3929 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3930
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003931 // TODO(bugs.webrtc.org/9456): Fix it.
3932 const int num_best_ipv4 = webrtc::metrics::NumEvents(
3933 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
3934 const int num_best_ipv6 = webrtc::metrics::NumEvents(
3935 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003936 if (TestIPv6()) {
3937 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
3938 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003939 EXPECT_EQ(0, num_best_ipv4);
3940 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003941 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003942 EXPECT_EQ(1, num_best_ipv4);
3943 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003944 }
3945
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003946 EXPECT_EQ(0, webrtc::metrics::NumEvents(
3947 "WebRTC.PeerConnection.CandidatePairType_UDP",
3948 webrtc::kIceCandidatePairHostHost));
3949 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3950 "WebRTC.PeerConnection.CandidatePairType_UDP",
3951 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07003952}
3953
3954constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
3955 cricket::PORTALLOCATOR_DISABLE_STUN |
3956 cricket::PORTALLOCATOR_DISABLE_RELAY;
3957constexpr uint32_t kFlagsIPv6NoStun =
3958 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
3959 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
3960constexpr uint32_t kFlagsIPv4Stun =
3961 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
3962
Seth Hampson2f0d7022018-02-20 11:54:42 -08003963INSTANTIATE_TEST_CASE_P(
3964 PeerConnectionIntegrationTest,
3965 PeerConnectionIntegrationIceStatesTest,
3966 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3967 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
3968 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
3969 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07003970
deadbeef1dcb1642017-03-29 21:08:16 -07003971// This test sets up a call between two parties with audio and video.
3972// During the call, the caller restarts ICE and the test verifies that
3973// new ICE candidates are generated and audio and video still can flow, and the
3974// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003975TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07003976 ASSERT_TRUE(CreatePeerConnectionWrappers());
3977 ConnectFakeSignaling();
3978 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08003979 caller()->AddAudioVideoTracks();
3980 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003981 caller()->CreateAndSetAndSignalOffer();
3982 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3983 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3984 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00003985 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3986 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07003987
3988 // To verify that the ICE restart actually occurs, get
3989 // ufrag/password/candidates before and after restart.
3990 // Create an SDP string of the first audio candidate for both clients.
3991 const webrtc::IceCandidateCollection* audio_candidates_caller =
3992 caller()->pc()->local_description()->candidates(0);
3993 const webrtc::IceCandidateCollection* audio_candidates_callee =
3994 callee()->pc()->local_description()->candidates(0);
3995 ASSERT_GT(audio_candidates_caller->count(), 0u);
3996 ASSERT_GT(audio_candidates_callee->count(), 0u);
3997 std::string caller_candidate_pre_restart;
3998 ASSERT_TRUE(
3999 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4000 std::string callee_candidate_pre_restart;
4001 ASSERT_TRUE(
4002 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4003 const cricket::SessionDescription* desc =
4004 caller()->pc()->local_description()->description();
4005 std::string caller_ufrag_pre_restart =
4006 desc->transport_infos()[0].description.ice_ufrag;
4007 desc = callee()->pc()->local_description()->description();
4008 std::string callee_ufrag_pre_restart =
4009 desc->transport_infos()[0].description.ice_ufrag;
4010
4011 // Have the caller initiate an ICE restart.
4012 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4013 caller()->CreateAndSetAndSignalOffer();
4014 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4015 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4016 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004017 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004018 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4019
4020 // Grab the ufrags/candidates again.
4021 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4022 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4023 ASSERT_GT(audio_candidates_caller->count(), 0u);
4024 ASSERT_GT(audio_candidates_callee->count(), 0u);
4025 std::string caller_candidate_post_restart;
4026 ASSERT_TRUE(
4027 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4028 std::string callee_candidate_post_restart;
4029 ASSERT_TRUE(
4030 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4031 desc = caller()->pc()->local_description()->description();
4032 std::string caller_ufrag_post_restart =
4033 desc->transport_infos()[0].description.ice_ufrag;
4034 desc = callee()->pc()->local_description()->description();
4035 std::string callee_ufrag_post_restart =
4036 desc->transport_infos()[0].description.ice_ufrag;
4037 // Sanity check that an ICE restart was actually negotiated in SDP.
4038 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4039 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4040 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4041 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
4042
4043 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004044 MediaExpectations media_expectations;
4045 media_expectations.ExpectBidirectionalAudioAndVideo();
4046 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004047}
4048
4049// Verify that audio/video can be received end-to-end when ICE renomination is
4050// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004051TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004052 PeerConnectionInterface::RTCConfiguration config;
4053 config.enable_ice_renomination = true;
4054 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4055 ConnectFakeSignaling();
4056 // Do normal offer/answer and wait for some frames to be received in each
4057 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004058 caller()->AddAudioVideoTracks();
4059 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004060 caller()->CreateAndSetAndSignalOffer();
4061 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4062 // Sanity check that ICE renomination was actually negotiated.
4063 const cricket::SessionDescription* desc =
4064 caller()->pc()->local_description()->description();
4065 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07004066 ASSERT_NE(
4067 info.description.transport_options.end(),
4068 std::find(info.description.transport_options.begin(),
4069 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004070 }
4071 desc = callee()->pc()->local_description()->description();
4072 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07004073 ASSERT_NE(
4074 info.description.transport_options.end(),
4075 std::find(info.description.transport_options.begin(),
4076 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004077 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004078 MediaExpectations media_expectations;
4079 media_expectations.ExpectBidirectionalAudioAndVideo();
4080 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004081}
4082
Steve Anton6f25b092017-10-23 09:39:20 -07004083// With a max bundle policy and RTCP muxing, adding a new media description to
4084// the connection should not affect ICE at all because the new media will use
4085// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004086TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004087 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004088 PeerConnectionInterface::RTCConfiguration config;
4089 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4090 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4091 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4092 config, PeerConnectionInterface::RTCConfiguration()));
4093 ConnectFakeSignaling();
4094
Steve Anton15324772018-01-16 10:26:49 -08004095 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004096 caller()->CreateAndSetAndSignalOffer();
4097 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004098 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4099 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004100
4101 caller()->clear_ice_connection_state_history();
4102
Steve Anton15324772018-01-16 10:26:49 -08004103 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004104 caller()->CreateAndSetAndSignalOffer();
4105 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4106
4107 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4108}
4109
deadbeef1dcb1642017-03-29 21:08:16 -07004110// This test sets up a call between two parties with audio and video. It then
4111// renegotiates setting the video m-line to "port 0", then later renegotiates
4112// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004113TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004114 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4115 ASSERT_TRUE(CreatePeerConnectionWrappers());
4116 ConnectFakeSignaling();
4117
4118 // Do initial negotiation, only sending media from the caller. Will result in
4119 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004120 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004121 caller()->CreateAndSetAndSignalOffer();
4122 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4123
4124 // Negotiate again, disabling the video "m=" section (the callee will set the
4125 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004126 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4127 PeerConnectionInterface::RTCOfferAnswerOptions options;
4128 options.offer_to_receive_video = 0;
4129 callee()->SetOfferAnswerOptions(options);
4130 } else {
4131 callee()->SetRemoteOfferHandler([this] {
4132 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4133 });
4134 }
deadbeef1dcb1642017-03-29 21:08:16 -07004135 caller()->CreateAndSetAndSignalOffer();
4136 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4137 // Sanity check that video "m=" section was actually rejected.
4138 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4139 callee()->pc()->local_description()->description());
4140 ASSERT_NE(nullptr, answer_video_content);
4141 ASSERT_TRUE(answer_video_content->rejected);
4142
4143 // Enable video and do negotiation again, making sure video is received
4144 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004145 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4146 PeerConnectionInterface::RTCOfferAnswerOptions options;
4147 options.offer_to_receive_video = 1;
4148 callee()->SetOfferAnswerOptions(options);
4149 } else {
4150 // The caller's transceiver is stopped, so we need to add another track.
4151 auto caller_transceiver =
4152 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4153 EXPECT_TRUE(caller_transceiver->stopped());
4154 caller()->AddVideoTrack();
4155 }
4156 callee()->AddVideoTrack();
4157 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004158 caller()->CreateAndSetAndSignalOffer();
4159 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004160
deadbeef1dcb1642017-03-29 21:08:16 -07004161 // Verify the caller receives frames from the newly added stream, and the
4162 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004163 MediaExpectations media_expectations;
4164 media_expectations.CalleeExpectsSomeAudio();
4165 media_expectations.ExpectBidirectionalVideo();
4166 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004167}
4168
deadbeef1dcb1642017-03-29 21:08:16 -07004169// This tests that if we negotiate after calling CreateSender but before we
4170// have a track, then set a track later, frames from the newly-set track are
4171// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004172TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004173 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4174 ASSERT_TRUE(CreatePeerConnectionWrappers());
4175 ConnectFakeSignaling();
4176 auto caller_audio_sender =
4177 caller()->pc()->CreateSender("audio", "caller_stream");
4178 auto caller_video_sender =
4179 caller()->pc()->CreateSender("video", "caller_stream");
4180 auto callee_audio_sender =
4181 callee()->pc()->CreateSender("audio", "callee_stream");
4182 auto callee_video_sender =
4183 callee()->pc()->CreateSender("video", "callee_stream");
4184 caller()->CreateAndSetAndSignalOffer();
4185 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4186 // Wait for ICE to complete, without any tracks being set.
4187 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4188 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4189 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4190 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4191 // Now set the tracks, and expect frames to immediately start flowing.
4192 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4193 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4194 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4195 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004196 MediaExpectations media_expectations;
4197 media_expectations.ExpectBidirectionalAudioAndVideo();
4198 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4199}
4200
4201// This tests that if we negotiate after calling AddTransceiver but before we
4202// have a track, then set a track later, frames from the newly-set tracks are
4203// received end-to-end.
4204TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4205 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4206 ASSERT_TRUE(CreatePeerConnectionWrappers());
4207 ConnectFakeSignaling();
4208 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4209 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4210 auto caller_audio_sender = audio_result.MoveValue()->sender();
4211 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4212 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4213 auto caller_video_sender = video_result.MoveValue()->sender();
4214 callee()->SetRemoteOfferHandler([this] {
4215 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4216 callee()->pc()->GetTransceivers()[0]->SetDirection(
4217 RtpTransceiverDirection::kSendRecv);
4218 callee()->pc()->GetTransceivers()[1]->SetDirection(
4219 RtpTransceiverDirection::kSendRecv);
4220 });
4221 caller()->CreateAndSetAndSignalOffer();
4222 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4223 // Wait for ICE to complete, without any tracks being set.
4224 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4225 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4226 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4227 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4228 // Now set the tracks, and expect frames to immediately start flowing.
4229 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4230 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4231 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4232 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4233 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4234 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4235 MediaExpectations media_expectations;
4236 media_expectations.ExpectBidirectionalAudioAndVideo();
4237 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004238}
4239
4240// This test verifies that a remote video track can be added via AddStream,
4241// and sent end-to-end. For this particular test, it's simply echoed back
4242// from the caller to the callee, rather than being forwarded to a third
4243// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004244TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004245 ASSERT_TRUE(CreatePeerConnectionWrappers());
4246 ConnectFakeSignaling();
4247 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004248 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004249 caller()->CreateAndSetAndSignalOffer();
4250 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004251 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004252
4253 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4254 // time).
4255 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4256 callee()->CreateAndSetAndSignalOffer();
4257 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4258
Seth Hampson2f0d7022018-02-20 11:54:42 -08004259 MediaExpectations media_expectations;
4260 media_expectations.ExpectBidirectionalVideo();
4261 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004262}
4263
4264// Test that we achieve the expected end-to-end connection time, using a
4265// fake clock and simulated latency on the media and signaling paths.
4266// We use a TURN<->TURN connection because this is usually the quickest to
4267// set up initially, especially when we're confident the connection will work
4268// and can start sending media before we get a STUN response.
4269//
4270// With various optimizations enabled, here are the network delays we expect to
4271// be on the critical path:
4272// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4273// signaling answer (with DTLS fingerprint).
4274// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4275// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4276// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004277TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004278 rtc::ScopedFakeClock fake_clock;
4279 // Some things use a time of "0" as a special value, so we need to start out
4280 // the fake clock at a nonzero time.
4281 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004282 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004283
4284 static constexpr int media_hop_delay_ms = 50;
4285 static constexpr int signaling_trip_delay_ms = 500;
4286 // For explanation of these values, see comment above.
4287 static constexpr int required_media_hops = 9;
4288 static constexpr int required_signaling_trips = 2;
4289 // For internal delays (such as posting an event asychronously).
4290 static constexpr int allowed_internal_delay_ms = 20;
4291 static constexpr int total_connection_time_ms =
4292 media_hop_delay_ms * required_media_hops +
4293 signaling_trip_delay_ms * required_signaling_trips +
4294 allowed_internal_delay_ms;
4295
4296 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4297 3478};
4298 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4299 0};
4300 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4301 3478};
4302 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4303 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004304 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4305 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004306
Seth Hampsonaed71642018-06-11 07:41:32 -07004307 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4308 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004309 // Bypass permission check on received packets so media can be sent before
4310 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004311 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4312 turn_server_1->set_enable_permission_checks(false);
4313 });
4314 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4315 turn_server_2->set_enable_permission_checks(false);
4316 });
deadbeef1dcb1642017-03-29 21:08:16 -07004317
4318 PeerConnectionInterface::RTCConfiguration client_1_config;
4319 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4320 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4321 ice_server_1.username = "test";
4322 ice_server_1.password = "test";
4323 client_1_config.servers.push_back(ice_server_1);
4324 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4325 client_1_config.presume_writable_when_fully_relayed = true;
4326
4327 PeerConnectionInterface::RTCConfiguration client_2_config;
4328 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4329 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4330 ice_server_2.username = "test";
4331 ice_server_2.password = "test";
4332 client_2_config.servers.push_back(ice_server_2);
4333 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4334 client_2_config.presume_writable_when_fully_relayed = true;
4335
4336 ASSERT_TRUE(
4337 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4338 // Set up the simulated delays.
4339 SetSignalingDelayMs(signaling_trip_delay_ms);
4340 ConnectFakeSignaling();
4341 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4342 virtual_socket_server()->UpdateDelayDistribution();
4343
4344 // Set "offer to receive audio/video" without adding any tracks, so we just
4345 // set up ICE/DTLS with no media.
4346 PeerConnectionInterface::RTCOfferAnswerOptions options;
4347 options.offer_to_receive_audio = 1;
4348 options.offer_to_receive_video = 1;
4349 caller()->SetOfferAnswerOptions(options);
4350 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004351 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4352 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004353 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4354 // If this is not done a DCHECK can be hit in ports.cc, because a large
4355 // negative number is calculated for the rtt due to the global clock changing.
4356 caller()->pc()->Close();
4357 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07004358}
4359
Jonas Orelandbdcee282017-10-10 14:01:40 +02004360// Verify that a TurnCustomizer passed in through RTCConfiguration
4361// is actually used by the underlying TURN candidate pair.
4362// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004363TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004364 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4365 3478};
4366 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4367 0};
4368 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4369 3478};
4370 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4371 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004372 CreateTurnServer(turn_server_1_internal_address,
4373 turn_server_1_external_address);
4374 CreateTurnServer(turn_server_2_internal_address,
4375 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004376
4377 PeerConnectionInterface::RTCConfiguration client_1_config;
4378 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4379 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4380 ice_server_1.username = "test";
4381 ice_server_1.password = "test";
4382 client_1_config.servers.push_back(ice_server_1);
4383 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004384 auto* customizer1 = CreateTurnCustomizer();
4385 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004386
4387 PeerConnectionInterface::RTCConfiguration client_2_config;
4388 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4389 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4390 ice_server_2.username = "test";
4391 ice_server_2.password = "test";
4392 client_2_config.servers.push_back(ice_server_2);
4393 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004394 auto* customizer2 = CreateTurnCustomizer();
4395 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004396
4397 ASSERT_TRUE(
4398 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4399 ConnectFakeSignaling();
4400
4401 // Set "offer to receive audio/video" without adding any tracks, so we just
4402 // set up ICE/DTLS with no media.
4403 PeerConnectionInterface::RTCOfferAnswerOptions options;
4404 options.offer_to_receive_audio = 1;
4405 options.offer_to_receive_video = 1;
4406 caller()->SetOfferAnswerOptions(options);
4407 caller()->CreateAndSetAndSignalOffer();
4408 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4409
Seth Hampsonaed71642018-06-11 07:41:32 -07004410 ExpectTurnCustomizerCountersIncremented(customizer1);
4411 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004412}
4413
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004414// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4415// send media between the caller and the callee.
4416TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4417 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4418 3478};
4419 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4420
4421 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004422 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4423 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004424
4425 webrtc::PeerConnectionInterface::IceServer ice_server;
4426 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4427 ice_server.username = "test";
4428 ice_server.password = "test";
4429
4430 PeerConnectionInterface::RTCConfiguration client_1_config;
4431 client_1_config.servers.push_back(ice_server);
4432 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4433
4434 PeerConnectionInterface::RTCConfiguration client_2_config;
4435 client_2_config.servers.push_back(ice_server);
4436 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4437
4438 ASSERT_TRUE(
4439 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4440
4441 // Do normal offer/answer and wait for ICE to complete.
4442 ConnectFakeSignaling();
4443 caller()->AddAudioVideoTracks();
4444 callee()->AddAudioVideoTracks();
4445 caller()->CreateAndSetAndSignalOffer();
4446 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4447 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4448 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4449
4450 MediaExpectations media_expectations;
4451 media_expectations.ExpectBidirectionalAudioAndVideo();
4452 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4453}
4454
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004455// Verify that a SSLCertificateVerifier passed in through
4456// PeerConnectionDependencies is actually used by the underlying SSL
4457// implementation to determine whether a certificate presented by the TURN
4458// server is accepted by the client. Note that openssladapter_unittest.cc
4459// contains more detailed, lower-level tests.
4460TEST_P(PeerConnectionIntegrationTest,
4461 SSLCertificateVerifierUsedForTurnConnections) {
4462 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4463 3478};
4464 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4465
4466 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4467 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004468 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4469 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004470
4471 webrtc::PeerConnectionInterface::IceServer ice_server;
4472 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4473 ice_server.username = "test";
4474 ice_server.password = "test";
4475
4476 PeerConnectionInterface::RTCConfiguration client_1_config;
4477 client_1_config.servers.push_back(ice_server);
4478 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4479
4480 PeerConnectionInterface::RTCConfiguration client_2_config;
4481 client_2_config.servers.push_back(ice_server);
4482 // Setting the type to kRelay forces the connection to go through a TURN
4483 // server.
4484 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4485
4486 // Get a copy to the pointer so we can verify calls later.
4487 rtc::TestCertificateVerifier* client_1_cert_verifier =
4488 new rtc::TestCertificateVerifier();
4489 client_1_cert_verifier->verify_certificate_ = true;
4490 rtc::TestCertificateVerifier* client_2_cert_verifier =
4491 new rtc::TestCertificateVerifier();
4492 client_2_cert_verifier->verify_certificate_ = true;
4493
4494 // Create the dependencies with the test certificate verifier.
4495 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4496 client_1_deps.tls_cert_verifier =
4497 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4498 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4499 client_2_deps.tls_cert_verifier =
4500 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4501
4502 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4503 client_1_config, std::move(client_1_deps), client_2_config,
4504 std::move(client_2_deps)));
4505 ConnectFakeSignaling();
4506
4507 // Set "offer to receive audio/video" without adding any tracks, so we just
4508 // set up ICE/DTLS with no media.
4509 PeerConnectionInterface::RTCOfferAnswerOptions options;
4510 options.offer_to_receive_audio = 1;
4511 options.offer_to_receive_video = 1;
4512 caller()->SetOfferAnswerOptions(options);
4513 caller()->CreateAndSetAndSignalOffer();
4514 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4515
4516 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4517 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004518}
4519
4520TEST_P(PeerConnectionIntegrationTest,
4521 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4522 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4523 3478};
4524 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4525
4526 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4527 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004528 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4529 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004530
4531 webrtc::PeerConnectionInterface::IceServer ice_server;
4532 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4533 ice_server.username = "test";
4534 ice_server.password = "test";
4535
4536 PeerConnectionInterface::RTCConfiguration client_1_config;
4537 client_1_config.servers.push_back(ice_server);
4538 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4539
4540 PeerConnectionInterface::RTCConfiguration client_2_config;
4541 client_2_config.servers.push_back(ice_server);
4542 // Setting the type to kRelay forces the connection to go through a TURN
4543 // server.
4544 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4545
4546 // Get a copy to the pointer so we can verify calls later.
4547 rtc::TestCertificateVerifier* client_1_cert_verifier =
4548 new rtc::TestCertificateVerifier();
4549 client_1_cert_verifier->verify_certificate_ = false;
4550 rtc::TestCertificateVerifier* client_2_cert_verifier =
4551 new rtc::TestCertificateVerifier();
4552 client_2_cert_verifier->verify_certificate_ = false;
4553
4554 // Create the dependencies with the test certificate verifier.
4555 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4556 client_1_deps.tls_cert_verifier =
4557 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4558 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4559 client_2_deps.tls_cert_verifier =
4560 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4561
4562 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4563 client_1_config, std::move(client_1_deps), client_2_config,
4564 std::move(client_2_deps)));
4565 ConnectFakeSignaling();
4566
4567 // Set "offer to receive audio/video" without adding any tracks, so we just
4568 // set up ICE/DTLS with no media.
4569 PeerConnectionInterface::RTCOfferAnswerOptions options;
4570 options.offer_to_receive_audio = 1;
4571 options.offer_to_receive_video = 1;
4572 caller()->SetOfferAnswerOptions(options);
4573 caller()->CreateAndSetAndSignalOffer();
4574 bool wait_res = true;
4575 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4576 // properly, should be able to just wait for a state of "failed" instead of
4577 // waiting a fixed 10 seconds.
4578 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4579 ASSERT_FALSE(wait_res);
4580
4581 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4582 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004583}
4584
deadbeefc964d0b2017-04-03 10:03:35 -07004585// Test that audio and video flow end-to-end when codec names don't use the
4586// expected casing, given that they're supposed to be case insensitive. To test
4587// this, all but one codec is removed from each media description, and its
4588// casing is changed.
4589//
4590// In the past, this has regressed and caused crashes/black video, due to the
4591// fact that code at some layers was doing case-insensitive comparisons and
4592// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004593TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004594 ASSERT_TRUE(CreatePeerConnectionWrappers());
4595 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004596 caller()->AddAudioVideoTracks();
4597 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004598
4599 // Remove all but one audio/video codec (opus and VP8), and change the
4600 // casing of the caller's generated offer.
4601 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4602 cricket::AudioContentDescription* audio =
4603 GetFirstAudioContentDescription(description);
4604 ASSERT_NE(nullptr, audio);
4605 auto audio_codecs = audio->codecs();
4606 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4607 [](const cricket::AudioCodec& codec) {
4608 return codec.name != "opus";
4609 }),
4610 audio_codecs.end());
4611 ASSERT_EQ(1u, audio_codecs.size());
4612 audio_codecs[0].name = "OpUs";
4613 audio->set_codecs(audio_codecs);
4614
4615 cricket::VideoContentDescription* video =
4616 GetFirstVideoContentDescription(description);
4617 ASSERT_NE(nullptr, video);
4618 auto video_codecs = video->codecs();
4619 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4620 [](const cricket::VideoCodec& codec) {
4621 return codec.name != "VP8";
4622 }),
4623 video_codecs.end());
4624 ASSERT_EQ(1u, video_codecs.size());
4625 video_codecs[0].name = "vP8";
4626 video->set_codecs(video_codecs);
4627 });
4628
4629 caller()->CreateAndSetAndSignalOffer();
4630 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4631
4632 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004633 MediaExpectations media_expectations;
4634 media_expectations.ExpectBidirectionalAudioAndVideo();
4635 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004636}
4637
Jonas Oreland49ac5952018-09-26 16:04:32 +02004638TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004639 ASSERT_TRUE(CreatePeerConnectionWrappers());
4640 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004641 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004642 caller()->CreateAndSetAndSignalOffer();
4643 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004644 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004645 MediaExpectations media_expectations;
4646 media_expectations.CalleeExpectsSomeAudio(1);
4647 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004648 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004649 auto receiver = callee()->pc()->GetReceivers()[0];
4650 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004651 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004652 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4653 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004654 sources[0].source_id());
4655 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4656}
4657
4658TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4659 ASSERT_TRUE(CreatePeerConnectionWrappers());
4660 ConnectFakeSignaling();
4661 caller()->AddVideoTrack();
4662 caller()->CreateAndSetAndSignalOffer();
4663 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4664 // Wait for one video frame to be received by the callee.
4665 MediaExpectations media_expectations;
4666 media_expectations.CalleeExpectsSomeVideo(1);
4667 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4668 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4669 auto receiver = callee()->pc()->GetReceivers()[0];
4670 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4671 auto sources = receiver->GetSources();
4672 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4673 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4674 sources[0].source_id());
4675 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004676}
4677
deadbeef2f425aa2017-04-14 10:41:32 -07004678// Test that if a track is removed and added again with a different stream ID,
4679// the new stream ID is successfully communicated in SDP and media continues to
4680// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004681// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4682// it will not reuse a transceiver that has already been sending. After creating
4683// a new transceiver it tries to create an offer with two senders of the same
4684// track ids and it fails.
4685TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004686 ASSERT_TRUE(CreatePeerConnectionWrappers());
4687 ConnectFakeSignaling();
4688
deadbeef2f425aa2017-04-14 10:41:32 -07004689 // Add track using stream 1, do offer/answer.
4690 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4691 caller()->CreateLocalAudioTrack();
4692 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004693 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004694 caller()->CreateAndSetAndSignalOffer();
4695 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004696 {
4697 MediaExpectations media_expectations;
4698 media_expectations.CalleeExpectsSomeAudio(1);
4699 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4700 }
deadbeef2f425aa2017-04-14 10:41:32 -07004701 // Remove the sender, and create a new one with the new stream.
4702 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004703 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004704 caller()->CreateAndSetAndSignalOffer();
4705 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4706 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004707 {
4708 MediaExpectations media_expectations;
4709 media_expectations.CalleeExpectsSomeAudio();
4710 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4711 }
deadbeef2f425aa2017-04-14 10:41:32 -07004712}
4713
Seth Hampson2f0d7022018-02-20 11:54:42 -08004714TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004715 ASSERT_TRUE(CreatePeerConnectionWrappers());
4716 ConnectFakeSignaling();
4717
Karl Wiberg918f50c2018-07-05 11:40:33 +02004718 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Elad Alon99c3fe52017-10-13 16:29:40 +02004719 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
4720 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
4721 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004722 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4723 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004724
Steve Anton15324772018-01-16 10:26:49 -08004725 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004726 caller()->CreateAndSetAndSignalOffer();
4727 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4728}
4729
Steve Antonede9ca52017-10-16 13:04:27 -07004730// Test that if candidates are only signaled by applying full session
4731// descriptions (instead of using AddIceCandidate), the peers can connect to
4732// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004733TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004734 ASSERT_TRUE(CreatePeerConnectionWrappers());
4735 // Each side will signal the session descriptions but not candidates.
4736 ConnectFakeSignalingForSdpOnly();
4737
4738 // Add audio video track and exchange the initial offer/answer with media
4739 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004740 caller()->AddAudioVideoTracks();
4741 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004742 caller()->CreateAndSetAndSignalOffer();
4743
4744 // Wait for all candidates to be gathered on both the caller and callee.
4745 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4746 caller()->ice_gathering_state(), kDefaultTimeout);
4747 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4748 callee()->ice_gathering_state(), kDefaultTimeout);
4749
4750 // The candidates will now be included in the session description, so
4751 // signaling them will start the ICE connection.
4752 caller()->CreateAndSetAndSignalOffer();
4753 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4754
4755 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004756 MediaExpectations media_expectations;
4757 media_expectations.ExpectBidirectionalAudioAndVideo();
4758 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004759}
4760
henrika5f6bf242017-11-01 11:06:56 +01004761// Test that SetAudioPlayout can be used to disable audio playout from the
4762// start, then later enable it. This may be useful, for example, if the caller
4763// needs to play a local ringtone until some event occurs, after which it
4764// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004765TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004766 ASSERT_TRUE(CreatePeerConnectionWrappers());
4767 ConnectFakeSignaling();
4768
4769 // Set up audio-only call where audio playout is disabled on caller's side.
4770 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004771 caller()->AddAudioTrack();
4772 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004773 caller()->CreateAndSetAndSignalOffer();
4774 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4775
4776 // Pump messages for a second.
4777 WAIT(false, 1000);
4778 // Since audio playout is disabled, the caller shouldn't have received
4779 // anything (at the playout level, at least).
4780 EXPECT_EQ(0, caller()->audio_frames_received());
4781 // As a sanity check, make sure the callee (for which playout isn't disabled)
4782 // did still see frames on its audio level.
4783 ASSERT_GT(callee()->audio_frames_received(), 0);
4784
4785 // Enable playout again, and ensure audio starts flowing.
4786 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004787 MediaExpectations media_expectations;
4788 media_expectations.ExpectBidirectionalAudio();
4789 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004790}
4791
4792double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4793 auto report = pc->NewGetStats();
4794 auto track_stats_list =
4795 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4796 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4797 for (const auto* track_stats : track_stats_list) {
4798 if (track_stats->remote_source.is_defined() &&
4799 *track_stats->remote_source) {
4800 remote_track_stats = track_stats;
4801 break;
4802 }
4803 }
4804
4805 if (!remote_track_stats->total_audio_energy.is_defined()) {
4806 return 0.0;
4807 }
4808 return *remote_track_stats->total_audio_energy;
4809}
4810
4811// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4812// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004813TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004814 DisableAudioPlayoutStillGeneratesAudioStats) {
4815 ASSERT_TRUE(CreatePeerConnectionWrappers());
4816 ConnectFakeSignaling();
4817
4818 // Set up audio-only call where playout is disabled but audio-processing is
4819 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004820 caller()->AddAudioTrack();
4821 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004822 caller()->pc()->SetAudioPlayout(false);
4823
4824 caller()->CreateAndSetAndSignalOffer();
4825 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4826
4827 // Wait for the callee to receive audio stats.
4828 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4829}
4830
henrika4f167df2017-11-01 14:45:55 +01004831// Test that SetAudioRecording can be used to disable audio recording from the
4832// start, then later enable it. This may be useful, for example, if the caller
4833// wants to ensure that no audio resources are active before a certain state
4834// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004835TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004836 ASSERT_TRUE(CreatePeerConnectionWrappers());
4837 ConnectFakeSignaling();
4838
4839 // Set up audio-only call where audio recording is disabled on caller's side.
4840 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08004841 caller()->AddAudioTrack();
4842 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01004843 caller()->CreateAndSetAndSignalOffer();
4844 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4845
4846 // Pump messages for a second.
4847 WAIT(false, 1000);
4848 // Since caller has disabled audio recording, the callee shouldn't have
4849 // received anything.
4850 EXPECT_EQ(0, callee()->audio_frames_received());
4851 // As a sanity check, make sure the caller did still see frames on its
4852 // audio level since audio recording is enabled on the calle side.
4853 ASSERT_GT(caller()->audio_frames_received(), 0);
4854
4855 // Enable audio recording again, and ensure audio starts flowing.
4856 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004857 MediaExpectations media_expectations;
4858 media_expectations.ExpectBidirectionalAudio();
4859 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01004860}
4861
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004862// Test that after closing PeerConnections, they stop sending any packets (ICE,
4863// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004864TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004865 // Set up audio/video/data, wait for some frames to be received.
4866 ASSERT_TRUE(CreatePeerConnectionWrappers());
4867 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004868 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004869#ifdef HAVE_SCTP
4870 caller()->CreateDataChannel();
4871#endif
4872 caller()->CreateAndSetAndSignalOffer();
4873 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004874 MediaExpectations media_expectations;
4875 media_expectations.CalleeExpectsSomeAudioAndVideo();
4876 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004877 // Close PeerConnections.
4878 caller()->pc()->Close();
4879 callee()->pc()->Close();
4880 // Pump messages for a second, and ensure no new packets end up sent.
4881 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
4882 WAIT(false, 1000);
4883 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
4884 EXPECT_EQ(sent_packets_a, sent_packets_b);
4885}
4886
Steve Anton7eca0932018-03-30 15:18:41 -07004887// Test that transport stats are generated by the RTCStatsCollector for a
4888// connection that only involves data channels. This is a regression test for
4889// crbug.com/826972.
4890#ifdef HAVE_SCTP
4891TEST_P(PeerConnectionIntegrationTest,
4892 TransportStatsReportedForDataChannelOnlyConnection) {
4893 ASSERT_TRUE(CreatePeerConnectionWrappers());
4894 ConnectFakeSignaling();
4895 caller()->CreateDataChannel();
4896
4897 caller()->CreateAndSetAndSignalOffer();
4898 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4899 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
4900
4901 auto caller_report = caller()->NewGetStats();
4902 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
4903 auto callee_report = callee()->NewGetStats();
4904 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
4905}
4906#endif // HAVE_SCTP
4907
Qingsi Wang7685e862018-06-11 20:15:46 -07004908TEST_P(PeerConnectionIntegrationTest,
4909 IceEventsGeneratedAndLoggedInRtcEventLog) {
4910 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
4911 ConnectFakeSignaling();
4912 PeerConnectionInterface::RTCOfferAnswerOptions options;
4913 options.offer_to_receive_audio = 1;
4914 caller()->SetOfferAnswerOptions(options);
4915 caller()->CreateAndSetAndSignalOffer();
4916 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4917 ASSERT_NE(nullptr, caller()->event_log_factory());
4918 ASSERT_NE(nullptr, callee()->event_log_factory());
4919 webrtc::FakeRtcEventLog* caller_event_log =
4920 static_cast<webrtc::FakeRtcEventLog*>(
4921 caller()->event_log_factory()->last_log_created());
4922 webrtc::FakeRtcEventLog* callee_event_log =
4923 static_cast<webrtc::FakeRtcEventLog*>(
4924 callee()->event_log_factory()->last_log_created());
4925 ASSERT_NE(nullptr, caller_event_log);
4926 ASSERT_NE(nullptr, callee_event_log);
4927 int caller_ice_config_count = caller_event_log->GetEventCount(
4928 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4929 int caller_ice_event_count = caller_event_log->GetEventCount(
4930 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4931 int callee_ice_config_count = callee_event_log->GetEventCount(
4932 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4933 int callee_ice_event_count = callee_event_log->GetEventCount(
4934 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4935 EXPECT_LT(0, caller_ice_config_count);
4936 EXPECT_LT(0, caller_ice_event_count);
4937 EXPECT_LT(0, callee_ice_config_count);
4938 EXPECT_LT(0, callee_ice_event_count);
4939}
4940
Seth Hampson2f0d7022018-02-20 11:54:42 -08004941INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
4942 PeerConnectionIntegrationTest,
4943 Values(SdpSemantics::kPlanB,
4944 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08004945
Steve Anton74255ff2018-01-24 18:32:57 -08004946// Tests that verify interoperability between Plan B and Unified Plan
4947// PeerConnections.
4948class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004949 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08004950 public ::testing::WithParamInterface<
4951 std::tuple<SdpSemantics, SdpSemantics>> {
4952 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004953 // Setting the SdpSemantics for the base test to kDefault does not matter
4954 // because we specify not to use the test semantics when creating
4955 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08004956 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07004957 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08004958 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08004959 callee_semantics_(std::get<1>(GetParam())) {}
4960
4961 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07004962 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
4963 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08004964 }
4965
4966 const SdpSemantics caller_semantics_;
4967 const SdpSemantics callee_semantics_;
4968};
4969
4970TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
4971 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4972 ConnectFakeSignaling();
4973
4974 caller()->CreateAndSetAndSignalOffer();
4975 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4976}
4977
4978TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
4979 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4980 ConnectFakeSignaling();
4981 auto audio_sender = caller()->AddAudioTrack();
4982
4983 caller()->CreateAndSetAndSignalOffer();
4984 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4985
4986 // Verify that one audio receiver has been created on the remote and that it
4987 // has the same track ID as the sending track.
4988 auto receivers = callee()->pc()->GetReceivers();
4989 ASSERT_EQ(1u, receivers.size());
4990 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
4991 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
4992
Seth Hampson2f0d7022018-02-20 11:54:42 -08004993 MediaExpectations media_expectations;
4994 media_expectations.CalleeExpectsSomeAudio();
4995 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004996}
4997
4998TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
4999 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5000 ConnectFakeSignaling();
5001 auto video_sender = caller()->AddVideoTrack();
5002 auto audio_sender = caller()->AddAudioTrack();
5003
5004 caller()->CreateAndSetAndSignalOffer();
5005 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5006
5007 // Verify that one audio and one video receiver have been created on the
5008 // remote and that they have the same track IDs as the sending tracks.
5009 auto audio_receivers =
5010 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5011 ASSERT_EQ(1u, audio_receivers.size());
5012 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5013 auto video_receivers =
5014 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5015 ASSERT_EQ(1u, video_receivers.size());
5016 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5017
Seth Hampson2f0d7022018-02-20 11:54:42 -08005018 MediaExpectations media_expectations;
5019 media_expectations.CalleeExpectsSomeAudioAndVideo();
5020 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005021}
5022
5023TEST_P(PeerConnectionIntegrationInteropTest,
5024 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5025 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5026 ConnectFakeSignaling();
5027 caller()->AddAudioVideoTracks();
5028 callee()->AddAudioVideoTracks();
5029
5030 caller()->CreateAndSetAndSignalOffer();
5031 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5032
Seth Hampson2f0d7022018-02-20 11:54:42 -08005033 MediaExpectations media_expectations;
5034 media_expectations.ExpectBidirectionalAudioAndVideo();
5035 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005036}
5037
5038TEST_P(PeerConnectionIntegrationInteropTest,
5039 ReverseRolesOneAudioLocalToOneVideoRemote) {
5040 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5041 ConnectFakeSignaling();
5042 caller()->AddAudioTrack();
5043 callee()->AddVideoTrack();
5044
5045 caller()->CreateAndSetAndSignalOffer();
5046 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5047
5048 // Verify that only the audio track has been negotiated.
5049 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5050 // Might also check that the callee's NegotiationNeeded flag is set.
5051
5052 // Reverse roles.
5053 callee()->CreateAndSetAndSignalOffer();
5054 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5055
Seth Hampson2f0d7022018-02-20 11:54:42 -08005056 MediaExpectations media_expectations;
5057 media_expectations.CallerExpectsSomeVideo();
5058 media_expectations.CalleeExpectsSomeAudio();
5059 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005060}
5061
Steve Antonba42e992018-04-09 14:10:01 -07005062INSTANTIATE_TEST_CASE_P(
5063 PeerConnectionIntegrationTest,
5064 PeerConnectionIntegrationInteropTest,
5065 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5066 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5067
5068// Test that if the Unified Plan side offers two video tracks then the Plan B
5069// side will only see the first one and ignore the second.
5070TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005071 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5072 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005073 ConnectFakeSignaling();
5074 auto first_sender = caller()->AddVideoTrack();
5075 caller()->AddVideoTrack();
5076
5077 caller()->CreateAndSetAndSignalOffer();
5078 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5079
5080 // Verify that there is only one receiver and it corresponds to the first
5081 // added track.
5082 auto receivers = callee()->pc()->GetReceivers();
5083 ASSERT_EQ(1u, receivers.size());
5084 EXPECT_TRUE(receivers[0]->track()->enabled());
5085 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5086
Seth Hampson2f0d7022018-02-20 11:54:42 -08005087 MediaExpectations media_expectations;
5088 media_expectations.CalleeExpectsSomeVideo();
5089 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005090}
5091
deadbeef1dcb1642017-03-29 21:08:16 -07005092} // namespace
5093
5094#endif // if !defined(THREAD_SANITIZER)