blob: dd69aebf568da411c3461b8ba902b6959a693725 [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);
154}
155
Seth Hampson5897a6e2018-04-03 11:16:33 -0700156// Removes all stream information besides the stream ids, simulating an
157// endpoint that only signals a=msid lines to convey stream_ids.
158void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
159 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700160 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700161 std::vector<std::string> stream_ids;
162 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700163 const StreamParams& first_stream =
164 content.media_description()->streams()[0];
165 track_id = first_stream.id;
166 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700167 }
168 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700169 StreamParams new_stream;
170 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700171 new_stream.set_stream_ids(stream_ids);
172 content.media_description()->AddStream(new_stream);
173 }
174}
175
zhihuangf8164932017-05-19 13:09:47 -0700176int FindFirstMediaStatsIndexByKind(
177 const std::string& kind,
178 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
179 media_stats_vec) {
180 for (size_t i = 0; i < media_stats_vec.size(); i++) {
181 if (media_stats_vec[i]->kind.ValueToString() == kind) {
182 return i;
183 }
184 }
185 return -1;
186}
187
deadbeef1dcb1642017-03-29 21:08:16 -0700188class SignalingMessageReceiver {
189 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800190 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700191 virtual void ReceiveIceMessage(const std::string& sdp_mid,
192 int sdp_mline_index,
193 const std::string& msg) = 0;
194
195 protected:
196 SignalingMessageReceiver() {}
197 virtual ~SignalingMessageReceiver() {}
198};
199
200class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
201 public:
202 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
203 : expected_media_type_(media_type) {}
204
205 void OnFirstPacketReceived(cricket::MediaType media_type) override {
206 ASSERT_EQ(expected_media_type_, media_type);
207 first_packet_received_ = true;
208 }
209
210 bool first_packet_received() const { return first_packet_received_; }
211
212 virtual ~MockRtpReceiverObserver() {}
213
214 private:
215 bool first_packet_received_ = false;
216 cricket::MediaType expected_media_type_;
217};
218
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700219// Used by PeerConnectionWrapper::OnIceCandidate to allow a test to modify an
220// ICE candidate before it is signaled.
221class IceCandidateReplacerInterface {
222 public:
223 virtual ~IceCandidateReplacerInterface() = default;
224 // Return nullptr to drop the candidate (it won't be signaled to the other
225 // side).
226 virtual std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
227 const webrtc::IceCandidateInterface*) = 0;
228};
229
deadbeef1dcb1642017-03-29 21:08:16 -0700230// Helper class that wraps a peer connection, observes it, and can accept
231// signaling messages from another wrapper.
232//
233// Uses a fake network, fake A/V capture, and optionally fake
234// encoders/decoders, though they aren't used by default since they don't
235// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700236// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800237// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700238class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800239 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700240 public:
241 // Different factory methods for convenience.
242 // TODO(deadbeef): Could use the pattern of:
243 //
244 // PeerConnectionWrapper =
245 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
246 //
247 // To reduce some code duplication.
248 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
249 const std::string& debug_name,
250 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
251 rtc::Thread* network_thread,
252 rtc::Thread* worker_thread) {
253 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700254 webrtc::PeerConnectionDependencies dependencies(nullptr);
255 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200256 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800257 worker_thread, nullptr,
258 /*media_transport_factory=*/nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700259 delete client;
260 return nullptr;
261 }
262 return client;
263 }
264
deadbeef2f425aa2017-04-14 10:41:32 -0700265 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
266 return peer_connection_factory_.get();
267 }
268
deadbeef1dcb1642017-03-29 21:08:16 -0700269 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
270
271 // If a signaling message receiver is set (via ConnectFakeSignaling), this
272 // will set the whole offer/answer exchange in motion. Just need to wait for
273 // the signaling state to reach "stable".
274 void CreateAndSetAndSignalOffer() {
275 auto offer = CreateOffer();
276 ASSERT_NE(nullptr, offer);
277 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
278 }
279
280 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
281 // when a remote offer is received (via fake signaling) and an answer is
282 // generated. By default, uses default options.
283 void SetOfferAnswerOptions(
284 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
285 offer_answer_options_ = options;
286 }
287
288 // Set a callback to be invoked when SDP is received via the fake signaling
289 // channel, which provides an opportunity to munge (modify) the SDP. This is
290 // used to test SDP being applied that a PeerConnection would normally not
291 // generate, but a non-JSEP endpoint might.
292 void SetReceivedSdpMunger(
293 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100294 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700295 }
296
deadbeefc964d0b2017-04-03 10:03:35 -0700297 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700298 // generated.
299 void SetGeneratedSdpMunger(
300 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100301 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700302 }
303
Seth Hampson2f0d7022018-02-20 11:54:42 -0800304 // Set a callback to be invoked when a remote offer is received via the fake
305 // signaling channel. This provides an opportunity to change the
306 // PeerConnection state before an answer is created and sent to the caller.
307 void SetRemoteOfferHandler(std::function<void()> handler) {
308 remote_offer_handler_ = std::move(handler);
309 }
310
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700311 void SetLocalIceCandidateReplacer(
312 std::unique_ptr<IceCandidateReplacerInterface> replacer) {
313 local_ice_candidate_replacer_ = std::move(replacer);
314 }
315
Steve Antonede9ca52017-10-16 13:04:27 -0700316 // Every ICE connection state in order that has been seen by the observer.
317 std::vector<PeerConnectionInterface::IceConnectionState>
318 ice_connection_state_history() const {
319 return ice_connection_state_history_;
320 }
Steve Anton6f25b092017-10-23 09:39:20 -0700321 void clear_ice_connection_state_history() {
322 ice_connection_state_history_.clear();
323 }
Steve Antonede9ca52017-10-16 13:04:27 -0700324
Jonas Olsson635474e2018-10-18 15:58:17 +0200325 // Every PeerConnection state in order that has been seen by the observer.
326 std::vector<PeerConnectionInterface::PeerConnectionState>
327 peer_connection_state_history() const {
328 return peer_connection_state_history_;
329 }
330
Steve Antonede9ca52017-10-16 13:04:27 -0700331 // Every ICE gathering state in order that has been seen by the observer.
332 std::vector<PeerConnectionInterface::IceGatheringState>
333 ice_gathering_state_history() const {
334 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700335 }
336
Steve Anton15324772018-01-16 10:26:49 -0800337 void AddAudioVideoTracks() {
338 AddAudioTrack();
339 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700340 }
341
Steve Anton74255ff2018-01-24 18:32:57 -0800342 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
343 return AddTrack(CreateLocalAudioTrack());
344 }
deadbeef1dcb1642017-03-29 21:08:16 -0700345
Steve Anton74255ff2018-01-24 18:32:57 -0800346 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
347 return AddTrack(CreateLocalVideoTrack());
348 }
deadbeef1dcb1642017-03-29 21:08:16 -0700349
350 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200351 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700352 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200353 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700354 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200355 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700356 // TODO(perkj): Test audio source when it is implemented. Currently audio
357 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700358 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700359 source);
360 }
361
362 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200363 webrtc::FakePeriodicVideoSource::Config config;
364 config.timestamp_offset_ms = rtc::TimeMillis();
365 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700366 }
367
368 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200369 CreateLocalVideoTrackWithConfig(
370 webrtc::FakePeriodicVideoSource::Config config) {
371 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700372 }
373
374 rtc::scoped_refptr<webrtc::VideoTrackInterface>
375 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200376 webrtc::FakePeriodicVideoSource::Config config;
377 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200378 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200379 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700380 }
381
Steve Anton74255ff2018-01-24 18:32:57 -0800382 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
383 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800384 const std::vector<std::string>& stream_ids = {}) {
385 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800386 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800387 return result.MoveValue();
388 }
389
390 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
391 cricket::MediaType media_type) {
392 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
393 for (auto receiver : pc()->GetReceivers()) {
394 if (receiver->media_type() == media_type) {
395 receivers.push_back(receiver);
396 }
397 }
398 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700399 }
400
Seth Hampson2f0d7022018-02-20 11:54:42 -0800401 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
402 cricket::MediaType media_type) {
403 for (auto transceiver : pc()->GetTransceivers()) {
404 if (transceiver->receiver()->media_type() == media_type) {
405 return transceiver;
406 }
407 }
408 return nullptr;
409 }
410
deadbeef1dcb1642017-03-29 21:08:16 -0700411 bool SignalingStateStable() {
412 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
413 }
414
415 void CreateDataChannel() { CreateDataChannel(nullptr); }
416
417 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700418 CreateDataChannel(kDataChannelLabel, init);
419 }
420
421 void CreateDataChannel(const std::string& label,
422 const webrtc::DataChannelInit* init) {
423 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700424 ASSERT_TRUE(data_channel_.get() != nullptr);
425 data_observer_.reset(new MockDataChannelObserver(data_channel_));
426 }
427
428 DataChannelInterface* data_channel() { return data_channel_; }
429 const MockDataChannelObserver* data_observer() const {
430 return data_observer_.get();
431 }
432
433 int audio_frames_received() const {
434 return fake_audio_capture_module_->frames_received();
435 }
436
437 // Takes minimum of video frames received for each track.
438 //
439 // Can be used like:
440 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
441 //
442 // To ensure that all video tracks received at least a certain number of
443 // frames.
444 int min_video_frames_received_per_track() const {
445 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200446 if (fake_video_renderers_.empty()) {
447 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700448 }
deadbeef1dcb1642017-03-29 21:08:16 -0700449
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200450 for (const auto& pair : fake_video_renderers_) {
451 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700452 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200453 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700454 }
455
456 // Returns a MockStatsObserver in a state after stats gathering finished,
457 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700458 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700459 webrtc::MediaStreamTrackInterface* track) {
460 rtc::scoped_refptr<MockStatsObserver> observer(
461 new rtc::RefCountedObject<MockStatsObserver>());
462 EXPECT_TRUE(peer_connection_->GetStats(
463 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
464 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
465 return observer;
466 }
467
468 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700469 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
470 return OldGetStatsForTrack(nullptr);
471 }
472
473 // Synchronously gets stats and returns them. If it times out, fails the test
474 // and returns null.
475 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
476 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
477 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
478 peer_connection_->GetStats(callback);
479 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
480 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700481 }
482
483 int rendered_width() {
484 EXPECT_FALSE(fake_video_renderers_.empty());
485 return fake_video_renderers_.empty()
486 ? 0
487 : fake_video_renderers_.begin()->second->width();
488 }
489
490 int rendered_height() {
491 EXPECT_FALSE(fake_video_renderers_.empty());
492 return fake_video_renderers_.empty()
493 ? 0
494 : fake_video_renderers_.begin()->second->height();
495 }
496
497 double rendered_aspect_ratio() {
498 if (rendered_height() == 0) {
499 return 0.0;
500 }
501 return static_cast<double>(rendered_width()) / rendered_height();
502 }
503
504 webrtc::VideoRotation rendered_rotation() {
505 EXPECT_FALSE(fake_video_renderers_.empty());
506 return fake_video_renderers_.empty()
507 ? webrtc::kVideoRotation_0
508 : fake_video_renderers_.begin()->second->rotation();
509 }
510
511 int local_rendered_width() {
512 return local_video_renderer_ ? local_video_renderer_->width() : 0;
513 }
514
515 int local_rendered_height() {
516 return local_video_renderer_ ? local_video_renderer_->height() : 0;
517 }
518
519 double local_rendered_aspect_ratio() {
520 if (local_rendered_height() == 0) {
521 return 0.0;
522 }
523 return static_cast<double>(local_rendered_width()) /
524 local_rendered_height();
525 }
526
527 size_t number_of_remote_streams() {
528 if (!pc()) {
529 return 0;
530 }
531 return pc()->remote_streams()->count();
532 }
533
534 StreamCollectionInterface* remote_streams() const {
535 if (!pc()) {
536 ADD_FAILURE();
537 return nullptr;
538 }
539 return pc()->remote_streams();
540 }
541
542 StreamCollectionInterface* local_streams() {
543 if (!pc()) {
544 ADD_FAILURE();
545 return nullptr;
546 }
547 return pc()->local_streams();
548 }
549
550 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
551 return pc()->signaling_state();
552 }
553
554 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
555 return pc()->ice_connection_state();
556 }
557
558 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
559 return pc()->ice_gathering_state();
560 }
561
562 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
563 // GetReceivers. They're updated automatically when a remote offer/answer
564 // from the fake signaling channel is applied, or when
565 // ResetRtpReceiverObservers below is called.
566 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
567 rtp_receiver_observers() {
568 return rtp_receiver_observers_;
569 }
570
571 void ResetRtpReceiverObservers() {
572 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100573 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
574 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700575 std::unique_ptr<MockRtpReceiverObserver> observer(
576 new MockRtpReceiverObserver(receiver->media_type()));
577 receiver->SetObserver(observer.get());
578 rtp_receiver_observers_.push_back(std::move(observer));
579 }
580 }
581
Steve Antonede9ca52017-10-16 13:04:27 -0700582 rtc::FakeNetworkManager* network() const {
583 return fake_network_manager_.get();
584 }
585 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
586
Qingsi Wang7685e862018-06-11 20:15:46 -0700587 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
588 return event_log_factory_;
589 }
590
deadbeef1dcb1642017-03-29 21:08:16 -0700591 private:
592 explicit PeerConnectionWrapper(const std::string& debug_name)
593 : debug_name_(debug_name) {}
594
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800595 bool Init(
596 const PeerConnectionFactory::Options* options,
597 const PeerConnectionInterface::RTCConfiguration* config,
598 webrtc::PeerConnectionDependencies dependencies,
599 rtc::Thread* network_thread,
600 rtc::Thread* worker_thread,
601 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
602 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700603 // There's an error in this test code if Init ends up being called twice.
604 RTC_DCHECK(!peer_connection_);
605 RTC_DCHECK(!peer_connection_factory_);
606
607 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700608 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700609
610 std::unique_ptr<cricket::PortAllocator> port_allocator(
611 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700612 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700613 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
614 if (!fake_audio_capture_module_) {
615 return false;
616 }
deadbeef1dcb1642017-03-29 21:08:16 -0700617 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700618
619 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
620 pc_factory_dependencies.network_thread = network_thread;
621 pc_factory_dependencies.worker_thread = worker_thread;
622 pc_factory_dependencies.signaling_thread = signaling_thread;
623 pc_factory_dependencies.media_engine =
624 cricket::WebRtcMediaEngineFactory::Create(
625 rtc::scoped_refptr<webrtc::AudioDeviceModule>(
626 fake_audio_capture_module_),
627 webrtc::CreateBuiltinAudioEncoderFactory(),
628 webrtc::CreateBuiltinAudioDecoderFactory(),
629 webrtc::CreateBuiltinVideoEncoderFactory(),
Qingsi Wang59844ce2018-11-01 04:45:53 +0000630 webrtc::CreateBuiltinVideoDecoderFactory(), nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -0700631 webrtc::AudioProcessingBuilder().Create());
632 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
633 if (event_log_factory) {
634 event_log_factory_ = event_log_factory.get();
635 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
636 } else {
637 pc_factory_dependencies.event_log_factory =
638 webrtc::CreateRtcEventLogFactory();
639 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800640 if (media_transport_factory) {
641 pc_factory_dependencies.media_transport_factory =
642 std::move(media_transport_factory);
643 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700644 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
645 std::move(pc_factory_dependencies));
646
deadbeef1dcb1642017-03-29 21:08:16 -0700647 if (!peer_connection_factory_) {
648 return false;
649 }
650 if (options) {
651 peer_connection_factory_->SetOptions(*options);
652 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800653 if (config) {
654 sdp_semantics_ = config->sdp_semantics;
655 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700656
657 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200658 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700659 return peer_connection_.get() != nullptr;
660 }
661
662 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700663 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700664 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700665 PeerConnectionInterface::RTCConfiguration modified_config;
666 // If |config| is null, this will result in a default configuration being
667 // used.
668 if (config) {
669 modified_config = *config;
670 }
671 // Disable resolution adaptation; we don't want it interfering with the
672 // test results.
673 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
674 // ratios and not specific resolutions, is this even necessary?
675 modified_config.set_cpu_adaptation(false);
676
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700677 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700678 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700679 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700680 }
681
682 void set_signaling_message_receiver(
683 SignalingMessageReceiver* signaling_message_receiver) {
684 signaling_message_receiver_ = signaling_message_receiver;
685 }
686
687 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
688
Steve Antonede9ca52017-10-16 13:04:27 -0700689 void set_signal_ice_candidates(bool signal) {
690 signal_ice_candidates_ = signal;
691 }
692
deadbeef1dcb1642017-03-29 21:08:16 -0700693 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200694 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700695 // Set max frame rate to 10fps to reduce the risk of test flakiness.
696 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200697 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700698
Niels Möller5c7efe72018-05-11 10:34:46 +0200699 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200700 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
701 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700702 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200703 peer_connection_factory_->CreateVideoTrack(
704 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700705 if (!local_video_renderer_) {
706 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
707 }
708 return track;
709 }
710
711 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100712 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800713 std::unique_ptr<SessionDescriptionInterface> desc =
714 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700715 if (received_sdp_munger_) {
716 received_sdp_munger_(desc->description());
717 }
718
719 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
720 // Setting a remote description may have changed the number of receivers,
721 // so reset the receiver observers.
722 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800723 if (remote_offer_handler_) {
724 remote_offer_handler_();
725 }
deadbeef1dcb1642017-03-29 21:08:16 -0700726 auto answer = CreateAnswer();
727 ASSERT_NE(nullptr, answer);
728 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
729 }
730
731 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100732 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800733 std::unique_ptr<SessionDescriptionInterface> desc =
734 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700735 if (received_sdp_munger_) {
736 received_sdp_munger_(desc->description());
737 }
738
739 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
740 // Set the RtpReceiverObserver after receivers are created.
741 ResetRtpReceiverObservers();
742 }
743
744 // Returns null on failure.
745 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
746 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
747 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
748 pc()->CreateOffer(observer, offer_answer_options_);
749 return WaitForDescriptionFromObserver(observer);
750 }
751
752 // Returns null on failure.
753 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
754 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
755 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
756 pc()->CreateAnswer(observer, offer_answer_options_);
757 return WaitForDescriptionFromObserver(observer);
758 }
759
760 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100761 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700762 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
763 if (!observer->result()) {
764 return nullptr;
765 }
766 auto description = observer->MoveDescription();
767 if (generated_sdp_munger_) {
768 generated_sdp_munger_(description->description());
769 }
770 return description;
771 }
772
773 // Setting the local description and sending the SDP message over the fake
774 // signaling channel are combined into the same method because the SDP
775 // message needs to be sent as soon as SetLocalDescription finishes, without
776 // waiting for the observer to be called. This ensures that ICE candidates
777 // don't outrace the description.
778 bool SetLocalDescriptionAndSendSdpMessage(
779 std::unique_ptr<SessionDescriptionInterface> desc) {
780 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
781 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100782 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800783 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700784 std::string sdp;
785 EXPECT_TRUE(desc->ToString(&sdp));
786 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800787 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
788 RemoveUnusedVideoRenderers();
789 }
deadbeef1dcb1642017-03-29 21:08:16 -0700790 // As mentioned above, we need to send the message immediately after
791 // SetLocalDescription.
792 SendSdpMessage(type, sdp);
793 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
794 return true;
795 }
796
797 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
798 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
799 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100800 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700801 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800802 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
803 RemoveUnusedVideoRenderers();
804 }
deadbeef1dcb1642017-03-29 21:08:16 -0700805 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
806 return observer->result();
807 }
808
Seth Hampson2f0d7022018-02-20 11:54:42 -0800809 // This is a work around to remove unused fake_video_renderers from
810 // transceivers that have either stopped or are no longer receiving.
811 void RemoveUnusedVideoRenderers() {
812 auto transceivers = pc()->GetTransceivers();
813 for (auto& transceiver : transceivers) {
814 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
815 continue;
816 }
817 // Remove fake video renderers from any stopped transceivers.
818 if (transceiver->stopped()) {
819 auto it =
820 fake_video_renderers_.find(transceiver->receiver()->track()->id());
821 if (it != fake_video_renderers_.end()) {
822 fake_video_renderers_.erase(it);
823 }
824 }
825 // Remove fake video renderers from any transceivers that are no longer
826 // receiving.
827 if ((transceiver->current_direction() &&
828 !webrtc::RtpTransceiverDirectionHasRecv(
829 *transceiver->current_direction()))) {
830 auto it =
831 fake_video_renderers_.find(transceiver->receiver()->track()->id());
832 if (it != fake_video_renderers_.end()) {
833 fake_video_renderers_.erase(it);
834 }
835 }
836 }
837 }
838
deadbeef1dcb1642017-03-29 21:08:16 -0700839 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
840 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800841 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700842 if (signaling_delay_ms_ == 0) {
843 RelaySdpMessageIfReceiverExists(type, msg);
844 } else {
845 invoker_.AsyncInvokeDelayed<void>(
846 RTC_FROM_HERE, rtc::Thread::Current(),
847 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
848 this, type, msg),
849 signaling_delay_ms_);
850 }
851 }
852
Steve Antona3a92c22017-12-07 10:27:41 -0800853 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700854 if (signaling_message_receiver_) {
855 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
856 }
857 }
858
859 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
860 // default).
861 void SendIceMessage(const std::string& sdp_mid,
862 int sdp_mline_index,
863 const std::string& msg) {
864 if (signaling_delay_ms_ == 0) {
865 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
866 } else {
867 invoker_.AsyncInvokeDelayed<void>(
868 RTC_FROM_HERE, rtc::Thread::Current(),
869 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
870 this, sdp_mid, sdp_mline_index, msg),
871 signaling_delay_ms_);
872 }
873 }
874
875 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
876 int sdp_mline_index,
877 const std::string& msg) {
878 if (signaling_message_receiver_) {
879 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
880 msg);
881 }
882 }
883
884 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800885 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
886 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700887 HandleIncomingOffer(msg);
888 } else {
889 HandleIncomingAnswer(msg);
890 }
891 }
892
893 void ReceiveIceMessage(const std::string& sdp_mid,
894 int sdp_mline_index,
895 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100896 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700897 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
898 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
899 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
900 }
901
902 // PeerConnectionObserver callbacks.
903 void OnSignalingChange(
904 webrtc::PeerConnectionInterface::SignalingState new_state) override {
905 EXPECT_EQ(pc()->signaling_state(), new_state);
906 }
Steve Anton15324772018-01-16 10:26:49 -0800907 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
908 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
909 streams) override {
910 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
911 rtc::scoped_refptr<VideoTrackInterface> video_track(
912 static_cast<VideoTrackInterface*>(receiver->track().get()));
913 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700914 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800915 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200916 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700917 }
918 }
Steve Anton15324772018-01-16 10:26:49 -0800919 void OnRemoveTrack(
920 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
921 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
922 auto it = fake_video_renderers_.find(receiver->track()->id());
923 RTC_DCHECK(it != fake_video_renderers_.end());
924 fake_video_renderers_.erase(it);
925 }
926 }
deadbeef1dcb1642017-03-29 21:08:16 -0700927 void OnRenegotiationNeeded() override {}
928 void OnIceConnectionChange(
929 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
930 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700931 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700932 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200933 void OnConnectionChange(
934 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
935 peer_connection_state_history_.push_back(new_state);
936 }
937
deadbeef1dcb1642017-03-29 21:08:16 -0700938 void OnIceGatheringChange(
939 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700940 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700941 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700942 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700943 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceIceCandidate(
944 const webrtc::IceCandidateInterface* candidate) {
945 std::string candidate_string;
946 candidate->ToString(&candidate_string);
947
948 auto owned_candidate =
949 local_ice_candidate_replacer_->ReplaceCandidate(candidate);
950 if (!owned_candidate) {
951 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer dropped \""
952 << candidate_string << "\"";
953 return nullptr;
954 }
955 std::string owned_candidate_string;
956 owned_candidate->ToString(&owned_candidate_string);
957 RTC_LOG(LS_INFO) << "LocalIceCandidateReplacer changed \""
958 << candidate_string << "\" to \"" << owned_candidate_string
959 << "\"";
960 return owned_candidate;
961 }
deadbeef1dcb1642017-03-29 21:08:16 -0700962 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100963 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700964
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700965 const webrtc::IceCandidateInterface* new_candidate = candidate;
966 std::unique_ptr<webrtc::IceCandidateInterface> owned_candidate;
967 if (local_ice_candidate_replacer_) {
968 owned_candidate = ReplaceIceCandidate(candidate);
969 if (!owned_candidate) {
970 return; // The candidate was dropped.
971 }
972 new_candidate = owned_candidate.get();
973 }
974
deadbeef1dcb1642017-03-29 21:08:16 -0700975 std::string ice_sdp;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700976 EXPECT_TRUE(new_candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700977 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700978 // Remote party may be deleted.
979 return;
980 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700981 SendIceMessage(new_candidate->sdp_mid(), new_candidate->sdp_mline_index(),
982 ice_sdp);
deadbeef1dcb1642017-03-29 21:08:16 -0700983 }
984 void OnDataChannel(
985 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100986 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700987 data_channel_ = data_channel;
988 data_observer_.reset(new MockDataChannelObserver(data_channel));
989 }
990
deadbeef1dcb1642017-03-29 21:08:16 -0700991 std::string debug_name_;
992
993 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
994
995 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
996 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
997 peer_connection_factory_;
998
Steve Antonede9ca52017-10-16 13:04:27 -0700999 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -07001000 // Needed to keep track of number of frames sent.
1001 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1002 // Needed to keep track of number of frames received.
1003 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1004 fake_video_renderers_;
1005 // Needed to ensure frames aren't received for removed tracks.
1006 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1007 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001008
1009 // For remote peer communication.
1010 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1011 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001012 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -07001013
Niels Möller5c7efe72018-05-11 10:34:46 +02001014 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001015 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001016 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1017 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001018 // |local_video_renderer_| attached to the first created local video track.
1019 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1020
Seth Hampson2f0d7022018-02-20 11:54:42 -08001021 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001022 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1023 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1024 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001025 std::function<void()> remote_offer_handler_;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07001026 std::unique_ptr<IceCandidateReplacerInterface> local_ice_candidate_replacer_;
deadbeef1dcb1642017-03-29 21:08:16 -07001027 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1028 std::unique_ptr<MockDataChannelObserver> data_observer_;
1029
1030 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1031
Steve Antonede9ca52017-10-16 13:04:27 -07001032 std::vector<PeerConnectionInterface::IceConnectionState>
1033 ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001034 std::vector<PeerConnectionInterface::PeerConnectionState>
1035 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001036 std::vector<PeerConnectionInterface::IceGatheringState>
1037 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001038
Qingsi Wang7685e862018-06-11 20:15:46 -07001039 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1040
deadbeef1dcb1642017-03-29 21:08:16 -07001041 rtc::AsyncInvoker invoker_;
1042
Seth Hampson2f0d7022018-02-20 11:54:42 -08001043 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001044};
1045
Elad Alon99c3fe52017-10-13 16:29:40 +02001046class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1047 public:
1048 virtual ~MockRtcEventLogOutput() = default;
1049 MOCK_CONST_METHOD0(IsActive, bool());
1050 MOCK_METHOD1(Write, bool(const std::string&));
1051};
1052
Seth Hampson2f0d7022018-02-20 11:54:42 -08001053// This helper object is used for both specifying how many audio/video frames
1054// are expected to be received for a caller/callee. It provides helper functions
1055// to specify these expectations. The object initially starts in a state of no
1056// expectations.
1057class MediaExpectations {
1058 public:
1059 enum ExpectFrames {
1060 kExpectSomeFrames,
1061 kExpectNoFrames,
1062 kNoExpectation,
1063 };
1064
1065 void ExpectBidirectionalAudioAndVideo() {
1066 ExpectBidirectionalAudio();
1067 ExpectBidirectionalVideo();
1068 }
1069
1070 void ExpectBidirectionalAudio() {
1071 CallerExpectsSomeAudio();
1072 CalleeExpectsSomeAudio();
1073 }
1074
1075 void ExpectNoAudio() {
1076 CallerExpectsNoAudio();
1077 CalleeExpectsNoAudio();
1078 }
1079
1080 void ExpectBidirectionalVideo() {
1081 CallerExpectsSomeVideo();
1082 CalleeExpectsSomeVideo();
1083 }
1084
1085 void ExpectNoVideo() {
1086 CallerExpectsNoVideo();
1087 CalleeExpectsNoVideo();
1088 }
1089
1090 void CallerExpectsSomeAudioAndVideo() {
1091 CallerExpectsSomeAudio();
1092 CallerExpectsSomeVideo();
1093 }
1094
1095 void CalleeExpectsSomeAudioAndVideo() {
1096 CalleeExpectsSomeAudio();
1097 CalleeExpectsSomeVideo();
1098 }
1099
1100 // Caller's audio functions.
1101 void CallerExpectsSomeAudio(
1102 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1103 caller_audio_expectation_ = kExpectSomeFrames;
1104 caller_audio_frames_expected_ = expected_audio_frames;
1105 }
1106
1107 void CallerExpectsNoAudio() {
1108 caller_audio_expectation_ = kExpectNoFrames;
1109 caller_audio_frames_expected_ = 0;
1110 }
1111
1112 // Caller's video functions.
1113 void CallerExpectsSomeVideo(
1114 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1115 caller_video_expectation_ = kExpectSomeFrames;
1116 caller_video_frames_expected_ = expected_video_frames;
1117 }
1118
1119 void CallerExpectsNoVideo() {
1120 caller_video_expectation_ = kExpectNoFrames;
1121 caller_video_frames_expected_ = 0;
1122 }
1123
1124 // Callee's audio functions.
1125 void CalleeExpectsSomeAudio(
1126 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1127 callee_audio_expectation_ = kExpectSomeFrames;
1128 callee_audio_frames_expected_ = expected_audio_frames;
1129 }
1130
1131 void CalleeExpectsNoAudio() {
1132 callee_audio_expectation_ = kExpectNoFrames;
1133 callee_audio_frames_expected_ = 0;
1134 }
1135
1136 // Callee's video functions.
1137 void CalleeExpectsSomeVideo(
1138 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1139 callee_video_expectation_ = kExpectSomeFrames;
1140 callee_video_frames_expected_ = expected_video_frames;
1141 }
1142
1143 void CalleeExpectsNoVideo() {
1144 callee_video_expectation_ = kExpectNoFrames;
1145 callee_video_frames_expected_ = 0;
1146 }
1147
1148 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1149 ExpectFrames caller_video_expectation_ = kNoExpectation;
1150 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1151 ExpectFrames callee_video_expectation_ = kNoExpectation;
1152 int caller_audio_frames_expected_ = 0;
1153 int caller_video_frames_expected_ = 0;
1154 int callee_audio_frames_expected_ = 0;
1155 int callee_video_frames_expected_ = 0;
1156};
1157
deadbeef1dcb1642017-03-29 21:08:16 -07001158// Tests two PeerConnections connecting to each other end-to-end, using a
1159// virtual network, fake A/V capture and fake encoder/decoders. The
1160// PeerConnections share the threads/socket servers, but use separate versions
1161// of everything else (including "PeerConnectionFactory"s).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001162class PeerConnectionIntegrationBaseTest : public testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001163 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001164 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1165 : sdp_semantics_(sdp_semantics),
1166 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001167 fss_(new rtc::FirewallSocketServer(ss_.get())),
1168 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001169 worker_thread_(rtc::Thread::Create()),
1170 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001171 network_thread_->SetName("PCNetworkThread", this);
1172 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001173 RTC_CHECK(network_thread_->Start());
1174 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001175 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001176 }
1177
Seth Hampson2f0d7022018-02-20 11:54:42 -08001178 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001179 // The PeerConnections should deleted before the TurnCustomizers.
1180 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1181 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1182 // that the TurnCustomizer outlives the life of the PeerConnection or else
1183 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001184 if (caller_) {
1185 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001186 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001187 }
1188 if (callee_) {
1189 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001190 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001191 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001192
1193 // If turn servers were created for the test they need to be destroyed on
1194 // the network thread.
1195 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1196 turn_servers_.clear();
1197 turn_customizers_.clear();
1198 });
deadbeef1dcb1642017-03-29 21:08:16 -07001199 }
1200
1201 bool SignalingStateStable() {
1202 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1203 }
1204
deadbeef71452802017-05-07 17:21:01 -07001205 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001206 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1207 // are connected. This is an important distinction. Once we have separate
1208 // ICE and DTLS state, this check needs to use the DTLS state.
1209 return (callee()->ice_connection_state() ==
1210 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1211 callee()->ice_connection_state() ==
1212 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1213 (caller()->ice_connection_state() ==
1214 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1215 caller()->ice_connection_state() ==
1216 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001217 }
1218
Qingsi Wang7685e862018-06-11 20:15:46 -07001219 // When |event_log_factory| is null, the default implementation of the event
1220 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001221 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1222 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001223 const PeerConnectionFactory::Options* options,
1224 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001225 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001226 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1227 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001228 RTCConfiguration modified_config;
1229 if (config) {
1230 modified_config = *config;
1231 }
Steve Anton3acffc32018-04-12 17:21:03 -07001232 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001233 if (!dependencies.cert_generator) {
1234 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001235 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001236 }
1237 std::unique_ptr<PeerConnectionWrapper> client(
1238 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001239
Niels Möllerf06f9232018-08-07 12:32:18 +02001240 if (!client->Init(options, &modified_config, std::move(dependencies),
1241 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001242 std::move(event_log_factory),
1243 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001244 return nullptr;
1245 }
1246 return client;
1247 }
1248
Qingsi Wang7685e862018-06-11 20:15:46 -07001249 std::unique_ptr<PeerConnectionWrapper>
1250 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1251 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001252 const PeerConnectionFactory::Options* options,
1253 const RTCConfiguration* config,
1254 webrtc::PeerConnectionDependencies dependencies) {
1255 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1256 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001257 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001258 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001259 std::move(event_log_factory),
1260 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001261 }
1262
deadbeef1dcb1642017-03-29 21:08:16 -07001263 bool CreatePeerConnectionWrappers() {
1264 return CreatePeerConnectionWrappersWithConfig(
1265 PeerConnectionInterface::RTCConfiguration(),
1266 PeerConnectionInterface::RTCConfiguration());
1267 }
1268
Steve Anton3acffc32018-04-12 17:21:03 -07001269 bool CreatePeerConnectionWrappersWithSdpSemantics(
1270 SdpSemantics caller_semantics,
1271 SdpSemantics callee_semantics) {
1272 // Can't specify the sdp_semantics in the passed-in configuration since it
1273 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1274 // stored in sdp_semantics_. So get around this by modifying the instance
1275 // variable before calling CreatePeerConnectionWrapper for the caller and
1276 // callee PeerConnections.
1277 SdpSemantics original_semantics = sdp_semantics_;
1278 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001279 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001280 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001281 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001282 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001283 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001284 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001285 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001286 sdp_semantics_ = original_semantics;
1287 return caller_ && callee_;
1288 }
1289
deadbeef1dcb1642017-03-29 21:08:16 -07001290 bool CreatePeerConnectionWrappersWithConfig(
1291 const PeerConnectionInterface::RTCConfiguration& caller_config,
1292 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001293 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001294 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001295 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1296 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001297 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001298 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001299 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1300 /*media_transport_factory=*/nullptr);
1301 return caller_ && callee_;
1302 }
1303
1304 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1305 const PeerConnectionInterface::RTCConfiguration& caller_config,
1306 const PeerConnectionInterface::RTCConfiguration& callee_config,
1307 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1308 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1309 caller_ =
1310 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1311 webrtc::PeerConnectionDependencies(nullptr),
1312 nullptr, std::move(caller_factory));
1313 callee_ =
1314 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1315 webrtc::PeerConnectionDependencies(nullptr),
1316 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001317 return caller_ && callee_;
1318 }
1319
1320 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1321 const PeerConnectionInterface::RTCConfiguration& caller_config,
1322 webrtc::PeerConnectionDependencies caller_dependencies,
1323 const PeerConnectionInterface::RTCConfiguration& callee_config,
1324 webrtc::PeerConnectionDependencies callee_dependencies) {
1325 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001326 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001327 std::move(caller_dependencies), nullptr,
1328 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001329 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001330 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001331 std::move(callee_dependencies), nullptr,
1332 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001333 return caller_ && callee_;
1334 }
1335
1336 bool CreatePeerConnectionWrappersWithOptions(
1337 const PeerConnectionFactory::Options& caller_options,
1338 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001339 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001340 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001341 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1342 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001343 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001344 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001345 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1346 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001347 return caller_ && callee_;
1348 }
1349
1350 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1351 PeerConnectionInterface::RTCConfiguration default_config;
1352 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001353 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001354 webrtc::PeerConnectionDependencies(nullptr));
1355 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001356 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001357 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001358 return caller_ && callee_;
1359 }
1360
Seth Hampson2f0d7022018-02-20 11:54:42 -08001361 std::unique_ptr<PeerConnectionWrapper>
1362 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001363 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1364 new FakeRTCCertificateGenerator());
1365 cert_generator->use_alternate_key();
1366
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001367 webrtc::PeerConnectionDependencies dependencies(nullptr);
1368 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001369 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001370 std::move(dependencies), nullptr,
1371 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001372 }
1373
Seth Hampsonaed71642018-06-11 07:41:32 -07001374 cricket::TestTurnServer* CreateTurnServer(
1375 rtc::SocketAddress internal_address,
1376 rtc::SocketAddress external_address,
1377 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1378 const std::string& common_name = "test turn server") {
1379 rtc::Thread* thread = network_thread();
1380 std::unique_ptr<cricket::TestTurnServer> turn_server =
1381 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1382 RTC_FROM_HERE,
1383 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001384 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001385 thread, internal_address, external_address, type,
1386 /*ignore_bad_certs=*/true, common_name);
1387 });
1388 turn_servers_.push_back(std::move(turn_server));
1389 // Interactions with the turn server should be done on the network thread.
1390 return turn_servers_.back().get();
1391 }
1392
1393 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1394 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1395 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1396 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001397 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001398 turn_customizers_.push_back(std::move(turn_customizer));
1399 // Interactions with the turn customizer should be done on the network
1400 // thread.
1401 return turn_customizers_.back().get();
1402 }
1403
1404 // Checks that the function counters for a TestTurnCustomizer are greater than
1405 // 0.
1406 void ExpectTurnCustomizerCountersIncremented(
1407 cricket::TestTurnCustomizer* turn_customizer) {
1408 unsigned int allow_channel_data_counter =
1409 network_thread()->Invoke<unsigned int>(
1410 RTC_FROM_HERE, [turn_customizer] {
1411 return turn_customizer->allow_channel_data_cnt_;
1412 });
1413 EXPECT_GT(allow_channel_data_counter, 0u);
1414 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1415 RTC_FROM_HERE,
1416 [turn_customizer] { return turn_customizer->modify_cnt_; });
1417 EXPECT_GT(modify_counter, 0u);
1418 }
1419
deadbeef1dcb1642017-03-29 21:08:16 -07001420 // Once called, SDP blobs and ICE candidates will be automatically signaled
1421 // between PeerConnections.
1422 void ConnectFakeSignaling() {
1423 caller_->set_signaling_message_receiver(callee_.get());
1424 callee_->set_signaling_message_receiver(caller_.get());
1425 }
1426
Steve Antonede9ca52017-10-16 13:04:27 -07001427 // Once called, SDP blobs will be automatically signaled between
1428 // PeerConnections. Note that ICE candidates will not be signaled unless they
1429 // are in the exchanged SDP blobs.
1430 void ConnectFakeSignalingForSdpOnly() {
1431 ConnectFakeSignaling();
1432 SetSignalIceCandidates(false);
1433 }
1434
deadbeef1dcb1642017-03-29 21:08:16 -07001435 void SetSignalingDelayMs(int delay_ms) {
1436 caller_->set_signaling_delay_ms(delay_ms);
1437 callee_->set_signaling_delay_ms(delay_ms);
1438 }
1439
Steve Antonede9ca52017-10-16 13:04:27 -07001440 void SetSignalIceCandidates(bool signal) {
1441 caller_->set_signal_ice_candidates(signal);
1442 callee_->set_signal_ice_candidates(signal);
1443 }
1444
deadbeef1dcb1642017-03-29 21:08:16 -07001445 // Messages may get lost on the unreliable DataChannel, so we send multiple
1446 // times to avoid test flakiness.
1447 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1448 const std::string& data,
1449 int retries) {
1450 for (int i = 0; i < retries; ++i) {
1451 dc->Send(DataBuffer(data));
1452 }
1453 }
1454
1455 rtc::Thread* network_thread() { return network_thread_.get(); }
1456
1457 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1458
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001459 webrtc::MediaTransportPair* loopback_media_transports() {
1460 return &loopback_media_transports_;
1461 }
1462
deadbeef1dcb1642017-03-29 21:08:16 -07001463 PeerConnectionWrapper* caller() { return caller_.get(); }
1464
1465 // Set the |caller_| to the |wrapper| passed in and return the
1466 // original |caller_|.
1467 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1468 PeerConnectionWrapper* wrapper) {
1469 PeerConnectionWrapper* old = caller_.release();
1470 caller_.reset(wrapper);
1471 return old;
1472 }
1473
1474 PeerConnectionWrapper* callee() { return callee_.get(); }
1475
1476 // Set the |callee_| to the |wrapper| passed in and return the
1477 // original |callee_|.
1478 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1479 PeerConnectionWrapper* wrapper) {
1480 PeerConnectionWrapper* old = callee_.release();
1481 callee_.reset(wrapper);
1482 return old;
1483 }
1484
Steve Antonede9ca52017-10-16 13:04:27 -07001485 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1486
Seth Hampson2f0d7022018-02-20 11:54:42 -08001487 // Expects the provided number of new frames to be received within
1488 // kMaxWaitForFramesMs. The new expected frames are specified in
1489 // |media_expectations|. Returns false if any of the expectations were
1490 // not met.
1491 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1492 // First initialize the expected frame counts based upon the current
1493 // frame count.
1494 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1495 if (media_expectations.caller_audio_expectation_ ==
1496 MediaExpectations::kExpectSomeFrames) {
1497 total_caller_audio_frames_expected +=
1498 media_expectations.caller_audio_frames_expected_;
1499 }
1500 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001501 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001502 if (media_expectations.caller_video_expectation_ ==
1503 MediaExpectations::kExpectSomeFrames) {
1504 total_caller_video_frames_expected +=
1505 media_expectations.caller_video_frames_expected_;
1506 }
1507 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1508 if (media_expectations.callee_audio_expectation_ ==
1509 MediaExpectations::kExpectSomeFrames) {
1510 total_callee_audio_frames_expected +=
1511 media_expectations.callee_audio_frames_expected_;
1512 }
1513 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001514 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001515 if (media_expectations.callee_video_expectation_ ==
1516 MediaExpectations::kExpectSomeFrames) {
1517 total_callee_video_frames_expected +=
1518 media_expectations.callee_video_frames_expected_;
1519 }
deadbeef1dcb1642017-03-29 21:08:16 -07001520
Seth Hampson2f0d7022018-02-20 11:54:42 -08001521 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001522 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001523 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001524 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001525 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001526 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001527 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001528 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001529 total_callee_video_frames_expected,
1530 kMaxWaitForFramesMs);
1531 bool expectations_correct =
1532 caller()->audio_frames_received() >=
1533 total_caller_audio_frames_expected &&
1534 caller()->min_video_frames_received_per_track() >=
1535 total_caller_video_frames_expected &&
1536 callee()->audio_frames_received() >=
1537 total_callee_audio_frames_expected &&
1538 callee()->min_video_frames_received_per_track() >=
1539 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001540
Seth Hampson2f0d7022018-02-20 11:54:42 -08001541 // After the combined wait, print out a more detailed message upon
1542 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001543 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001544 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001545 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001546 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001547 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001548 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001549 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001550 total_callee_video_frames_expected);
1551
1552 // We want to make sure nothing unexpected was received.
1553 if (media_expectations.caller_audio_expectation_ ==
1554 MediaExpectations::kExpectNoFrames) {
1555 EXPECT_EQ(caller()->audio_frames_received(),
1556 total_caller_audio_frames_expected);
1557 if (caller()->audio_frames_received() !=
1558 total_caller_audio_frames_expected) {
1559 expectations_correct = false;
1560 }
1561 }
1562 if (media_expectations.caller_video_expectation_ ==
1563 MediaExpectations::kExpectNoFrames) {
1564 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1565 total_caller_video_frames_expected);
1566 if (caller()->min_video_frames_received_per_track() !=
1567 total_caller_video_frames_expected) {
1568 expectations_correct = false;
1569 }
1570 }
1571 if (media_expectations.callee_audio_expectation_ ==
1572 MediaExpectations::kExpectNoFrames) {
1573 EXPECT_EQ(callee()->audio_frames_received(),
1574 total_callee_audio_frames_expected);
1575 if (callee()->audio_frames_received() !=
1576 total_callee_audio_frames_expected) {
1577 expectations_correct = false;
1578 }
1579 }
1580 if (media_expectations.callee_video_expectation_ ==
1581 MediaExpectations::kExpectNoFrames) {
1582 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1583 total_callee_video_frames_expected);
1584 if (callee()->min_video_frames_received_per_track() !=
1585 total_callee_video_frames_expected) {
1586 expectations_correct = false;
1587 }
1588 }
1589 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001590 }
1591
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001592 void TestNegotiatedCipherSuite(
1593 const PeerConnectionFactory::Options& caller_options,
1594 const PeerConnectionFactory::Options& callee_options,
1595 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001596 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1597 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001598 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001599 caller()->AddAudioVideoTracks();
1600 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001601 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001602 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001603 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001604 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001605 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001606 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001607 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1608 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001609 }
1610
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001611 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1612 bool remote_gcm_enabled,
1613 int expected_cipher_suite) {
1614 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001615 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1616 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001617 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001618 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1619 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001620 TestNegotiatedCipherSuite(caller_options, callee_options,
1621 expected_cipher_suite);
1622 }
1623
Seth Hampson2f0d7022018-02-20 11:54:42 -08001624 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001625 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001626
deadbeef1dcb1642017-03-29 21:08:16 -07001627 private:
1628 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001629 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001630 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001631 // |network_thread_| and |worker_thread_| are used by both
1632 // |caller_| and |callee_| so they must be destroyed
1633 // later.
1634 std::unique_ptr<rtc::Thread> network_thread_;
1635 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001636 // The turn servers and turn customizers should be accessed & deleted on the
1637 // network thread to avoid a race with the socket read/write that occurs
1638 // on the network thread.
1639 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1640 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001641 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001642 std::unique_ptr<PeerConnectionWrapper> caller_;
1643 std::unique_ptr<PeerConnectionWrapper> callee_;
1644};
1645
Seth Hampson2f0d7022018-02-20 11:54:42 -08001646class PeerConnectionIntegrationTest
1647 : public PeerConnectionIntegrationBaseTest,
1648 public ::testing::WithParamInterface<SdpSemantics> {
1649 protected:
1650 PeerConnectionIntegrationTest()
1651 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1652};
1653
1654class PeerConnectionIntegrationTestPlanB
1655 : public PeerConnectionIntegrationBaseTest {
1656 protected:
1657 PeerConnectionIntegrationTestPlanB()
1658 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1659};
1660
1661class PeerConnectionIntegrationTestUnifiedPlan
1662 : public PeerConnectionIntegrationBaseTest {
1663 protected:
1664 PeerConnectionIntegrationTestUnifiedPlan()
1665 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1666};
1667
deadbeef1dcb1642017-03-29 21:08:16 -07001668// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1669// includes testing that the callback is invoked if an observer is connected
1670// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001671TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001672 RtpReceiverObserverOnFirstPacketReceived) {
1673 ASSERT_TRUE(CreatePeerConnectionWrappers());
1674 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001675 caller()->AddAudioVideoTracks();
1676 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001677 // Start offer/answer exchange and wait for it to complete.
1678 caller()->CreateAndSetAndSignalOffer();
1679 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1680 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001681 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1682 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001683 // Wait for all "first packet received" callbacks to be fired.
1684 EXPECT_TRUE_WAIT(
1685 std::all_of(caller()->rtp_receiver_observers().begin(),
1686 caller()->rtp_receiver_observers().end(),
1687 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1688 return o->first_packet_received();
1689 }),
1690 kMaxWaitForFramesMs);
1691 EXPECT_TRUE_WAIT(
1692 std::all_of(callee()->rtp_receiver_observers().begin(),
1693 callee()->rtp_receiver_observers().end(),
1694 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1695 return o->first_packet_received();
1696 }),
1697 kMaxWaitForFramesMs);
1698 // If new observers are set after the first packet was already received, the
1699 // callback should still be invoked.
1700 caller()->ResetRtpReceiverObservers();
1701 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001702 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1703 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001704 EXPECT_TRUE(
1705 std::all_of(caller()->rtp_receiver_observers().begin(),
1706 caller()->rtp_receiver_observers().end(),
1707 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1708 return o->first_packet_received();
1709 }));
1710 EXPECT_TRUE(
1711 std::all_of(callee()->rtp_receiver_observers().begin(),
1712 callee()->rtp_receiver_observers().end(),
1713 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1714 return o->first_packet_received();
1715 }));
1716}
1717
1718class DummyDtmfObserver : public DtmfSenderObserverInterface {
1719 public:
1720 DummyDtmfObserver() : completed_(false) {}
1721
1722 // Implements DtmfSenderObserverInterface.
1723 void OnToneChange(const std::string& tone) override {
1724 tones_.push_back(tone);
1725 if (tone.empty()) {
1726 completed_ = true;
1727 }
1728 }
1729
1730 const std::vector<std::string>& tones() const { return tones_; }
1731 bool completed() const { return completed_; }
1732
1733 private:
1734 bool completed_;
1735 std::vector<std::string> tones_;
1736};
1737
1738// Assumes |sender| already has an audio track added and the offer/answer
1739// exchange is done.
1740void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1741 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001742 // We should be able to get a DTMF sender from the local sender.
1743 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1744 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1745 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001746 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001747 dtmf_sender->RegisterObserver(&observer);
1748
1749 // Test the DtmfSender object just created.
1750 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1751 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1752
1753 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1754 std::vector<std::string> tones = {"1", "a", ""};
1755 EXPECT_EQ(tones, observer.tones());
1756 dtmf_sender->UnregisterObserver();
1757 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1758}
1759
1760// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1761// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001762TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001763 ASSERT_TRUE(CreatePeerConnectionWrappers());
1764 ConnectFakeSignaling();
1765 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001766 caller()->AddAudioTrack();
1767 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001768 caller()->CreateAndSetAndSignalOffer();
1769 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001770 // DTLS must finish before the DTMF sender can be used reliably.
1771 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001772 TestDtmfFromSenderToReceiver(caller(), callee());
1773 TestDtmfFromSenderToReceiver(callee(), caller());
1774}
1775
1776// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1777// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001778TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001779 ASSERT_TRUE(CreatePeerConnectionWrappers());
1780 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001781
deadbeef1dcb1642017-03-29 21:08:16 -07001782 // Do normal offer/answer and wait for some frames to be received in each
1783 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001784 caller()->AddAudioVideoTracks();
1785 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001786 caller()->CreateAndSetAndSignalOffer();
1787 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001788 MediaExpectations media_expectations;
1789 media_expectations.ExpectBidirectionalAudioAndVideo();
1790 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001791 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1792 webrtc::kEnumCounterKeyProtocolDtls));
1793 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1794 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001795}
1796
1797// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001798TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001799 PeerConnectionInterface::RTCConfiguration sdes_config;
1800 sdes_config.enable_dtls_srtp.emplace(false);
1801 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1802 ConnectFakeSignaling();
1803
1804 // Do normal offer/answer and wait for some frames to be received in each
1805 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001806 caller()->AddAudioVideoTracks();
1807 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001808 caller()->CreateAndSetAndSignalOffer();
1809 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001810 MediaExpectations media_expectations;
1811 media_expectations.ExpectBidirectionalAudioAndVideo();
1812 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001813 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1814 webrtc::kEnumCounterKeyProtocolSdes));
1815 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1816 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001817}
1818
Steve Anton8c0f7a72017-10-03 10:03:10 -07001819// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1820// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001821TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001822 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1823 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1824 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1825 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1826 return pc->GetRemoteAudioSSLCertificate();
1827 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001828 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1829 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1830 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1831 return pc->GetRemoteAudioSSLCertChain();
1832 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001833
1834 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1835 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1836
1837 // Configure each side with a known certificate so they can be compared later.
1838 PeerConnectionInterface::RTCConfiguration caller_config;
1839 caller_config.enable_dtls_srtp.emplace(true);
1840 caller_config.certificates.push_back(caller_cert);
1841 PeerConnectionInterface::RTCConfiguration callee_config;
1842 callee_config.enable_dtls_srtp.emplace(true);
1843 callee_config.certificates.push_back(callee_cert);
1844 ASSERT_TRUE(
1845 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1846 ConnectFakeSignaling();
1847
1848 // When first initialized, there should not be a remote SSL certificate (and
1849 // calling this method should not crash).
1850 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1851 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001852 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1853 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001854
Steve Anton15324772018-01-16 10:26:49 -08001855 caller()->AddAudioTrack();
1856 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001857 caller()->CreateAndSetAndSignalOffer();
1858 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1859 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1860
1861 // Once DTLS has been connected, each side should return the other's SSL
1862 // certificate when calling GetRemoteAudioSSLCertificate.
1863
1864 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1865 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001866 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001867 caller_remote_cert->ToPEMString());
1868
1869 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1870 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001871 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001872 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001873
1874 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1875 ASSERT_TRUE(caller_remote_cert_chain);
1876 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1877 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001878 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001879 remote_cert->ToPEMString());
1880
1881 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1882 ASSERT_TRUE(callee_remote_cert_chain);
1883 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1884 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001885 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001886 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001887}
1888
deadbeef1dcb1642017-03-29 21:08:16 -07001889// This test sets up a call between two parties with a source resolution of
1890// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001891TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001892 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1893 ASSERT_TRUE(CreatePeerConnectionWrappers());
1894 ConnectFakeSignaling();
1895
Niels Möller5c7efe72018-05-11 10:34:46 +02001896 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1897 webrtc::FakePeriodicVideoSource::Config config;
1898 config.width = 1280;
1899 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001900 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001901 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1902 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001903
1904 // Do normal offer/answer and wait for at least one frame to be received in
1905 // each direction.
1906 caller()->CreateAndSetAndSignalOffer();
1907 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1908 callee()->min_video_frames_received_per_track() > 0,
1909 kMaxWaitForFramesMs);
1910
1911 // Check rendered aspect ratio.
1912 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1913 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1914 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1915 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1916}
1917
1918// This test sets up an one-way call, with media only from caller to
1919// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001920TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001921 ASSERT_TRUE(CreatePeerConnectionWrappers());
1922 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001923 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001924 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001925 MediaExpectations media_expectations;
1926 media_expectations.CalleeExpectsSomeAudioAndVideo();
1927 media_expectations.CallerExpectsNoAudio();
1928 media_expectations.CallerExpectsNoVideo();
1929 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001930}
1931
1932// This test sets up a audio call initially, with the callee rejecting video
1933// initially. Then later the callee decides to upgrade to audio/video, and
1934// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001935TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001936 ASSERT_TRUE(CreatePeerConnectionWrappers());
1937 ConnectFakeSignaling();
1938 // Initially, offer an audio/video stream from the caller, but refuse to
1939 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001940 caller()->AddAudioVideoTracks();
1941 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001942 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1943 PeerConnectionInterface::RTCOfferAnswerOptions options;
1944 options.offer_to_receive_video = 0;
1945 callee()->SetOfferAnswerOptions(options);
1946 } else {
1947 callee()->SetRemoteOfferHandler([this] {
1948 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1949 });
1950 }
deadbeef1dcb1642017-03-29 21:08:16 -07001951 // Do offer/answer and make sure audio is still received end-to-end.
1952 caller()->CreateAndSetAndSignalOffer();
1953 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001954 {
1955 MediaExpectations media_expectations;
1956 media_expectations.ExpectBidirectionalAudio();
1957 media_expectations.ExpectNoVideo();
1958 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1959 }
deadbeef1dcb1642017-03-29 21:08:16 -07001960 // Sanity check that the callee's description has a rejected video section.
1961 ASSERT_NE(nullptr, callee()->pc()->local_description());
1962 const ContentInfo* callee_video_content =
1963 GetFirstVideoContent(callee()->pc()->local_description()->description());
1964 ASSERT_NE(nullptr, callee_video_content);
1965 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001966
deadbeef1dcb1642017-03-29 21:08:16 -07001967 // Now negotiate with video and ensure negotiation succeeds, with video
1968 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001969 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001970 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1971 PeerConnectionInterface::RTCOfferAnswerOptions options;
1972 options.offer_to_receive_video = 1;
1973 callee()->SetOfferAnswerOptions(options);
1974 } else {
1975 callee()->SetRemoteOfferHandler(nullptr);
1976 caller()->SetRemoteOfferHandler([this] {
1977 // The caller creates a new transceiver to receive video on when receiving
1978 // the offer, but by default it is send only.
1979 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001980 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001981 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1982 transceivers[2]->receiver()->media_type());
1983 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1984 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1985 });
1986 }
deadbeef1dcb1642017-03-29 21:08:16 -07001987 callee()->CreateAndSetAndSignalOffer();
1988 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001989 {
1990 // Expect additional audio frames to be received after the upgrade.
1991 MediaExpectations media_expectations;
1992 media_expectations.ExpectBidirectionalAudioAndVideo();
1993 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1994 }
deadbeef1dcb1642017-03-29 21:08:16 -07001995}
1996
deadbeef4389b4d2017-09-07 09:07:36 -07001997// Simpler than the above test; just add an audio track to an established
1998// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001999TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002000 ASSERT_TRUE(CreatePeerConnectionWrappers());
2001 ConnectFakeSignaling();
2002 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002003 caller()->AddVideoTrack();
2004 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002005 caller()->CreateAndSetAndSignalOffer();
2006 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2007 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002008 caller()->AddAudioTrack();
2009 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002010 caller()->CreateAndSetAndSignalOffer();
2011 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2012 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002013 MediaExpectations media_expectations;
2014 media_expectations.ExpectBidirectionalAudioAndVideo();
2015 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002016}
2017
deadbeef1dcb1642017-03-29 21:08:16 -07002018// This test sets up a call that's transferred to a new caller with a different
2019// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002020TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002021 ASSERT_TRUE(CreatePeerConnectionWrappers());
2022 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002023 caller()->AddAudioVideoTracks();
2024 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002025 caller()->CreateAndSetAndSignalOffer();
2026 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2027
2028 // Keep the original peer around which will still send packets to the
2029 // receiving client. These SRTP packets will be dropped.
2030 std::unique_ptr<PeerConnectionWrapper> original_peer(
2031 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002032 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002033 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2034 // directly above.
2035 original_peer->pc()->Close();
2036
2037 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002038 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002039 caller()->CreateAndSetAndSignalOffer();
2040 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2041 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002042 MediaExpectations media_expectations;
2043 media_expectations.ExpectBidirectionalAudioAndVideo();
2044 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002045}
2046
2047// This test sets up a call that's transferred to a new callee with a different
2048// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002049TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002050 ASSERT_TRUE(CreatePeerConnectionWrappers());
2051 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002052 caller()->AddAudioVideoTracks();
2053 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002054 caller()->CreateAndSetAndSignalOffer();
2055 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2056
2057 // Keep the original peer around which will still send packets to the
2058 // receiving client. These SRTP packets will be dropped.
2059 std::unique_ptr<PeerConnectionWrapper> original_peer(
2060 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002061 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002062 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2063 // directly above.
2064 original_peer->pc()->Close();
2065
2066 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002067 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002068 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2069 caller()->CreateAndSetAndSignalOffer();
2070 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2071 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002072 MediaExpectations media_expectations;
2073 media_expectations.ExpectBidirectionalAudioAndVideo();
2074 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002075}
2076
2077// This test sets up a non-bundled call and negotiates bundling at the same
2078// time as starting an ICE restart. When bundling is in effect in the restart,
2079// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002080TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002081 ASSERT_TRUE(CreatePeerConnectionWrappers());
2082 ConnectFakeSignaling();
2083
Steve Anton15324772018-01-16 10:26:49 -08002084 caller()->AddAudioVideoTracks();
2085 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002086 // Remove the bundle group from the SDP received by the callee.
2087 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2088 desc->RemoveGroupByName("BUNDLE");
2089 });
2090 caller()->CreateAndSetAndSignalOffer();
2091 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002092 {
2093 MediaExpectations media_expectations;
2094 media_expectations.ExpectBidirectionalAudioAndVideo();
2095 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2096 }
deadbeef1dcb1642017-03-29 21:08:16 -07002097 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2098 callee()->SetReceivedSdpMunger(nullptr);
2099 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2100 caller()->CreateAndSetAndSignalOffer();
2101 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2102
2103 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002104 {
2105 MediaExpectations media_expectations;
2106 media_expectations.ExpectBidirectionalAudioAndVideo();
2107 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2108 }
deadbeef1dcb1642017-03-29 21:08:16 -07002109}
2110
2111// Test CVO (Coordination of Video Orientation). If a video source is rotated
2112// and both peers support the CVO RTP header extension, the actual video frames
2113// don't need to be encoded in different resolutions, since the rotation is
2114// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002115TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002116 ASSERT_TRUE(CreatePeerConnectionWrappers());
2117 ConnectFakeSignaling();
2118 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002119 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002120 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002121 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002122 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2123
2124 // Wait for video frames to be received by both sides.
2125 caller()->CreateAndSetAndSignalOffer();
2126 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2127 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2128 callee()->min_video_frames_received_per_track() > 0,
2129 kMaxWaitForFramesMs);
2130
2131 // Ensure that the aspect ratio is unmodified.
2132 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2133 // not just assumed.
2134 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2135 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2136 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2137 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2138 // Ensure that the CVO bits were surfaced to the renderer.
2139 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2140 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2141}
2142
2143// Test that when the CVO extension isn't supported, video is rotated the
2144// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002145TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002146 ASSERT_TRUE(CreatePeerConnectionWrappers());
2147 ConnectFakeSignaling();
2148 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002149 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002150 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002151 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002152 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2153
2154 // Remove the CVO extension from the offered SDP.
2155 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2156 cricket::VideoContentDescription* video =
2157 GetFirstVideoContentDescription(desc);
2158 video->ClearRtpHeaderExtensions();
2159 });
2160 // Wait for video frames to be received by both sides.
2161 caller()->CreateAndSetAndSignalOffer();
2162 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2163 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2164 callee()->min_video_frames_received_per_track() > 0,
2165 kMaxWaitForFramesMs);
2166
2167 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2168 // rotation.
2169 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2170 // not just assumed.
2171 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2172 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2173 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2174 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2175 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2176 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2177 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2178}
2179
deadbeef1dcb1642017-03-29 21:08:16 -07002180// Test that if the answerer rejects the audio m= section, no audio is sent or
2181// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002182TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002183 ASSERT_TRUE(CreatePeerConnectionWrappers());
2184 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002185 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002186 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2187 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2188 // it will reject the audio m= section completely.
2189 PeerConnectionInterface::RTCOfferAnswerOptions options;
2190 options.offer_to_receive_audio = 0;
2191 callee()->SetOfferAnswerOptions(options);
2192 } else {
2193 // Stopping the audio RtpTransceiver will cause the media section to be
2194 // rejected in the answer.
2195 callee()->SetRemoteOfferHandler([this] {
2196 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2197 });
2198 }
Steve Anton15324772018-01-16 10:26:49 -08002199 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002200 // Do offer/answer and wait for successful end-to-end video frames.
2201 caller()->CreateAndSetAndSignalOffer();
2202 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002203 MediaExpectations media_expectations;
2204 media_expectations.ExpectBidirectionalVideo();
2205 media_expectations.ExpectNoAudio();
2206 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2207
deadbeef1dcb1642017-03-29 21:08:16 -07002208 // Sanity check that the callee's description has a rejected audio section.
2209 ASSERT_NE(nullptr, callee()->pc()->local_description());
2210 const ContentInfo* callee_audio_content =
2211 GetFirstAudioContent(callee()->pc()->local_description()->description());
2212 ASSERT_NE(nullptr, callee_audio_content);
2213 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002214 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2215 // The caller's transceiver should have stopped after receiving the answer.
2216 EXPECT_TRUE(caller()
2217 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2218 ->stopped());
2219 }
deadbeef1dcb1642017-03-29 21:08:16 -07002220}
2221
2222// Test that if the answerer rejects the video m= section, no video is sent or
2223// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002224TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002225 ASSERT_TRUE(CreatePeerConnectionWrappers());
2226 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002227 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002228 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2229 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2230 // it will reject the video m= section completely.
2231 PeerConnectionInterface::RTCOfferAnswerOptions options;
2232 options.offer_to_receive_video = 0;
2233 callee()->SetOfferAnswerOptions(options);
2234 } else {
2235 // Stopping the video RtpTransceiver will cause the media section to be
2236 // rejected in the answer.
2237 callee()->SetRemoteOfferHandler([this] {
2238 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2239 });
2240 }
Steve Anton15324772018-01-16 10:26:49 -08002241 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002242 // Do offer/answer and wait for successful end-to-end audio frames.
2243 caller()->CreateAndSetAndSignalOffer();
2244 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002245 MediaExpectations media_expectations;
2246 media_expectations.ExpectBidirectionalAudio();
2247 media_expectations.ExpectNoVideo();
2248 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2249
deadbeef1dcb1642017-03-29 21:08:16 -07002250 // Sanity check that the callee's description has a rejected video section.
2251 ASSERT_NE(nullptr, callee()->pc()->local_description());
2252 const ContentInfo* callee_video_content =
2253 GetFirstVideoContent(callee()->pc()->local_description()->description());
2254 ASSERT_NE(nullptr, callee_video_content);
2255 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002256 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2257 // The caller's transceiver should have stopped after receiving the answer.
2258 EXPECT_TRUE(caller()
2259 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2260 ->stopped());
2261 }
deadbeef1dcb1642017-03-29 21:08:16 -07002262}
2263
2264// Test that if the answerer rejects both audio and video m= sections, nothing
2265// bad happens.
2266// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2267// test anything but the fact that negotiation succeeds, which doesn't mean
2268// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002269TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002270 ASSERT_TRUE(CreatePeerConnectionWrappers());
2271 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002272 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002273 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2274 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2275 // will reject both audio and video m= sections.
2276 PeerConnectionInterface::RTCOfferAnswerOptions options;
2277 options.offer_to_receive_audio = 0;
2278 options.offer_to_receive_video = 0;
2279 callee()->SetOfferAnswerOptions(options);
2280 } else {
2281 callee()->SetRemoteOfferHandler([this] {
2282 // Stopping all transceivers will cause all media sections to be rejected.
2283 for (auto transceiver : callee()->pc()->GetTransceivers()) {
2284 transceiver->Stop();
2285 }
2286 });
2287 }
deadbeef1dcb1642017-03-29 21:08:16 -07002288 // Do offer/answer and wait for stable signaling state.
2289 caller()->CreateAndSetAndSignalOffer();
2290 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002291
deadbeef1dcb1642017-03-29 21:08:16 -07002292 // Sanity check that the callee's description has rejected m= sections.
2293 ASSERT_NE(nullptr, callee()->pc()->local_description());
2294 const ContentInfo* callee_audio_content =
2295 GetFirstAudioContent(callee()->pc()->local_description()->description());
2296 ASSERT_NE(nullptr, callee_audio_content);
2297 EXPECT_TRUE(callee_audio_content->rejected);
2298 const ContentInfo* callee_video_content =
2299 GetFirstVideoContent(callee()->pc()->local_description()->description());
2300 ASSERT_NE(nullptr, callee_video_content);
2301 EXPECT_TRUE(callee_video_content->rejected);
2302}
2303
2304// This test sets up an audio and video call between two parties. After the
2305// call runs for a while, the caller sends an updated offer with video being
2306// rejected. Once the re-negotiation is done, the video flow should stop and
2307// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002308TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002309 ASSERT_TRUE(CreatePeerConnectionWrappers());
2310 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002311 caller()->AddAudioVideoTracks();
2312 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002313 caller()->CreateAndSetAndSignalOffer();
2314 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002315 {
2316 MediaExpectations media_expectations;
2317 media_expectations.ExpectBidirectionalAudioAndVideo();
2318 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2319 }
deadbeef1dcb1642017-03-29 21:08:16 -07002320 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002321 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2322 caller()->SetGeneratedSdpMunger(
2323 [](cricket::SessionDescription* description) {
2324 for (cricket::ContentInfo& content : description->contents()) {
2325 if (cricket::IsVideoContent(&content)) {
2326 content.rejected = true;
2327 }
2328 }
2329 });
2330 } else {
2331 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2332 }
deadbeef1dcb1642017-03-29 21:08:16 -07002333 caller()->CreateAndSetAndSignalOffer();
2334 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2335
2336 // Sanity check that the caller's description has a rejected video section.
2337 ASSERT_NE(nullptr, caller()->pc()->local_description());
2338 const ContentInfo* caller_video_content =
2339 GetFirstVideoContent(caller()->pc()->local_description()->description());
2340 ASSERT_NE(nullptr, caller_video_content);
2341 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002342 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002343 {
2344 MediaExpectations media_expectations;
2345 media_expectations.ExpectBidirectionalAudio();
2346 media_expectations.ExpectNoVideo();
2347 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2348 }
deadbeef1dcb1642017-03-29 21:08:16 -07002349}
2350
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002351// Do one offer/answer with audio, another that disables it (rejecting the m=
2352// section), and another that re-enables it. Regression test for:
2353// bugs.webrtc.org/6023
2354TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2355 ASSERT_TRUE(CreatePeerConnectionWrappers());
2356 ConnectFakeSignaling();
2357
2358 // Add audio track, do normal offer/answer.
2359 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2360 caller()->CreateLocalAudioTrack();
2361 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2362 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2363 caller()->CreateAndSetAndSignalOffer();
2364 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2365
2366 // Remove audio track, and set offer_to_receive_audio to false to cause the
2367 // m= section to be completely disabled, not just "recvonly".
2368 caller()->pc()->RemoveTrack(sender);
2369 PeerConnectionInterface::RTCOfferAnswerOptions options;
2370 options.offer_to_receive_audio = 0;
2371 caller()->SetOfferAnswerOptions(options);
2372 caller()->CreateAndSetAndSignalOffer();
2373 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2374
2375 // Add the audio track again, expecting negotiation to succeed and frames to
2376 // flow.
2377 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2378 options.offer_to_receive_audio = 1;
2379 caller()->SetOfferAnswerOptions(options);
2380 caller()->CreateAndSetAndSignalOffer();
2381 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2382
2383 MediaExpectations media_expectations;
2384 media_expectations.CalleeExpectsSomeAudio();
2385 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2386}
2387
deadbeef1dcb1642017-03-29 21:08:16 -07002388// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2389// is needed to support legacy endpoints.
2390// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2391// add a test for an end-to-end test without MID signaling either (basically,
2392// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002393TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002394 ASSERT_TRUE(CreatePeerConnectionWrappers());
2395 ConnectFakeSignaling();
2396 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002397 caller()->AddAudioVideoTracks();
2398 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002399 // Remove SSRCs and MSIDs from the received offer SDP.
2400 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002401 caller()->CreateAndSetAndSignalOffer();
2402 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002403 MediaExpectations media_expectations;
2404 media_expectations.ExpectBidirectionalAudioAndVideo();
2405 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002406}
2407
Seth Hampson5897a6e2018-04-03 11:16:33 -07002408// Basic end-to-end test, without SSRC signaling. This means that the track
2409// was created properly and frames are delivered when the MSIDs are communicated
2410// with a=msid lines and no a=ssrc lines.
2411TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2412 EndToEndCallWithoutSsrcSignaling) {
2413 const char kStreamId[] = "streamId";
2414 ASSERT_TRUE(CreatePeerConnectionWrappers());
2415 ConnectFakeSignaling();
2416 // Add just audio tracks.
2417 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2418 callee()->AddAudioTrack();
2419
2420 // Remove SSRCs from the received offer SDP.
2421 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2422 caller()->CreateAndSetAndSignalOffer();
2423 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2424 MediaExpectations media_expectations;
2425 media_expectations.ExpectBidirectionalAudio();
2426 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2427}
2428
Steve Antondf527fd2018-04-27 15:52:03 -07002429// Tests that video flows between multiple video tracks when SSRCs are not
2430// signaled. This exercises the MID RTP header extension which is needed to
2431// demux the incoming video tracks.
2432TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2433 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2434 ASSERT_TRUE(CreatePeerConnectionWrappers());
2435 ConnectFakeSignaling();
2436 caller()->AddVideoTrack();
2437 caller()->AddVideoTrack();
2438 callee()->AddVideoTrack();
2439 callee()->AddVideoTrack();
2440
2441 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2442 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2443 caller()->CreateAndSetAndSignalOffer();
2444 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2445 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2446 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2447
2448 // Expect video to be received in both directions on both tracks.
2449 MediaExpectations media_expectations;
2450 media_expectations.ExpectBidirectionalVideo();
2451 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2452}
2453
deadbeef1dcb1642017-03-29 21:08:16 -07002454// Test that if two video tracks are sent (from caller to callee, in this test),
2455// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002456TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002457 ASSERT_TRUE(CreatePeerConnectionWrappers());
2458 ConnectFakeSignaling();
2459 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002460 caller()->AddAudioVideoTracks();
2461 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002462 caller()->CreateAndSetAndSignalOffer();
2463 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002464 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002465
2466 MediaExpectations media_expectations;
2467 media_expectations.CalleeExpectsSomeAudioAndVideo();
2468 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002469}
2470
2471static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2472 bool first = true;
2473 for (cricket::ContentInfo& content : desc->contents()) {
2474 if (first) {
2475 first = false;
2476 continue;
2477 }
2478 content.bundle_only = true;
2479 }
2480 first = true;
2481 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2482 if (first) {
2483 first = false;
2484 continue;
2485 }
2486 transport.description.ice_ufrag.clear();
2487 transport.description.ice_pwd.clear();
2488 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2489 transport.description.identity_fingerprint.reset(nullptr);
2490 }
2491}
2492
2493// Test that if applying a true "max bundle" offer, which uses ports of 0,
2494// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2495// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2496// successfully and media flows.
2497// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2498// TODO(deadbeef): Won't need this test once we start generating actual
2499// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002500TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002501 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2502 ASSERT_TRUE(CreatePeerConnectionWrappers());
2503 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002504 caller()->AddAudioVideoTracks();
2505 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002506 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2507 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2508 // but the first m= section.
2509 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2510 caller()->CreateAndSetAndSignalOffer();
2511 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002512 MediaExpectations media_expectations;
2513 media_expectations.ExpectBidirectionalAudioAndVideo();
2514 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002515}
2516
2517// Test that we can receive the audio output level from a remote audio track.
2518// TODO(deadbeef): Use a fake audio source and verify that the output level is
2519// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002520TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002521 ASSERT_TRUE(CreatePeerConnectionWrappers());
2522 ConnectFakeSignaling();
2523 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002524 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002525 caller()->CreateAndSetAndSignalOffer();
2526 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2527
2528 // Get the audio output level stats. Note that the level is not available
2529 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002530 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002531 kMaxWaitForFramesMs);
2532}
2533
2534// Test that an audio input level is reported.
2535// TODO(deadbeef): Use a fake audio source and verify that the input level is
2536// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002537TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002538 ASSERT_TRUE(CreatePeerConnectionWrappers());
2539 ConnectFakeSignaling();
2540 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002541 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002542 caller()->CreateAndSetAndSignalOffer();
2543 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2544
2545 // Get the audio input level stats. The level should be available very
2546 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002547 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002548 kMaxWaitForStatsMs);
2549}
2550
2551// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002552TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002553 ASSERT_TRUE(CreatePeerConnectionWrappers());
2554 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002555 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002556 // Do offer/answer, wait for the callee to receive some frames.
2557 caller()->CreateAndSetAndSignalOffer();
2558 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002559
2560 MediaExpectations media_expectations;
2561 media_expectations.CalleeExpectsSomeAudioAndVideo();
2562 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002563
2564 // Get a handle to the remote tracks created, so they can be used as GetStats
2565 // filters.
Steve Anton15324772018-01-16 10:26:49 -08002566 for (auto receiver : callee()->pc()->GetReceivers()) {
2567 // We received frames, so we definitely should have nonzero "received bytes"
2568 // stats at this point.
2569 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2570 0);
2571 }
deadbeef1dcb1642017-03-29 21:08:16 -07002572}
2573
2574// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002575TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002576 ASSERT_TRUE(CreatePeerConnectionWrappers());
2577 ConnectFakeSignaling();
2578 auto audio_track = caller()->CreateLocalAudioTrack();
2579 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002580 caller()->AddTrack(audio_track);
2581 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002582 // Do offer/answer, wait for the callee to receive some frames.
2583 caller()->CreateAndSetAndSignalOffer();
2584 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002585 MediaExpectations media_expectations;
2586 media_expectations.CalleeExpectsSomeAudioAndVideo();
2587 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002588
2589 // The callee received frames, so we definitely should have nonzero "sent
2590 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002591 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2592 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2593}
2594
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002595// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002596TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002597 ASSERT_TRUE(CreatePeerConnectionWrappers());
2598 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002599 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002600
Steve Anton15324772018-01-16 10:26:49 -08002601 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002602
2603 // Do offer/answer, wait for the callee to receive some frames.
2604 caller()->CreateAndSetAndSignalOffer();
2605 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2606
2607 // Get the remote audio track created on the receiver, so they can be used as
2608 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002609 auto receivers = callee()->pc()->GetReceivers();
2610 ASSERT_EQ(1u, receivers.size());
2611 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002612
2613 // Get the audio output level stats. Note that the level is not available
2614 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002615 EXPECT_TRUE_WAIT(
2616 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2617 0,
2618 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002619}
2620
Steve Antona41959e2018-11-28 11:15:33 -08002621// Test that the track ID is associated with all local and remote SSRC stats
2622// using the old GetStats() and more than 1 audio and more than 1 video track.
2623// This is a regression test for crbug.com/906988
2624TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2625 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2626 ASSERT_TRUE(CreatePeerConnectionWrappers());
2627 ConnectFakeSignaling();
2628 auto audio_sender_1 = caller()->AddAudioTrack();
2629 auto video_sender_1 = caller()->AddVideoTrack();
2630 auto audio_sender_2 = caller()->AddAudioTrack();
2631 auto video_sender_2 = caller()->AddVideoTrack();
2632 caller()->CreateAndSetAndSignalOffer();
2633 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2634
2635 MediaExpectations media_expectations;
2636 media_expectations.CalleeExpectsSomeAudioAndVideo();
2637 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2638
2639 std::vector<std::string> track_ids = {
2640 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2641 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2642
2643 auto caller_stats = caller()->OldGetStats();
2644 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2645 auto callee_stats = callee()->OldGetStats();
2646 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2647}
2648
Steve Antonffa6ce42018-11-30 09:26:08 -08002649// Test that the new GetStats() returns stats for all outgoing/incoming streams
2650// with the correct track IDs if there are more than one audio and more than one
2651// video senders/receivers.
2652TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2653 ASSERT_TRUE(CreatePeerConnectionWrappers());
2654 ConnectFakeSignaling();
2655 auto audio_sender_1 = caller()->AddAudioTrack();
2656 auto video_sender_1 = caller()->AddVideoTrack();
2657 auto audio_sender_2 = caller()->AddAudioTrack();
2658 auto video_sender_2 = caller()->AddVideoTrack();
2659 caller()->CreateAndSetAndSignalOffer();
2660 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2661
2662 MediaExpectations media_expectations;
2663 media_expectations.CalleeExpectsSomeAudioAndVideo();
2664 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2665
2666 std::vector<std::string> track_ids = {
2667 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2668 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2669
2670 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2671 caller()->NewGetStats();
2672 ASSERT_TRUE(caller_report);
2673 auto outbound_stream_stats =
2674 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2675 ASSERT_EQ(4u, outbound_stream_stats.size());
2676 std::vector<std::string> outbound_track_ids;
2677 for (const auto& stat : outbound_stream_stats) {
2678 ASSERT_TRUE(stat->bytes_sent.is_defined());
2679 EXPECT_LT(0u, *stat->bytes_sent);
2680 ASSERT_TRUE(stat->track_id.is_defined());
2681 const auto* track_stat =
2682 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2683 ASSERT_TRUE(track_stat);
2684 outbound_track_ids.push_back(*track_stat->track_identifier);
2685 }
2686 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2687
2688 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2689 callee()->NewGetStats();
2690 ASSERT_TRUE(callee_report);
2691 auto inbound_stream_stats =
2692 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2693 ASSERT_EQ(4u, inbound_stream_stats.size());
2694 std::vector<std::string> inbound_track_ids;
2695 for (const auto& stat : inbound_stream_stats) {
2696 ASSERT_TRUE(stat->bytes_received.is_defined());
2697 EXPECT_LT(0u, *stat->bytes_received);
2698 ASSERT_TRUE(stat->track_id.is_defined());
2699 const auto* track_stat =
2700 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2701 ASSERT_TRUE(track_stat);
2702 inbound_track_ids.push_back(*track_stat->track_identifier);
2703 }
2704 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2705}
2706
2707// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002708// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2709// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002710TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002711 GetStatsForUnsignaledStreamWithNewStatsApi) {
2712 ASSERT_TRUE(CreatePeerConnectionWrappers());
2713 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002714 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002715 // Remove SSRCs and MSIDs from the received offer SDP.
2716 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2717 caller()->CreateAndSetAndSignalOffer();
2718 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002719 MediaExpectations media_expectations;
2720 media_expectations.CalleeExpectsSomeAudio(1);
2721 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002722
2723 // We received a frame, so we should have nonzero "bytes received" stats for
2724 // the unsignaled stream, if stats are working for it.
2725 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2726 callee()->NewGetStats();
2727 ASSERT_NE(nullptr, report);
2728 auto inbound_stream_stats =
2729 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2730 ASSERT_EQ(1U, inbound_stream_stats.size());
2731 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2732 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002733 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2734}
2735
Taylor Brandstettera4653442018-06-19 09:44:26 -07002736// Same as above but for the legacy stats implementation.
2737TEST_P(PeerConnectionIntegrationTest,
2738 GetStatsForUnsignaledStreamWithOldStatsApi) {
2739 ASSERT_TRUE(CreatePeerConnectionWrappers());
2740 ConnectFakeSignaling();
2741 caller()->AddAudioTrack();
2742 // Remove SSRCs and MSIDs from the received offer SDP.
2743 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2744 caller()->CreateAndSetAndSignalOffer();
2745 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2746
2747 // Note that, since the old stats implementation associates SSRCs with tracks
2748 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2749 // associated track ID. So we can't use the track "selector" argument.
2750 //
2751 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2752 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002753 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002754 kDefaultTimeout);
2755}
2756
zhihuangf8164932017-05-19 13:09:47 -07002757// Test that we can successfully get the media related stats (audio level
2758// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002759TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002760 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2761 ASSERT_TRUE(CreatePeerConnectionWrappers());
2762 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002763 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002764 // Remove SSRCs and MSIDs from the received offer SDP.
2765 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2766 caller()->CreateAndSetAndSignalOffer();
2767 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002768 MediaExpectations media_expectations;
2769 media_expectations.CalleeExpectsSomeAudio(1);
2770 media_expectations.CalleeExpectsSomeVideo(1);
2771 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002772
2773 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2774 callee()->NewGetStats();
2775 ASSERT_NE(nullptr, report);
2776
2777 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2778 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2779 ASSERT_GE(audio_index, 0);
2780 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002781}
2782
deadbeef4e2deab2017-09-20 13:56:21 -07002783// Helper for test below.
2784void ModifySsrcs(cricket::SessionDescription* desc) {
2785 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002786 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002787 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002788 for (uint32_t& ssrc : stream.ssrcs) {
2789 ssrc = rtc::CreateRandomId();
2790 }
2791 }
2792 }
2793}
2794
2795// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2796// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2797// This should result in two "RTCInboundRTPStreamStats", but only one
2798// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2799// being reset to 0 once the SSRC change occurs.
2800//
2801// Regression test for this bug:
2802// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2803//
2804// The bug causes the track stats to only represent one of the two streams:
2805// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2806// that the track stat counters would reset to 0 when the new stream is
2807// received, and a 50% chance that they'll stop updating (while
2808// "concealed_samples" continues increasing, due to silence being generated for
2809// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002810TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002811 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002812 ASSERT_TRUE(CreatePeerConnectionWrappers());
2813 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002814 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002815 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2816 // that doesn't signal SSRCs (from the callee's perspective).
2817 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2818 caller()->CreateAndSetAndSignalOffer();
2819 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2820 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002821 {
2822 MediaExpectations media_expectations;
2823 media_expectations.CalleeExpectsSomeAudio(50);
2824 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2825 }
deadbeef4e2deab2017-09-20 13:56:21 -07002826 // Some audio frames were received, so we should have nonzero "samples
2827 // received" for the track.
2828 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2829 callee()->NewGetStats();
2830 ASSERT_NE(nullptr, report);
2831 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2832 ASSERT_EQ(1U, track_stats.size());
2833 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2834 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2835 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2836
2837 // Create a new offer and munge it to cause the caller to use a new SSRC.
2838 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2839 caller()->CreateAndSetAndSignalOffer();
2840 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2841 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2842 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002843 {
2844 MediaExpectations media_expectations;
2845 media_expectations.CalleeExpectsSomeAudio(25);
2846 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2847 }
deadbeef4e2deab2017-09-20 13:56:21 -07002848
2849 report = callee()->NewGetStats();
2850 ASSERT_NE(nullptr, report);
2851 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2852 ASSERT_EQ(1U, track_stats.size());
2853 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2854 // The "total samples received" stat should only be greater than it was
2855 // before.
2856 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2857 // Right now, the new SSRC will cause the counters to reset to 0.
2858 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2859
2860 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002861 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002862 // good sign that we're seeing stats from the old stream that's no longer
2863 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002864 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002865 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2866 EXPECT_LT(*track_stats[0]->concealed_samples,
2867 *track_stats[0]->total_samples_received *
2868 kAcceptableConcealedSamplesPercentage);
2869
2870 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2871 // sanity check that the SSRC really changed.
2872 // TODO(deadbeef): This isn't working right now, because we're not returning
2873 // *any* stats for the inactive stream. Uncomment when the bug is completely
2874 // fixed.
2875 // auto inbound_stream_stats =
2876 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2877 // ASSERT_EQ(2U, inbound_stream_stats.size());
2878}
2879
deadbeef1dcb1642017-03-29 21:08:16 -07002880// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002881TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002882 PeerConnectionFactory::Options dtls_10_options;
2883 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2884 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2885 dtls_10_options));
2886 ConnectFakeSignaling();
2887 // Do normal offer/answer and wait for some frames to be received in each
2888 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002889 caller()->AddAudioVideoTracks();
2890 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002891 caller()->CreateAndSetAndSignalOffer();
2892 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002893 MediaExpectations media_expectations;
2894 media_expectations.ExpectBidirectionalAudioAndVideo();
2895 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002896}
2897
2898// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002899TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002900 PeerConnectionFactory::Options dtls_10_options;
2901 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2902 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2903 dtls_10_options));
2904 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002905 caller()->AddAudioVideoTracks();
2906 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002907 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002908 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002909 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002910 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002911 kDefaultTimeout);
2912 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002913 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002914 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002915 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002916 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2917 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002918}
2919
2920// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002921TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002922 PeerConnectionFactory::Options dtls_12_options;
2923 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2924 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2925 dtls_12_options));
2926 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002927 caller()->AddAudioVideoTracks();
2928 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002929 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002930 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002931 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002932 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002933 kDefaultTimeout);
2934 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002935 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002936 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002937 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002938 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2939 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002940}
2941
2942// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2943// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002944TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002945 PeerConnectionFactory::Options caller_options;
2946 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2947 PeerConnectionFactory::Options callee_options;
2948 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2949 ASSERT_TRUE(
2950 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2951 ConnectFakeSignaling();
2952 // Do normal offer/answer and wait for some frames to be received in each
2953 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002954 caller()->AddAudioVideoTracks();
2955 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002956 caller()->CreateAndSetAndSignalOffer();
2957 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002958 MediaExpectations media_expectations;
2959 media_expectations.ExpectBidirectionalAudioAndVideo();
2960 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002961}
2962
2963// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2964// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002965TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07002966 PeerConnectionFactory::Options caller_options;
2967 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2968 PeerConnectionFactory::Options callee_options;
2969 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2970 ASSERT_TRUE(
2971 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2972 ConnectFakeSignaling();
2973 // Do normal offer/answer and wait for some frames to be received in each
2974 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002975 caller()->AddAudioVideoTracks();
2976 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002977 caller()->CreateAndSetAndSignalOffer();
2978 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002979 MediaExpectations media_expectations;
2980 media_expectations.ExpectBidirectionalAudioAndVideo();
2981 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002982}
2983
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002984// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
2985// works as expected; the cipher should only be used if enabled by both sides.
2986TEST_P(PeerConnectionIntegrationTest,
2987 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
2988 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002989 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002990 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002991 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
2992 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002993 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2994 TestNegotiatedCipherSuite(caller_options, callee_options,
2995 expected_cipher_suite);
2996}
2997
2998TEST_P(PeerConnectionIntegrationTest,
2999 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3000 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003001 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3002 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003003 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003004 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003005 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3006 TestNegotiatedCipherSuite(caller_options, callee_options,
3007 expected_cipher_suite);
3008}
3009
3010TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3011 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003012 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003013 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003014 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003015 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3016 TestNegotiatedCipherSuite(caller_options, callee_options,
3017 expected_cipher_suite);
3018}
3019
deadbeef1dcb1642017-03-29 21:08:16 -07003020// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003021TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003022 bool local_gcm_enabled = false;
3023 bool remote_gcm_enabled = false;
3024 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3025 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3026 expected_cipher_suite);
3027}
3028
3029// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003030TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003031 bool local_gcm_enabled = true;
3032 bool remote_gcm_enabled = true;
3033 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3034 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3035 expected_cipher_suite);
3036}
3037
3038// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003039TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003040 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
3041 bool local_gcm_enabled = true;
3042 bool remote_gcm_enabled = false;
3043 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3044 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3045 expected_cipher_suite);
3046}
3047
3048// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003049TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003050 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
3051 bool local_gcm_enabled = false;
3052 bool remote_gcm_enabled = true;
3053 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3054 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3055 expected_cipher_suite);
3056}
3057
deadbeef7914b8c2017-04-21 03:23:33 -07003058// Verify that media can be transmitted end-to-end when GCM crypto suites are
3059// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3060// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3061// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003062TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003063 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003064 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07003065 ASSERT_TRUE(
3066 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3067 ConnectFakeSignaling();
3068 // Do normal offer/answer and wait for some frames to be received in each
3069 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003070 caller()->AddAudioVideoTracks();
3071 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003072 caller()->CreateAndSetAndSignalOffer();
3073 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003074 MediaExpectations media_expectations;
3075 media_expectations.ExpectBidirectionalAudioAndVideo();
3076 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003077}
3078
deadbeef1dcb1642017-03-29 21:08:16 -07003079// This test sets up a call between two parties with audio, video and an RTP
3080// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003081TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003082 PeerConnectionInterface::RTCConfiguration rtc_config;
3083 rtc_config.enable_rtp_data_channel = true;
3084 rtc_config.enable_dtls_srtp = false;
3085 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003086 ConnectFakeSignaling();
3087 // Expect that data channel created on caller side will show up for callee as
3088 // well.
3089 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003090 caller()->AddAudioVideoTracks();
3091 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003092 caller()->CreateAndSetAndSignalOffer();
3093 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3094 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003095 MediaExpectations media_expectations;
3096 media_expectations.ExpectBidirectionalAudioAndVideo();
3097 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003098 ASSERT_NE(nullptr, caller()->data_channel());
3099 ASSERT_NE(nullptr, callee()->data_channel());
3100 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3101 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3102
3103 // Ensure data can be sent in both directions.
3104 std::string data = "hello world";
3105 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3106 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3107 kDefaultTimeout);
3108 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3109 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3110 kDefaultTimeout);
3111}
3112
3113// Ensure that an RTP data channel is signaled as closed for the caller when
3114// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003115TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003116 RtpDataChannelSignaledClosedInCalleeOffer) {
3117 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003118 PeerConnectionInterface::RTCConfiguration rtc_config;
3119 rtc_config.enable_rtp_data_channel = true;
3120 rtc_config.enable_dtls_srtp = false;
3121 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003122 ConnectFakeSignaling();
3123 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003124 caller()->AddAudioVideoTracks();
3125 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003126 caller()->CreateAndSetAndSignalOffer();
3127 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3128 ASSERT_NE(nullptr, caller()->data_channel());
3129 ASSERT_NE(nullptr, callee()->data_channel());
3130 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3131 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3132
3133 // Close the data channel on the callee, and do an updated offer/answer.
3134 callee()->data_channel()->Close();
3135 callee()->CreateAndSetAndSignalOffer();
3136 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3137 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3138 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3139}
3140
3141// Tests that data is buffered in an RTP data channel until an observer is
3142// registered for it.
3143//
3144// NOTE: RTP data channels can receive data before the underlying
3145// transport has detected that a channel is writable and thus data can be
3146// received before the data channel state changes to open. That is hard to test
3147// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003148TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003149 DataBufferedUntilRtpDataChannelObserverRegistered) {
3150 // Use fake clock and simulated network delay so that we predictably can wait
3151 // until an SCTP message has been delivered without "sleep()"ing.
3152 rtc::ScopedFakeClock fake_clock;
3153 // Some things use a time of "0" as a special value, so we need to start out
3154 // the fake clock at a nonzero time.
3155 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003156 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003157 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3158 virtual_socket_server()->UpdateDelayDistribution();
3159
Niels Möllerf06f9232018-08-07 12:32:18 +02003160 PeerConnectionInterface::RTCConfiguration rtc_config;
3161 rtc_config.enable_rtp_data_channel = true;
3162 rtc_config.enable_dtls_srtp = false;
3163 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003164 ConnectFakeSignaling();
3165 caller()->CreateDataChannel();
3166 caller()->CreateAndSetAndSignalOffer();
3167 ASSERT_TRUE(caller()->data_channel() != nullptr);
3168 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3169 kDefaultTimeout, fake_clock);
3170 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3171 kDefaultTimeout, fake_clock);
3172 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3173 callee()->data_channel()->state(), kDefaultTimeout,
3174 fake_clock);
3175
3176 // Unregister the observer which is normally automatically registered.
3177 callee()->data_channel()->UnregisterObserver();
3178 // Send data and advance fake clock until it should have been received.
3179 std::string data = "hello world";
3180 caller()->data_channel()->Send(DataBuffer(data));
3181 SIMULATED_WAIT(false, 50, fake_clock);
3182
3183 // Attach data channel and expect data to be received immediately. Note that
3184 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3185 // further, but data can be received even if the callback is asynchronous.
3186 MockDataChannelObserver new_observer(callee()->data_channel());
3187 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3188 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003189 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3190 // If this is not done a DCHECK can be hit in ports.cc, because a large
3191 // negative number is calculated for the rtt due to the global clock changing.
3192 caller()->pc()->Close();
3193 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07003194}
3195
3196// This test sets up a call between two parties with audio, video and but only
3197// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003198TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003199 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3200 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003201 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003202 rtc_config_1.enable_dtls_srtp = false;
3203 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3204 rtc_config_2.enable_dtls_srtp = false;
3205 rtc_config_2.enable_dtls_srtp = false;
3206 ASSERT_TRUE(
3207 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003208 ConnectFakeSignaling();
3209 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003210 caller()->AddAudioVideoTracks();
3211 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003212 caller()->CreateAndSetAndSignalOffer();
3213 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3214 // The caller should still have a data channel, but it should be closed, and
3215 // one should ever have been created for the callee.
3216 EXPECT_TRUE(caller()->data_channel() != nullptr);
3217 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3218 EXPECT_EQ(nullptr, callee()->data_channel());
3219}
3220
3221// This test sets up a call between two parties with audio, and video. When
3222// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003223TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003224 PeerConnectionInterface::RTCConfiguration rtc_config;
3225 rtc_config.enable_rtp_data_channel = true;
3226 rtc_config.enable_dtls_srtp = false;
3227 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003228 ConnectFakeSignaling();
3229 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003230 caller()->AddAudioVideoTracks();
3231 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003232 caller()->CreateAndSetAndSignalOffer();
3233 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3234 // Create data channel and do new offer and answer.
3235 caller()->CreateDataChannel();
3236 caller()->CreateAndSetAndSignalOffer();
3237 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3238 ASSERT_NE(nullptr, caller()->data_channel());
3239 ASSERT_NE(nullptr, callee()->data_channel());
3240 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3241 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3242 // Ensure data can be sent in both directions.
3243 std::string data = "hello world";
3244 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3245 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3246 kDefaultTimeout);
3247 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3248 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3249 kDefaultTimeout);
3250}
3251
3252#ifdef HAVE_SCTP
3253
3254// This test sets up a call between two parties with audio, video and an SCTP
3255// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003256TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003257 ASSERT_TRUE(CreatePeerConnectionWrappers());
3258 ConnectFakeSignaling();
3259 // Expect that data channel created on caller side will show up for callee as
3260 // well.
3261 caller()->CreateDataChannel();
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 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003267 MediaExpectations media_expectations;
3268 media_expectations.ExpectBidirectionalAudioAndVideo();
3269 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003270 // Caller data channel should already exist (it created one). Callee data
3271 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3272 ASSERT_NE(nullptr, caller()->data_channel());
3273 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3274 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3275 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3276
3277 // Ensure data can be sent in both directions.
3278 std::string data = "hello world";
3279 caller()->data_channel()->Send(DataBuffer(data));
3280 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3281 kDefaultTimeout);
3282 callee()->data_channel()->Send(DataBuffer(data));
3283 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3284 kDefaultTimeout);
3285}
3286
3287// Ensure that when the callee closes an SCTP data channel, the closing
3288// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003289TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003290 // Same procedure as above test.
3291 ASSERT_TRUE(CreatePeerConnectionWrappers());
3292 ConnectFakeSignaling();
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 ASSERT_NE(nullptr, caller()->data_channel());
3299 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3300 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3301 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3302
3303 // Close the data channel on the callee side, and wait for it to reach the
3304 // "closed" state on both sides.
3305 callee()->data_channel()->Close();
3306 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3307 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3308}
3309
Seth Hampson2f0d7022018-02-20 11:54:42 -08003310TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003311 ASSERT_TRUE(CreatePeerConnectionWrappers());
3312 ConnectFakeSignaling();
3313 webrtc::DataChannelInit init;
3314 init.id = 53;
3315 init.maxRetransmits = 52;
3316 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003317 caller()->AddAudioVideoTracks();
3318 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003319 caller()->CreateAndSetAndSignalOffer();
3320 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003321 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3322 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07003323 EXPECT_EQ(init.id, callee()->data_channel()->id());
3324 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3325 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3326 EXPECT_FALSE(callee()->data_channel()->negotiated());
3327}
3328
deadbeef1dcb1642017-03-29 21:08:16 -07003329// Test usrsctp's ability to process unordered data stream, where data actually
3330// arrives out of order using simulated delays. Previously there have been some
3331// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003332TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003333 // Introduce random network delays.
3334 // Otherwise it's not a true "unordered" test.
3335 virtual_socket_server()->set_delay_mean(20);
3336 virtual_socket_server()->set_delay_stddev(5);
3337 virtual_socket_server()->UpdateDelayDistribution();
3338 // Normal procedure, but with unordered data channel config.
3339 ASSERT_TRUE(CreatePeerConnectionWrappers());
3340 ConnectFakeSignaling();
3341 webrtc::DataChannelInit init;
3342 init.ordered = false;
3343 caller()->CreateDataChannel(&init);
3344 caller()->CreateAndSetAndSignalOffer();
3345 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3346 ASSERT_NE(nullptr, caller()->data_channel());
3347 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3348 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3349 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3350
3351 static constexpr int kNumMessages = 100;
3352 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3353 static constexpr size_t kMaxMessageSize = 4096;
3354 // Create and send random messages.
3355 std::vector<std::string> sent_messages;
3356 for (int i = 0; i < kNumMessages; ++i) {
3357 size_t length =
3358 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3359 std::string message;
3360 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3361 caller()->data_channel()->Send(DataBuffer(message));
3362 callee()->data_channel()->Send(DataBuffer(message));
3363 sent_messages.push_back(message);
3364 }
3365
3366 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003367 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003368 caller()->data_observer()->received_message_count(),
3369 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003370 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003371 callee()->data_observer()->received_message_count(),
3372 kDefaultTimeout);
3373
3374 // Sort and compare to make sure none of the messages were corrupted.
3375 std::vector<std::string> caller_received_messages =
3376 caller()->data_observer()->messages();
3377 std::vector<std::string> callee_received_messages =
3378 callee()->data_observer()->messages();
3379 std::sort(sent_messages.begin(), sent_messages.end());
3380 std::sort(caller_received_messages.begin(), caller_received_messages.end());
3381 std::sort(callee_received_messages.begin(), callee_received_messages.end());
3382 EXPECT_EQ(sent_messages, caller_received_messages);
3383 EXPECT_EQ(sent_messages, callee_received_messages);
3384}
3385
3386// This test sets up a call between two parties with audio, and video. When
3387// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003388TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003389 ASSERT_TRUE(CreatePeerConnectionWrappers());
3390 ConnectFakeSignaling();
3391 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003392 caller()->AddAudioVideoTracks();
3393 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003394 caller()->CreateAndSetAndSignalOffer();
3395 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3396 // Create data channel and do new offer and answer.
3397 caller()->CreateDataChannel();
3398 caller()->CreateAndSetAndSignalOffer();
3399 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3400 // Caller data channel should already exist (it created one). Callee data
3401 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3402 ASSERT_NE(nullptr, caller()->data_channel());
3403 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3404 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3405 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3406 // Ensure data can be sent in both directions.
3407 std::string data = "hello world";
3408 caller()->data_channel()->Send(DataBuffer(data));
3409 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3410 kDefaultTimeout);
3411 callee()->data_channel()->Send(DataBuffer(data));
3412 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3413 kDefaultTimeout);
3414}
3415
deadbeef7914b8c2017-04-21 03:23:33 -07003416// Set up a connection initially just using SCTP data channels, later upgrading
3417// to audio/video, ensuring frames are received end-to-end. Effectively the
3418// inverse of the test above.
3419// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003420TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003421 ASSERT_TRUE(CreatePeerConnectionWrappers());
3422 ConnectFakeSignaling();
3423 // Do initial offer/answer with just data channel.
3424 caller()->CreateDataChannel();
3425 caller()->CreateAndSetAndSignalOffer();
3426 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3427 // Wait until data can be sent over the data channel.
3428 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3429 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3430 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3431
3432 // Do subsequent offer/answer with two-way audio and video. Audio and video
3433 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003434 caller()->AddAudioVideoTracks();
3435 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003436 caller()->CreateAndSetAndSignalOffer();
3437 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003438 MediaExpectations media_expectations;
3439 media_expectations.ExpectBidirectionalAudioAndVideo();
3440 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003441}
3442
deadbeef8b7e9ad2017-05-25 09:38:55 -07003443static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07003444 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08003445 GetFirstDataContentDescription(desc);
3446 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003447 dcd_offer->set_use_sctpmap(false);
3448 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3449}
3450
3451// Test that the data channel works when a spec-compliant SCTP m= section is
3452// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3453// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003454TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003455 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3456 ASSERT_TRUE(CreatePeerConnectionWrappers());
3457 ConnectFakeSignaling();
3458 caller()->CreateDataChannel();
3459 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3460 caller()->CreateAndSetAndSignalOffer();
3461 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3462 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3463 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3464 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3465
3466 // Ensure data can be sent in both directions.
3467 std::string data = "hello world";
3468 caller()->data_channel()->Send(DataBuffer(data));
3469 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3470 kDefaultTimeout);
3471 callee()->data_channel()->Send(DataBuffer(data));
3472 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3473 kDefaultTimeout);
3474}
3475
deadbeef1dcb1642017-03-29 21:08:16 -07003476#endif // HAVE_SCTP
3477
Bjorn Mellema2eb0a72018-11-09 10:13:51 -08003478// This test sets up a call between two parties with a media transport data
3479// channel.
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003480TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
3481 PeerConnectionInterface::RTCConfiguration rtc_config;
3482 rtc_config.use_media_transport_for_data_channels = true;
3483 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3484 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3485 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3486 loopback_media_transports()->second_factory()));
3487 ConnectFakeSignaling();
3488
3489 // Expect that data channel created on caller side will show up for callee as
3490 // well.
3491 caller()->CreateDataChannel();
3492 caller()->CreateAndSetAndSignalOffer();
3493 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3494
3495 // Ensure that the media transport is ready.
3496 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3497 loopback_media_transports()->FlushAsyncInvokes();
3498
3499 // Caller data channel should already exist (it created one). Callee data
3500 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3501 ASSERT_NE(nullptr, caller()->data_channel());
3502 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3503 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3504 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3505
3506 // Ensure data can be sent in both directions.
3507 std::string data = "hello world";
3508 caller()->data_channel()->Send(DataBuffer(data));
3509 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3510 kDefaultTimeout);
3511 callee()->data_channel()->Send(DataBuffer(data));
3512 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3513 kDefaultTimeout);
3514}
3515
3516// Ensure that when the callee closes a media transport data channel, the
3517// closing procedure results in the data channel being closed for the caller
3518// as well.
3519TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
3520 PeerConnectionInterface::RTCConfiguration rtc_config;
3521 rtc_config.use_media_transport_for_data_channels = true;
3522 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3523 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3524 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3525 loopback_media_transports()->second_factory()));
3526 ConnectFakeSignaling();
3527
3528 // Create a data channel on the caller and signal it to the callee.
3529 caller()->CreateDataChannel();
3530 caller()->CreateAndSetAndSignalOffer();
3531 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3532
3533 // Ensure that the media transport is ready.
3534 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3535 loopback_media_transports()->FlushAsyncInvokes();
3536
3537 // Data channels exist and open on both ends of the connection.
3538 ASSERT_NE(nullptr, caller()->data_channel());
3539 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3540 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3541 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3542
3543 // Close the data channel on the callee side, and wait for it to reach the
3544 // "closed" state on both sides.
3545 callee()->data_channel()->Close();
3546 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3547 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3548}
3549
3550TEST_P(PeerConnectionIntegrationTest,
3551 MediaTransportDataChannelConfigSentToOtherSide) {
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 with a non-default configuration and signal it to the
3561 // callee.
3562 webrtc::DataChannelInit init;
3563 init.id = 53;
3564 init.maxRetransmits = 52;
3565 caller()->CreateDataChannel("data-channel", &init);
3566 caller()->CreateAndSetAndSignalOffer();
3567 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3568
3569 // Ensure that the media transport is ready.
3570 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3571 loopback_media_transports()->FlushAsyncInvokes();
3572
3573 // Ensure that the data channel exists on the callee with the correct
3574 // configuration.
3575 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3576 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3577 EXPECT_EQ(init.id, callee()->data_channel()->id());
3578 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3579 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3580 EXPECT_FALSE(callee()->data_channel()->negotiated());
3581}
3582
Niels Möllerc68d2822018-11-20 14:52:05 +01003583TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
3584 PeerConnectionInterface::RTCConfiguration rtc_config;
3585 rtc_config.use_media_transport = 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 caller()->AddAudioTrack();
3593 callee()->AddAudioTrack();
3594 // Start offer/answer exchange and wait for it to complete.
3595 caller()->CreateAndSetAndSignalOffer();
3596 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3597
3598 // Ensure that the media transport is ready.
3599 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3600 loopback_media_transports()->FlushAsyncInvokes();
3601
3602 MediaExpectations media_expectations;
3603 media_expectations.ExpectBidirectionalAudio();
3604 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3605
3606 webrtc::MediaTransportPair::Stats first_stats =
3607 loopback_media_transports()->FirstStats();
3608 webrtc::MediaTransportPair::Stats second_stats =
3609 loopback_media_transports()->SecondStats();
3610
3611 EXPECT_GT(first_stats.received_audio_frames, 0);
3612 EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
3613
3614 EXPECT_GT(second_stats.received_audio_frames, 0);
3615 EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
3616}
3617
deadbeef1dcb1642017-03-29 21:08:16 -07003618// Test that the ICE connection and gathering states eventually reach
3619// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003620TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003621 ASSERT_TRUE(CreatePeerConnectionWrappers());
3622 ConnectFakeSignaling();
3623 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003624 caller()->AddAudioVideoTracks();
3625 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003626 caller()->CreateAndSetAndSignalOffer();
3627 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3628 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3629 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3630 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3631 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3632 // After the best candidate pair is selected and all candidates are signaled,
3633 // the ICE connection state should reach "complete".
3634 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3635 // answerer/"callee" by default) only reaches "connected". When this is
3636 // fixed, this test should be updated.
3637 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3638 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003639 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3640 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003641}
3642
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003643// Replaces the first candidate with a static address and configures a
3644// MockAsyncResolver to return the replaced address the first time the static
3645// address is resolved. Candidates past the first will not be signaled.
3646class ReplaceFirstCandidateAddressDropOthers final
3647 : public IceCandidateReplacerInterface {
3648 public:
3649 ReplaceFirstCandidateAddressDropOthers(
3650 const SocketAddress& new_address,
3651 rtc::MockAsyncResolver* mock_async_resolver)
3652 : mock_async_resolver_(mock_async_resolver), new_address_(new_address) {
3653 RTC_DCHECK(mock_async_resolver);
3654 }
3655
3656 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3657 const webrtc::IceCandidateInterface* candidate) override {
3658 if (replaced_candidate_) {
3659 return nullptr;
3660 }
3661
3662 replaced_candidate_ = true;
3663 cricket::Candidate new_candidate(candidate->candidate());
3664 new_candidate.set_address(new_address_);
3665 EXPECT_CALL(*mock_async_resolver_, GetResolvedAddress(_, _))
3666 .WillOnce(DoAll(SetArgPointee<1>(candidate->candidate().address()),
3667 Return(true)));
3668 EXPECT_CALL(*mock_async_resolver_, Destroy(_));
3669 return webrtc::CreateIceCandidate(
3670 candidate->sdp_mid(), candidate->sdp_mline_index(), new_candidate);
3671 }
3672
3673 private:
3674 rtc::MockAsyncResolver* mock_async_resolver_;
3675 SocketAddress new_address_;
3676 bool replaced_candidate_ = false;
3677};
3678
3679// Drops all candidates before they are signaled.
3680class DropAllCandidates final : public IceCandidateReplacerInterface {
3681 public:
3682 std::unique_ptr<webrtc::IceCandidateInterface> ReplaceCandidate(
3683 const webrtc::IceCandidateInterface*) override {
3684 return nullptr;
3685 }
3686};
3687
3688// Replace the first caller ICE candidate IP with a fake hostname and drop the
3689// other candidates. Drop all candidates on the callee side (to avoid a prflx
3690// connection). Use a mock resolver to resolve the hostname back to the original
3691// IP on the callee side and check that the ice connection connects.
3692TEST_P(PeerConnectionIntegrationTest,
3693 IceStatesReachCompletionWithRemoteHostname) {
3694 webrtc::MockAsyncResolverFactory* callee_mock_async_resolver_factory;
3695 {
3696 auto resolver_factory =
3697 absl::make_unique<webrtc::MockAsyncResolverFactory>();
3698 callee_mock_async_resolver_factory = resolver_factory.get();
3699 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3700 callee_deps.async_resolver_factory = std::move(resolver_factory);
3701
3702 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3703 RTCConfiguration(), webrtc::PeerConnectionDependencies(nullptr),
3704 RTCConfiguration(), std::move(callee_deps)));
3705 }
3706
3707 rtc::MockAsyncResolver mock_async_resolver;
3708
3709 // This also verifies that the injected AsyncResolverFactory is used by
3710 // P2PTransportChannel.
3711 EXPECT_CALL(*callee_mock_async_resolver_factory, Create())
3712 .WillOnce(Return(&mock_async_resolver));
3713 caller()->SetLocalIceCandidateReplacer(
3714 absl::make_unique<ReplaceFirstCandidateAddressDropOthers>(
3715 SocketAddress("a.b", 10000), &mock_async_resolver));
3716 callee()->SetLocalIceCandidateReplacer(
3717 absl::make_unique<DropAllCandidates>());
3718
3719 ConnectFakeSignaling();
3720 caller()->AddAudioVideoTracks();
3721 callee()->AddAudioVideoTracks();
3722 caller()->CreateAndSetAndSignalOffer();
3723 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3724 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3725 caller()->ice_connection_state(), kDefaultTimeout);
3726 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3727 callee()->ice_connection_state(), kDefaultTimeout);
3728}
3729
Steve Antonede9ca52017-10-16 13:04:27 -07003730// Test that firewalling the ICE connection causes the clients to identify the
3731// disconnected state and then removing the firewall causes them to reconnect.
3732class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003733 : public PeerConnectionIntegrationBaseTest,
3734 public ::testing::WithParamInterface<
3735 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003736 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003737 PeerConnectionIntegrationIceStatesTest()
3738 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3739 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003740 }
3741
3742 void StartStunServer(const SocketAddress& server_address) {
3743 stun_server_.reset(
3744 cricket::TestStunServer::Create(network_thread(), server_address));
3745 }
3746
3747 bool TestIPv6() {
3748 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3749 }
3750
3751 void SetPortAllocatorFlags() {
Qingsi Wanga2d60672018-04-11 16:57:45 -07003752 network_thread()->Invoke<void>(
3753 RTC_FROM_HERE,
3754 rtc::Bind(&cricket::PortAllocator::set_flags,
3755 caller()->port_allocator(), port_allocator_flags_));
3756 network_thread()->Invoke<void>(
3757 RTC_FROM_HERE,
3758 rtc::Bind(&cricket::PortAllocator::set_flags,
3759 callee()->port_allocator(), port_allocator_flags_));
Steve Antonede9ca52017-10-16 13:04:27 -07003760 }
3761
3762 std::vector<SocketAddress> CallerAddresses() {
3763 std::vector<SocketAddress> addresses;
3764 addresses.push_back(SocketAddress("1.1.1.1", 0));
3765 if (TestIPv6()) {
3766 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3767 }
3768 return addresses;
3769 }
3770
3771 std::vector<SocketAddress> CalleeAddresses() {
3772 std::vector<SocketAddress> addresses;
3773 addresses.push_back(SocketAddress("2.2.2.2", 0));
3774 if (TestIPv6()) {
3775 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3776 }
3777 return addresses;
3778 }
3779
3780 void SetUpNetworkInterfaces() {
3781 // Remove the default interfaces added by the test infrastructure.
3782 caller()->network()->RemoveInterface(kDefaultLocalAddress);
3783 callee()->network()->RemoveInterface(kDefaultLocalAddress);
3784
3785 // Add network addresses for test.
3786 for (const auto& caller_address : CallerAddresses()) {
3787 caller()->network()->AddInterface(caller_address);
3788 }
3789 for (const auto& callee_address : CalleeAddresses()) {
3790 callee()->network()->AddInterface(callee_address);
3791 }
3792 }
3793
3794 private:
3795 uint32_t port_allocator_flags_;
3796 std::unique_ptr<cricket::TestStunServer> stun_server_;
3797};
3798
3799// Tests that the PeerConnection goes through all the ICE gathering/connection
3800// states over the duration of the call. This includes Disconnected and Failed
3801// states, induced by putting a firewall between the peers and waiting for them
3802// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003803TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
3804 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
3805 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
3806 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07003807
3808 const SocketAddress kStunServerAddress =
3809 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3810 StartStunServer(kStunServerAddress);
3811
3812 PeerConnectionInterface::RTCConfiguration config;
3813 PeerConnectionInterface::IceServer ice_stun_server;
3814 ice_stun_server.urls.push_back(
3815 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3816 kStunServerAddress.PortAsString());
3817 config.servers.push_back(ice_stun_server);
3818
3819 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3820 ConnectFakeSignaling();
3821 SetPortAllocatorFlags();
3822 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003823 caller()->AddAudioVideoTracks();
3824 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003825
3826 // Initial state before anything happens.
3827 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3828 caller()->ice_gathering_state());
3829 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3830 caller()->ice_connection_state());
3831
3832 // Start the call by creating the offer, setting it as the local description,
3833 // then sending it to the peer who will respond with an answer. This happens
3834 // asynchronously so that we can watch the states as it runs in the
3835 // background.
3836 caller()->CreateAndSetAndSignalOffer();
3837
Steve Anton83119dd2017-11-10 16:19:52 -08003838 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3839 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003840
3841 // Verify that the observer was notified of the intermediate transitions.
3842 EXPECT_THAT(caller()->ice_connection_state_history(),
3843 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3844 PeerConnectionInterface::kIceConnectionConnected,
3845 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02003846 // After the ice transport transitions from checking to connected we revert
3847 // back to new as the standard requires, as at that point the DTLS transport
3848 // is in the "new" state while no transports are "connecting", "checking",
3849 // "failed" or disconnected. This is pretty unintuitive, and we might want to
3850 // amend the spec to handle this case more gracefully.
3851 EXPECT_THAT(
3852 caller()->peer_connection_state_history(),
3853 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
3854 PeerConnectionInterface::PeerConnectionState::kNew,
3855 PeerConnectionInterface::PeerConnectionState::kConnecting,
3856 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07003857 EXPECT_THAT(caller()->ice_gathering_state_history(),
3858 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
3859 PeerConnectionInterface::kIceGatheringComplete));
3860
3861 // Block connections to/from the caller and wait for ICE to become
3862 // disconnected.
3863 for (const auto& caller_address : CallerAddresses()) {
3864 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3865 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003866 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08003867 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
3868 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003869
3870 // Let ICE re-establish by removing the firewall rules.
3871 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01003872 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08003873 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3874 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003875
3876 // According to RFC7675, if there is no response within 30 seconds then the
3877 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08003878 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07003879 constexpr int kConsentTimeout = 30000;
3880 for (const auto& caller_address : CallerAddresses()) {
3881 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3882 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003883 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08003884 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
3885 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003886}
3887
3888// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
3889// and that the statistics in the metric observers are updated correctly.
3890TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
3891 ASSERT_TRUE(CreatePeerConnectionWrappers());
3892 ConnectFakeSignaling();
3893 SetPortAllocatorFlags();
3894 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003895 caller()->AddAudioVideoTracks();
3896 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003897 caller()->CreateAndSetAndSignalOffer();
3898
3899 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3900
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003901 // TODO(bugs.webrtc.org/9456): Fix it.
3902 const int num_best_ipv4 = webrtc::metrics::NumEvents(
3903 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
3904 const int num_best_ipv6 = webrtc::metrics::NumEvents(
3905 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003906 if (TestIPv6()) {
3907 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
3908 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003909 EXPECT_EQ(0, num_best_ipv4);
3910 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003911 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003912 EXPECT_EQ(1, num_best_ipv4);
3913 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003914 }
3915
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003916 EXPECT_EQ(0, webrtc::metrics::NumEvents(
3917 "WebRTC.PeerConnection.CandidatePairType_UDP",
3918 webrtc::kIceCandidatePairHostHost));
3919 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3920 "WebRTC.PeerConnection.CandidatePairType_UDP",
3921 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07003922}
3923
3924constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
3925 cricket::PORTALLOCATOR_DISABLE_STUN |
3926 cricket::PORTALLOCATOR_DISABLE_RELAY;
3927constexpr uint32_t kFlagsIPv6NoStun =
3928 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
3929 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
3930constexpr uint32_t kFlagsIPv4Stun =
3931 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
3932
Seth Hampson2f0d7022018-02-20 11:54:42 -08003933INSTANTIATE_TEST_CASE_P(
3934 PeerConnectionIntegrationTest,
3935 PeerConnectionIntegrationIceStatesTest,
3936 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3937 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
3938 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
3939 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07003940
deadbeef1dcb1642017-03-29 21:08:16 -07003941// This test sets up a call between two parties with audio and video.
3942// During the call, the caller restarts ICE and the test verifies that
3943// new ICE candidates are generated and audio and video still can flow, and the
3944// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003945TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07003946 ASSERT_TRUE(CreatePeerConnectionWrappers());
3947 ConnectFakeSignaling();
3948 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08003949 caller()->AddAudioVideoTracks();
3950 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003951 caller()->CreateAndSetAndSignalOffer();
3952 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3953 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3954 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00003955 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3956 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07003957
3958 // To verify that the ICE restart actually occurs, get
3959 // ufrag/password/candidates before and after restart.
3960 // Create an SDP string of the first audio candidate for both clients.
3961 const webrtc::IceCandidateCollection* audio_candidates_caller =
3962 caller()->pc()->local_description()->candidates(0);
3963 const webrtc::IceCandidateCollection* audio_candidates_callee =
3964 callee()->pc()->local_description()->candidates(0);
3965 ASSERT_GT(audio_candidates_caller->count(), 0u);
3966 ASSERT_GT(audio_candidates_callee->count(), 0u);
3967 std::string caller_candidate_pre_restart;
3968 ASSERT_TRUE(
3969 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
3970 std::string callee_candidate_pre_restart;
3971 ASSERT_TRUE(
3972 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3973 const cricket::SessionDescription* desc =
3974 caller()->pc()->local_description()->description();
3975 std::string caller_ufrag_pre_restart =
3976 desc->transport_infos()[0].description.ice_ufrag;
3977 desc = callee()->pc()->local_description()->description();
3978 std::string callee_ufrag_pre_restart =
3979 desc->transport_infos()[0].description.ice_ufrag;
3980
3981 // Have the caller initiate an ICE restart.
3982 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3983 caller()->CreateAndSetAndSignalOffer();
3984 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3985 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3986 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00003987 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07003988 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3989
3990 // Grab the ufrags/candidates again.
3991 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3992 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3993 ASSERT_GT(audio_candidates_caller->count(), 0u);
3994 ASSERT_GT(audio_candidates_callee->count(), 0u);
3995 std::string caller_candidate_post_restart;
3996 ASSERT_TRUE(
3997 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3998 std::string callee_candidate_post_restart;
3999 ASSERT_TRUE(
4000 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4001 desc = caller()->pc()->local_description()->description();
4002 std::string caller_ufrag_post_restart =
4003 desc->transport_infos()[0].description.ice_ufrag;
4004 desc = callee()->pc()->local_description()->description();
4005 std::string callee_ufrag_post_restart =
4006 desc->transport_infos()[0].description.ice_ufrag;
4007 // Sanity check that an ICE restart was actually negotiated in SDP.
4008 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4009 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4010 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4011 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
4012
4013 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004014 MediaExpectations media_expectations;
4015 media_expectations.ExpectBidirectionalAudioAndVideo();
4016 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004017}
4018
4019// Verify that audio/video can be received end-to-end when ICE renomination is
4020// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004021TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004022 PeerConnectionInterface::RTCConfiguration config;
4023 config.enable_ice_renomination = true;
4024 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4025 ConnectFakeSignaling();
4026 // Do normal offer/answer and wait for some frames to be received in each
4027 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004028 caller()->AddAudioVideoTracks();
4029 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004030 caller()->CreateAndSetAndSignalOffer();
4031 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4032 // Sanity check that ICE renomination was actually negotiated.
4033 const cricket::SessionDescription* desc =
4034 caller()->pc()->local_description()->description();
4035 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07004036 ASSERT_NE(
4037 info.description.transport_options.end(),
4038 std::find(info.description.transport_options.begin(),
4039 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004040 }
4041 desc = callee()->pc()->local_description()->description();
4042 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07004043 ASSERT_NE(
4044 info.description.transport_options.end(),
4045 std::find(info.description.transport_options.begin(),
4046 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004047 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004048 MediaExpectations media_expectations;
4049 media_expectations.ExpectBidirectionalAudioAndVideo();
4050 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004051}
4052
Steve Anton6f25b092017-10-23 09:39:20 -07004053// With a max bundle policy and RTCP muxing, adding a new media description to
4054// the connection should not affect ICE at all because the new media will use
4055// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004056TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004057 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004058 PeerConnectionInterface::RTCConfiguration config;
4059 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4060 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4061 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4062 config, PeerConnectionInterface::RTCConfiguration()));
4063 ConnectFakeSignaling();
4064
Steve Anton15324772018-01-16 10:26:49 -08004065 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004066 caller()->CreateAndSetAndSignalOffer();
4067 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004068 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4069 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004070
4071 caller()->clear_ice_connection_state_history();
4072
Steve Anton15324772018-01-16 10:26:49 -08004073 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004074 caller()->CreateAndSetAndSignalOffer();
4075 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4076
4077 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4078}
4079
deadbeef1dcb1642017-03-29 21:08:16 -07004080// This test sets up a call between two parties with audio and video. It then
4081// renegotiates setting the video m-line to "port 0", then later renegotiates
4082// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004083TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004084 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4085 ASSERT_TRUE(CreatePeerConnectionWrappers());
4086 ConnectFakeSignaling();
4087
4088 // Do initial negotiation, only sending media from the caller. Will result in
4089 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004090 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004091 caller()->CreateAndSetAndSignalOffer();
4092 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4093
4094 // Negotiate again, disabling the video "m=" section (the callee will set the
4095 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004096 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4097 PeerConnectionInterface::RTCOfferAnswerOptions options;
4098 options.offer_to_receive_video = 0;
4099 callee()->SetOfferAnswerOptions(options);
4100 } else {
4101 callee()->SetRemoteOfferHandler([this] {
4102 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4103 });
4104 }
deadbeef1dcb1642017-03-29 21:08:16 -07004105 caller()->CreateAndSetAndSignalOffer();
4106 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4107 // Sanity check that video "m=" section was actually rejected.
4108 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4109 callee()->pc()->local_description()->description());
4110 ASSERT_NE(nullptr, answer_video_content);
4111 ASSERT_TRUE(answer_video_content->rejected);
4112
4113 // Enable video and do negotiation again, making sure video is received
4114 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004115 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4116 PeerConnectionInterface::RTCOfferAnswerOptions options;
4117 options.offer_to_receive_video = 1;
4118 callee()->SetOfferAnswerOptions(options);
4119 } else {
4120 // The caller's transceiver is stopped, so we need to add another track.
4121 auto caller_transceiver =
4122 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4123 EXPECT_TRUE(caller_transceiver->stopped());
4124 caller()->AddVideoTrack();
4125 }
4126 callee()->AddVideoTrack();
4127 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004128 caller()->CreateAndSetAndSignalOffer();
4129 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004130
deadbeef1dcb1642017-03-29 21:08:16 -07004131 // Verify the caller receives frames from the newly added stream, and the
4132 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004133 MediaExpectations media_expectations;
4134 media_expectations.CalleeExpectsSomeAudio();
4135 media_expectations.ExpectBidirectionalVideo();
4136 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004137}
4138
deadbeef1dcb1642017-03-29 21:08:16 -07004139// This tests that if we negotiate after calling CreateSender but before we
4140// have a track, then set a track later, frames from the newly-set track are
4141// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004142TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004143 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4144 ASSERT_TRUE(CreatePeerConnectionWrappers());
4145 ConnectFakeSignaling();
4146 auto caller_audio_sender =
4147 caller()->pc()->CreateSender("audio", "caller_stream");
4148 auto caller_video_sender =
4149 caller()->pc()->CreateSender("video", "caller_stream");
4150 auto callee_audio_sender =
4151 callee()->pc()->CreateSender("audio", "callee_stream");
4152 auto callee_video_sender =
4153 callee()->pc()->CreateSender("video", "callee_stream");
4154 caller()->CreateAndSetAndSignalOffer();
4155 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4156 // Wait for ICE to complete, without any tracks being set.
4157 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4158 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4159 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4160 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4161 // Now set the tracks, and expect frames to immediately start flowing.
4162 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4163 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4164 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4165 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004166 MediaExpectations media_expectations;
4167 media_expectations.ExpectBidirectionalAudioAndVideo();
4168 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4169}
4170
4171// This tests that if we negotiate after calling AddTransceiver but before we
4172// have a track, then set a track later, frames from the newly-set tracks are
4173// received end-to-end.
4174TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4175 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4176 ASSERT_TRUE(CreatePeerConnectionWrappers());
4177 ConnectFakeSignaling();
4178 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4179 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4180 auto caller_audio_sender = audio_result.MoveValue()->sender();
4181 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4182 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4183 auto caller_video_sender = video_result.MoveValue()->sender();
4184 callee()->SetRemoteOfferHandler([this] {
4185 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4186 callee()->pc()->GetTransceivers()[0]->SetDirection(
4187 RtpTransceiverDirection::kSendRecv);
4188 callee()->pc()->GetTransceivers()[1]->SetDirection(
4189 RtpTransceiverDirection::kSendRecv);
4190 });
4191 caller()->CreateAndSetAndSignalOffer();
4192 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4193 // Wait for ICE to complete, without any tracks being set.
4194 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4195 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4196 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4197 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4198 // Now set the tracks, and expect frames to immediately start flowing.
4199 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4200 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4201 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4202 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4203 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4204 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4205 MediaExpectations media_expectations;
4206 media_expectations.ExpectBidirectionalAudioAndVideo();
4207 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004208}
4209
4210// This test verifies that a remote video track can be added via AddStream,
4211// and sent end-to-end. For this particular test, it's simply echoed back
4212// from the caller to the callee, rather than being forwarded to a third
4213// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004214TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004215 ASSERT_TRUE(CreatePeerConnectionWrappers());
4216 ConnectFakeSignaling();
4217 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004218 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004219 caller()->CreateAndSetAndSignalOffer();
4220 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004221 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004222
4223 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4224 // time).
4225 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4226 callee()->CreateAndSetAndSignalOffer();
4227 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4228
Seth Hampson2f0d7022018-02-20 11:54:42 -08004229 MediaExpectations media_expectations;
4230 media_expectations.ExpectBidirectionalVideo();
4231 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004232}
4233
4234// Test that we achieve the expected end-to-end connection time, using a
4235// fake clock and simulated latency on the media and signaling paths.
4236// We use a TURN<->TURN connection because this is usually the quickest to
4237// set up initially, especially when we're confident the connection will work
4238// and can start sending media before we get a STUN response.
4239//
4240// With various optimizations enabled, here are the network delays we expect to
4241// be on the critical path:
4242// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4243// signaling answer (with DTLS fingerprint).
4244// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4245// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4246// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004247TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004248 rtc::ScopedFakeClock fake_clock;
4249 // Some things use a time of "0" as a special value, so we need to start out
4250 // the fake clock at a nonzero time.
4251 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004252 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004253
4254 static constexpr int media_hop_delay_ms = 50;
4255 static constexpr int signaling_trip_delay_ms = 500;
4256 // For explanation of these values, see comment above.
4257 static constexpr int required_media_hops = 9;
4258 static constexpr int required_signaling_trips = 2;
4259 // For internal delays (such as posting an event asychronously).
4260 static constexpr int allowed_internal_delay_ms = 20;
4261 static constexpr int total_connection_time_ms =
4262 media_hop_delay_ms * required_media_hops +
4263 signaling_trip_delay_ms * required_signaling_trips +
4264 allowed_internal_delay_ms;
4265
4266 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4267 3478};
4268 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4269 0};
4270 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4271 3478};
4272 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4273 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004274 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4275 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004276
Seth Hampsonaed71642018-06-11 07:41:32 -07004277 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4278 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004279 // Bypass permission check on received packets so media can be sent before
4280 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004281 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4282 turn_server_1->set_enable_permission_checks(false);
4283 });
4284 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4285 turn_server_2->set_enable_permission_checks(false);
4286 });
deadbeef1dcb1642017-03-29 21:08:16 -07004287
4288 PeerConnectionInterface::RTCConfiguration client_1_config;
4289 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4290 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4291 ice_server_1.username = "test";
4292 ice_server_1.password = "test";
4293 client_1_config.servers.push_back(ice_server_1);
4294 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4295 client_1_config.presume_writable_when_fully_relayed = true;
4296
4297 PeerConnectionInterface::RTCConfiguration client_2_config;
4298 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4299 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4300 ice_server_2.username = "test";
4301 ice_server_2.password = "test";
4302 client_2_config.servers.push_back(ice_server_2);
4303 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4304 client_2_config.presume_writable_when_fully_relayed = true;
4305
4306 ASSERT_TRUE(
4307 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4308 // Set up the simulated delays.
4309 SetSignalingDelayMs(signaling_trip_delay_ms);
4310 ConnectFakeSignaling();
4311 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4312 virtual_socket_server()->UpdateDelayDistribution();
4313
4314 // Set "offer to receive audio/video" without adding any tracks, so we just
4315 // set up ICE/DTLS with no media.
4316 PeerConnectionInterface::RTCOfferAnswerOptions options;
4317 options.offer_to_receive_audio = 1;
4318 options.offer_to_receive_video = 1;
4319 caller()->SetOfferAnswerOptions(options);
4320 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004321 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4322 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004323 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4324 // If this is not done a DCHECK can be hit in ports.cc, because a large
4325 // negative number is calculated for the rtt due to the global clock changing.
4326 caller()->pc()->Close();
4327 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07004328}
4329
Jonas Orelandbdcee282017-10-10 14:01:40 +02004330// Verify that a TurnCustomizer passed in through RTCConfiguration
4331// is actually used by the underlying TURN candidate pair.
4332// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004333TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004334 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4335 3478};
4336 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4337 0};
4338 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4339 3478};
4340 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4341 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004342 CreateTurnServer(turn_server_1_internal_address,
4343 turn_server_1_external_address);
4344 CreateTurnServer(turn_server_2_internal_address,
4345 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004346
4347 PeerConnectionInterface::RTCConfiguration client_1_config;
4348 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4349 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4350 ice_server_1.username = "test";
4351 ice_server_1.password = "test";
4352 client_1_config.servers.push_back(ice_server_1);
4353 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004354 auto* customizer1 = CreateTurnCustomizer();
4355 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004356
4357 PeerConnectionInterface::RTCConfiguration client_2_config;
4358 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4359 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4360 ice_server_2.username = "test";
4361 ice_server_2.password = "test";
4362 client_2_config.servers.push_back(ice_server_2);
4363 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004364 auto* customizer2 = CreateTurnCustomizer();
4365 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004366
4367 ASSERT_TRUE(
4368 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4369 ConnectFakeSignaling();
4370
4371 // Set "offer to receive audio/video" without adding any tracks, so we just
4372 // set up ICE/DTLS with no media.
4373 PeerConnectionInterface::RTCOfferAnswerOptions options;
4374 options.offer_to_receive_audio = 1;
4375 options.offer_to_receive_video = 1;
4376 caller()->SetOfferAnswerOptions(options);
4377 caller()->CreateAndSetAndSignalOffer();
4378 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4379
Seth Hampsonaed71642018-06-11 07:41:32 -07004380 ExpectTurnCustomizerCountersIncremented(customizer1);
4381 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004382}
4383
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004384// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4385// send media between the caller and the callee.
4386TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4387 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4388 3478};
4389 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4390
4391 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004392 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4393 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004394
4395 webrtc::PeerConnectionInterface::IceServer ice_server;
4396 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4397 ice_server.username = "test";
4398 ice_server.password = "test";
4399
4400 PeerConnectionInterface::RTCConfiguration client_1_config;
4401 client_1_config.servers.push_back(ice_server);
4402 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4403
4404 PeerConnectionInterface::RTCConfiguration client_2_config;
4405 client_2_config.servers.push_back(ice_server);
4406 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4407
4408 ASSERT_TRUE(
4409 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4410
4411 // Do normal offer/answer and wait for ICE to complete.
4412 ConnectFakeSignaling();
4413 caller()->AddAudioVideoTracks();
4414 callee()->AddAudioVideoTracks();
4415 caller()->CreateAndSetAndSignalOffer();
4416 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4417 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4418 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4419
4420 MediaExpectations media_expectations;
4421 media_expectations.ExpectBidirectionalAudioAndVideo();
4422 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4423}
4424
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004425// Verify that a SSLCertificateVerifier passed in through
4426// PeerConnectionDependencies is actually used by the underlying SSL
4427// implementation to determine whether a certificate presented by the TURN
4428// server is accepted by the client. Note that openssladapter_unittest.cc
4429// contains more detailed, lower-level tests.
4430TEST_P(PeerConnectionIntegrationTest,
4431 SSLCertificateVerifierUsedForTurnConnections) {
4432 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4433 3478};
4434 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4435
4436 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4437 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004438 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4439 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004440
4441 webrtc::PeerConnectionInterface::IceServer ice_server;
4442 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4443 ice_server.username = "test";
4444 ice_server.password = "test";
4445
4446 PeerConnectionInterface::RTCConfiguration client_1_config;
4447 client_1_config.servers.push_back(ice_server);
4448 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4449
4450 PeerConnectionInterface::RTCConfiguration client_2_config;
4451 client_2_config.servers.push_back(ice_server);
4452 // Setting the type to kRelay forces the connection to go through a TURN
4453 // server.
4454 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4455
4456 // Get a copy to the pointer so we can verify calls later.
4457 rtc::TestCertificateVerifier* client_1_cert_verifier =
4458 new rtc::TestCertificateVerifier();
4459 client_1_cert_verifier->verify_certificate_ = true;
4460 rtc::TestCertificateVerifier* client_2_cert_verifier =
4461 new rtc::TestCertificateVerifier();
4462 client_2_cert_verifier->verify_certificate_ = true;
4463
4464 // Create the dependencies with the test certificate verifier.
4465 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4466 client_1_deps.tls_cert_verifier =
4467 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4468 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4469 client_2_deps.tls_cert_verifier =
4470 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4471
4472 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4473 client_1_config, std::move(client_1_deps), client_2_config,
4474 std::move(client_2_deps)));
4475 ConnectFakeSignaling();
4476
4477 // Set "offer to receive audio/video" without adding any tracks, so we just
4478 // set up ICE/DTLS with no media.
4479 PeerConnectionInterface::RTCOfferAnswerOptions options;
4480 options.offer_to_receive_audio = 1;
4481 options.offer_to_receive_video = 1;
4482 caller()->SetOfferAnswerOptions(options);
4483 caller()->CreateAndSetAndSignalOffer();
4484 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4485
4486 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4487 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004488}
4489
4490TEST_P(PeerConnectionIntegrationTest,
4491 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4492 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4493 3478};
4494 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4495
4496 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4497 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004498 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4499 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004500
4501 webrtc::PeerConnectionInterface::IceServer ice_server;
4502 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4503 ice_server.username = "test";
4504 ice_server.password = "test";
4505
4506 PeerConnectionInterface::RTCConfiguration client_1_config;
4507 client_1_config.servers.push_back(ice_server);
4508 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4509
4510 PeerConnectionInterface::RTCConfiguration client_2_config;
4511 client_2_config.servers.push_back(ice_server);
4512 // Setting the type to kRelay forces the connection to go through a TURN
4513 // server.
4514 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4515
4516 // Get a copy to the pointer so we can verify calls later.
4517 rtc::TestCertificateVerifier* client_1_cert_verifier =
4518 new rtc::TestCertificateVerifier();
4519 client_1_cert_verifier->verify_certificate_ = false;
4520 rtc::TestCertificateVerifier* client_2_cert_verifier =
4521 new rtc::TestCertificateVerifier();
4522 client_2_cert_verifier->verify_certificate_ = false;
4523
4524 // Create the dependencies with the test certificate verifier.
4525 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4526 client_1_deps.tls_cert_verifier =
4527 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4528 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4529 client_2_deps.tls_cert_verifier =
4530 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4531
4532 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4533 client_1_config, std::move(client_1_deps), client_2_config,
4534 std::move(client_2_deps)));
4535 ConnectFakeSignaling();
4536
4537 // Set "offer to receive audio/video" without adding any tracks, so we just
4538 // set up ICE/DTLS with no media.
4539 PeerConnectionInterface::RTCOfferAnswerOptions options;
4540 options.offer_to_receive_audio = 1;
4541 options.offer_to_receive_video = 1;
4542 caller()->SetOfferAnswerOptions(options);
4543 caller()->CreateAndSetAndSignalOffer();
4544 bool wait_res = true;
4545 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4546 // properly, should be able to just wait for a state of "failed" instead of
4547 // waiting a fixed 10 seconds.
4548 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4549 ASSERT_FALSE(wait_res);
4550
4551 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4552 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004553}
4554
deadbeefc964d0b2017-04-03 10:03:35 -07004555// Test that audio and video flow end-to-end when codec names don't use the
4556// expected casing, given that they're supposed to be case insensitive. To test
4557// this, all but one codec is removed from each media description, and its
4558// casing is changed.
4559//
4560// In the past, this has regressed and caused crashes/black video, due to the
4561// fact that code at some layers was doing case-insensitive comparisons and
4562// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004563TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004564 ASSERT_TRUE(CreatePeerConnectionWrappers());
4565 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004566 caller()->AddAudioVideoTracks();
4567 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004568
4569 // Remove all but one audio/video codec (opus and VP8), and change the
4570 // casing of the caller's generated offer.
4571 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4572 cricket::AudioContentDescription* audio =
4573 GetFirstAudioContentDescription(description);
4574 ASSERT_NE(nullptr, audio);
4575 auto audio_codecs = audio->codecs();
4576 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4577 [](const cricket::AudioCodec& codec) {
4578 return codec.name != "opus";
4579 }),
4580 audio_codecs.end());
4581 ASSERT_EQ(1u, audio_codecs.size());
4582 audio_codecs[0].name = "OpUs";
4583 audio->set_codecs(audio_codecs);
4584
4585 cricket::VideoContentDescription* video =
4586 GetFirstVideoContentDescription(description);
4587 ASSERT_NE(nullptr, video);
4588 auto video_codecs = video->codecs();
4589 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4590 [](const cricket::VideoCodec& codec) {
4591 return codec.name != "VP8";
4592 }),
4593 video_codecs.end());
4594 ASSERT_EQ(1u, video_codecs.size());
4595 video_codecs[0].name = "vP8";
4596 video->set_codecs(video_codecs);
4597 });
4598
4599 caller()->CreateAndSetAndSignalOffer();
4600 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4601
4602 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004603 MediaExpectations media_expectations;
4604 media_expectations.ExpectBidirectionalAudioAndVideo();
4605 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004606}
4607
Jonas Oreland49ac5952018-09-26 16:04:32 +02004608TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004609 ASSERT_TRUE(CreatePeerConnectionWrappers());
4610 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004611 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004612 caller()->CreateAndSetAndSignalOffer();
4613 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004614 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004615 MediaExpectations media_expectations;
4616 media_expectations.CalleeExpectsSomeAudio(1);
4617 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004618 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004619 auto receiver = callee()->pc()->GetReceivers()[0];
4620 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004621 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004622 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4623 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004624 sources[0].source_id());
4625 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4626}
4627
4628TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4629 ASSERT_TRUE(CreatePeerConnectionWrappers());
4630 ConnectFakeSignaling();
4631 caller()->AddVideoTrack();
4632 caller()->CreateAndSetAndSignalOffer();
4633 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4634 // Wait for one video frame to be received by the callee.
4635 MediaExpectations media_expectations;
4636 media_expectations.CalleeExpectsSomeVideo(1);
4637 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4638 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4639 auto receiver = callee()->pc()->GetReceivers()[0];
4640 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4641 auto sources = receiver->GetSources();
4642 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4643 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4644 sources[0].source_id());
4645 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004646}
4647
deadbeef2f425aa2017-04-14 10:41:32 -07004648// Test that if a track is removed and added again with a different stream ID,
4649// the new stream ID is successfully communicated in SDP and media continues to
4650// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004651// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4652// it will not reuse a transceiver that has already been sending. After creating
4653// a new transceiver it tries to create an offer with two senders of the same
4654// track ids and it fails.
4655TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004656 ASSERT_TRUE(CreatePeerConnectionWrappers());
4657 ConnectFakeSignaling();
4658
deadbeef2f425aa2017-04-14 10:41:32 -07004659 // Add track using stream 1, do offer/answer.
4660 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4661 caller()->CreateLocalAudioTrack();
4662 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004663 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004664 caller()->CreateAndSetAndSignalOffer();
4665 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004666 {
4667 MediaExpectations media_expectations;
4668 media_expectations.CalleeExpectsSomeAudio(1);
4669 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4670 }
deadbeef2f425aa2017-04-14 10:41:32 -07004671 // Remove the sender, and create a new one with the new stream.
4672 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004673 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004674 caller()->CreateAndSetAndSignalOffer();
4675 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4676 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004677 {
4678 MediaExpectations media_expectations;
4679 media_expectations.CalleeExpectsSomeAudio();
4680 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4681 }
deadbeef2f425aa2017-04-14 10:41:32 -07004682}
4683
Seth Hampson2f0d7022018-02-20 11:54:42 -08004684TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004685 ASSERT_TRUE(CreatePeerConnectionWrappers());
4686 ConnectFakeSignaling();
4687
Karl Wiberg918f50c2018-07-05 11:40:33 +02004688 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Elad Alon99c3fe52017-10-13 16:29:40 +02004689 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
4690 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
4691 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004692 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4693 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004694
Steve Anton15324772018-01-16 10:26:49 -08004695 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004696 caller()->CreateAndSetAndSignalOffer();
4697 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4698}
4699
Steve Antonede9ca52017-10-16 13:04:27 -07004700// Test that if candidates are only signaled by applying full session
4701// descriptions (instead of using AddIceCandidate), the peers can connect to
4702// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004703TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004704 ASSERT_TRUE(CreatePeerConnectionWrappers());
4705 // Each side will signal the session descriptions but not candidates.
4706 ConnectFakeSignalingForSdpOnly();
4707
4708 // Add audio video track and exchange the initial offer/answer with media
4709 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004710 caller()->AddAudioVideoTracks();
4711 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004712 caller()->CreateAndSetAndSignalOffer();
4713
4714 // Wait for all candidates to be gathered on both the caller and callee.
4715 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4716 caller()->ice_gathering_state(), kDefaultTimeout);
4717 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4718 callee()->ice_gathering_state(), kDefaultTimeout);
4719
4720 // The candidates will now be included in the session description, so
4721 // signaling them will start the ICE connection.
4722 caller()->CreateAndSetAndSignalOffer();
4723 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4724
4725 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004726 MediaExpectations media_expectations;
4727 media_expectations.ExpectBidirectionalAudioAndVideo();
4728 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004729}
4730
henrika5f6bf242017-11-01 11:06:56 +01004731// Test that SetAudioPlayout can be used to disable audio playout from the
4732// start, then later enable it. This may be useful, for example, if the caller
4733// needs to play a local ringtone until some event occurs, after which it
4734// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004735TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004736 ASSERT_TRUE(CreatePeerConnectionWrappers());
4737 ConnectFakeSignaling();
4738
4739 // Set up audio-only call where audio playout is disabled on caller's side.
4740 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004741 caller()->AddAudioTrack();
4742 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004743 caller()->CreateAndSetAndSignalOffer();
4744 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4745
4746 // Pump messages for a second.
4747 WAIT(false, 1000);
4748 // Since audio playout is disabled, the caller shouldn't have received
4749 // anything (at the playout level, at least).
4750 EXPECT_EQ(0, caller()->audio_frames_received());
4751 // As a sanity check, make sure the callee (for which playout isn't disabled)
4752 // did still see frames on its audio level.
4753 ASSERT_GT(callee()->audio_frames_received(), 0);
4754
4755 // Enable playout again, and ensure audio starts flowing.
4756 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004757 MediaExpectations media_expectations;
4758 media_expectations.ExpectBidirectionalAudio();
4759 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004760}
4761
4762double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4763 auto report = pc->NewGetStats();
4764 auto track_stats_list =
4765 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4766 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4767 for (const auto* track_stats : track_stats_list) {
4768 if (track_stats->remote_source.is_defined() &&
4769 *track_stats->remote_source) {
4770 remote_track_stats = track_stats;
4771 break;
4772 }
4773 }
4774
4775 if (!remote_track_stats->total_audio_energy.is_defined()) {
4776 return 0.0;
4777 }
4778 return *remote_track_stats->total_audio_energy;
4779}
4780
4781// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4782// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004783TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004784 DisableAudioPlayoutStillGeneratesAudioStats) {
4785 ASSERT_TRUE(CreatePeerConnectionWrappers());
4786 ConnectFakeSignaling();
4787
4788 // Set up audio-only call where playout is disabled but audio-processing is
4789 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004790 caller()->AddAudioTrack();
4791 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004792 caller()->pc()->SetAudioPlayout(false);
4793
4794 caller()->CreateAndSetAndSignalOffer();
4795 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4796
4797 // Wait for the callee to receive audio stats.
4798 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4799}
4800
henrika4f167df2017-11-01 14:45:55 +01004801// Test that SetAudioRecording can be used to disable audio recording from the
4802// start, then later enable it. This may be useful, for example, if the caller
4803// wants to ensure that no audio resources are active before a certain state
4804// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004805TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004806 ASSERT_TRUE(CreatePeerConnectionWrappers());
4807 ConnectFakeSignaling();
4808
4809 // Set up audio-only call where audio recording is disabled on caller's side.
4810 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08004811 caller()->AddAudioTrack();
4812 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01004813 caller()->CreateAndSetAndSignalOffer();
4814 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4815
4816 // Pump messages for a second.
4817 WAIT(false, 1000);
4818 // Since caller has disabled audio recording, the callee shouldn't have
4819 // received anything.
4820 EXPECT_EQ(0, callee()->audio_frames_received());
4821 // As a sanity check, make sure the caller did still see frames on its
4822 // audio level since audio recording is enabled on the calle side.
4823 ASSERT_GT(caller()->audio_frames_received(), 0);
4824
4825 // Enable audio recording again, and ensure audio starts flowing.
4826 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004827 MediaExpectations media_expectations;
4828 media_expectations.ExpectBidirectionalAudio();
4829 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01004830}
4831
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004832// Test that after closing PeerConnections, they stop sending any packets (ICE,
4833// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004834TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004835 // Set up audio/video/data, wait for some frames to be received.
4836 ASSERT_TRUE(CreatePeerConnectionWrappers());
4837 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004838 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004839#ifdef HAVE_SCTP
4840 caller()->CreateDataChannel();
4841#endif
4842 caller()->CreateAndSetAndSignalOffer();
4843 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004844 MediaExpectations media_expectations;
4845 media_expectations.CalleeExpectsSomeAudioAndVideo();
4846 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004847 // Close PeerConnections.
4848 caller()->pc()->Close();
4849 callee()->pc()->Close();
4850 // Pump messages for a second, and ensure no new packets end up sent.
4851 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
4852 WAIT(false, 1000);
4853 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
4854 EXPECT_EQ(sent_packets_a, sent_packets_b);
4855}
4856
Steve Anton7eca0932018-03-30 15:18:41 -07004857// Test that transport stats are generated by the RTCStatsCollector for a
4858// connection that only involves data channels. This is a regression test for
4859// crbug.com/826972.
4860#ifdef HAVE_SCTP
4861TEST_P(PeerConnectionIntegrationTest,
4862 TransportStatsReportedForDataChannelOnlyConnection) {
4863 ASSERT_TRUE(CreatePeerConnectionWrappers());
4864 ConnectFakeSignaling();
4865 caller()->CreateDataChannel();
4866
4867 caller()->CreateAndSetAndSignalOffer();
4868 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4869 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
4870
4871 auto caller_report = caller()->NewGetStats();
4872 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
4873 auto callee_report = callee()->NewGetStats();
4874 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
4875}
4876#endif // HAVE_SCTP
4877
Qingsi Wang7685e862018-06-11 20:15:46 -07004878TEST_P(PeerConnectionIntegrationTest,
4879 IceEventsGeneratedAndLoggedInRtcEventLog) {
4880 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
4881 ConnectFakeSignaling();
4882 PeerConnectionInterface::RTCOfferAnswerOptions options;
4883 options.offer_to_receive_audio = 1;
4884 caller()->SetOfferAnswerOptions(options);
4885 caller()->CreateAndSetAndSignalOffer();
4886 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4887 ASSERT_NE(nullptr, caller()->event_log_factory());
4888 ASSERT_NE(nullptr, callee()->event_log_factory());
4889 webrtc::FakeRtcEventLog* caller_event_log =
4890 static_cast<webrtc::FakeRtcEventLog*>(
4891 caller()->event_log_factory()->last_log_created());
4892 webrtc::FakeRtcEventLog* callee_event_log =
4893 static_cast<webrtc::FakeRtcEventLog*>(
4894 callee()->event_log_factory()->last_log_created());
4895 ASSERT_NE(nullptr, caller_event_log);
4896 ASSERT_NE(nullptr, callee_event_log);
4897 int caller_ice_config_count = caller_event_log->GetEventCount(
4898 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4899 int caller_ice_event_count = caller_event_log->GetEventCount(
4900 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4901 int callee_ice_config_count = callee_event_log->GetEventCount(
4902 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4903 int callee_ice_event_count = callee_event_log->GetEventCount(
4904 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4905 EXPECT_LT(0, caller_ice_config_count);
4906 EXPECT_LT(0, caller_ice_event_count);
4907 EXPECT_LT(0, callee_ice_config_count);
4908 EXPECT_LT(0, callee_ice_event_count);
4909}
4910
Seth Hampson2f0d7022018-02-20 11:54:42 -08004911INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
4912 PeerConnectionIntegrationTest,
4913 Values(SdpSemantics::kPlanB,
4914 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08004915
Steve Anton74255ff2018-01-24 18:32:57 -08004916// Tests that verify interoperability between Plan B and Unified Plan
4917// PeerConnections.
4918class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004919 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08004920 public ::testing::WithParamInterface<
4921 std::tuple<SdpSemantics, SdpSemantics>> {
4922 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004923 // Setting the SdpSemantics for the base test to kDefault does not matter
4924 // because we specify not to use the test semantics when creating
4925 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08004926 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07004927 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08004928 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08004929 callee_semantics_(std::get<1>(GetParam())) {}
4930
4931 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07004932 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
4933 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08004934 }
4935
4936 const SdpSemantics caller_semantics_;
4937 const SdpSemantics callee_semantics_;
4938};
4939
4940TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
4941 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4942 ConnectFakeSignaling();
4943
4944 caller()->CreateAndSetAndSignalOffer();
4945 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4946}
4947
4948TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
4949 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4950 ConnectFakeSignaling();
4951 auto audio_sender = caller()->AddAudioTrack();
4952
4953 caller()->CreateAndSetAndSignalOffer();
4954 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4955
4956 // Verify that one audio receiver has been created on the remote and that it
4957 // has the same track ID as the sending track.
4958 auto receivers = callee()->pc()->GetReceivers();
4959 ASSERT_EQ(1u, receivers.size());
4960 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
4961 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
4962
Seth Hampson2f0d7022018-02-20 11:54:42 -08004963 MediaExpectations media_expectations;
4964 media_expectations.CalleeExpectsSomeAudio();
4965 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004966}
4967
4968TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
4969 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4970 ConnectFakeSignaling();
4971 auto video_sender = caller()->AddVideoTrack();
4972 auto audio_sender = caller()->AddAudioTrack();
4973
4974 caller()->CreateAndSetAndSignalOffer();
4975 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4976
4977 // Verify that one audio and one video receiver have been created on the
4978 // remote and that they have the same track IDs as the sending tracks.
4979 auto audio_receivers =
4980 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
4981 ASSERT_EQ(1u, audio_receivers.size());
4982 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
4983 auto video_receivers =
4984 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
4985 ASSERT_EQ(1u, video_receivers.size());
4986 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
4987
Seth Hampson2f0d7022018-02-20 11:54:42 -08004988 MediaExpectations media_expectations;
4989 media_expectations.CalleeExpectsSomeAudioAndVideo();
4990 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004991}
4992
4993TEST_P(PeerConnectionIntegrationInteropTest,
4994 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
4995 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4996 ConnectFakeSignaling();
4997 caller()->AddAudioVideoTracks();
4998 callee()->AddAudioVideoTracks();
4999
5000 caller()->CreateAndSetAndSignalOffer();
5001 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5002
Seth Hampson2f0d7022018-02-20 11:54:42 -08005003 MediaExpectations media_expectations;
5004 media_expectations.ExpectBidirectionalAudioAndVideo();
5005 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005006}
5007
5008TEST_P(PeerConnectionIntegrationInteropTest,
5009 ReverseRolesOneAudioLocalToOneVideoRemote) {
5010 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5011 ConnectFakeSignaling();
5012 caller()->AddAudioTrack();
5013 callee()->AddVideoTrack();
5014
5015 caller()->CreateAndSetAndSignalOffer();
5016 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5017
5018 // Verify that only the audio track has been negotiated.
5019 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5020 // Might also check that the callee's NegotiationNeeded flag is set.
5021
5022 // Reverse roles.
5023 callee()->CreateAndSetAndSignalOffer();
5024 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5025
Seth Hampson2f0d7022018-02-20 11:54:42 -08005026 MediaExpectations media_expectations;
5027 media_expectations.CallerExpectsSomeVideo();
5028 media_expectations.CalleeExpectsSomeAudio();
5029 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005030}
5031
Steve Antonba42e992018-04-09 14:10:01 -07005032INSTANTIATE_TEST_CASE_P(
5033 PeerConnectionIntegrationTest,
5034 PeerConnectionIntegrationInteropTest,
5035 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5036 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5037
5038// Test that if the Unified Plan side offers two video tracks then the Plan B
5039// side will only see the first one and ignore the second.
5040TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005041 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5042 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005043 ConnectFakeSignaling();
5044 auto first_sender = caller()->AddVideoTrack();
5045 caller()->AddVideoTrack();
5046
5047 caller()->CreateAndSetAndSignalOffer();
5048 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5049
5050 // Verify that there is only one receiver and it corresponds to the first
5051 // added track.
5052 auto receivers = callee()->pc()->GetReceivers();
5053 ASSERT_EQ(1u, receivers.size());
5054 EXPECT_TRUE(receivers[0]->track()->enabled());
5055 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5056
Seth Hampson2f0d7022018-02-20 11:54:42 -08005057 MediaExpectations media_expectations;
5058 media_expectations.CalleeExpectsSomeVideo();
5059 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005060}
5061
deadbeef1dcb1642017-03-29 21:08:16 -07005062} // namespace
5063
5064#endif // if !defined(THREAD_SANITIZER)