1 /*
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
25 #include "absl/algorithm/container.h"
26 #include "api/media_stream_interface.h"
27 #include "api/peer_connection_interface.h"
28 #include "api/peer_connection_proxy.h"
29 #include "api/rtc_event_log/rtc_event_log_factory.h"
30 #include "api/rtp_receiver_interface.h"
31 #include "api/task_queue/default_task_queue_factory.h"
32 #include "api/transport/field_trial_based_config.h"
33 #include "api/uma_metrics.h"
34 #include "api/video_codecs/sdp_video_format.h"
35 #include "call/call.h"
36 #include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
37 #include "media/engine/fake_webrtc_video_engine.h"
38 #include "media/engine/webrtc_media_engine.h"
39 #include "media/engine/webrtc_media_engine_defaults.h"
40 #include "modules/audio_processing/test/audio_processing_builder_for_testing.h"
41 #include "p2p/base/fake_ice_transport.h"
42 #include "p2p/base/mock_async_resolver.h"
43 #include "p2p/base/p2p_constants.h"
44 #include "p2p/base/port_interface.h"
45 #include "p2p/base/test_stun_server.h"
46 #include "p2p/base/test_turn_customizer.h"
47 #include "p2p/base/test_turn_server.h"
48 #include "p2p/client/basic_port_allocator.h"
49 #include "pc/dtmf_sender.h"
50 #include "pc/local_audio_source.h"
51 #include "pc/media_session.h"
52 #include "pc/peer_connection.h"
53 #include "pc/peer_connection_factory.h"
54 #include "pc/rtp_media_utils.h"
55 #include "pc/session_description.h"
56 #include "pc/test/fake_audio_capture_module.h"
57 #include "pc/test/fake_periodic_video_track_source.h"
58 #include "pc/test/fake_rtc_certificate_generator.h"
59 #include "pc/test/fake_video_track_renderer.h"
60 #include "pc/test/mock_peer_connection_observers.h"
61 #include "rtc_base/fake_clock.h"
62 #include "rtc_base/fake_mdns_responder.h"
63 #include "rtc_base/fake_network.h"
64 #include "rtc_base/firewall_socket_server.h"
65 #include "rtc_base/gunit.h"
66 #include "rtc_base/numerics/safe_conversions.h"
67 #include "rtc_base/test_certificate_verifier.h"
68 #include "rtc_base/time_utils.h"
69 #include "rtc_base/virtual_socket_server.h"
70 #include "system_wrappers/include/metrics.h"
71 #include "test/field_trial.h"
72 #include "test/gmock.h"
73
74 namespace webrtc {
75 namespace {
76
77 using ::cricket::ContentInfo;
78 using ::cricket::StreamParams;
79 using ::rtc::SocketAddress;
80 using ::testing::_;
81 using ::testing::Combine;
82 using ::testing::Contains;
83 using ::testing::DoAll;
84 using ::testing::ElementsAre;
85 using ::testing::NiceMock;
86 using ::testing::Return;
87 using ::testing::SetArgPointee;
88 using ::testing::UnorderedElementsAreArray;
89 using ::testing::Values;
90 using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
91
92 static const int kDefaultTimeout = 10000;
93 static const int kMaxWaitForStatsMs = 3000;
94 static const int kMaxWaitForActivationMs = 5000;
95 static const int kMaxWaitForFramesMs = 10000;
96 // Default number of audio/video frames to wait for before considering a test
97 // successful.
98 static const int kDefaultExpectedAudioFrameCount = 3;
99 static const int kDefaultExpectedVideoFrameCount = 3;
100
101 static const char kDataChannelLabel[] = "data_channel";
102
103 // SRTP cipher name negotiated by the tests. This must be updated if the
104 // default changes.
105 static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
106 static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
107
108 static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
109
110 // Helper function for constructing offer/answer options to initiate an ICE
111 // restart.
IceRestartOfferAnswerOptions()112 PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
113 PeerConnectionInterface::RTCOfferAnswerOptions options;
114 options.ice_restart = true;
115 return options;
116 }
117
118 // Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
119 // attribute from received SDP, simulating a legacy endpoint.
RemoveSsrcsAndMsids(cricket::SessionDescription * desc)120 void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
121 for (ContentInfo& content : desc->contents()) {
122 content.media_description()->mutable_streams().clear();
123 }
124 desc->set_msid_supported(false);
125 desc->set_msid_signaling(0);
126 }
127
128 // Removes all stream information besides the stream ids, simulating an
129 // endpoint that only signals a=msid lines to convey stream_ids.
RemoveSsrcsAndKeepMsids(cricket::SessionDescription * desc)130 void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
131 for (ContentInfo& content : desc->contents()) {
132 std::string track_id;
133 std::vector<std::string> stream_ids;
134 if (!content.media_description()->streams().empty()) {
135 const StreamParams& first_stream =
136 content.media_description()->streams()[0];
137 track_id = first_stream.id;
138 stream_ids = first_stream.stream_ids();
139 }
140 content.media_description()->mutable_streams().clear();
141 StreamParams new_stream;
142 new_stream.id = track_id;
143 new_stream.set_stream_ids(stream_ids);
144 content.media_description()->AddStream(new_stream);
145 }
146 }
147
FindFirstMediaStatsIndexByKind(const std::string & kind,const std::vector<const webrtc::RTCMediaStreamTrackStats * > & media_stats_vec)148 int FindFirstMediaStatsIndexByKind(
149 const std::string& kind,
150 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
151 media_stats_vec) {
152 for (size_t i = 0; i < media_stats_vec.size(); i++) {
153 if (media_stats_vec[i]->kind.ValueToString() == kind) {
154 return i;
155 }
156 }
157 return -1;
158 }
159
160 class SignalingMessageReceiver {
161 public:
162 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
163 virtual void ReceiveIceMessage(const std::string& sdp_mid,
164 int sdp_mline_index,
165 const std::string& msg) = 0;
166
167 protected:
SignalingMessageReceiver()168 SignalingMessageReceiver() {}
~SignalingMessageReceiver()169 virtual ~SignalingMessageReceiver() {}
170 };
171
172 class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
173 public:
MockRtpReceiverObserver(cricket::MediaType media_type)174 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
175 : expected_media_type_(media_type) {}
176
OnFirstPacketReceived(cricket::MediaType media_type)177 void OnFirstPacketReceived(cricket::MediaType media_type) override {
178 ASSERT_EQ(expected_media_type_, media_type);
179 first_packet_received_ = true;
180 }
181
first_packet_received() const182 bool first_packet_received() const { return first_packet_received_; }
183
~MockRtpReceiverObserver()184 virtual ~MockRtpReceiverObserver() {}
185
186 private:
187 bool first_packet_received_ = false;
188 cricket::MediaType expected_media_type_;
189 };
190
191 // Helper class that wraps a peer connection, observes it, and can accept
192 // signaling messages from another wrapper.
193 //
194 // Uses a fake network, fake A/V capture, and optionally fake
195 // encoders/decoders, though they aren't used by default since they don't
196 // advertise support of any codecs.
197 // TODO(steveanton): See how this could become a subclass of
198 // PeerConnectionWrapper defined in peerconnectionwrapper.h.
199 class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
200 public SignalingMessageReceiver {
201 public:
202 // Different factory methods for convenience.
203 // TODO(deadbeef): Could use the pattern of:
204 //
205 // PeerConnectionWrapper =
206 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
207 //
208 // To reduce some code duplication.
CreateWithDtlsIdentityStore(const std::string & debug_name,std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,rtc::Thread * network_thread,rtc::Thread * worker_thread)209 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
210 const std::string& debug_name,
211 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
212 rtc::Thread* network_thread,
213 rtc::Thread* worker_thread) {
214 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
215 webrtc::PeerConnectionDependencies dependencies(nullptr);
216 dependencies.cert_generator = std::move(cert_generator);
217 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
218 worker_thread, nullptr,
219 /*reset_encoder_factory=*/false,
220 /*reset_decoder_factory=*/false)) {
221 delete client;
222 return nullptr;
223 }
224 return client;
225 }
226
pc_factory() const227 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
228 return peer_connection_factory_.get();
229 }
230
pc() const231 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
232
233 // If a signaling message receiver is set (via ConnectFakeSignaling), this
234 // will set the whole offer/answer exchange in motion. Just need to wait for
235 // the signaling state to reach "stable".
CreateAndSetAndSignalOffer()236 void CreateAndSetAndSignalOffer() {
237 auto offer = CreateOfferAndWait();
238 ASSERT_NE(nullptr, offer);
239 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
240 }
241
242 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
243 // when a remote offer is received (via fake signaling) and an answer is
244 // generated. By default, uses default options.
SetOfferAnswerOptions(const PeerConnectionInterface::RTCOfferAnswerOptions & options)245 void SetOfferAnswerOptions(
246 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
247 offer_answer_options_ = options;
248 }
249
250 // Set a callback to be invoked when SDP is received via the fake signaling
251 // channel, which provides an opportunity to munge (modify) the SDP. This is
252 // used to test SDP being applied that a PeerConnection would normally not
253 // generate, but a non-JSEP endpoint might.
SetReceivedSdpMunger(std::function<void (cricket::SessionDescription *)> munger)254 void SetReceivedSdpMunger(
255 std::function<void(cricket::SessionDescription*)> munger) {
256 received_sdp_munger_ = std::move(munger);
257 }
258
259 // Similar to the above, but this is run on SDP immediately after it's
260 // generated.
SetGeneratedSdpMunger(std::function<void (cricket::SessionDescription *)> munger)261 void SetGeneratedSdpMunger(
262 std::function<void(cricket::SessionDescription*)> munger) {
263 generated_sdp_munger_ = std::move(munger);
264 }
265
266 // Set a callback to be invoked when a remote offer is received via the fake
267 // signaling channel. This provides an opportunity to change the
268 // PeerConnection state before an answer is created and sent to the caller.
SetRemoteOfferHandler(std::function<void ()> handler)269 void SetRemoteOfferHandler(std::function<void()> handler) {
270 remote_offer_handler_ = std::move(handler);
271 }
272
SetRemoteAsyncResolver(rtc::MockAsyncResolver * resolver)273 void SetRemoteAsyncResolver(rtc::MockAsyncResolver* resolver) {
274 remote_async_resolver_ = resolver;
275 }
276
277 // Every ICE connection state in order that has been seen by the observer.
278 std::vector<PeerConnectionInterface::IceConnectionState>
ice_connection_state_history() const279 ice_connection_state_history() const {
280 return ice_connection_state_history_;
281 }
clear_ice_connection_state_history()282 void clear_ice_connection_state_history() {
283 ice_connection_state_history_.clear();
284 }
285
286 // Every standardized ICE connection state in order that has been seen by the
287 // observer.
288 std::vector<PeerConnectionInterface::IceConnectionState>
standardized_ice_connection_state_history() const289 standardized_ice_connection_state_history() const {
290 return standardized_ice_connection_state_history_;
291 }
292
293 // Every PeerConnection state in order that has been seen by the observer.
294 std::vector<PeerConnectionInterface::PeerConnectionState>
peer_connection_state_history() const295 peer_connection_state_history() const {
296 return peer_connection_state_history_;
297 }
298
299 // Every ICE gathering state in order that has been seen by the observer.
300 std::vector<PeerConnectionInterface::IceGatheringState>
ice_gathering_state_history() const301 ice_gathering_state_history() const {
302 return ice_gathering_state_history_;
303 }
304 std::vector<cricket::CandidatePairChangeEvent>
ice_candidate_pair_change_history() const305 ice_candidate_pair_change_history() const {
306 return ice_candidate_pair_change_history_;
307 }
308
309 // Every PeerConnection signaling state in order that has been seen by the
310 // observer.
311 std::vector<PeerConnectionInterface::SignalingState>
peer_connection_signaling_state_history() const312 peer_connection_signaling_state_history() const {
313 return peer_connection_signaling_state_history_;
314 }
315
AddAudioVideoTracks()316 void AddAudioVideoTracks() {
317 AddAudioTrack();
318 AddVideoTrack();
319 }
320
AddAudioTrack()321 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
322 return AddTrack(CreateLocalAudioTrack());
323 }
324
AddVideoTrack()325 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
326 return AddTrack(CreateLocalVideoTrack());
327 }
328
CreateLocalAudioTrack()329 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
330 cricket::AudioOptions options;
331 // Disable highpass filter so that we can get all the test audio frames.
332 options.highpass_filter = false;
333 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
334 peer_connection_factory_->CreateAudioSource(options);
335 // TODO(perkj): Test audio source when it is implemented. Currently audio
336 // always use the default input.
337 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
338 source);
339 }
340
CreateLocalVideoTrack()341 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
342 webrtc::FakePeriodicVideoSource::Config config;
343 config.timestamp_offset_ms = rtc::TimeMillis();
344 return CreateLocalVideoTrackInternal(config);
345 }
346
347 rtc::scoped_refptr<webrtc::VideoTrackInterface>
CreateLocalVideoTrackWithConfig(webrtc::FakePeriodicVideoSource::Config config)348 CreateLocalVideoTrackWithConfig(
349 webrtc::FakePeriodicVideoSource::Config config) {
350 return CreateLocalVideoTrackInternal(config);
351 }
352
353 rtc::scoped_refptr<webrtc::VideoTrackInterface>
CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation)354 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
355 webrtc::FakePeriodicVideoSource::Config config;
356 config.rotation = rotation;
357 config.timestamp_offset_ms = rtc::TimeMillis();
358 return CreateLocalVideoTrackInternal(config);
359 }
360
AddTrack(rtc::scoped_refptr<MediaStreamTrackInterface> track,const std::vector<std::string> & stream_ids={})361 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
362 rtc::scoped_refptr<MediaStreamTrackInterface> track,
363 const std::vector<std::string>& stream_ids = {}) {
364 auto result = pc()->AddTrack(track, stream_ids);
365 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
366 return result.MoveValue();
367 }
368
GetReceiversOfType(cricket::MediaType media_type)369 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
370 cricket::MediaType media_type) {
371 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
372 for (const auto& receiver : pc()->GetReceivers()) {
373 if (receiver->media_type() == media_type) {
374 receivers.push_back(receiver);
375 }
376 }
377 return receivers;
378 }
379
GetFirstTransceiverOfType(cricket::MediaType media_type)380 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
381 cricket::MediaType media_type) {
382 for (auto transceiver : pc()->GetTransceivers()) {
383 if (transceiver->receiver()->media_type() == media_type) {
384 return transceiver;
385 }
386 }
387 return nullptr;
388 }
389
SignalingStateStable()390 bool SignalingStateStable() {
391 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
392 }
393
CreateDataChannel()394 void CreateDataChannel() { CreateDataChannel(nullptr); }
395
CreateDataChannel(const webrtc::DataChannelInit * init)396 void CreateDataChannel(const webrtc::DataChannelInit* init) {
397 CreateDataChannel(kDataChannelLabel, init);
398 }
399
CreateDataChannel(const std::string & label,const webrtc::DataChannelInit * init)400 void CreateDataChannel(const std::string& label,
401 const webrtc::DataChannelInit* init) {
402 data_channel_ = pc()->CreateDataChannel(label, init);
403 ASSERT_TRUE(data_channel_.get() != nullptr);
404 data_observer_.reset(new MockDataChannelObserver(data_channel_));
405 }
406
data_channel()407 DataChannelInterface* data_channel() { return data_channel_; }
data_observer() const408 const MockDataChannelObserver* data_observer() const {
409 return data_observer_.get();
410 }
411
audio_frames_received() const412 int audio_frames_received() const {
413 return fake_audio_capture_module_->frames_received();
414 }
415
416 // Takes minimum of video frames received for each track.
417 //
418 // Can be used like:
419 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
420 //
421 // To ensure that all video tracks received at least a certain number of
422 // frames.
min_video_frames_received_per_track() const423 int min_video_frames_received_per_track() const {
424 int min_frames = INT_MAX;
425 if (fake_video_renderers_.empty()) {
426 return 0;
427 }
428
429 for (const auto& pair : fake_video_renderers_) {
430 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
431 }
432 return min_frames;
433 }
434
435 // Returns a MockStatsObserver in a state after stats gathering finished,
436 // which can be used to access the gathered stats.
OldGetStatsForTrack(webrtc::MediaStreamTrackInterface * track)437 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
438 webrtc::MediaStreamTrackInterface* track) {
439 rtc::scoped_refptr<MockStatsObserver> observer(
440 new rtc::RefCountedObject<MockStatsObserver>());
441 EXPECT_TRUE(peer_connection_->GetStats(
442 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
443 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
444 return observer;
445 }
446
447 // Version that doesn't take a track "filter", and gathers all stats.
OldGetStats()448 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
449 return OldGetStatsForTrack(nullptr);
450 }
451
452 // Synchronously gets stats and returns them. If it times out, fails the test
453 // and returns null.
NewGetStats()454 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
455 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
456 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
457 peer_connection_->GetStats(callback);
458 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
459 return callback->report();
460 }
461
rendered_width()462 int rendered_width() {
463 EXPECT_FALSE(fake_video_renderers_.empty());
464 return fake_video_renderers_.empty()
465 ? 0
466 : fake_video_renderers_.begin()->second->width();
467 }
468
rendered_height()469 int rendered_height() {
470 EXPECT_FALSE(fake_video_renderers_.empty());
471 return fake_video_renderers_.empty()
472 ? 0
473 : fake_video_renderers_.begin()->second->height();
474 }
475
rendered_aspect_ratio()476 double rendered_aspect_ratio() {
477 if (rendered_height() == 0) {
478 return 0.0;
479 }
480 return static_cast<double>(rendered_width()) / rendered_height();
481 }
482
rendered_rotation()483 webrtc::VideoRotation rendered_rotation() {
484 EXPECT_FALSE(fake_video_renderers_.empty());
485 return fake_video_renderers_.empty()
486 ? webrtc::kVideoRotation_0
487 : fake_video_renderers_.begin()->second->rotation();
488 }
489
local_rendered_width()490 int local_rendered_width() {
491 return local_video_renderer_ ? local_video_renderer_->width() : 0;
492 }
493
local_rendered_height()494 int local_rendered_height() {
495 return local_video_renderer_ ? local_video_renderer_->height() : 0;
496 }
497
local_rendered_aspect_ratio()498 double local_rendered_aspect_ratio() {
499 if (local_rendered_height() == 0) {
500 return 0.0;
501 }
502 return static_cast<double>(local_rendered_width()) /
503 local_rendered_height();
504 }
505
number_of_remote_streams()506 size_t number_of_remote_streams() {
507 if (!pc()) {
508 return 0;
509 }
510 return pc()->remote_streams()->count();
511 }
512
remote_streams() const513 StreamCollectionInterface* remote_streams() const {
514 if (!pc()) {
515 ADD_FAILURE();
516 return nullptr;
517 }
518 return pc()->remote_streams();
519 }
520
local_streams()521 StreamCollectionInterface* local_streams() {
522 if (!pc()) {
523 ADD_FAILURE();
524 return nullptr;
525 }
526 return pc()->local_streams();
527 }
528
signaling_state()529 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
530 return pc()->signaling_state();
531 }
532
ice_connection_state()533 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
534 return pc()->ice_connection_state();
535 }
536
537 webrtc::PeerConnectionInterface::IceConnectionState
standardized_ice_connection_state()538 standardized_ice_connection_state() {
539 return pc()->standardized_ice_connection_state();
540 }
541
ice_gathering_state()542 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
543 return pc()->ice_gathering_state();
544 }
545
546 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
547 // GetReceivers. They're updated automatically when a remote offer/answer
548 // from the fake signaling channel is applied, or when
549 // ResetRtpReceiverObservers below is called.
550 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
rtp_receiver_observers()551 rtp_receiver_observers() {
552 return rtp_receiver_observers_;
553 }
554
ResetRtpReceiverObservers()555 void ResetRtpReceiverObservers() {
556 rtp_receiver_observers_.clear();
557 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
558 pc()->GetReceivers()) {
559 std::unique_ptr<MockRtpReceiverObserver> observer(
560 new MockRtpReceiverObserver(receiver->media_type()));
561 receiver->SetObserver(observer.get());
562 rtp_receiver_observers_.push_back(std::move(observer));
563 }
564 }
565
network_manager() const566 rtc::FakeNetworkManager* network_manager() const {
567 return fake_network_manager_.get();
568 }
port_allocator() const569 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
570
event_log_factory() const571 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
572 return event_log_factory_;
573 }
574
last_candidate_gathered() const575 const cricket::Candidate& last_candidate_gathered() const {
576 return last_candidate_gathered_;
577 }
error_event() const578 const cricket::IceCandidateErrorEvent& error_event() const {
579 return error_event_;
580 }
581
582 // Sets the mDNS responder for the owned fake network manager and keeps a
583 // reference to the responder.
SetMdnsResponder(std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder)584 void SetMdnsResponder(
585 std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder) {
586 RTC_DCHECK(mdns_responder != nullptr);
587 mdns_responder_ = mdns_responder.get();
588 network_manager()->set_mdns_responder(std::move(mdns_responder));
589 }
590
591 // Returns null on failure.
CreateOfferAndWait()592 std::unique_ptr<SessionDescriptionInterface> CreateOfferAndWait() {
593 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
594 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
595 pc()->CreateOffer(observer, offer_answer_options_);
596 return WaitForDescriptionFromObserver(observer);
597 }
Rollback()598 bool Rollback() {
599 return SetRemoteDescription(
600 webrtc::CreateSessionDescription(SdpType::kRollback, ""));
601 }
602
603 private:
PeerConnectionWrapper(const std::string & debug_name)604 explicit PeerConnectionWrapper(const std::string& debug_name)
605 : debug_name_(debug_name) {}
606
Init(const PeerConnectionFactory::Options * options,const PeerConnectionInterface::RTCConfiguration * config,webrtc::PeerConnectionDependencies dependencies,rtc::Thread * network_thread,rtc::Thread * worker_thread,std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,bool reset_encoder_factory,bool reset_decoder_factory)607 bool Init(
608 const PeerConnectionFactory::Options* options,
609 const PeerConnectionInterface::RTCConfiguration* config,
610 webrtc::PeerConnectionDependencies dependencies,
611 rtc::Thread* network_thread,
612 rtc::Thread* worker_thread,
613 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
614 bool reset_encoder_factory,
615 bool reset_decoder_factory) {
616 // There's an error in this test code if Init ends up being called twice.
617 RTC_DCHECK(!peer_connection_);
618 RTC_DCHECK(!peer_connection_factory_);
619
620 fake_network_manager_.reset(new rtc::FakeNetworkManager());
621 fake_network_manager_->AddInterface(kDefaultLocalAddress);
622
623 std::unique_ptr<cricket::PortAllocator> port_allocator(
624 new cricket::BasicPortAllocator(fake_network_manager_.get()));
625 port_allocator_ = port_allocator.get();
626 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
627 if (!fake_audio_capture_module_) {
628 return false;
629 }
630 rtc::Thread* const signaling_thread = rtc::Thread::Current();
631
632 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
633 pc_factory_dependencies.network_thread = network_thread;
634 pc_factory_dependencies.worker_thread = worker_thread;
635 pc_factory_dependencies.signaling_thread = signaling_thread;
636 pc_factory_dependencies.task_queue_factory =
637 webrtc::CreateDefaultTaskQueueFactory();
638 pc_factory_dependencies.trials = std::make_unique<FieldTrialBasedConfig>();
639 cricket::MediaEngineDependencies media_deps;
640 media_deps.task_queue_factory =
641 pc_factory_dependencies.task_queue_factory.get();
642 media_deps.adm = fake_audio_capture_module_;
643 webrtc::SetMediaEngineDefaults(&media_deps);
644
645 if (reset_encoder_factory) {
646 media_deps.video_encoder_factory.reset();
647 }
648 if (reset_decoder_factory) {
649 media_deps.video_decoder_factory.reset();
650 }
651
652 if (!media_deps.audio_processing) {
653 // If the standard Creation method for APM returns a null pointer, instead
654 // use the builder for testing to create an APM object.
655 media_deps.audio_processing = AudioProcessingBuilderForTesting().Create();
656 }
657
658 media_deps.trials = pc_factory_dependencies.trials.get();
659
660 pc_factory_dependencies.media_engine =
661 cricket::CreateMediaEngine(std::move(media_deps));
662 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
663 if (event_log_factory) {
664 event_log_factory_ = event_log_factory.get();
665 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
666 } else {
667 pc_factory_dependencies.event_log_factory =
668 std::make_unique<webrtc::RtcEventLogFactory>(
669 pc_factory_dependencies.task_queue_factory.get());
670 }
671 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
672 std::move(pc_factory_dependencies));
673
674 if (!peer_connection_factory_) {
675 return false;
676 }
677 if (options) {
678 peer_connection_factory_->SetOptions(*options);
679 }
680 if (config) {
681 sdp_semantics_ = config->sdp_semantics;
682 }
683
684 dependencies.allocator = std::move(port_allocator);
685 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
686 return peer_connection_.get() != nullptr;
687 }
688
CreatePeerConnection(const PeerConnectionInterface::RTCConfiguration * config,webrtc::PeerConnectionDependencies dependencies)689 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
690 const PeerConnectionInterface::RTCConfiguration* config,
691 webrtc::PeerConnectionDependencies dependencies) {
692 PeerConnectionInterface::RTCConfiguration modified_config;
693 // If |config| is null, this will result in a default configuration being
694 // used.
695 if (config) {
696 modified_config = *config;
697 }
698 // Disable resolution adaptation; we don't want it interfering with the
699 // test results.
700 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
701 // ratios and not specific resolutions, is this even necessary?
702 modified_config.set_cpu_adaptation(false);
703
704 dependencies.observer = this;
705 return peer_connection_factory_->CreatePeerConnection(
706 modified_config, std::move(dependencies));
707 }
708
set_signaling_message_receiver(SignalingMessageReceiver * signaling_message_receiver)709 void set_signaling_message_receiver(
710 SignalingMessageReceiver* signaling_message_receiver) {
711 signaling_message_receiver_ = signaling_message_receiver;
712 }
713
set_signaling_delay_ms(int delay_ms)714 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
715
set_signal_ice_candidates(bool signal)716 void set_signal_ice_candidates(bool signal) {
717 signal_ice_candidates_ = signal;
718 }
719
CreateLocalVideoTrackInternal(webrtc::FakePeriodicVideoSource::Config config)720 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
721 webrtc::FakePeriodicVideoSource::Config config) {
722 // Set max frame rate to 10fps to reduce the risk of test flakiness.
723 // TODO(deadbeef): Do something more robust.
724 config.frame_interval_ms = 100;
725
726 video_track_sources_.emplace_back(
727 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
728 config, false /* remote */));
729 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
730 peer_connection_factory_->CreateVideoTrack(
731 rtc::CreateRandomUuid(), video_track_sources_.back()));
732 if (!local_video_renderer_) {
733 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
734 }
735 return track;
736 }
737
HandleIncomingOffer(const std::string & msg)738 void HandleIncomingOffer(const std::string& msg) {
739 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
740 std::unique_ptr<SessionDescriptionInterface> desc =
741 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
742 if (received_sdp_munger_) {
743 received_sdp_munger_(desc->description());
744 }
745
746 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
747 // Setting a remote description may have changed the number of receivers,
748 // so reset the receiver observers.
749 ResetRtpReceiverObservers();
750 if (remote_offer_handler_) {
751 remote_offer_handler_();
752 }
753 auto answer = CreateAnswer();
754 ASSERT_NE(nullptr, answer);
755 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
756 }
757
HandleIncomingAnswer(const std::string & msg)758 void HandleIncomingAnswer(const std::string& msg) {
759 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
760 std::unique_ptr<SessionDescriptionInterface> desc =
761 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
762 if (received_sdp_munger_) {
763 received_sdp_munger_(desc->description());
764 }
765
766 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
767 // Set the RtpReceiverObserver after receivers are created.
768 ResetRtpReceiverObservers();
769 }
770
771 // Returns null on failure.
CreateAnswer()772 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
773 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
774 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
775 pc()->CreateAnswer(observer, offer_answer_options_);
776 return WaitForDescriptionFromObserver(observer);
777 }
778
WaitForDescriptionFromObserver(MockCreateSessionDescriptionObserver * observer)779 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
780 MockCreateSessionDescriptionObserver* observer) {
781 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
782 if (!observer->result()) {
783 return nullptr;
784 }
785 auto description = observer->MoveDescription();
786 if (generated_sdp_munger_) {
787 generated_sdp_munger_(description->description());
788 }
789 return description;
790 }
791
792 // Setting the local description and sending the SDP message over the fake
793 // signaling channel are combined into the same method because the SDP
794 // message needs to be sent as soon as SetLocalDescription finishes, without
795 // waiting for the observer to be called. This ensures that ICE candidates
796 // don't outrace the description.
SetLocalDescriptionAndSendSdpMessage(std::unique_ptr<SessionDescriptionInterface> desc)797 bool SetLocalDescriptionAndSendSdpMessage(
798 std::unique_ptr<SessionDescriptionInterface> desc) {
799 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
800 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
801 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
802 SdpType type = desc->GetType();
803 std::string sdp;
804 EXPECT_TRUE(desc->ToString(&sdp));
805 RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
806 pc()->SetLocalDescription(observer, desc.release());
807 RemoveUnusedVideoRenderers();
808 // As mentioned above, we need to send the message immediately after
809 // SetLocalDescription.
810 SendSdpMessage(type, sdp);
811 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
812 return true;
813 }
814
SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc)815 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
816 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
817 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
818 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
819 pc()->SetRemoteDescription(observer, desc.release());
820 RemoveUnusedVideoRenderers();
821 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
822 return observer->result();
823 }
824
825 // This is a work around to remove unused fake_video_renderers from
826 // transceivers that have either stopped or are no longer receiving.
RemoveUnusedVideoRenderers()827 void RemoveUnusedVideoRenderers() {
828 if (sdp_semantics_ != SdpSemantics::kUnifiedPlan) {
829 return;
830 }
831 auto transceivers = pc()->GetTransceivers();
832 std::set<std::string> active_renderers;
833 for (auto& transceiver : transceivers) {
834 // Note - we don't check for direction here. This function is called
835 // before direction is set, and in that case, we should not remove
836 // the renderer.
837 if (transceiver->receiver()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
838 active_renderers.insert(transceiver->receiver()->track()->id());
839 }
840 }
841 for (auto it = fake_video_renderers_.begin();
842 it != fake_video_renderers_.end();) {
843 // Remove fake video renderers belonging to any non-active transceivers.
844 if (!active_renderers.count(it->first)) {
845 it = fake_video_renderers_.erase(it);
846 } else {
847 it++;
848 }
849 }
850 }
851
852 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
853 // default).
SendSdpMessage(SdpType type,const std::string & msg)854 void SendSdpMessage(SdpType type, const std::string& msg) {
855 if (signaling_delay_ms_ == 0) {
856 RelaySdpMessageIfReceiverExists(type, msg);
857 } else {
858 invoker_.AsyncInvokeDelayed<void>(
859 RTC_FROM_HERE, rtc::Thread::Current(),
860 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
861 this, type, msg),
862 signaling_delay_ms_);
863 }
864 }
865
RelaySdpMessageIfReceiverExists(SdpType type,const std::string & msg)866 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
867 if (signaling_message_receiver_) {
868 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
869 }
870 }
871
872 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
873 // default).
SendIceMessage(const std::string & sdp_mid,int sdp_mline_index,const std::string & msg)874 void SendIceMessage(const std::string& sdp_mid,
875 int sdp_mline_index,
876 const std::string& msg) {
877 if (signaling_delay_ms_ == 0) {
878 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
879 } else {
880 invoker_.AsyncInvokeDelayed<void>(
881 RTC_FROM_HERE, rtc::Thread::Current(),
882 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
883 this, sdp_mid, sdp_mline_index, msg),
884 signaling_delay_ms_);
885 }
886 }
887
RelayIceMessageIfReceiverExists(const std::string & sdp_mid,int sdp_mline_index,const std::string & msg)888 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
889 int sdp_mline_index,
890 const std::string& msg) {
891 if (signaling_message_receiver_) {
892 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
893 msg);
894 }
895 }
896
897 // SignalingMessageReceiver callbacks.
ReceiveSdpMessage(SdpType type,const std::string & msg)898 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
899 if (type == SdpType::kOffer) {
900 HandleIncomingOffer(msg);
901 } else {
902 HandleIncomingAnswer(msg);
903 }
904 }
905
ReceiveIceMessage(const std::string & sdp_mid,int sdp_mline_index,const std::string & msg)906 void ReceiveIceMessage(const std::string& sdp_mid,
907 int sdp_mline_index,
908 const std::string& msg) override {
909 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
910 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
911 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
912 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
913 }
914
915 // PeerConnectionObserver callbacks.
OnSignalingChange(webrtc::PeerConnectionInterface::SignalingState new_state)916 void OnSignalingChange(
917 webrtc::PeerConnectionInterface::SignalingState new_state) override {
918 EXPECT_EQ(pc()->signaling_state(), new_state);
919 peer_connection_signaling_state_history_.push_back(new_state);
920 }
OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,const std::vector<rtc::scoped_refptr<MediaStreamInterface>> & streams)921 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
922 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
923 streams) override {
924 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
925 rtc::scoped_refptr<VideoTrackInterface> video_track(
926 static_cast<VideoTrackInterface*>(receiver->track().get()));
927 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
928 fake_video_renderers_.end());
929 fake_video_renderers_[video_track->id()] =
930 std::make_unique<FakeVideoTrackRenderer>(video_track);
931 }
932 }
OnRemoveTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver)933 void OnRemoveTrack(
934 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
935 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
936 auto it = fake_video_renderers_.find(receiver->track()->id());
937 if (it != fake_video_renderers_.end()) {
938 fake_video_renderers_.erase(it);
939 } else {
940 RTC_LOG(LS_ERROR) << "OnRemoveTrack called for non-active renderer";
941 }
942 }
943 }
OnRenegotiationNeeded()944 void OnRenegotiationNeeded() override {}
OnIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state)945 void OnIceConnectionChange(
946 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
947 EXPECT_EQ(pc()->ice_connection_state(), new_state);
948 ice_connection_state_history_.push_back(new_state);
949 }
OnStandardizedIceConnectionChange(webrtc::PeerConnectionInterface::IceConnectionState new_state)950 void OnStandardizedIceConnectionChange(
951 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
952 standardized_ice_connection_state_history_.push_back(new_state);
953 }
OnConnectionChange(webrtc::PeerConnectionInterface::PeerConnectionState new_state)954 void OnConnectionChange(
955 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
956 peer_connection_state_history_.push_back(new_state);
957 }
958
OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState new_state)959 void OnIceGatheringChange(
960 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
961 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
962 ice_gathering_state_history_.push_back(new_state);
963 }
964
OnIceSelectedCandidatePairChanged(const cricket::CandidatePairChangeEvent & event)965 void OnIceSelectedCandidatePairChanged(
966 const cricket::CandidatePairChangeEvent& event) {
967 ice_candidate_pair_change_history_.push_back(event);
968 }
969
OnIceCandidate(const webrtc::IceCandidateInterface * candidate)970 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
971 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
972
973 if (remote_async_resolver_) {
974 const auto& local_candidate = candidate->candidate();
975 if (local_candidate.address().IsUnresolvedIP()) {
976 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
977 rtc::SocketAddress resolved_addr(local_candidate.address());
978 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
979 local_candidate.address().hostname());
980 RTC_DCHECK(!resolved_ip.IsNil());
981 resolved_addr.SetResolvedIP(resolved_ip);
982 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
983 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
984 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
985 }
986 }
987
988 std::string ice_sdp;
989 EXPECT_TRUE(candidate->ToString(&ice_sdp));
990 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
991 // Remote party may be deleted.
992 return;
993 }
994 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
995 last_candidate_gathered_ = candidate->candidate();
996 }
OnIceCandidateError(const std::string & address,int port,const std::string & url,int error_code,const std::string & error_text)997 void OnIceCandidateError(const std::string& address,
998 int port,
999 const std::string& url,
1000 int error_code,
1001 const std::string& error_text) override {
1002 error_event_ = cricket::IceCandidateErrorEvent(address, port, url,
1003 error_code, error_text);
1004 }
OnDataChannel(rtc::scoped_refptr<DataChannelInterface> data_channel)1005 void OnDataChannel(
1006 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
1007 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
1008 data_channel_ = data_channel;
1009 data_observer_.reset(new MockDataChannelObserver(data_channel));
1010 }
1011
1012 std::string debug_name_;
1013
1014 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
1015 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
1016 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
1017
1018 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
1019 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
1020 peer_connection_factory_;
1021
1022 cricket::PortAllocator* port_allocator_;
1023 // Needed to keep track of number of frames sent.
1024 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1025 // Needed to keep track of number of frames received.
1026 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1027 fake_video_renderers_;
1028 // Needed to ensure frames aren't received for removed tracks.
1029 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1030 removed_fake_video_renderers_;
1031
1032 // For remote peer communication.
1033 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1034 int signaling_delay_ms_ = 0;
1035 bool signal_ice_candidates_ = true;
1036 cricket::Candidate last_candidate_gathered_;
1037 cricket::IceCandidateErrorEvent error_event_;
1038
1039 // Store references to the video sources we've created, so that we can stop
1040 // them, if required.
1041 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1042 video_track_sources_;
1043 // |local_video_renderer_| attached to the first created local video track.
1044 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1045
1046 SdpSemantics sdp_semantics_;
1047 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1048 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1049 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
1050 std::function<void()> remote_offer_handler_;
1051 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
1052 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1053 std::unique_ptr<MockDataChannelObserver> data_observer_;
1054
1055 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1056
1057 std::vector<PeerConnectionInterface::IceConnectionState>
1058 ice_connection_state_history_;
1059 std::vector<PeerConnectionInterface::IceConnectionState>
1060 standardized_ice_connection_state_history_;
1061 std::vector<PeerConnectionInterface::PeerConnectionState>
1062 peer_connection_state_history_;
1063 std::vector<PeerConnectionInterface::IceGatheringState>
1064 ice_gathering_state_history_;
1065 std::vector<cricket::CandidatePairChangeEvent>
1066 ice_candidate_pair_change_history_;
1067 std::vector<PeerConnectionInterface::SignalingState>
1068 peer_connection_signaling_state_history_;
1069 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1070
1071 rtc::AsyncInvoker invoker_;
1072
1073 friend class PeerConnectionIntegrationBaseTest;
1074 };
1075
1076 class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1077 public:
1078 virtual ~MockRtcEventLogOutput() = default;
1079 MOCK_METHOD(bool, IsActive, (), (const, override));
1080 MOCK_METHOD(bool, Write, (const std::string&), (override));
1081 };
1082
1083 // This helper object is used for both specifying how many audio/video frames
1084 // are expected to be received for a caller/callee. It provides helper functions
1085 // to specify these expectations. The object initially starts in a state of no
1086 // expectations.
1087 class MediaExpectations {
1088 public:
1089 enum ExpectFrames {
1090 kExpectSomeFrames,
1091 kExpectNoFrames,
1092 kNoExpectation,
1093 };
1094
ExpectBidirectionalAudioAndVideo()1095 void ExpectBidirectionalAudioAndVideo() {
1096 ExpectBidirectionalAudio();
1097 ExpectBidirectionalVideo();
1098 }
1099
ExpectBidirectionalAudio()1100 void ExpectBidirectionalAudio() {
1101 CallerExpectsSomeAudio();
1102 CalleeExpectsSomeAudio();
1103 }
1104
ExpectNoAudio()1105 void ExpectNoAudio() {
1106 CallerExpectsNoAudio();
1107 CalleeExpectsNoAudio();
1108 }
1109
ExpectBidirectionalVideo()1110 void ExpectBidirectionalVideo() {
1111 CallerExpectsSomeVideo();
1112 CalleeExpectsSomeVideo();
1113 }
1114
ExpectNoVideo()1115 void ExpectNoVideo() {
1116 CallerExpectsNoVideo();
1117 CalleeExpectsNoVideo();
1118 }
1119
CallerExpectsSomeAudioAndVideo()1120 void CallerExpectsSomeAudioAndVideo() {
1121 CallerExpectsSomeAudio();
1122 CallerExpectsSomeVideo();
1123 }
1124
CalleeExpectsSomeAudioAndVideo()1125 void CalleeExpectsSomeAudioAndVideo() {
1126 CalleeExpectsSomeAudio();
1127 CalleeExpectsSomeVideo();
1128 }
1129
1130 // Caller's audio functions.
CallerExpectsSomeAudio(int expected_audio_frames=kDefaultExpectedAudioFrameCount)1131 void CallerExpectsSomeAudio(
1132 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1133 caller_audio_expectation_ = kExpectSomeFrames;
1134 caller_audio_frames_expected_ = expected_audio_frames;
1135 }
1136
CallerExpectsNoAudio()1137 void CallerExpectsNoAudio() {
1138 caller_audio_expectation_ = kExpectNoFrames;
1139 caller_audio_frames_expected_ = 0;
1140 }
1141
1142 // Caller's video functions.
CallerExpectsSomeVideo(int expected_video_frames=kDefaultExpectedVideoFrameCount)1143 void CallerExpectsSomeVideo(
1144 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1145 caller_video_expectation_ = kExpectSomeFrames;
1146 caller_video_frames_expected_ = expected_video_frames;
1147 }
1148
CallerExpectsNoVideo()1149 void CallerExpectsNoVideo() {
1150 caller_video_expectation_ = kExpectNoFrames;
1151 caller_video_frames_expected_ = 0;
1152 }
1153
1154 // Callee's audio functions.
CalleeExpectsSomeAudio(int expected_audio_frames=kDefaultExpectedAudioFrameCount)1155 void CalleeExpectsSomeAudio(
1156 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1157 callee_audio_expectation_ = kExpectSomeFrames;
1158 callee_audio_frames_expected_ = expected_audio_frames;
1159 }
1160
CalleeExpectsNoAudio()1161 void CalleeExpectsNoAudio() {
1162 callee_audio_expectation_ = kExpectNoFrames;
1163 callee_audio_frames_expected_ = 0;
1164 }
1165
1166 // Callee's video functions.
CalleeExpectsSomeVideo(int expected_video_frames=kDefaultExpectedVideoFrameCount)1167 void CalleeExpectsSomeVideo(
1168 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1169 callee_video_expectation_ = kExpectSomeFrames;
1170 callee_video_frames_expected_ = expected_video_frames;
1171 }
1172
CalleeExpectsNoVideo()1173 void CalleeExpectsNoVideo() {
1174 callee_video_expectation_ = kExpectNoFrames;
1175 callee_video_frames_expected_ = 0;
1176 }
1177
1178 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1179 ExpectFrames caller_video_expectation_ = kNoExpectation;
1180 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1181 ExpectFrames callee_video_expectation_ = kNoExpectation;
1182 int caller_audio_frames_expected_ = 0;
1183 int caller_video_frames_expected_ = 0;
1184 int callee_audio_frames_expected_ = 0;
1185 int callee_video_frames_expected_ = 0;
1186 };
1187
1188 class MockIceTransport : public webrtc::IceTransportInterface {
1189 public:
MockIceTransport(const std::string & name,int component)1190 MockIceTransport(const std::string& name, int component)
1191 : internal_(std::make_unique<cricket::FakeIceTransport>(
1192 name,
1193 component,
1194 nullptr /* network_thread */)) {}
1195 ~MockIceTransport() = default;
internal()1196 cricket::IceTransportInternal* internal() { return internal_.get(); }
1197
1198 private:
1199 std::unique_ptr<cricket::FakeIceTransport> internal_;
1200 };
1201
1202 class MockIceTransportFactory : public IceTransportFactory {
1203 public:
1204 ~MockIceTransportFactory() override = default;
CreateIceTransport(const std::string & transport_name,int component,IceTransportInit init)1205 rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
1206 const std::string& transport_name,
1207 int component,
1208 IceTransportInit init) {
1209 RecordIceTransportCreated();
1210 return new rtc::RefCountedObject<MockIceTransport>(transport_name,
1211 component);
1212 }
1213 MOCK_METHOD(void, RecordIceTransportCreated, ());
1214 };
1215
1216 // Tests two PeerConnections connecting to each other end-to-end, using a
1217 // virtual network, fake A/V capture and fake encoder/decoders. The
1218 // PeerConnections share the threads/socket servers, but use separate versions
1219 // of everything else (including "PeerConnectionFactory"s).
1220 class PeerConnectionIntegrationBaseTest : public ::testing::Test {
1221 public:
PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)1222 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1223 : sdp_semantics_(sdp_semantics),
1224 ss_(new rtc::VirtualSocketServer()),
1225 fss_(new rtc::FirewallSocketServer(ss_.get())),
1226 network_thread_(new rtc::Thread(fss_.get())),
1227 worker_thread_(rtc::Thread::Create()) {
1228 network_thread_->SetName("PCNetworkThread", this);
1229 worker_thread_->SetName("PCWorkerThread", this);
1230 RTC_CHECK(network_thread_->Start());
1231 RTC_CHECK(worker_thread_->Start());
1232 webrtc::metrics::Reset();
1233 }
1234
~PeerConnectionIntegrationBaseTest()1235 ~PeerConnectionIntegrationBaseTest() {
1236 // The PeerConnections should deleted before the TurnCustomizers.
1237 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1238 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1239 // that the TurnCustomizer outlives the life of the PeerConnection or else
1240 // when Send() is called it will hit a seg fault.
1241 if (caller_) {
1242 caller_->set_signaling_message_receiver(nullptr);
1243 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
1244 }
1245 if (callee_) {
1246 callee_->set_signaling_message_receiver(nullptr);
1247 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
1248 }
1249
1250 // If turn servers were created for the test they need to be destroyed on
1251 // the network thread.
1252 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1253 turn_servers_.clear();
1254 turn_customizers_.clear();
1255 });
1256 }
1257
SignalingStateStable()1258 bool SignalingStateStable() {
1259 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1260 }
1261
DtlsConnected()1262 bool DtlsConnected() {
1263 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1264 // are connected. This is an important distinction. Once we have separate
1265 // ICE and DTLS state, this check needs to use the DTLS state.
1266 return (callee()->ice_connection_state() ==
1267 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1268 callee()->ice_connection_state() ==
1269 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1270 (caller()->ice_connection_state() ==
1271 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1272 caller()->ice_connection_state() ==
1273 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
1274 }
1275
1276 // When |event_log_factory| is null, the default implementation of the event
1277 // log factory will be used.
CreatePeerConnectionWrapper(const std::string & debug_name,const PeerConnectionFactory::Options * options,const RTCConfiguration * config,webrtc::PeerConnectionDependencies dependencies,std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,bool reset_encoder_factory,bool reset_decoder_factory)1278 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1279 const std::string& debug_name,
1280 const PeerConnectionFactory::Options* options,
1281 const RTCConfiguration* config,
1282 webrtc::PeerConnectionDependencies dependencies,
1283 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1284 bool reset_encoder_factory,
1285 bool reset_decoder_factory) {
1286 RTCConfiguration modified_config;
1287 if (config) {
1288 modified_config = *config;
1289 }
1290 modified_config.sdp_semantics = sdp_semantics_;
1291 if (!dependencies.cert_generator) {
1292 dependencies.cert_generator =
1293 std::make_unique<FakeRTCCertificateGenerator>();
1294 }
1295 std::unique_ptr<PeerConnectionWrapper> client(
1296 new PeerConnectionWrapper(debug_name));
1297
1298 if (!client->Init(options, &modified_config, std::move(dependencies),
1299 network_thread_.get(), worker_thread_.get(),
1300 std::move(event_log_factory), reset_encoder_factory,
1301 reset_decoder_factory)) {
1302 return nullptr;
1303 }
1304 return client;
1305 }
1306
1307 std::unique_ptr<PeerConnectionWrapper>
CreatePeerConnectionWrapperWithFakeRtcEventLog(const std::string & debug_name,const PeerConnectionFactory::Options * options,const RTCConfiguration * config,webrtc::PeerConnectionDependencies dependencies)1308 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1309 const std::string& debug_name,
1310 const PeerConnectionFactory::Options* options,
1311 const RTCConfiguration* config,
1312 webrtc::PeerConnectionDependencies dependencies) {
1313 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1314 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
1315 return CreatePeerConnectionWrapper(debug_name, options, config,
1316 std::move(dependencies),
1317 std::move(event_log_factory),
1318 /*reset_encoder_factory=*/false,
1319 /*reset_decoder_factory=*/false);
1320 }
1321
CreatePeerConnectionWrappers()1322 bool CreatePeerConnectionWrappers() {
1323 return CreatePeerConnectionWrappersWithConfig(
1324 PeerConnectionInterface::RTCConfiguration(),
1325 PeerConnectionInterface::RTCConfiguration());
1326 }
1327
CreatePeerConnectionWrappersWithSdpSemantics(SdpSemantics caller_semantics,SdpSemantics callee_semantics)1328 bool CreatePeerConnectionWrappersWithSdpSemantics(
1329 SdpSemantics caller_semantics,
1330 SdpSemantics callee_semantics) {
1331 // Can't specify the sdp_semantics in the passed-in configuration since it
1332 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1333 // stored in sdp_semantics_. So get around this by modifying the instance
1334 // variable before calling CreatePeerConnectionWrapper for the caller and
1335 // callee PeerConnections.
1336 SdpSemantics original_semantics = sdp_semantics_;
1337 sdp_semantics_ = caller_semantics;
1338 caller_ = CreatePeerConnectionWrapper(
1339 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1340 nullptr,
1341 /*reset_encoder_factory=*/false,
1342 /*reset_decoder_factory=*/false);
1343 sdp_semantics_ = callee_semantics;
1344 callee_ = CreatePeerConnectionWrapper(
1345 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1346 nullptr,
1347 /*reset_encoder_factory=*/false,
1348 /*reset_decoder_factory=*/false);
1349 sdp_semantics_ = original_semantics;
1350 return caller_ && callee_;
1351 }
1352
CreatePeerConnectionWrappersWithConfig(const PeerConnectionInterface::RTCConfiguration & caller_config,const PeerConnectionInterface::RTCConfiguration & callee_config)1353 bool CreatePeerConnectionWrappersWithConfig(
1354 const PeerConnectionInterface::RTCConfiguration& caller_config,
1355 const PeerConnectionInterface::RTCConfiguration& callee_config) {
1356 caller_ = CreatePeerConnectionWrapper(
1357 "Caller", nullptr, &caller_config,
1358 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1359 /*reset_encoder_factory=*/false,
1360 /*reset_decoder_factory=*/false);
1361 callee_ = CreatePeerConnectionWrapper(
1362 "Callee", nullptr, &callee_config,
1363 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1364 /*reset_encoder_factory=*/false,
1365 /*reset_decoder_factory=*/false);
1366 return caller_ && callee_;
1367 }
1368
CreatePeerConnectionWrappersWithConfigAndDeps(const PeerConnectionInterface::RTCConfiguration & caller_config,webrtc::PeerConnectionDependencies caller_dependencies,const PeerConnectionInterface::RTCConfiguration & callee_config,webrtc::PeerConnectionDependencies callee_dependencies)1369 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1370 const PeerConnectionInterface::RTCConfiguration& caller_config,
1371 webrtc::PeerConnectionDependencies caller_dependencies,
1372 const PeerConnectionInterface::RTCConfiguration& callee_config,
1373 webrtc::PeerConnectionDependencies callee_dependencies) {
1374 caller_ =
1375 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1376 std::move(caller_dependencies), nullptr,
1377 /*reset_encoder_factory=*/false,
1378 /*reset_decoder_factory=*/false);
1379 callee_ =
1380 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1381 std::move(callee_dependencies), nullptr,
1382 /*reset_encoder_factory=*/false,
1383 /*reset_decoder_factory=*/false);
1384 return caller_ && callee_;
1385 }
1386
CreatePeerConnectionWrappersWithOptions(const PeerConnectionFactory::Options & caller_options,const PeerConnectionFactory::Options & callee_options)1387 bool CreatePeerConnectionWrappersWithOptions(
1388 const PeerConnectionFactory::Options& caller_options,
1389 const PeerConnectionFactory::Options& callee_options) {
1390 caller_ = CreatePeerConnectionWrapper(
1391 "Caller", &caller_options, nullptr,
1392 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1393 /*reset_encoder_factory=*/false,
1394 /*reset_decoder_factory=*/false);
1395 callee_ = CreatePeerConnectionWrapper(
1396 "Callee", &callee_options, nullptr,
1397 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1398 /*reset_encoder_factory=*/false,
1399 /*reset_decoder_factory=*/false);
1400 return caller_ && callee_;
1401 }
1402
CreatePeerConnectionWrappersWithFakeRtcEventLog()1403 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1404 PeerConnectionInterface::RTCConfiguration default_config;
1405 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
1406 "Caller", nullptr, &default_config,
1407 webrtc::PeerConnectionDependencies(nullptr));
1408 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
1409 "Callee", nullptr, &default_config,
1410 webrtc::PeerConnectionDependencies(nullptr));
1411 return caller_ && callee_;
1412 }
1413
1414 std::unique_ptr<PeerConnectionWrapper>
CreatePeerConnectionWrapperWithAlternateKey()1415 CreatePeerConnectionWrapperWithAlternateKey() {
1416 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1417 new FakeRTCCertificateGenerator());
1418 cert_generator->use_alternate_key();
1419
1420 webrtc::PeerConnectionDependencies dependencies(nullptr);
1421 dependencies.cert_generator = std::move(cert_generator);
1422 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
1423 std::move(dependencies), nullptr,
1424 /*reset_encoder_factory=*/false,
1425 /*reset_decoder_factory=*/false);
1426 }
1427
CreateOneDirectionalPeerConnectionWrappers(bool caller_to_callee)1428 bool CreateOneDirectionalPeerConnectionWrappers(bool caller_to_callee) {
1429 caller_ = CreatePeerConnectionWrapper(
1430 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1431 nullptr,
1432 /*reset_encoder_factory=*/!caller_to_callee,
1433 /*reset_decoder_factory=*/caller_to_callee);
1434 callee_ = CreatePeerConnectionWrapper(
1435 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1436 nullptr,
1437 /*reset_encoder_factory=*/caller_to_callee,
1438 /*reset_decoder_factory=*/!caller_to_callee);
1439 return caller_ && callee_;
1440 }
1441
CreateTurnServer(rtc::SocketAddress internal_address,rtc::SocketAddress external_address,cricket::ProtocolType type=cricket::ProtocolType::PROTO_UDP,const std::string & common_name="test turn server")1442 cricket::TestTurnServer* CreateTurnServer(
1443 rtc::SocketAddress internal_address,
1444 rtc::SocketAddress external_address,
1445 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1446 const std::string& common_name = "test turn server") {
1447 rtc::Thread* thread = network_thread();
1448 std::unique_ptr<cricket::TestTurnServer> turn_server =
1449 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1450 RTC_FROM_HERE,
1451 [thread, internal_address, external_address, type, common_name] {
1452 return std::make_unique<cricket::TestTurnServer>(
1453 thread, internal_address, external_address, type,
1454 /*ignore_bad_certs=*/true, common_name);
1455 });
1456 turn_servers_.push_back(std::move(turn_server));
1457 // Interactions with the turn server should be done on the network thread.
1458 return turn_servers_.back().get();
1459 }
1460
CreateTurnCustomizer()1461 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1462 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1463 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1464 RTC_FROM_HERE,
1465 [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
1466 turn_customizers_.push_back(std::move(turn_customizer));
1467 // Interactions with the turn customizer should be done on the network
1468 // thread.
1469 return turn_customizers_.back().get();
1470 }
1471
1472 // Checks that the function counters for a TestTurnCustomizer are greater than
1473 // 0.
ExpectTurnCustomizerCountersIncremented(cricket::TestTurnCustomizer * turn_customizer)1474 void ExpectTurnCustomizerCountersIncremented(
1475 cricket::TestTurnCustomizer* turn_customizer) {
1476 unsigned int allow_channel_data_counter =
1477 network_thread()->Invoke<unsigned int>(
1478 RTC_FROM_HERE, [turn_customizer] {
1479 return turn_customizer->allow_channel_data_cnt_;
1480 });
1481 EXPECT_GT(allow_channel_data_counter, 0u);
1482 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1483 RTC_FROM_HERE,
1484 [turn_customizer] { return turn_customizer->modify_cnt_; });
1485 EXPECT_GT(modify_counter, 0u);
1486 }
1487
1488 // Once called, SDP blobs and ICE candidates will be automatically signaled
1489 // between PeerConnections.
ConnectFakeSignaling()1490 void ConnectFakeSignaling() {
1491 caller_->set_signaling_message_receiver(callee_.get());
1492 callee_->set_signaling_message_receiver(caller_.get());
1493 }
1494
1495 // Once called, SDP blobs will be automatically signaled between
1496 // PeerConnections. Note that ICE candidates will not be signaled unless they
1497 // are in the exchanged SDP blobs.
ConnectFakeSignalingForSdpOnly()1498 void ConnectFakeSignalingForSdpOnly() {
1499 ConnectFakeSignaling();
1500 SetSignalIceCandidates(false);
1501 }
1502
SetSignalingDelayMs(int delay_ms)1503 void SetSignalingDelayMs(int delay_ms) {
1504 caller_->set_signaling_delay_ms(delay_ms);
1505 callee_->set_signaling_delay_ms(delay_ms);
1506 }
1507
SetSignalIceCandidates(bool signal)1508 void SetSignalIceCandidates(bool signal) {
1509 caller_->set_signal_ice_candidates(signal);
1510 callee_->set_signal_ice_candidates(signal);
1511 }
1512
1513 // Messages may get lost on the unreliable DataChannel, so we send multiple
1514 // times to avoid test flakiness.
SendRtpDataWithRetries(webrtc::DataChannelInterface * dc,const std::string & data,int retries)1515 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1516 const std::string& data,
1517 int retries) {
1518 for (int i = 0; i < retries; ++i) {
1519 dc->Send(DataBuffer(data));
1520 }
1521 }
1522
network_thread()1523 rtc::Thread* network_thread() { return network_thread_.get(); }
1524
virtual_socket_server()1525 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1526
caller()1527 PeerConnectionWrapper* caller() { return caller_.get(); }
1528
1529 // Set the |caller_| to the |wrapper| passed in and return the
1530 // original |caller_|.
SetCallerPcWrapperAndReturnCurrent(PeerConnectionWrapper * wrapper)1531 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1532 PeerConnectionWrapper* wrapper) {
1533 PeerConnectionWrapper* old = caller_.release();
1534 caller_.reset(wrapper);
1535 return old;
1536 }
1537
callee()1538 PeerConnectionWrapper* callee() { return callee_.get(); }
1539
1540 // Set the |callee_| to the |wrapper| passed in and return the
1541 // original |callee_|.
SetCalleePcWrapperAndReturnCurrent(PeerConnectionWrapper * wrapper)1542 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1543 PeerConnectionWrapper* wrapper) {
1544 PeerConnectionWrapper* old = callee_.release();
1545 callee_.reset(wrapper);
1546 return old;
1547 }
1548
SetPortAllocatorFlags(uint32_t caller_flags,uint32_t callee_flags)1549 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1550 network_thread()->Invoke<void>(
1551 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1552 caller()->port_allocator(), caller_flags));
1553 network_thread()->Invoke<void>(
1554 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1555 callee()->port_allocator(), callee_flags));
1556 }
1557
firewall() const1558 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1559
1560 // Expects the provided number of new frames to be received within
1561 // kMaxWaitForFramesMs. The new expected frames are specified in
1562 // |media_expectations|. Returns false if any of the expectations were
1563 // not met.
ExpectNewFrames(const MediaExpectations & media_expectations)1564 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1565 // Make sure there are no bogus tracks confusing the issue.
1566 caller()->RemoveUnusedVideoRenderers();
1567 callee()->RemoveUnusedVideoRenderers();
1568 // First initialize the expected frame counts based upon the current
1569 // frame count.
1570 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1571 if (media_expectations.caller_audio_expectation_ ==
1572 MediaExpectations::kExpectSomeFrames) {
1573 total_caller_audio_frames_expected +=
1574 media_expectations.caller_audio_frames_expected_;
1575 }
1576 int total_caller_video_frames_expected =
1577 caller()->min_video_frames_received_per_track();
1578 if (media_expectations.caller_video_expectation_ ==
1579 MediaExpectations::kExpectSomeFrames) {
1580 total_caller_video_frames_expected +=
1581 media_expectations.caller_video_frames_expected_;
1582 }
1583 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1584 if (media_expectations.callee_audio_expectation_ ==
1585 MediaExpectations::kExpectSomeFrames) {
1586 total_callee_audio_frames_expected +=
1587 media_expectations.callee_audio_frames_expected_;
1588 }
1589 int total_callee_video_frames_expected =
1590 callee()->min_video_frames_received_per_track();
1591 if (media_expectations.callee_video_expectation_ ==
1592 MediaExpectations::kExpectSomeFrames) {
1593 total_callee_video_frames_expected +=
1594 media_expectations.callee_video_frames_expected_;
1595 }
1596
1597 // Wait for the expected frames.
1598 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
1599 total_caller_audio_frames_expected &&
1600 caller()->min_video_frames_received_per_track() >=
1601 total_caller_video_frames_expected &&
1602 callee()->audio_frames_received() >=
1603 total_callee_audio_frames_expected &&
1604 callee()->min_video_frames_received_per_track() >=
1605 total_callee_video_frames_expected,
1606 kMaxWaitForFramesMs);
1607 bool expectations_correct =
1608 caller()->audio_frames_received() >=
1609 total_caller_audio_frames_expected &&
1610 caller()->min_video_frames_received_per_track() >=
1611 total_caller_video_frames_expected &&
1612 callee()->audio_frames_received() >=
1613 total_callee_audio_frames_expected &&
1614 callee()->min_video_frames_received_per_track() >=
1615 total_callee_video_frames_expected;
1616
1617 // After the combined wait, print out a more detailed message upon
1618 // failure.
1619 EXPECT_GE(caller()->audio_frames_received(),
1620 total_caller_audio_frames_expected);
1621 EXPECT_GE(caller()->min_video_frames_received_per_track(),
1622 total_caller_video_frames_expected);
1623 EXPECT_GE(callee()->audio_frames_received(),
1624 total_callee_audio_frames_expected);
1625 EXPECT_GE(callee()->min_video_frames_received_per_track(),
1626 total_callee_video_frames_expected);
1627
1628 // We want to make sure nothing unexpected was received.
1629 if (media_expectations.caller_audio_expectation_ ==
1630 MediaExpectations::kExpectNoFrames) {
1631 EXPECT_EQ(caller()->audio_frames_received(),
1632 total_caller_audio_frames_expected);
1633 if (caller()->audio_frames_received() !=
1634 total_caller_audio_frames_expected) {
1635 expectations_correct = false;
1636 }
1637 }
1638 if (media_expectations.caller_video_expectation_ ==
1639 MediaExpectations::kExpectNoFrames) {
1640 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1641 total_caller_video_frames_expected);
1642 if (caller()->min_video_frames_received_per_track() !=
1643 total_caller_video_frames_expected) {
1644 expectations_correct = false;
1645 }
1646 }
1647 if (media_expectations.callee_audio_expectation_ ==
1648 MediaExpectations::kExpectNoFrames) {
1649 EXPECT_EQ(callee()->audio_frames_received(),
1650 total_callee_audio_frames_expected);
1651 if (callee()->audio_frames_received() !=
1652 total_callee_audio_frames_expected) {
1653 expectations_correct = false;
1654 }
1655 }
1656 if (media_expectations.callee_video_expectation_ ==
1657 MediaExpectations::kExpectNoFrames) {
1658 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1659 total_callee_video_frames_expected);
1660 if (callee()->min_video_frames_received_per_track() !=
1661 total_callee_video_frames_expected) {
1662 expectations_correct = false;
1663 }
1664 }
1665 return expectations_correct;
1666 }
1667
ClosePeerConnections()1668 void ClosePeerConnections() {
1669 caller()->pc()->Close();
1670 callee()->pc()->Close();
1671 }
1672
TestNegotiatedCipherSuite(const PeerConnectionFactory::Options & caller_options,const PeerConnectionFactory::Options & callee_options,int expected_cipher_suite)1673 void TestNegotiatedCipherSuite(
1674 const PeerConnectionFactory::Options& caller_options,
1675 const PeerConnectionFactory::Options& callee_options,
1676 int expected_cipher_suite) {
1677 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1678 callee_options));
1679 ConnectFakeSignaling();
1680 caller()->AddAudioVideoTracks();
1681 callee()->AddAudioVideoTracks();
1682 caller()->CreateAndSetAndSignalOffer();
1683 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1684 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
1685 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
1686 // TODO(bugs.webrtc.org/9456): Fix it.
1687 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
1688 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1689 expected_cipher_suite));
1690 }
1691
TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,bool remote_gcm_enabled,bool aes_ctr_enabled,int expected_cipher_suite)1692 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1693 bool remote_gcm_enabled,
1694 bool aes_ctr_enabled,
1695 int expected_cipher_suite) {
1696 PeerConnectionFactory::Options caller_options;
1697 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1698 local_gcm_enabled;
1699 caller_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1700 aes_ctr_enabled;
1701 PeerConnectionFactory::Options callee_options;
1702 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1703 remote_gcm_enabled;
1704 callee_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1705 aes_ctr_enabled;
1706 TestNegotiatedCipherSuite(caller_options, callee_options,
1707 expected_cipher_suite);
1708 }
1709
1710 protected:
1711 SdpSemantics sdp_semantics_;
1712
1713 private:
1714 // |ss_| is used by |network_thread_| so it must be destroyed later.
1715 std::unique_ptr<rtc::VirtualSocketServer> ss_;
1716 std::unique_ptr<rtc::FirewallSocketServer> fss_;
1717 // |network_thread_| and |worker_thread_| are used by both
1718 // |caller_| and |callee_| so they must be destroyed
1719 // later.
1720 std::unique_ptr<rtc::Thread> network_thread_;
1721 std::unique_ptr<rtc::Thread> worker_thread_;
1722 // The turn servers and turn customizers should be accessed & deleted on the
1723 // network thread to avoid a race with the socket read/write that occurs
1724 // on the network thread.
1725 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1726 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
1727 std::unique_ptr<PeerConnectionWrapper> caller_;
1728 std::unique_ptr<PeerConnectionWrapper> callee_;
1729 };
1730
1731 class PeerConnectionIntegrationTest
1732 : public PeerConnectionIntegrationBaseTest,
1733 public ::testing::WithParamInterface<SdpSemantics> {
1734 protected:
PeerConnectionIntegrationTest()1735 PeerConnectionIntegrationTest()
1736 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1737 };
1738
1739 // Fake clock must be set before threads are started to prevent race on
1740 // Set/GetClockForTesting().
1741 // To achieve that, multiple inheritance is used as a mixin pattern
1742 // where order of construction is finely controlled.
1743 // This also ensures peerconnection is closed before switching back to non-fake
1744 // clock, avoiding other races and DCHECK failures such as in rtp_sender.cc.
1745 class FakeClockForTest : public rtc::ScopedFakeClock {
1746 protected:
FakeClockForTest()1747 FakeClockForTest() {
1748 // Some things use a time of "0" as a special value, so we need to start out
1749 // the fake clock at a nonzero time.
1750 // TODO(deadbeef): Fix this.
1751 AdvanceTime(webrtc::TimeDelta::Seconds(1));
1752 }
1753
1754 // Explicit handle.
FakeClock()1755 ScopedFakeClock& FakeClock() { return *this; }
1756 };
1757
1758 // Ensure FakeClockForTest is constructed first (see class for rationale).
1759 class PeerConnectionIntegrationTestWithFakeClock
1760 : public FakeClockForTest,
1761 public PeerConnectionIntegrationTest {};
1762
1763 class PeerConnectionIntegrationTestPlanB
1764 : public PeerConnectionIntegrationBaseTest {
1765 protected:
PeerConnectionIntegrationTestPlanB()1766 PeerConnectionIntegrationTestPlanB()
1767 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1768 };
1769
1770 class PeerConnectionIntegrationTestUnifiedPlan
1771 : public PeerConnectionIntegrationBaseTest {
1772 protected:
PeerConnectionIntegrationTestUnifiedPlan()1773 PeerConnectionIntegrationTestUnifiedPlan()
1774 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1775 };
1776
1777 // Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1778 // includes testing that the callback is invoked if an observer is connected
1779 // after the first packet has already been received.
TEST_P(PeerConnectionIntegrationTest,RtpReceiverObserverOnFirstPacketReceived)1780 TEST_P(PeerConnectionIntegrationTest,
1781 RtpReceiverObserverOnFirstPacketReceived) {
1782 ASSERT_TRUE(CreatePeerConnectionWrappers());
1783 ConnectFakeSignaling();
1784 caller()->AddAudioVideoTracks();
1785 callee()->AddAudioVideoTracks();
1786 // Start offer/answer exchange and wait for it to complete.
1787 caller()->CreateAndSetAndSignalOffer();
1788 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1789 // Should be one receiver each for audio/video.
1790 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1791 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
1792 // Wait for all "first packet received" callbacks to be fired.
1793 EXPECT_TRUE_WAIT(
1794 absl::c_all_of(caller()->rtp_receiver_observers(),
1795 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1796 return o->first_packet_received();
1797 }),
1798 kMaxWaitForFramesMs);
1799 EXPECT_TRUE_WAIT(
1800 absl::c_all_of(callee()->rtp_receiver_observers(),
1801 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1802 return o->first_packet_received();
1803 }),
1804 kMaxWaitForFramesMs);
1805 // If new observers are set after the first packet was already received, the
1806 // callback should still be invoked.
1807 caller()->ResetRtpReceiverObservers();
1808 callee()->ResetRtpReceiverObservers();
1809 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1810 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
1811 EXPECT_TRUE(
1812 absl::c_all_of(caller()->rtp_receiver_observers(),
1813 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1814 return o->first_packet_received();
1815 }));
1816 EXPECT_TRUE(
1817 absl::c_all_of(callee()->rtp_receiver_observers(),
1818 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1819 return o->first_packet_received();
1820 }));
1821 }
1822
1823 class DummyDtmfObserver : public DtmfSenderObserverInterface {
1824 public:
DummyDtmfObserver()1825 DummyDtmfObserver() : completed_(false) {}
1826
1827 // Implements DtmfSenderObserverInterface.
OnToneChange(const std::string & tone)1828 void OnToneChange(const std::string& tone) override {
1829 tones_.push_back(tone);
1830 if (tone.empty()) {
1831 completed_ = true;
1832 }
1833 }
1834
tones() const1835 const std::vector<std::string>& tones() const { return tones_; }
completed() const1836 bool completed() const { return completed_; }
1837
1838 private:
1839 bool completed_;
1840 std::vector<std::string> tones_;
1841 };
1842
1843 // Assumes |sender| already has an audio track added and the offer/answer
1844 // exchange is done.
TestDtmfFromSenderToReceiver(PeerConnectionWrapper * sender,PeerConnectionWrapper * receiver)1845 void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1846 PeerConnectionWrapper* receiver) {
1847 // We should be able to get a DTMF sender from the local sender.
1848 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1849 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1850 ASSERT_TRUE(dtmf_sender);
1851 DummyDtmfObserver observer;
1852 dtmf_sender->RegisterObserver(&observer);
1853
1854 // Test the DtmfSender object just created.
1855 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1856 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1857
1858 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1859 std::vector<std::string> tones = {"1", "a", ""};
1860 EXPECT_EQ(tones, observer.tones());
1861 dtmf_sender->UnregisterObserver();
1862 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1863 }
1864
1865 // Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1866 // direction).
TEST_P(PeerConnectionIntegrationTest,DtmfSenderObserver)1867 TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
1868 ASSERT_TRUE(CreatePeerConnectionWrappers());
1869 ConnectFakeSignaling();
1870 // Only need audio for DTMF.
1871 caller()->AddAudioTrack();
1872 callee()->AddAudioTrack();
1873 caller()->CreateAndSetAndSignalOffer();
1874 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1875 // DTLS must finish before the DTMF sender can be used reliably.
1876 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1877 TestDtmfFromSenderToReceiver(caller(), callee());
1878 TestDtmfFromSenderToReceiver(callee(), caller());
1879 }
1880
1881 // Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1882 // between two connections, using DTLS-SRTP.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithDtls)1883 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
1884 ASSERT_TRUE(CreatePeerConnectionWrappers());
1885 ConnectFakeSignaling();
1886
1887 // Do normal offer/answer and wait for some frames to be received in each
1888 // direction.
1889 caller()->AddAudioVideoTracks();
1890 callee()->AddAudioVideoTracks();
1891 caller()->CreateAndSetAndSignalOffer();
1892 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1893 MediaExpectations media_expectations;
1894 media_expectations.ExpectBidirectionalAudioAndVideo();
1895 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1896 EXPECT_METRIC_LE(
1897 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1898 webrtc::kEnumCounterKeyProtocolDtls));
1899 EXPECT_METRIC_EQ(
1900 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1901 webrtc::kEnumCounterKeyProtocolSdes));
1902 }
1903
1904 // Uses SDES instead of DTLS for key agreement.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithSdes)1905 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
1906 PeerConnectionInterface::RTCConfiguration sdes_config;
1907 sdes_config.enable_dtls_srtp.emplace(false);
1908 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1909 ConnectFakeSignaling();
1910
1911 // Do normal offer/answer and wait for some frames to be received in each
1912 // direction.
1913 caller()->AddAudioVideoTracks();
1914 callee()->AddAudioVideoTracks();
1915 caller()->CreateAndSetAndSignalOffer();
1916 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1917 MediaExpectations media_expectations;
1918 media_expectations.ExpectBidirectionalAudioAndVideo();
1919 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1920 EXPECT_METRIC_LE(
1921 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1922 webrtc::kEnumCounterKeyProtocolSdes));
1923 EXPECT_METRIC_EQ(
1924 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1925 webrtc::kEnumCounterKeyProtocolDtls));
1926 }
1927
1928 // Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1929 // option to offer encrypted versions of all header extensions alongside the
1930 // unencrypted versions.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithEncryptedRtpHeaderExtensions)1931 TEST_P(PeerConnectionIntegrationTest,
1932 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1933 CryptoOptions crypto_options;
1934 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1935 PeerConnectionInterface::RTCConfiguration config;
1936 config.crypto_options = crypto_options;
1937 // Note: This allows offering >14 RTP header extensions.
1938 config.offer_extmap_allow_mixed = true;
1939 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1940 ConnectFakeSignaling();
1941
1942 // Do normal offer/answer and wait for some frames to be received in each
1943 // direction.
1944 caller()->AddAudioVideoTracks();
1945 callee()->AddAudioVideoTracks();
1946 caller()->CreateAndSetAndSignalOffer();
1947 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1948 MediaExpectations media_expectations;
1949 media_expectations.ExpectBidirectionalAudioAndVideo();
1950 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1951 }
1952
1953 // This test sets up a call between two parties with a source resolution of
1954 // 1280x720 and verifies that a 16:9 aspect ratio is received.
TEST_P(PeerConnectionIntegrationTest,Send1280By720ResolutionAndReceive16To9AspectRatio)1955 TEST_P(PeerConnectionIntegrationTest,
1956 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1957 ASSERT_TRUE(CreatePeerConnectionWrappers());
1958 ConnectFakeSignaling();
1959
1960 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1961 webrtc::FakePeriodicVideoSource::Config config;
1962 config.width = 1280;
1963 config.height = 720;
1964 config.timestamp_offset_ms = rtc::TimeMillis();
1965 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1966 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
1967
1968 // Do normal offer/answer and wait for at least one frame to be received in
1969 // each direction.
1970 caller()->CreateAndSetAndSignalOffer();
1971 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1972 callee()->min_video_frames_received_per_track() > 0,
1973 kMaxWaitForFramesMs);
1974
1975 // Check rendered aspect ratio.
1976 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1977 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1978 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1979 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1980 }
1981
1982 // This test sets up an one-way call, with media only from caller to
1983 // callee.
TEST_P(PeerConnectionIntegrationTest,OneWayMediaCall)1984 TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
1985 ASSERT_TRUE(CreatePeerConnectionWrappers());
1986 ConnectFakeSignaling();
1987 caller()->AddAudioVideoTracks();
1988 caller()->CreateAndSetAndSignalOffer();
1989 MediaExpectations media_expectations;
1990 media_expectations.CalleeExpectsSomeAudioAndVideo();
1991 media_expectations.CallerExpectsNoAudio();
1992 media_expectations.CallerExpectsNoVideo();
1993 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1994 }
1995
1996 // Tests that send only works without the caller having a decoder factory and
1997 // the callee having an encoder factory.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithSendOnlyVideo)1998 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSendOnlyVideo) {
1999 ASSERT_TRUE(
2000 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/true));
2001 ConnectFakeSignaling();
2002 // Add one-directional video, from caller to callee.
2003 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2004 caller()->CreateLocalVideoTrack();
2005 caller()->AddTrack(caller_track);
2006 PeerConnectionInterface::RTCOfferAnswerOptions options;
2007 options.offer_to_receive_video = 0;
2008 caller()->SetOfferAnswerOptions(options);
2009 caller()->CreateAndSetAndSignalOffer();
2010 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2011 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
2012
2013 // Expect video to be received in one direction.
2014 MediaExpectations media_expectations;
2015 media_expectations.CallerExpectsNoVideo();
2016 media_expectations.CalleeExpectsSomeVideo();
2017
2018 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2019 }
2020
2021 // Tests that receive only works without the caller having an encoder factory
2022 // and the callee having a decoder factory.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithReceiveOnlyVideo)2023 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithReceiveOnlyVideo) {
2024 ASSERT_TRUE(
2025 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/false));
2026 ConnectFakeSignaling();
2027 // Add one-directional video, from callee to caller.
2028 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2029 callee()->CreateLocalVideoTrack();
2030 callee()->AddTrack(callee_track);
2031 PeerConnectionInterface::RTCOfferAnswerOptions options;
2032 options.offer_to_receive_video = 1;
2033 caller()->SetOfferAnswerOptions(options);
2034 caller()->CreateAndSetAndSignalOffer();
2035 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2036 ASSERT_EQ(caller()->pc()->GetReceivers().size(), 1u);
2037
2038 // Expect video to be received in one direction.
2039 MediaExpectations media_expectations;
2040 media_expectations.CallerExpectsSomeVideo();
2041 media_expectations.CalleeExpectsNoVideo();
2042
2043 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2044 }
2045
TEST_P(PeerConnectionIntegrationTest,EndToEndCallAddReceiveVideoToSendOnlyCall)2046 TEST_P(PeerConnectionIntegrationTest,
2047 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2048 ASSERT_TRUE(CreatePeerConnectionWrappers());
2049 ConnectFakeSignaling();
2050 // Add one-directional video, from caller to callee.
2051 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2052 caller()->CreateLocalVideoTrack();
2053 caller()->AddTrack(caller_track);
2054 caller()->CreateAndSetAndSignalOffer();
2055 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2056
2057 // Add receive video.
2058 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2059 callee()->CreateLocalVideoTrack();
2060 callee()->AddTrack(callee_track);
2061 caller()->CreateAndSetAndSignalOffer();
2062 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2063
2064 // Ensure that video frames are received end-to-end.
2065 MediaExpectations media_expectations;
2066 media_expectations.ExpectBidirectionalVideo();
2067 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2068 }
2069
TEST_P(PeerConnectionIntegrationTest,EndToEndCallAddSendVideoToReceiveOnlyCall)2070 TEST_P(PeerConnectionIntegrationTest,
2071 EndToEndCallAddSendVideoToReceiveOnlyCall) {
2072 ASSERT_TRUE(CreatePeerConnectionWrappers());
2073 ConnectFakeSignaling();
2074 // Add one-directional video, from callee to caller.
2075 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2076 callee()->CreateLocalVideoTrack();
2077 callee()->AddTrack(callee_track);
2078 caller()->CreateAndSetAndSignalOffer();
2079 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2080
2081 // Add send video.
2082 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2083 caller()->CreateLocalVideoTrack();
2084 caller()->AddTrack(caller_track);
2085 caller()->CreateAndSetAndSignalOffer();
2086 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2087
2088 // Expect video to be received in one direction.
2089 MediaExpectations media_expectations;
2090 media_expectations.ExpectBidirectionalVideo();
2091 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2092 }
2093
TEST_P(PeerConnectionIntegrationTest,EndToEndCallRemoveReceiveVideoFromSendReceiveCall)2094 TEST_P(PeerConnectionIntegrationTest,
2095 EndToEndCallRemoveReceiveVideoFromSendReceiveCall) {
2096 ASSERT_TRUE(CreatePeerConnectionWrappers());
2097 ConnectFakeSignaling();
2098 // Add send video, from caller to callee.
2099 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2100 caller()->CreateLocalVideoTrack();
2101 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2102 caller()->AddTrack(caller_track);
2103 // Add receive video, from callee to caller.
2104 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2105 callee()->CreateLocalVideoTrack();
2106
2107 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2108 callee()->AddTrack(callee_track);
2109 caller()->CreateAndSetAndSignalOffer();
2110 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2111
2112 // Remove receive video (i.e., callee sender track).
2113 callee()->pc()->RemoveTrack(callee_sender);
2114
2115 caller()->CreateAndSetAndSignalOffer();
2116 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2117
2118 // Expect one-directional video.
2119 MediaExpectations media_expectations;
2120 media_expectations.CallerExpectsNoVideo();
2121 media_expectations.CalleeExpectsSomeVideo();
2122
2123 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2124 }
2125
TEST_P(PeerConnectionIntegrationTest,EndToEndCallRemoveSendVideoFromSendReceiveCall)2126 TEST_P(PeerConnectionIntegrationTest,
2127 EndToEndCallRemoveSendVideoFromSendReceiveCall) {
2128 ASSERT_TRUE(CreatePeerConnectionWrappers());
2129 ConnectFakeSignaling();
2130 // Add send video, from caller to callee.
2131 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2132 caller()->CreateLocalVideoTrack();
2133 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2134 caller()->AddTrack(caller_track);
2135 // Add receive video, from callee to caller.
2136 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2137 callee()->CreateLocalVideoTrack();
2138
2139 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2140 callee()->AddTrack(callee_track);
2141 caller()->CreateAndSetAndSignalOffer();
2142 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2143
2144 // Remove send video (i.e., caller sender track).
2145 caller()->pc()->RemoveTrack(caller_sender);
2146
2147 caller()->CreateAndSetAndSignalOffer();
2148 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2149
2150 // Expect one-directional video.
2151 MediaExpectations media_expectations;
2152 media_expectations.CalleeExpectsNoVideo();
2153 media_expectations.CallerExpectsSomeVideo();
2154
2155 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2156 }
2157
2158 // This test sets up a audio call initially, with the callee rejecting video
2159 // initially. Then later the callee decides to upgrade to audio/video, and
2160 // initiates a new offer/answer exchange.
TEST_P(PeerConnectionIntegrationTest,AudioToVideoUpgrade)2161 TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
2162 ASSERT_TRUE(CreatePeerConnectionWrappers());
2163 ConnectFakeSignaling();
2164 // Initially, offer an audio/video stream from the caller, but refuse to
2165 // send/receive video on the callee side.
2166 caller()->AddAudioVideoTracks();
2167 callee()->AddAudioTrack();
2168 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2169 PeerConnectionInterface::RTCOfferAnswerOptions options;
2170 options.offer_to_receive_video = 0;
2171 callee()->SetOfferAnswerOptions(options);
2172 } else {
2173 callee()->SetRemoteOfferHandler([this] {
2174 callee()
2175 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2176 ->StopInternal();
2177 });
2178 }
2179 // Do offer/answer and make sure audio is still received end-to-end.
2180 caller()->CreateAndSetAndSignalOffer();
2181 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2182 {
2183 MediaExpectations media_expectations;
2184 media_expectations.ExpectBidirectionalAudio();
2185 media_expectations.ExpectNoVideo();
2186 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2187 }
2188 // Sanity check that the callee's description has a rejected video section.
2189 ASSERT_NE(nullptr, callee()->pc()->local_description());
2190 const ContentInfo* callee_video_content =
2191 GetFirstVideoContent(callee()->pc()->local_description()->description());
2192 ASSERT_NE(nullptr, callee_video_content);
2193 EXPECT_TRUE(callee_video_content->rejected);
2194
2195 // Now negotiate with video and ensure negotiation succeeds, with video
2196 // frames and additional audio frames being received.
2197 callee()->AddVideoTrack();
2198 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2199 PeerConnectionInterface::RTCOfferAnswerOptions options;
2200 options.offer_to_receive_video = 1;
2201 callee()->SetOfferAnswerOptions(options);
2202 } else {
2203 callee()->SetRemoteOfferHandler(nullptr);
2204 caller()->SetRemoteOfferHandler([this] {
2205 // The caller creates a new transceiver to receive video on when receiving
2206 // the offer, but by default it is send only.
2207 auto transceivers = caller()->pc()->GetTransceivers();
2208 ASSERT_EQ(2U, transceivers.size());
2209 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2210 transceivers[1]->receiver()->media_type());
2211 transceivers[1]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2212 transceivers[1]->SetDirectionWithError(
2213 RtpTransceiverDirection::kSendRecv);
2214 });
2215 }
2216 callee()->CreateAndSetAndSignalOffer();
2217 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2218 {
2219 // Expect additional audio frames to be received after the upgrade.
2220 MediaExpectations media_expectations;
2221 media_expectations.ExpectBidirectionalAudioAndVideo();
2222 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2223 }
2224 }
2225
2226 // Simpler than the above test; just add an audio track to an established
2227 // video-only connection.
TEST_P(PeerConnectionIntegrationTest,AddAudioToVideoOnlyCall)2228 TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
2229 ASSERT_TRUE(CreatePeerConnectionWrappers());
2230 ConnectFakeSignaling();
2231 // Do initial offer/answer with just a video track.
2232 caller()->AddVideoTrack();
2233 callee()->AddVideoTrack();
2234 caller()->CreateAndSetAndSignalOffer();
2235 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2236 // Now add an audio track and do another offer/answer.
2237 caller()->AddAudioTrack();
2238 callee()->AddAudioTrack();
2239 caller()->CreateAndSetAndSignalOffer();
2240 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2241 // Ensure both audio and video frames are received end-to-end.
2242 MediaExpectations media_expectations;
2243 media_expectations.ExpectBidirectionalAudioAndVideo();
2244 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2245 }
2246
2247 // This test sets up a call that's transferred to a new caller with a different
2248 // DTLS fingerprint.
TEST_P(PeerConnectionIntegrationTest,CallTransferredForCallee)2249 TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
2250 ASSERT_TRUE(CreatePeerConnectionWrappers());
2251 ConnectFakeSignaling();
2252 caller()->AddAudioVideoTracks();
2253 callee()->AddAudioVideoTracks();
2254 caller()->CreateAndSetAndSignalOffer();
2255 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2256
2257 // Keep the original peer around which will still send packets to the
2258 // receiving client. These SRTP packets will be dropped.
2259 std::unique_ptr<PeerConnectionWrapper> original_peer(
2260 SetCallerPcWrapperAndReturnCurrent(
2261 CreatePeerConnectionWrapperWithAlternateKey().release()));
2262 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2263 // directly above.
2264 original_peer->pc()->Close();
2265
2266 ConnectFakeSignaling();
2267 caller()->AddAudioVideoTracks();
2268 caller()->CreateAndSetAndSignalOffer();
2269 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2270 // Wait for some additional frames to be transmitted end-to-end.
2271 MediaExpectations media_expectations;
2272 media_expectations.ExpectBidirectionalAudioAndVideo();
2273 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2274 }
2275
2276 // This test sets up a call that's transferred to a new callee with a different
2277 // DTLS fingerprint.
TEST_P(PeerConnectionIntegrationTest,CallTransferredForCaller)2278 TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
2279 ASSERT_TRUE(CreatePeerConnectionWrappers());
2280 ConnectFakeSignaling();
2281 caller()->AddAudioVideoTracks();
2282 callee()->AddAudioVideoTracks();
2283 caller()->CreateAndSetAndSignalOffer();
2284 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2285
2286 // Keep the original peer around which will still send packets to the
2287 // receiving client. These SRTP packets will be dropped.
2288 std::unique_ptr<PeerConnectionWrapper> original_peer(
2289 SetCalleePcWrapperAndReturnCurrent(
2290 CreatePeerConnectionWrapperWithAlternateKey().release()));
2291 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2292 // directly above.
2293 original_peer->pc()->Close();
2294
2295 ConnectFakeSignaling();
2296 callee()->AddAudioVideoTracks();
2297 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2298 caller()->CreateAndSetAndSignalOffer();
2299 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2300 // Wait for some additional frames to be transmitted end-to-end.
2301 MediaExpectations media_expectations;
2302 media_expectations.ExpectBidirectionalAudioAndVideo();
2303 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2304 }
2305
2306 // This test sets up a non-bundled call and negotiates bundling at the same
2307 // time as starting an ICE restart. When bundling is in effect in the restart,
2308 // the DTLS-SRTP context should be successfully reset.
TEST_P(PeerConnectionIntegrationTest,BundlingEnabledWhileIceRestartOccurs)2309 TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
2310 ASSERT_TRUE(CreatePeerConnectionWrappers());
2311 ConnectFakeSignaling();
2312
2313 caller()->AddAudioVideoTracks();
2314 callee()->AddAudioVideoTracks();
2315 // Remove the bundle group from the SDP received by the callee.
2316 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2317 desc->RemoveGroupByName("BUNDLE");
2318 });
2319 caller()->CreateAndSetAndSignalOffer();
2320 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2321 {
2322 MediaExpectations media_expectations;
2323 media_expectations.ExpectBidirectionalAudioAndVideo();
2324 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2325 }
2326 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2327 callee()->SetReceivedSdpMunger(nullptr);
2328 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2329 caller()->CreateAndSetAndSignalOffer();
2330 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2331
2332 // Expect additional frames to be received after the ICE restart.
2333 {
2334 MediaExpectations media_expectations;
2335 media_expectations.ExpectBidirectionalAudioAndVideo();
2336 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2337 }
2338 }
2339
2340 // Test CVO (Coordination of Video Orientation). If a video source is rotated
2341 // and both peers support the CVO RTP header extension, the actual video frames
2342 // don't need to be encoded in different resolutions, since the rotation is
2343 // communicated through the RTP header extension.
TEST_P(PeerConnectionIntegrationTest,RotatedVideoWithCVOExtension)2344 TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
2345 ASSERT_TRUE(CreatePeerConnectionWrappers());
2346 ConnectFakeSignaling();
2347 // Add rotated video tracks.
2348 caller()->AddTrack(
2349 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
2350 callee()->AddTrack(
2351 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2352
2353 // Wait for video frames to be received by both sides.
2354 caller()->CreateAndSetAndSignalOffer();
2355 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2356 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2357 callee()->min_video_frames_received_per_track() > 0,
2358 kMaxWaitForFramesMs);
2359
2360 // Ensure that the aspect ratio is unmodified.
2361 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2362 // not just assumed.
2363 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2364 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2365 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2366 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2367 // Ensure that the CVO bits were surfaced to the renderer.
2368 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2369 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2370 }
2371
2372 // Test that when the CVO extension isn't supported, video is rotated the
2373 // old-fashioned way, by encoding rotated frames.
TEST_P(PeerConnectionIntegrationTest,RotatedVideoWithoutCVOExtension)2374 TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
2375 ASSERT_TRUE(CreatePeerConnectionWrappers());
2376 ConnectFakeSignaling();
2377 // Add rotated video tracks.
2378 caller()->AddTrack(
2379 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
2380 callee()->AddTrack(
2381 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2382
2383 // Remove the CVO extension from the offered SDP.
2384 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2385 cricket::VideoContentDescription* video =
2386 GetFirstVideoContentDescription(desc);
2387 video->ClearRtpHeaderExtensions();
2388 });
2389 // Wait for video frames to be received by both sides.
2390 caller()->CreateAndSetAndSignalOffer();
2391 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2392 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2393 callee()->min_video_frames_received_per_track() > 0,
2394 kMaxWaitForFramesMs);
2395
2396 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2397 // rotation.
2398 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2399 // not just assumed.
2400 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2401 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2402 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2403 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2404 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2405 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2406 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2407 }
2408
2409 // Test that if the answerer rejects the audio m= section, no audio is sent or
2410 // received, but video still can be.
TEST_P(PeerConnectionIntegrationTest,AnswererRejectsAudioSection)2411 TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
2412 ASSERT_TRUE(CreatePeerConnectionWrappers());
2413 ConnectFakeSignaling();
2414 caller()->AddAudioVideoTracks();
2415 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2416 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2417 // it will reject the audio m= section completely.
2418 PeerConnectionInterface::RTCOfferAnswerOptions options;
2419 options.offer_to_receive_audio = 0;
2420 callee()->SetOfferAnswerOptions(options);
2421 } else {
2422 // Stopping the audio RtpTransceiver will cause the media section to be
2423 // rejected in the answer.
2424 callee()->SetRemoteOfferHandler([this] {
2425 callee()
2426 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2427 ->StopInternal();
2428 });
2429 }
2430 callee()->AddTrack(callee()->CreateLocalVideoTrack());
2431 // Do offer/answer and wait for successful end-to-end video frames.
2432 caller()->CreateAndSetAndSignalOffer();
2433 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2434 MediaExpectations media_expectations;
2435 media_expectations.ExpectBidirectionalVideo();
2436 media_expectations.ExpectNoAudio();
2437 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2438
2439 // Sanity check that the callee's description has a rejected audio section.
2440 ASSERT_NE(nullptr, callee()->pc()->local_description());
2441 const ContentInfo* callee_audio_content =
2442 GetFirstAudioContent(callee()->pc()->local_description()->description());
2443 ASSERT_NE(nullptr, callee_audio_content);
2444 EXPECT_TRUE(callee_audio_content->rejected);
2445 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2446 // The caller's transceiver should have stopped after receiving the answer,
2447 // and thus no longer listed in transceivers.
2448 EXPECT_EQ(nullptr,
2449 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO));
2450 }
2451 }
2452
2453 // Test that if the answerer rejects the video m= section, no video is sent or
2454 // received, but audio still can be.
TEST_P(PeerConnectionIntegrationTest,AnswererRejectsVideoSection)2455 TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
2456 ASSERT_TRUE(CreatePeerConnectionWrappers());
2457 ConnectFakeSignaling();
2458 caller()->AddAudioVideoTracks();
2459 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2460 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2461 // it will reject the video m= section completely.
2462 PeerConnectionInterface::RTCOfferAnswerOptions options;
2463 options.offer_to_receive_video = 0;
2464 callee()->SetOfferAnswerOptions(options);
2465 } else {
2466 // Stopping the video RtpTransceiver will cause the media section to be
2467 // rejected in the answer.
2468 callee()->SetRemoteOfferHandler([this] {
2469 callee()
2470 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2471 ->StopInternal();
2472 });
2473 }
2474 callee()->AddTrack(callee()->CreateLocalAudioTrack());
2475 // Do offer/answer and wait for successful end-to-end audio frames.
2476 caller()->CreateAndSetAndSignalOffer();
2477 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2478 MediaExpectations media_expectations;
2479 media_expectations.ExpectBidirectionalAudio();
2480 media_expectations.ExpectNoVideo();
2481 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2482
2483 // Sanity check that the callee's description has a rejected video section.
2484 ASSERT_NE(nullptr, callee()->pc()->local_description());
2485 const ContentInfo* callee_video_content =
2486 GetFirstVideoContent(callee()->pc()->local_description()->description());
2487 ASSERT_NE(nullptr, callee_video_content);
2488 EXPECT_TRUE(callee_video_content->rejected);
2489 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2490 // The caller's transceiver should have stopped after receiving the answer,
2491 // and thus is no longer present.
2492 EXPECT_EQ(nullptr,
2493 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO));
2494 }
2495 }
2496
2497 // Test that if the answerer rejects both audio and video m= sections, nothing
2498 // bad happens.
2499 // TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2500 // test anything but the fact that negotiation succeeds, which doesn't mean
2501 // much.
TEST_P(PeerConnectionIntegrationTest,AnswererRejectsAudioAndVideoSections)2502 TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
2503 ASSERT_TRUE(CreatePeerConnectionWrappers());
2504 ConnectFakeSignaling();
2505 caller()->AddAudioVideoTracks();
2506 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2507 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2508 // will reject both audio and video m= sections.
2509 PeerConnectionInterface::RTCOfferAnswerOptions options;
2510 options.offer_to_receive_audio = 0;
2511 options.offer_to_receive_video = 0;
2512 callee()->SetOfferAnswerOptions(options);
2513 } else {
2514 callee()->SetRemoteOfferHandler([this] {
2515 // Stopping all transceivers will cause all media sections to be rejected.
2516 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
2517 transceiver->StopInternal();
2518 }
2519 });
2520 }
2521 // Do offer/answer and wait for stable signaling state.
2522 caller()->CreateAndSetAndSignalOffer();
2523 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2524
2525 // Sanity check that the callee's description has rejected m= sections.
2526 ASSERT_NE(nullptr, callee()->pc()->local_description());
2527 const ContentInfo* callee_audio_content =
2528 GetFirstAudioContent(callee()->pc()->local_description()->description());
2529 ASSERT_NE(nullptr, callee_audio_content);
2530 EXPECT_TRUE(callee_audio_content->rejected);
2531 const ContentInfo* callee_video_content =
2532 GetFirstVideoContent(callee()->pc()->local_description()->description());
2533 ASSERT_NE(nullptr, callee_video_content);
2534 EXPECT_TRUE(callee_video_content->rejected);
2535 }
2536
2537 // This test sets up an audio and video call between two parties. After the
2538 // call runs for a while, the caller sends an updated offer with video being
2539 // rejected. Once the re-negotiation is done, the video flow should stop and
2540 // the audio flow should continue.
TEST_P(PeerConnectionIntegrationTest,VideoRejectedInSubsequentOffer)2541 TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
2542 ASSERT_TRUE(CreatePeerConnectionWrappers());
2543 ConnectFakeSignaling();
2544 caller()->AddAudioVideoTracks();
2545 callee()->AddAudioVideoTracks();
2546 caller()->CreateAndSetAndSignalOffer();
2547 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2548 {
2549 MediaExpectations media_expectations;
2550 media_expectations.ExpectBidirectionalAudioAndVideo();
2551 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2552 }
2553 // Renegotiate, rejecting the video m= section.
2554 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2555 caller()->SetGeneratedSdpMunger(
2556 [](cricket::SessionDescription* description) {
2557 for (cricket::ContentInfo& content : description->contents()) {
2558 if (cricket::IsVideoContent(&content)) {
2559 content.rejected = true;
2560 }
2561 }
2562 });
2563 } else {
2564 caller()
2565 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2566 ->StopInternal();
2567 }
2568 caller()->CreateAndSetAndSignalOffer();
2569 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2570
2571 // Sanity check that the caller's description has a rejected video section.
2572 ASSERT_NE(nullptr, caller()->pc()->local_description());
2573 const ContentInfo* caller_video_content =
2574 GetFirstVideoContent(caller()->pc()->local_description()->description());
2575 ASSERT_NE(nullptr, caller_video_content);
2576 EXPECT_TRUE(caller_video_content->rejected);
2577 // Wait for some additional audio frames to be received.
2578 {
2579 MediaExpectations media_expectations;
2580 media_expectations.ExpectBidirectionalAudio();
2581 media_expectations.ExpectNoVideo();
2582 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2583 }
2584 }
2585
2586 // Do one offer/answer with audio, another that disables it (rejecting the m=
2587 // section), and another that re-enables it. Regression test for:
2588 // bugs.webrtc.org/6023
TEST_F(PeerConnectionIntegrationTestPlanB,EnableAudioAfterRejecting)2589 TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2590 ASSERT_TRUE(CreatePeerConnectionWrappers());
2591 ConnectFakeSignaling();
2592
2593 // Add audio track, do normal offer/answer.
2594 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2595 caller()->CreateLocalAudioTrack();
2596 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2597 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2598 caller()->CreateAndSetAndSignalOffer();
2599 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2600
2601 // Remove audio track, and set offer_to_receive_audio to false to cause the
2602 // m= section to be completely disabled, not just "recvonly".
2603 caller()->pc()->RemoveTrack(sender);
2604 PeerConnectionInterface::RTCOfferAnswerOptions options;
2605 options.offer_to_receive_audio = 0;
2606 caller()->SetOfferAnswerOptions(options);
2607 caller()->CreateAndSetAndSignalOffer();
2608 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2609
2610 // Add the audio track again, expecting negotiation to succeed and frames to
2611 // flow.
2612 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2613 options.offer_to_receive_audio = 1;
2614 caller()->SetOfferAnswerOptions(options);
2615 caller()->CreateAndSetAndSignalOffer();
2616 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2617
2618 MediaExpectations media_expectations;
2619 media_expectations.CalleeExpectsSomeAudio();
2620 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2621 }
2622
2623 // Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2624 // is needed to support legacy endpoints.
2625 // TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2626 // add a test for an end-to-end test without MID signaling either (basically,
2627 // the minimum acceptable SDP).
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithoutSsrcOrMsidSignaling)2628 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
2629 ASSERT_TRUE(CreatePeerConnectionWrappers());
2630 ConnectFakeSignaling();
2631 // Add audio and video, testing that packets can be demuxed on payload type.
2632 caller()->AddAudioVideoTracks();
2633 callee()->AddAudioVideoTracks();
2634 // Remove SSRCs and MSIDs from the received offer SDP.
2635 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2636 caller()->CreateAndSetAndSignalOffer();
2637 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2638 MediaExpectations media_expectations;
2639 media_expectations.ExpectBidirectionalAudioAndVideo();
2640 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2641 }
2642
2643 // Basic end-to-end test, without SSRC signaling. This means that the track
2644 // was created properly and frames are delivered when the MSIDs are communicated
2645 // with a=msid lines and no a=ssrc lines.
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,EndToEndCallWithoutSsrcSignaling)2646 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2647 EndToEndCallWithoutSsrcSignaling) {
2648 const char kStreamId[] = "streamId";
2649 ASSERT_TRUE(CreatePeerConnectionWrappers());
2650 ConnectFakeSignaling();
2651 // Add just audio tracks.
2652 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2653 callee()->AddAudioTrack();
2654
2655 // Remove SSRCs from the received offer SDP.
2656 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2657 caller()->CreateAndSetAndSignalOffer();
2658 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2659 MediaExpectations media_expectations;
2660 media_expectations.ExpectBidirectionalAudio();
2661 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2662 }
2663
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,EndToEndCallAddReceiveVideoToSendOnlyCall)2664 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2665 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2666 ASSERT_TRUE(CreatePeerConnectionWrappers());
2667 ConnectFakeSignaling();
2668 // Add one-directional video, from caller to callee.
2669 rtc::scoped_refptr<webrtc::VideoTrackInterface> track =
2670 caller()->CreateLocalVideoTrack();
2671
2672 RtpTransceiverInit video_transceiver_init;
2673 video_transceiver_init.stream_ids = {"video1"};
2674 video_transceiver_init.direction = RtpTransceiverDirection::kSendOnly;
2675 auto video_sender =
2676 caller()->pc()->AddTransceiver(track, video_transceiver_init).MoveValue();
2677 caller()->CreateAndSetAndSignalOffer();
2678 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2679
2680 // Add receive direction.
2681 video_sender->SetDirectionWithError(RtpTransceiverDirection::kSendRecv);
2682
2683 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2684 callee()->CreateLocalVideoTrack();
2685
2686 callee()->AddTrack(callee_track);
2687 caller()->CreateAndSetAndSignalOffer();
2688 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2689 // Ensure that video frames are received end-to-end.
2690 MediaExpectations media_expectations;
2691 media_expectations.ExpectBidirectionalVideo();
2692 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2693 }
2694
2695 // Tests that video flows between multiple video tracks when SSRCs are not
2696 // signaled. This exercises the MID RTP header extension which is needed to
2697 // demux the incoming video tracks.
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc)2698 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2699 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2700 ASSERT_TRUE(CreatePeerConnectionWrappers());
2701 ConnectFakeSignaling();
2702 caller()->AddVideoTrack();
2703 caller()->AddVideoTrack();
2704 callee()->AddVideoTrack();
2705 callee()->AddVideoTrack();
2706
2707 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2708 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2709 caller()->CreateAndSetAndSignalOffer();
2710 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2711 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2712 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2713
2714 // Expect video to be received in both directions on both tracks.
2715 MediaExpectations media_expectations;
2716 media_expectations.ExpectBidirectionalVideo();
2717 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2718 }
2719
2720 // Used for the test below.
RemoveBundleGroupSsrcsAndMidExtension(cricket::SessionDescription * desc)2721 void RemoveBundleGroupSsrcsAndMidExtension(cricket::SessionDescription* desc) {
2722 RemoveSsrcsAndKeepMsids(desc);
2723 desc->RemoveGroupByName("BUNDLE");
2724 for (ContentInfo& content : desc->contents()) {
2725 cricket::MediaContentDescription* media = content.media_description();
2726 cricket::RtpHeaderExtensions extensions = media->rtp_header_extensions();
2727 extensions.erase(std::remove_if(extensions.begin(), extensions.end(),
2728 [](const RtpExtension& extension) {
2729 return extension.uri ==
2730 RtpExtension::kMidUri;
2731 }),
2732 extensions.end());
2733 media->set_rtp_header_extensions(extensions);
2734 }
2735 }
2736
2737 // Tests that video flows between multiple video tracks when BUNDLE is not used,
2738 // SSRCs are not signaled and the MID RTP header extension is not used. This
2739 // relies on demuxing by payload type, which normally doesn't work if you have
2740 // multiple media sections using the same payload type, but which should work as
2741 // long as the media sections aren't bundled.
2742 // Regression test for: http://crbug.com/webrtc/12023
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,EndToEndCallWithTwoVideoTracksNoBundleNoSignaledSsrcAndNoMid)2743 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2744 EndToEndCallWithTwoVideoTracksNoBundleNoSignaledSsrcAndNoMid) {
2745 ASSERT_TRUE(CreatePeerConnectionWrappers());
2746 ConnectFakeSignaling();
2747 caller()->AddVideoTrack();
2748 caller()->AddVideoTrack();
2749 callee()->AddVideoTrack();
2750 callee()->AddVideoTrack();
2751 caller()->SetReceivedSdpMunger(&RemoveBundleGroupSsrcsAndMidExtension);
2752 callee()->SetReceivedSdpMunger(&RemoveBundleGroupSsrcsAndMidExtension);
2753 caller()->CreateAndSetAndSignalOffer();
2754 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2755 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2756 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2757 // Make sure we are not bundled.
2758 ASSERT_NE(caller()->pc()->GetSenders()[0]->dtls_transport(),
2759 caller()->pc()->GetSenders()[1]->dtls_transport());
2760
2761 // Expect video to be received in both directions on both tracks.
2762 MediaExpectations media_expectations;
2763 media_expectations.ExpectBidirectionalVideo();
2764 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2765 }
2766
2767 // Used for the test below.
ModifyPayloadTypesAndRemoveMidExtension(cricket::SessionDescription * desc)2768 void ModifyPayloadTypesAndRemoveMidExtension(
2769 cricket::SessionDescription* desc) {
2770 int pt = 96;
2771 for (ContentInfo& content : desc->contents()) {
2772 cricket::MediaContentDescription* media = content.media_description();
2773 cricket::RtpHeaderExtensions extensions = media->rtp_header_extensions();
2774 extensions.erase(std::remove_if(extensions.begin(), extensions.end(),
2775 [](const RtpExtension& extension) {
2776 return extension.uri ==
2777 RtpExtension::kMidUri;
2778 }),
2779 extensions.end());
2780 media->set_rtp_header_extensions(extensions);
2781 cricket::VideoContentDescription* video = media->as_video();
2782 ASSERT_TRUE(video != nullptr);
2783 std::vector<cricket::VideoCodec> codecs = {{pt++, "VP8"}};
2784 video->set_codecs(codecs);
2785 }
2786 }
2787
2788 // Tests that two video tracks can be demultiplexed by payload type alone, by
2789 // using different payload types for the same codec in different m= sections.
2790 // This practice is discouraged but historically has been supported.
2791 // Regression test for: http://crbug.com/webrtc/12029
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,EndToEndCallWithTwoVideoTracksDemultiplexedByPayloadType)2792 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2793 EndToEndCallWithTwoVideoTracksDemultiplexedByPayloadType) {
2794 ASSERT_TRUE(CreatePeerConnectionWrappers());
2795 ConnectFakeSignaling();
2796 caller()->AddVideoTrack();
2797 caller()->AddVideoTrack();
2798 callee()->AddVideoTrack();
2799 callee()->AddVideoTrack();
2800 caller()->SetGeneratedSdpMunger(&ModifyPayloadTypesAndRemoveMidExtension);
2801 callee()->SetGeneratedSdpMunger(&ModifyPayloadTypesAndRemoveMidExtension);
2802 // We can't remove SSRCs from the generated SDP because then no send streams
2803 // would be created.
2804 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2805 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2806 caller()->CreateAndSetAndSignalOffer();
2807 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2808 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2809 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2810 // Make sure we are bundled.
2811 ASSERT_EQ(caller()->pc()->GetSenders()[0]->dtls_transport(),
2812 caller()->pc()->GetSenders()[1]->dtls_transport());
2813
2814 // Expect video to be received in both directions on both tracks.
2815 MediaExpectations media_expectations;
2816 media_expectations.ExpectBidirectionalVideo();
2817 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2818 }
2819
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,NoStreamsMsidLinePresent)2820 TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2821 ASSERT_TRUE(CreatePeerConnectionWrappers());
2822 ConnectFakeSignaling();
2823 caller()->AddAudioTrack();
2824 caller()->AddVideoTrack();
2825 caller()->CreateAndSetAndSignalOffer();
2826 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2827 auto callee_receivers = callee()->pc()->GetReceivers();
2828 ASSERT_EQ(2u, callee_receivers.size());
2829 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2830 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2831 }
2832
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,NoStreamsMsidLineMissing)2833 TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2834 ASSERT_TRUE(CreatePeerConnectionWrappers());
2835 ConnectFakeSignaling();
2836 caller()->AddAudioTrack();
2837 caller()->AddVideoTrack();
2838 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2839 caller()->CreateAndSetAndSignalOffer();
2840 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2841 auto callee_receivers = callee()->pc()->GetReceivers();
2842 ASSERT_EQ(2u, callee_receivers.size());
2843 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2844 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2845 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2846 callee_receivers[1]->stream_ids()[0]);
2847 EXPECT_EQ(callee_receivers[0]->streams()[0],
2848 callee_receivers[1]->streams()[0]);
2849 }
2850
2851 // Test that if two video tracks are sent (from caller to callee, in this test),
2852 // they're transmitted correctly end-to-end.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithTwoVideoTracks)2853 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
2854 ASSERT_TRUE(CreatePeerConnectionWrappers());
2855 ConnectFakeSignaling();
2856 // Add one audio/video stream, and one video-only stream.
2857 caller()->AddAudioVideoTracks();
2858 caller()->AddVideoTrack();
2859 caller()->CreateAndSetAndSignalOffer();
2860 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2861 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
2862
2863 MediaExpectations media_expectations;
2864 media_expectations.CalleeExpectsSomeAudioAndVideo();
2865 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2866 }
2867
MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription * desc)2868 static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2869 bool first = true;
2870 for (cricket::ContentInfo& content : desc->contents()) {
2871 if (first) {
2872 first = false;
2873 continue;
2874 }
2875 content.bundle_only = true;
2876 }
2877 first = true;
2878 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2879 if (first) {
2880 first = false;
2881 continue;
2882 }
2883 transport.description.ice_ufrag.clear();
2884 transport.description.ice_pwd.clear();
2885 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2886 transport.description.identity_fingerprint.reset(nullptr);
2887 }
2888 }
2889
2890 // Test that if applying a true "max bundle" offer, which uses ports of 0,
2891 // "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2892 // "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2893 // successfully and media flows.
2894 // TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2895 // TODO(deadbeef): Won't need this test once we start generating actual
2896 // standards-compliant SDP.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithSpecCompliantMaxBundleOffer)2897 TEST_P(PeerConnectionIntegrationTest,
2898 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2899 ASSERT_TRUE(CreatePeerConnectionWrappers());
2900 ConnectFakeSignaling();
2901 caller()->AddAudioVideoTracks();
2902 callee()->AddAudioVideoTracks();
2903 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2904 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2905 // but the first m= section.
2906 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2907 caller()->CreateAndSetAndSignalOffer();
2908 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2909 MediaExpectations media_expectations;
2910 media_expectations.ExpectBidirectionalAudioAndVideo();
2911 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2912 }
2913
2914 // Test that we can receive the audio output level from a remote audio track.
2915 // TODO(deadbeef): Use a fake audio source and verify that the output level is
2916 // exactly what the source on the other side was configured with.
TEST_P(PeerConnectionIntegrationTest,GetAudioOutputLevelStatsWithOldStatsApi)2917 TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
2918 ASSERT_TRUE(CreatePeerConnectionWrappers());
2919 ConnectFakeSignaling();
2920 // Just add an audio track.
2921 caller()->AddAudioTrack();
2922 caller()->CreateAndSetAndSignalOffer();
2923 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2924
2925 // Get the audio output level stats. Note that the level is not available
2926 // until an RTCP packet has been received.
2927 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
2928 kMaxWaitForFramesMs);
2929 }
2930
2931 // Test that an audio input level is reported.
2932 // TODO(deadbeef): Use a fake audio source and verify that the input level is
2933 // exactly what the source was configured with.
TEST_P(PeerConnectionIntegrationTest,GetAudioInputLevelStatsWithOldStatsApi)2934 TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
2935 ASSERT_TRUE(CreatePeerConnectionWrappers());
2936 ConnectFakeSignaling();
2937 // Just add an audio track.
2938 caller()->AddAudioTrack();
2939 caller()->CreateAndSetAndSignalOffer();
2940 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2941
2942 // Get the audio input level stats. The level should be available very
2943 // soon after the test starts.
2944 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
2945 kMaxWaitForStatsMs);
2946 }
2947
2948 // Test that we can get incoming byte counts from both audio and video tracks.
TEST_P(PeerConnectionIntegrationTest,GetBytesReceivedStatsWithOldStatsApi)2949 TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
2950 ASSERT_TRUE(CreatePeerConnectionWrappers());
2951 ConnectFakeSignaling();
2952 caller()->AddAudioVideoTracks();
2953 // Do offer/answer, wait for the callee to receive some frames.
2954 caller()->CreateAndSetAndSignalOffer();
2955 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2956
2957 MediaExpectations media_expectations;
2958 media_expectations.CalleeExpectsSomeAudioAndVideo();
2959 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2960
2961 // Get a handle to the remote tracks created, so they can be used as GetStats
2962 // filters.
2963 for (const auto& receiver : callee()->pc()->GetReceivers()) {
2964 // We received frames, so we definitely should have nonzero "received bytes"
2965 // stats at this point.
2966 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2967 0);
2968 }
2969 }
2970
2971 // Test that we can get outgoing byte counts from both audio and video tracks.
TEST_P(PeerConnectionIntegrationTest,GetBytesSentStatsWithOldStatsApi)2972 TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
2973 ASSERT_TRUE(CreatePeerConnectionWrappers());
2974 ConnectFakeSignaling();
2975 auto audio_track = caller()->CreateLocalAudioTrack();
2976 auto video_track = caller()->CreateLocalVideoTrack();
2977 caller()->AddTrack(audio_track);
2978 caller()->AddTrack(video_track);
2979 // Do offer/answer, wait for the callee to receive some frames.
2980 caller()->CreateAndSetAndSignalOffer();
2981 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2982 MediaExpectations media_expectations;
2983 media_expectations.CalleeExpectsSomeAudioAndVideo();
2984 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2985
2986 // The callee received frames, so we definitely should have nonzero "sent
2987 // bytes" stats at this point.
2988 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2989 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2990 }
2991
2992 // Test that we can get capture start ntp time.
TEST_P(PeerConnectionIntegrationTest,GetCaptureStartNtpTimeWithOldStatsApi)2993 TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
2994 ASSERT_TRUE(CreatePeerConnectionWrappers());
2995 ConnectFakeSignaling();
2996 caller()->AddAudioTrack();
2997
2998 callee()->AddAudioTrack();
2999
3000 // Do offer/answer, wait for the callee to receive some frames.
3001 caller()->CreateAndSetAndSignalOffer();
3002 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3003
3004 // Get the remote audio track created on the receiver, so they can be used as
3005 // GetStats filters.
3006 auto receivers = callee()->pc()->GetReceivers();
3007 ASSERT_EQ(1u, receivers.size());
3008 auto remote_audio_track = receivers[0]->track();
3009
3010 // Get the audio output level stats. Note that the level is not available
3011 // until an RTCP packet has been received.
3012 EXPECT_TRUE_WAIT(
3013 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
3014 0,
3015 2 * kMaxWaitForFramesMs);
3016 }
3017
3018 // Test that the track ID is associated with all local and remote SSRC stats
3019 // using the old GetStats() and more than 1 audio and more than 1 video track.
3020 // This is a regression test for crbug.com/906988
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,OldGetStatsAssociatesTrackIdForManyMediaSections)3021 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
3022 OldGetStatsAssociatesTrackIdForManyMediaSections) {
3023 ASSERT_TRUE(CreatePeerConnectionWrappers());
3024 ConnectFakeSignaling();
3025 auto audio_sender_1 = caller()->AddAudioTrack();
3026 auto video_sender_1 = caller()->AddVideoTrack();
3027 auto audio_sender_2 = caller()->AddAudioTrack();
3028 auto video_sender_2 = caller()->AddVideoTrack();
3029 caller()->CreateAndSetAndSignalOffer();
3030 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3031
3032 MediaExpectations media_expectations;
3033 media_expectations.CalleeExpectsSomeAudioAndVideo();
3034 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3035
3036 std::vector<std::string> track_ids = {
3037 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3038 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3039
3040 auto caller_stats = caller()->OldGetStats();
3041 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3042 auto callee_stats = callee()->OldGetStats();
3043 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3044 }
3045
3046 // Test that the new GetStats() returns stats for all outgoing/incoming streams
3047 // with the correct track IDs if there are more than one audio and more than one
3048 // video senders/receivers.
TEST_P(PeerConnectionIntegrationTest,NewGetStatsManyAudioAndManyVideoStreams)3049 TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
3050 ASSERT_TRUE(CreatePeerConnectionWrappers());
3051 ConnectFakeSignaling();
3052 auto audio_sender_1 = caller()->AddAudioTrack();
3053 auto video_sender_1 = caller()->AddVideoTrack();
3054 auto audio_sender_2 = caller()->AddAudioTrack();
3055 auto video_sender_2 = caller()->AddVideoTrack();
3056 caller()->CreateAndSetAndSignalOffer();
3057 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3058
3059 MediaExpectations media_expectations;
3060 media_expectations.CalleeExpectsSomeAudioAndVideo();
3061 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3062
3063 std::vector<std::string> track_ids = {
3064 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3065 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3066
3067 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
3068 caller()->NewGetStats();
3069 ASSERT_TRUE(caller_report);
3070 auto outbound_stream_stats =
3071 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
3072 ASSERT_EQ(outbound_stream_stats.size(), 4u);
3073 std::vector<std::string> outbound_track_ids;
3074 for (const auto& stat : outbound_stream_stats) {
3075 ASSERT_TRUE(stat->bytes_sent.is_defined());
3076 EXPECT_LT(0u, *stat->bytes_sent);
3077 if (*stat->kind == "video") {
3078 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
3079 EXPECT_GT(*stat->key_frames_encoded, 0u);
3080 ASSERT_TRUE(stat->frames_encoded.is_defined());
3081 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
3082 }
3083 ASSERT_TRUE(stat->track_id.is_defined());
3084 const auto* track_stat =
3085 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3086 ASSERT_TRUE(track_stat);
3087 outbound_track_ids.push_back(*track_stat->track_identifier);
3088 }
3089 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
3090
3091 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
3092 callee()->NewGetStats();
3093 ASSERT_TRUE(callee_report);
3094 auto inbound_stream_stats =
3095 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3096 ASSERT_EQ(4u, inbound_stream_stats.size());
3097 std::vector<std::string> inbound_track_ids;
3098 for (const auto& stat : inbound_stream_stats) {
3099 ASSERT_TRUE(stat->bytes_received.is_defined());
3100 EXPECT_LT(0u, *stat->bytes_received);
3101 if (*stat->kind == "video") {
3102 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
3103 EXPECT_GT(*stat->key_frames_decoded, 0u);
3104 ASSERT_TRUE(stat->frames_decoded.is_defined());
3105 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
3106 }
3107 ASSERT_TRUE(stat->track_id.is_defined());
3108 const auto* track_stat =
3109 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3110 ASSERT_TRUE(track_stat);
3111 inbound_track_ids.push_back(*track_stat->track_identifier);
3112 }
3113 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
3114 }
3115
3116 // Test that we can get stats (using the new stats implementation) for
3117 // unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
3118 // SDP.
TEST_P(PeerConnectionIntegrationTest,GetStatsForUnsignaledStreamWithNewStatsApi)3119 TEST_P(PeerConnectionIntegrationTest,
3120 GetStatsForUnsignaledStreamWithNewStatsApi) {
3121 ASSERT_TRUE(CreatePeerConnectionWrappers());
3122 ConnectFakeSignaling();
3123 caller()->AddAudioTrack();
3124 // Remove SSRCs and MSIDs from the received offer SDP.
3125 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3126 caller()->CreateAndSetAndSignalOffer();
3127 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3128 MediaExpectations media_expectations;
3129 media_expectations.CalleeExpectsSomeAudio(1);
3130 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3131
3132 // We received a frame, so we should have nonzero "bytes received" stats for
3133 // the unsignaled stream, if stats are working for it.
3134 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3135 callee()->NewGetStats();
3136 ASSERT_NE(nullptr, report);
3137 auto inbound_stream_stats =
3138 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3139 ASSERT_EQ(1U, inbound_stream_stats.size());
3140 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
3141 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
3142 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
3143 }
3144
3145 // Same as above but for the legacy stats implementation.
TEST_P(PeerConnectionIntegrationTest,GetStatsForUnsignaledStreamWithOldStatsApi)3146 TEST_P(PeerConnectionIntegrationTest,
3147 GetStatsForUnsignaledStreamWithOldStatsApi) {
3148 ASSERT_TRUE(CreatePeerConnectionWrappers());
3149 ConnectFakeSignaling();
3150 caller()->AddAudioTrack();
3151 // Remove SSRCs and MSIDs from the received offer SDP.
3152 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3153 caller()->CreateAndSetAndSignalOffer();
3154 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3155
3156 // Note that, since the old stats implementation associates SSRCs with tracks
3157 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
3158 // associated track ID. So we can't use the track "selector" argument.
3159 //
3160 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
3161 // return cached stats if not enough time has passed since the last update.
3162 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
3163 kDefaultTimeout);
3164 }
3165
3166 // Test that we can successfully get the media related stats (audio level
3167 // etc.) for the unsignaled stream.
TEST_P(PeerConnectionIntegrationTest,GetMediaStatsForUnsignaledStreamWithNewStatsApi)3168 TEST_P(PeerConnectionIntegrationTest,
3169 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
3170 ASSERT_TRUE(CreatePeerConnectionWrappers());
3171 ConnectFakeSignaling();
3172 caller()->AddAudioVideoTracks();
3173 // Remove SSRCs and MSIDs from the received offer SDP.
3174 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3175 caller()->CreateAndSetAndSignalOffer();
3176 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3177 MediaExpectations media_expectations;
3178 media_expectations.CalleeExpectsSomeAudio(1);
3179 media_expectations.CalleeExpectsSomeVideo(1);
3180 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3181
3182 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3183 callee()->NewGetStats();
3184 ASSERT_NE(nullptr, report);
3185
3186 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3187 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
3188 ASSERT_GE(audio_index, 0);
3189 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
3190 }
3191
3192 // Helper for test below.
ModifySsrcs(cricket::SessionDescription * desc)3193 void ModifySsrcs(cricket::SessionDescription* desc) {
3194 for (ContentInfo& content : desc->contents()) {
3195 for (StreamParams& stream :
3196 content.media_description()->mutable_streams()) {
3197 for (uint32_t& ssrc : stream.ssrcs) {
3198 ssrc = rtc::CreateRandomId();
3199 }
3200 }
3201 }
3202 }
3203
3204 // Test that the "RTCMediaSteamTrackStats" object is updated correctly when
3205 // SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
3206 // This should result in two "RTCInboundRTPStreamStats", but only one
3207 // "RTCMediaStreamTrackStats", whose counters go up continuously rather than
3208 // being reset to 0 once the SSRC change occurs.
3209 //
3210 // Regression test for this bug:
3211 // https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
3212 //
3213 // The bug causes the track stats to only represent one of the two streams:
3214 // whichever one has the higher SSRC. So with this bug, there was a 50% chance
3215 // that the track stat counters would reset to 0 when the new stream is
3216 // received, and a 50% chance that they'll stop updating (while
3217 // "concealed_samples" continues increasing, due to silence being generated for
3218 // the inactive stream).
TEST_P(PeerConnectionIntegrationTest,TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges)3219 TEST_P(PeerConnectionIntegrationTest,
3220 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
3221 ASSERT_TRUE(CreatePeerConnectionWrappers());
3222 ConnectFakeSignaling();
3223 caller()->AddAudioTrack();
3224 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
3225 // that doesn't signal SSRCs (from the callee's perspective).
3226 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3227 caller()->CreateAndSetAndSignalOffer();
3228 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3229 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
3230 {
3231 MediaExpectations media_expectations;
3232 media_expectations.CalleeExpectsSomeAudio(50);
3233 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3234 }
3235 // Some audio frames were received, so we should have nonzero "samples
3236 // received" for the track.
3237 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3238 callee()->NewGetStats();
3239 ASSERT_NE(nullptr, report);
3240 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3241 ASSERT_EQ(1U, track_stats.size());
3242 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3243 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
3244 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
3245
3246 // Create a new offer and munge it to cause the caller to use a new SSRC.
3247 caller()->SetGeneratedSdpMunger(ModifySsrcs);
3248 caller()->CreateAndSetAndSignalOffer();
3249 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3250 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
3251 // SSRC.
3252 {
3253 MediaExpectations media_expectations;
3254 media_expectations.CalleeExpectsSomeAudio(25);
3255 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3256 }
3257
3258 report = callee()->NewGetStats();
3259 ASSERT_NE(nullptr, report);
3260 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3261 ASSERT_EQ(1U, track_stats.size());
3262 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3263 // The "total samples received" stat should only be greater than it was
3264 // before.
3265 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
3266 // Right now, the new SSRC will cause the counters to reset to 0.
3267 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
3268
3269 // Additionally, the percentage of concealed samples (samples generated to
3270 // conceal packet loss) should be less than 50%. If it's greater, that's a
3271 // good sign that we're seeing stats from the old stream that's no longer
3272 // receiving packets, and is generating concealed samples of silence.
3273 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
3274 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
3275 EXPECT_LT(*track_stats[0]->concealed_samples,
3276 *track_stats[0]->total_samples_received *
3277 kAcceptableConcealedSamplesPercentage);
3278
3279 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
3280 // sanity check that the SSRC really changed.
3281 // TODO(deadbeef): This isn't working right now, because we're not returning
3282 // *any* stats for the inactive stream. Uncomment when the bug is completely
3283 // fixed.
3284 // auto inbound_stream_stats =
3285 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3286 // ASSERT_EQ(2U, inbound_stream_stats.size());
3287 }
3288
3289 // Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithDtls10)3290 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
3291 PeerConnectionFactory::Options dtls_10_options;
3292 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3293 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3294 dtls_10_options));
3295 ConnectFakeSignaling();
3296 // Do normal offer/answer and wait for some frames to be received in each
3297 // direction.
3298 caller()->AddAudioVideoTracks();
3299 callee()->AddAudioVideoTracks();
3300 caller()->CreateAndSetAndSignalOffer();
3301 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3302 MediaExpectations media_expectations;
3303 media_expectations.ExpectBidirectionalAudioAndVideo();
3304 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3305 }
3306
3307 // Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
TEST_P(PeerConnectionIntegrationTest,Dtls10CipherStatsAndUmaMetrics)3308 TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
3309 PeerConnectionFactory::Options dtls_10_options;
3310 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3311 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3312 dtls_10_options));
3313 ConnectFakeSignaling();
3314 caller()->AddAudioVideoTracks();
3315 callee()->AddAudioVideoTracks();
3316 caller()->CreateAndSetAndSignalOffer();
3317 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
3318 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
3319 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
3320 kDefaultTimeout);
3321 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
3322 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
3323 // TODO(bugs.webrtc.org/9456): Fix it.
3324 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3325 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3326 kDefaultSrtpCryptoSuite));
3327 }
3328
3329 // Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
TEST_P(PeerConnectionIntegrationTest,Dtls12CipherStatsAndUmaMetrics)3330 TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
3331 PeerConnectionFactory::Options dtls_12_options;
3332 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3333 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3334 dtls_12_options));
3335 ConnectFakeSignaling();
3336 caller()->AddAudioVideoTracks();
3337 callee()->AddAudioVideoTracks();
3338 caller()->CreateAndSetAndSignalOffer();
3339 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
3340 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
3341 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
3342 kDefaultTimeout);
3343 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
3344 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
3345 // TODO(bugs.webrtc.org/9456): Fix it.
3346 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3347 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3348 kDefaultSrtpCryptoSuite));
3349 }
3350
3351 // Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3352 // callee only supports 1.0.
TEST_P(PeerConnectionIntegrationTest,CallerDtls12ToCalleeDtls10)3353 TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
3354 PeerConnectionFactory::Options caller_options;
3355 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3356 PeerConnectionFactory::Options callee_options;
3357 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3358 ASSERT_TRUE(
3359 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3360 ConnectFakeSignaling();
3361 // Do normal offer/answer and wait for some frames to be received in each
3362 // direction.
3363 caller()->AddAudioVideoTracks();
3364 callee()->AddAudioVideoTracks();
3365 caller()->CreateAndSetAndSignalOffer();
3366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3367 MediaExpectations media_expectations;
3368 media_expectations.ExpectBidirectionalAudioAndVideo();
3369 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3370 }
3371
3372 // Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3373 // callee supports 1.2.
TEST_P(PeerConnectionIntegrationTest,CallerDtls10ToCalleeDtls12)3374 TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
3375 PeerConnectionFactory::Options caller_options;
3376 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3377 PeerConnectionFactory::Options callee_options;
3378 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3379 ASSERT_TRUE(
3380 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3381 ConnectFakeSignaling();
3382 // Do normal offer/answer and wait for some frames to be received in each
3383 // direction.
3384 caller()->AddAudioVideoTracks();
3385 callee()->AddAudioVideoTracks();
3386 caller()->CreateAndSetAndSignalOffer();
3387 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3388 MediaExpectations media_expectations;
3389 media_expectations.ExpectBidirectionalAudioAndVideo();
3390 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3391 }
3392
3393 // The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3394 // works as expected; the cipher should only be used if enabled by both sides.
TEST_P(PeerConnectionIntegrationTest,Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported)3395 TEST_P(PeerConnectionIntegrationTest,
3396 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3397 PeerConnectionFactory::Options caller_options;
3398 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
3399 PeerConnectionFactory::Options callee_options;
3400 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3401 false;
3402 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3403 TestNegotiatedCipherSuite(caller_options, callee_options,
3404 expected_cipher_suite);
3405 }
3406
TEST_P(PeerConnectionIntegrationTest,Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported)3407 TEST_P(PeerConnectionIntegrationTest,
3408 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3409 PeerConnectionFactory::Options caller_options;
3410 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3411 false;
3412 PeerConnectionFactory::Options callee_options;
3413 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
3414 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3415 TestNegotiatedCipherSuite(caller_options, callee_options,
3416 expected_cipher_suite);
3417 }
3418
TEST_P(PeerConnectionIntegrationTest,Aes128Sha1_32_CipherUsedWhenSupported)3419 TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3420 PeerConnectionFactory::Options caller_options;
3421 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
3422 PeerConnectionFactory::Options callee_options;
3423 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
3424 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3425 TestNegotiatedCipherSuite(caller_options, callee_options,
3426 expected_cipher_suite);
3427 }
3428
3429 // Test that a non-GCM cipher is used if both sides only support non-GCM.
TEST_P(PeerConnectionIntegrationTest,NonGcmCipherUsedWhenGcmNotSupported)3430 TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
3431 bool local_gcm_enabled = false;
3432 bool remote_gcm_enabled = false;
3433 bool aes_ctr_enabled = true;
3434 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3435 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3436 aes_ctr_enabled, expected_cipher_suite);
3437 }
3438
3439 // Test that a GCM cipher is used if both ends support it and non-GCM is
3440 // disabled.
TEST_P(PeerConnectionIntegrationTest,GcmCipherUsedWhenOnlyGcmSupported)3441 TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenOnlyGcmSupported) {
3442 bool local_gcm_enabled = true;
3443 bool remote_gcm_enabled = true;
3444 bool aes_ctr_enabled = false;
3445 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3446 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3447 aes_ctr_enabled, expected_cipher_suite);
3448 }
3449
3450 // Verify that media can be transmitted end-to-end when GCM crypto suites are
3451 // enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3452 // only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3453 // works with it.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithGcmCipher)3454 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
3455 PeerConnectionFactory::Options gcm_options;
3456 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
3457 gcm_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher = false;
3458 ASSERT_TRUE(
3459 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3460 ConnectFakeSignaling();
3461 // Do normal offer/answer and wait for some frames to be received in each
3462 // direction.
3463 caller()->AddAudioVideoTracks();
3464 callee()->AddAudioVideoTracks();
3465 caller()->CreateAndSetAndSignalOffer();
3466 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3467 MediaExpectations media_expectations;
3468 media_expectations.ExpectBidirectionalAudioAndVideo();
3469 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3470 }
3471
3472 // This test sets up a call between two parties with audio, video and an RTP
3473 // data channel.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithRtpDataChannel)3474 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
3475 PeerConnectionInterface::RTCConfiguration rtc_config;
3476 rtc_config.enable_rtp_data_channel = true;
3477 rtc_config.enable_dtls_srtp = false;
3478 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
3479 ConnectFakeSignaling();
3480 // Expect that data channel created on caller side will show up for callee as
3481 // well.
3482 caller()->CreateDataChannel();
3483 caller()->AddAudioVideoTracks();
3484 callee()->AddAudioVideoTracks();
3485 caller()->CreateAndSetAndSignalOffer();
3486 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3487 // Ensure the existence of the RTP data channel didn't impede audio/video.
3488 MediaExpectations media_expectations;
3489 media_expectations.ExpectBidirectionalAudioAndVideo();
3490 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3491 ASSERT_NE(nullptr, caller()->data_channel());
3492 ASSERT_NE(nullptr, callee()->data_channel());
3493 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3494 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3495
3496 // Ensure data can be sent in both directions.
3497 std::string data = "hello world";
3498 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3499 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3500 kDefaultTimeout);
3501 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3502 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3503 kDefaultTimeout);
3504 }
3505
TEST_P(PeerConnectionIntegrationTest,RtpDataChannelWorksAfterRollback)3506 TEST_P(PeerConnectionIntegrationTest, RtpDataChannelWorksAfterRollback) {
3507 PeerConnectionInterface::RTCConfiguration rtc_config;
3508 rtc_config.enable_rtp_data_channel = true;
3509 rtc_config.enable_dtls_srtp = false;
3510 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
3511 ConnectFakeSignaling();
3512 auto data_channel = caller()->pc()->CreateDataChannel("label_1", nullptr);
3513 ASSERT_TRUE(data_channel.get() != nullptr);
3514 caller()->CreateAndSetAndSignalOffer();
3515 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3516
3517 caller()->CreateDataChannel("label_2", nullptr);
3518 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
3519 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
3520 caller()->pc()->SetLocalDescription(observer,
3521 caller()->CreateOfferAndWait().release());
3522 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
3523 caller()->Rollback();
3524
3525 std::string data = "hello world";
3526 SendRtpDataWithRetries(data_channel, data, 5);
3527 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3528 kDefaultTimeout);
3529 }
3530
3531 // Ensure that an RTP data channel is signaled as closed for the caller when
3532 // the callee rejects it in a subsequent offer.
TEST_P(PeerConnectionIntegrationTest,RtpDataChannelSignaledClosedInCalleeOffer)3533 TEST_P(PeerConnectionIntegrationTest,
3534 RtpDataChannelSignaledClosedInCalleeOffer) {
3535 // Same procedure as above test.
3536 PeerConnectionInterface::RTCConfiguration rtc_config;
3537 rtc_config.enable_rtp_data_channel = true;
3538 rtc_config.enable_dtls_srtp = false;
3539 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
3540 ConnectFakeSignaling();
3541 caller()->CreateDataChannel();
3542 caller()->AddAudioVideoTracks();
3543 callee()->AddAudioVideoTracks();
3544 caller()->CreateAndSetAndSignalOffer();
3545 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3546 ASSERT_NE(nullptr, caller()->data_channel());
3547 ASSERT_NE(nullptr, callee()->data_channel());
3548 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3549 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3550
3551 // Close the data channel on the callee, and do an updated offer/answer.
3552 callee()->data_channel()->Close();
3553 callee()->CreateAndSetAndSignalOffer();
3554 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3555 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3556 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3557 }
3558
3559 // Tests that data is buffered in an RTP data channel until an observer is
3560 // registered for it.
3561 //
3562 // NOTE: RTP data channels can receive data before the underlying
3563 // transport has detected that a channel is writable and thus data can be
3564 // received before the data channel state changes to open. That is hard to test
3565 // but the same buffering is expected to be used in that case.
3566 //
3567 // Use fake clock and simulated network delay so that we predictably can wait
3568 // until an SCTP message has been delivered without "sleep()"ing.
TEST_P(PeerConnectionIntegrationTestWithFakeClock,DataBufferedUntilRtpDataChannelObserverRegistered)3569 TEST_P(PeerConnectionIntegrationTestWithFakeClock,
3570 DataBufferedUntilRtpDataChannelObserverRegistered) {
3571 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3572 virtual_socket_server()->UpdateDelayDistribution();
3573
3574 PeerConnectionInterface::RTCConfiguration rtc_config;
3575 rtc_config.enable_rtp_data_channel = true;
3576 rtc_config.enable_dtls_srtp = false;
3577 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
3578 ConnectFakeSignaling();
3579 caller()->CreateDataChannel();
3580 caller()->CreateAndSetAndSignalOffer();
3581 ASSERT_TRUE(caller()->data_channel() != nullptr);
3582 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3583 kDefaultTimeout, FakeClock());
3584 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3585 kDefaultTimeout, FakeClock());
3586 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3587 callee()->data_channel()->state(), kDefaultTimeout,
3588 FakeClock());
3589
3590 // Unregister the observer which is normally automatically registered.
3591 callee()->data_channel()->UnregisterObserver();
3592 // Send data and advance fake clock until it should have been received.
3593 std::string data = "hello world";
3594 caller()->data_channel()->Send(DataBuffer(data));
3595 SIMULATED_WAIT(false, 50, FakeClock());
3596
3597 // Attach data channel and expect data to be received immediately. Note that
3598 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3599 // further, but data can be received even if the callback is asynchronous.
3600 MockDataChannelObserver new_observer(callee()->data_channel());
3601 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3602 FakeClock());
3603 }
3604
3605 // This test sets up a call between two parties with audio, video and but only
3606 // the caller client supports RTP data channels.
TEST_P(PeerConnectionIntegrationTest,RtpDataChannelsRejectedByCallee)3607 TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
3608 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3609 rtc_config_1.enable_rtp_data_channel = true;
3610 // Must disable DTLS to make negotiation succeed.
3611 rtc_config_1.enable_dtls_srtp = false;
3612 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3613 rtc_config_2.enable_dtls_srtp = false;
3614 rtc_config_2.enable_dtls_srtp = false;
3615 ASSERT_TRUE(
3616 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
3617 ConnectFakeSignaling();
3618 caller()->CreateDataChannel();
3619 ASSERT_TRUE(caller()->data_channel() != nullptr);
3620 caller()->AddAudioVideoTracks();
3621 callee()->AddAudioVideoTracks();
3622 caller()->CreateAndSetAndSignalOffer();
3623 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3624 // The caller should still have a data channel, but it should be closed, and
3625 // one should ever have been created for the callee.
3626 EXPECT_TRUE(caller()->data_channel() != nullptr);
3627 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3628 EXPECT_EQ(nullptr, callee()->data_channel());
3629 }
3630
3631 // This test sets up a call between two parties with audio, and video. When
3632 // audio and video is setup and flowing, an RTP data channel is negotiated.
TEST_P(PeerConnectionIntegrationTest,AddRtpDataChannelInSubsequentOffer)3633 TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
3634 PeerConnectionInterface::RTCConfiguration rtc_config;
3635 rtc_config.enable_rtp_data_channel = true;
3636 rtc_config.enable_dtls_srtp = false;
3637 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
3638 ConnectFakeSignaling();
3639 // Do initial offer/answer with audio/video.
3640 caller()->AddAudioVideoTracks();
3641 callee()->AddAudioVideoTracks();
3642 caller()->CreateAndSetAndSignalOffer();
3643 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3644 // Create data channel and do new offer and answer.
3645 caller()->CreateDataChannel();
3646 caller()->CreateAndSetAndSignalOffer();
3647 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3648 ASSERT_NE(nullptr, caller()->data_channel());
3649 ASSERT_NE(nullptr, callee()->data_channel());
3650 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3651 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3652 // Ensure data can be sent in both directions.
3653 std::string data = "hello world";
3654 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3655 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3656 kDefaultTimeout);
3657 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3658 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3659 kDefaultTimeout);
3660 }
3661
3662 #ifdef HAVE_SCTP
3663
3664 // This test sets up a call between two parties with audio, video and an SCTP
3665 // data channel.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithSctpDataChannel)3666 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
3667 ASSERT_TRUE(CreatePeerConnectionWrappers());
3668 ConnectFakeSignaling();
3669 // Expect that data channel created on caller side will show up for callee as
3670 // well.
3671 caller()->CreateDataChannel();
3672 caller()->AddAudioVideoTracks();
3673 callee()->AddAudioVideoTracks();
3674 caller()->CreateAndSetAndSignalOffer();
3675 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3676 // Ensure the existence of the SCTP data channel didn't impede audio/video.
3677 MediaExpectations media_expectations;
3678 media_expectations.ExpectBidirectionalAudioAndVideo();
3679 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3680 // Caller data channel should already exist (it created one). Callee data
3681 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3682 ASSERT_NE(nullptr, caller()->data_channel());
3683 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3684 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3685 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3686
3687 // Ensure data can be sent in both directions.
3688 std::string data = "hello world";
3689 caller()->data_channel()->Send(DataBuffer(data));
3690 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3691 kDefaultTimeout);
3692 callee()->data_channel()->Send(DataBuffer(data));
3693 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3694 kDefaultTimeout);
3695 }
3696
3697 // Ensure that when the callee closes an SCTP data channel, the closing
3698 // procedure results in the data channel being closed for the caller as well.
TEST_P(PeerConnectionIntegrationTest,CalleeClosesSctpDataChannel)3699 TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
3700 // Same procedure as above test.
3701 ASSERT_TRUE(CreatePeerConnectionWrappers());
3702 ConnectFakeSignaling();
3703 caller()->CreateDataChannel();
3704 caller()->AddAudioVideoTracks();
3705 callee()->AddAudioVideoTracks();
3706 caller()->CreateAndSetAndSignalOffer();
3707 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3708 ASSERT_NE(nullptr, caller()->data_channel());
3709 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3710 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3711 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3712
3713 // Close the data channel on the callee side, and wait for it to reach the
3714 // "closed" state on both sides.
3715 callee()->data_channel()->Close();
3716 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3717 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3718 }
3719
TEST_P(PeerConnectionIntegrationTest,SctpDataChannelConfigSentToOtherSide)3720 TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
3721 ASSERT_TRUE(CreatePeerConnectionWrappers());
3722 ConnectFakeSignaling();
3723 webrtc::DataChannelInit init;
3724 init.id = 53;
3725 init.maxRetransmits = 52;
3726 caller()->CreateDataChannel("data-channel", &init);
3727 caller()->AddAudioVideoTracks();
3728 callee()->AddAudioVideoTracks();
3729 caller()->CreateAndSetAndSignalOffer();
3730 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3731 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3732 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3733 // Since "negotiated" is false, the "id" parameter should be ignored.
3734 EXPECT_NE(init.id, callee()->data_channel()->id());
3735 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3736 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3737 EXPECT_FALSE(callee()->data_channel()->negotiated());
3738 }
3739
3740 // Test usrsctp's ability to process unordered data stream, where data actually
3741 // arrives out of order using simulated delays. Previously there have been some
3742 // bugs in this area.
TEST_P(PeerConnectionIntegrationTest,StressTestUnorderedSctpDataChannel)3743 TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
3744 // Introduce random network delays.
3745 // Otherwise it's not a true "unordered" test.
3746 virtual_socket_server()->set_delay_mean(20);
3747 virtual_socket_server()->set_delay_stddev(5);
3748 virtual_socket_server()->UpdateDelayDistribution();
3749 // Normal procedure, but with unordered data channel config.
3750 ASSERT_TRUE(CreatePeerConnectionWrappers());
3751 ConnectFakeSignaling();
3752 webrtc::DataChannelInit init;
3753 init.ordered = false;
3754 caller()->CreateDataChannel(&init);
3755 caller()->CreateAndSetAndSignalOffer();
3756 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3757 ASSERT_NE(nullptr, caller()->data_channel());
3758 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3759 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3760 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3761
3762 static constexpr int kNumMessages = 100;
3763 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3764 static constexpr size_t kMaxMessageSize = 4096;
3765 // Create and send random messages.
3766 std::vector<std::string> sent_messages;
3767 for (int i = 0; i < kNumMessages; ++i) {
3768 size_t length =
3769 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3770 std::string message;
3771 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3772 caller()->data_channel()->Send(DataBuffer(message));
3773 callee()->data_channel()->Send(DataBuffer(message));
3774 sent_messages.push_back(message);
3775 }
3776
3777 // Wait for all messages to be received.
3778 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
3779 caller()->data_observer()->received_message_count(),
3780 kDefaultTimeout);
3781 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
3782 callee()->data_observer()->received_message_count(),
3783 kDefaultTimeout);
3784
3785 // Sort and compare to make sure none of the messages were corrupted.
3786 std::vector<std::string> caller_received_messages =
3787 caller()->data_observer()->messages();
3788 std::vector<std::string> callee_received_messages =
3789 callee()->data_observer()->messages();
3790 absl::c_sort(sent_messages);
3791 absl::c_sort(caller_received_messages);
3792 absl::c_sort(callee_received_messages);
3793 EXPECT_EQ(sent_messages, caller_received_messages);
3794 EXPECT_EQ(sent_messages, callee_received_messages);
3795 }
3796
3797 // This test sets up a call between two parties with audio, and video. When
3798 // audio and video are setup and flowing, an SCTP data channel is negotiated.
TEST_P(PeerConnectionIntegrationTest,AddSctpDataChannelInSubsequentOffer)3799 TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
3800 ASSERT_TRUE(CreatePeerConnectionWrappers());
3801 ConnectFakeSignaling();
3802 // Do initial offer/answer with audio/video.
3803 caller()->AddAudioVideoTracks();
3804 callee()->AddAudioVideoTracks();
3805 caller()->CreateAndSetAndSignalOffer();
3806 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3807 // Create data channel and do new offer and answer.
3808 caller()->CreateDataChannel();
3809 caller()->CreateAndSetAndSignalOffer();
3810 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3811 // Caller data channel should already exist (it created one). Callee data
3812 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3813 ASSERT_NE(nullptr, caller()->data_channel());
3814 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3815 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3816 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3817 // Ensure data can be sent in both directions.
3818 std::string data = "hello world";
3819 caller()->data_channel()->Send(DataBuffer(data));
3820 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3821 kDefaultTimeout);
3822 callee()->data_channel()->Send(DataBuffer(data));
3823 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3824 kDefaultTimeout);
3825 }
3826
3827 // Set up a connection initially just using SCTP data channels, later upgrading
3828 // to audio/video, ensuring frames are received end-to-end. Effectively the
3829 // inverse of the test above.
3830 // This was broken in M57; see https://crbug.com/711243
TEST_P(PeerConnectionIntegrationTest,SctpDataChannelToAudioVideoUpgrade)3831 TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
3832 ASSERT_TRUE(CreatePeerConnectionWrappers());
3833 ConnectFakeSignaling();
3834 // Do initial offer/answer with just data channel.
3835 caller()->CreateDataChannel();
3836 caller()->CreateAndSetAndSignalOffer();
3837 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3838 // Wait until data can be sent over the data channel.
3839 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3840 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3841 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3842
3843 // Do subsequent offer/answer with two-way audio and video. Audio and video
3844 // should end up bundled on the DTLS/ICE transport already used for data.
3845 caller()->AddAudioVideoTracks();
3846 callee()->AddAudioVideoTracks();
3847 caller()->CreateAndSetAndSignalOffer();
3848 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3849 MediaExpectations media_expectations;
3850 media_expectations.ExpectBidirectionalAudioAndVideo();
3851 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3852 }
3853
MakeSpecCompliantSctpOffer(cricket::SessionDescription * desc)3854 static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
3855 cricket::SctpDataContentDescription* dcd_offer =
3856 GetFirstSctpDataContentDescription(desc);
3857 // See https://crbug.com/webrtc/11211 - this function is a no-op
3858 ASSERT_TRUE(dcd_offer);
3859 dcd_offer->set_use_sctpmap(false);
3860 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3861 }
3862
3863 // Test that the data channel works when a spec-compliant SCTP m= section is
3864 // offered (using "a=sctp-port" instead of "a=sctpmap", and using
3865 // "UDP/DTLS/SCTP" as the protocol).
TEST_P(PeerConnectionIntegrationTest,DataChannelWorksWhenSpecCompliantSctpOfferReceived)3866 TEST_P(PeerConnectionIntegrationTest,
3867 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3868 ASSERT_TRUE(CreatePeerConnectionWrappers());
3869 ConnectFakeSignaling();
3870 caller()->CreateDataChannel();
3871 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3872 caller()->CreateAndSetAndSignalOffer();
3873 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3874 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3875 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3876 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3877
3878 // Ensure data can be sent in both directions.
3879 std::string data = "hello world";
3880 caller()->data_channel()->Send(DataBuffer(data));
3881 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3882 kDefaultTimeout);
3883 callee()->data_channel()->Send(DataBuffer(data));
3884 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3885 kDefaultTimeout);
3886 }
3887
3888 #endif // HAVE_SCTP
3889
3890 // Test that the ICE connection and gathering states eventually reach
3891 // "complete".
TEST_P(PeerConnectionIntegrationTest,IceStatesReachCompletion)3892 TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
3893 ASSERT_TRUE(CreatePeerConnectionWrappers());
3894 ConnectFakeSignaling();
3895 // Do normal offer/answer.
3896 caller()->AddAudioVideoTracks();
3897 callee()->AddAudioVideoTracks();
3898 caller()->CreateAndSetAndSignalOffer();
3899 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3900 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3901 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3902 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3903 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3904 // After the best candidate pair is selected and all candidates are signaled,
3905 // the ICE connection state should reach "complete".
3906 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3907 // answerer/"callee" by default) only reaches "connected". When this is
3908 // fixed, this test should be updated.
3909 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3910 caller()->ice_connection_state(), kDefaultTimeout);
3911 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3912 callee()->ice_connection_state(), kDefaultTimeout);
3913 }
3914
3915 constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
3916 cricket::PORTALLOCATOR_DISABLE_RELAY |
3917 cricket::PORTALLOCATOR_DISABLE_TCP;
3918
3919 // Use a mock resolver to resolve the hostname back to the original IP on both
3920 // sides and check that the ICE connection connects.
TEST_P(PeerConnectionIntegrationTest,IceStatesReachCompletionWithRemoteHostname)3921 TEST_P(PeerConnectionIntegrationTest,
3922 IceStatesReachCompletionWithRemoteHostname) {
3923 auto caller_resolver_factory =
3924 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3925 auto callee_resolver_factory =
3926 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3927 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
3928 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
3929
3930 // This also verifies that the injected AsyncResolverFactory is used by
3931 // P2PTransportChannel.
3932 EXPECT_CALL(*caller_resolver_factory, Create())
3933 .WillOnce(Return(&caller_async_resolver));
3934 webrtc::PeerConnectionDependencies caller_deps(nullptr);
3935 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
3936
3937 EXPECT_CALL(*callee_resolver_factory, Create())
3938 .WillOnce(Return(&callee_async_resolver));
3939 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3940 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
3941
3942 PeerConnectionInterface::RTCConfiguration config;
3943 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3944 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3945
3946 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3947 config, std::move(caller_deps), config, std::move(callee_deps)));
3948
3949 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
3950 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
3951
3952 // Enable hostname candidates with mDNS names.
3953 caller()->SetMdnsResponder(
3954 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
3955 callee()->SetMdnsResponder(
3956 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
3957
3958 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
3959
3960 ConnectFakeSignaling();
3961 caller()->AddAudioVideoTracks();
3962 callee()->AddAudioVideoTracks();
3963 caller()->CreateAndSetAndSignalOffer();
3964 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3965 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3966 caller()->ice_connection_state(), kDefaultTimeout);
3967 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3968 callee()->ice_connection_state(), kDefaultTimeout);
3969
3970 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3971 "WebRTC.PeerConnection.CandidatePairType_UDP",
3972 webrtc::kIceCandidatePairHostNameHostName));
3973 }
3974
3975 // Test that firewalling the ICE connection causes the clients to identify the
3976 // disconnected state and then removing the firewall causes them to reconnect.
3977 class PeerConnectionIntegrationIceStatesTest
3978 : public PeerConnectionIntegrationBaseTest,
3979 public ::testing::WithParamInterface<
3980 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
3981 protected:
PeerConnectionIntegrationIceStatesTest()3982 PeerConnectionIntegrationIceStatesTest()
3983 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3984 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
3985 }
3986
StartStunServer(const SocketAddress & server_address)3987 void StartStunServer(const SocketAddress& server_address) {
3988 stun_server_.reset(
3989 cricket::TestStunServer::Create(network_thread(), server_address));
3990 }
3991
TestIPv6()3992 bool TestIPv6() {
3993 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3994 }
3995
SetPortAllocatorFlags()3996 void SetPortAllocatorFlags() {
3997 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
3998 port_allocator_flags_, port_allocator_flags_);
3999 }
4000
CallerAddresses()4001 std::vector<SocketAddress> CallerAddresses() {
4002 std::vector<SocketAddress> addresses;
4003 addresses.push_back(SocketAddress("1.1.1.1", 0));
4004 if (TestIPv6()) {
4005 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
4006 }
4007 return addresses;
4008 }
4009
CalleeAddresses()4010 std::vector<SocketAddress> CalleeAddresses() {
4011 std::vector<SocketAddress> addresses;
4012 addresses.push_back(SocketAddress("2.2.2.2", 0));
4013 if (TestIPv6()) {
4014 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
4015 }
4016 return addresses;
4017 }
4018
SetUpNetworkInterfaces()4019 void SetUpNetworkInterfaces() {
4020 // Remove the default interfaces added by the test infrastructure.
4021 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4022 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4023
4024 // Add network addresses for test.
4025 for (const auto& caller_address : CallerAddresses()) {
4026 caller()->network_manager()->AddInterface(caller_address);
4027 }
4028 for (const auto& callee_address : CalleeAddresses()) {
4029 callee()->network_manager()->AddInterface(callee_address);
4030 }
4031 }
4032
4033 private:
4034 uint32_t port_allocator_flags_;
4035 std::unique_ptr<cricket::TestStunServer> stun_server_;
4036 };
4037
4038 // Ensure FakeClockForTest is constructed first (see class for rationale).
4039 class PeerConnectionIntegrationIceStatesTestWithFakeClock
4040 : public FakeClockForTest,
4041 public PeerConnectionIntegrationIceStatesTest {};
4042
4043 // Tests that the PeerConnection goes through all the ICE gathering/connection
4044 // states over the duration of the call. This includes Disconnected and Failed
4045 // states, induced by putting a firewall between the peers and waiting for them
4046 // to time out.
TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,VerifyIceStates)4047 TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock, VerifyIceStates) {
4048 const SocketAddress kStunServerAddress =
4049 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4050 StartStunServer(kStunServerAddress);
4051
4052 PeerConnectionInterface::RTCConfiguration config;
4053 PeerConnectionInterface::IceServer ice_stun_server;
4054 ice_stun_server.urls.push_back(
4055 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4056 kStunServerAddress.PortAsString());
4057 config.servers.push_back(ice_stun_server);
4058
4059 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4060 ConnectFakeSignaling();
4061 SetPortAllocatorFlags();
4062 SetUpNetworkInterfaces();
4063 caller()->AddAudioVideoTracks();
4064 callee()->AddAudioVideoTracks();
4065
4066 // Initial state before anything happens.
4067 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4068 caller()->ice_gathering_state());
4069 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4070 caller()->ice_connection_state());
4071 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4072 caller()->standardized_ice_connection_state());
4073
4074 // Start the call by creating the offer, setting it as the local description,
4075 // then sending it to the peer who will respond with an answer. This happens
4076 // asynchronously so that we can watch the states as it runs in the
4077 // background.
4078 caller()->CreateAndSetAndSignalOffer();
4079
4080 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4081 caller()->ice_connection_state(), kDefaultTimeout,
4082 FakeClock());
4083 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4084 caller()->standardized_ice_connection_state(),
4085 kDefaultTimeout, FakeClock());
4086
4087 // Verify that the observer was notified of the intermediate transitions.
4088 EXPECT_THAT(caller()->ice_connection_state_history(),
4089 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4090 PeerConnectionInterface::kIceConnectionConnected,
4091 PeerConnectionInterface::kIceConnectionCompleted));
4092 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4093 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4094 PeerConnectionInterface::kIceConnectionConnected,
4095 PeerConnectionInterface::kIceConnectionCompleted));
4096 EXPECT_THAT(
4097 caller()->peer_connection_state_history(),
4098 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
4099 PeerConnectionInterface::PeerConnectionState::kConnected));
4100 EXPECT_THAT(caller()->ice_gathering_state_history(),
4101 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4102 PeerConnectionInterface::kIceGatheringComplete));
4103
4104 // Block connections to/from the caller and wait for ICE to become
4105 // disconnected.
4106 for (const auto& caller_address : CallerAddresses()) {
4107 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4108 }
4109 RTC_LOG(LS_INFO) << "Firewall rules applied";
4110 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4111 caller()->ice_connection_state(), kDefaultTimeout,
4112 FakeClock());
4113 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4114 caller()->standardized_ice_connection_state(),
4115 kDefaultTimeout, FakeClock());
4116
4117 // Let ICE re-establish by removing the firewall rules.
4118 firewall()->ClearRules();
4119 RTC_LOG(LS_INFO) << "Firewall rules cleared";
4120 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4121 caller()->ice_connection_state(), kDefaultTimeout,
4122 FakeClock());
4123 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4124 caller()->standardized_ice_connection_state(),
4125 kDefaultTimeout, FakeClock());
4126
4127 // According to RFC7675, if there is no response within 30 seconds then the
4128 // peer should consider the other side to have rejected the connection. This
4129 // is signaled by the state transitioning to "failed".
4130 constexpr int kConsentTimeout = 30000;
4131 for (const auto& caller_address : CallerAddresses()) {
4132 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4133 }
4134 RTC_LOG(LS_INFO) << "Firewall rules applied again";
4135 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4136 caller()->ice_connection_state(), kConsentTimeout,
4137 FakeClock());
4138 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4139 caller()->standardized_ice_connection_state(),
4140 kConsentTimeout, FakeClock());
4141 }
4142
4143 // Tests that if the connection doesn't get set up properly we eventually reach
4144 // the "failed" iceConnectionState.
TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,IceStateSetupFailure)4145 TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,
4146 IceStateSetupFailure) {
4147 // Block connections to/from the caller and wait for ICE to become
4148 // disconnected.
4149 for (const auto& caller_address : CallerAddresses()) {
4150 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4151 }
4152
4153 ASSERT_TRUE(CreatePeerConnectionWrappers());
4154 ConnectFakeSignaling();
4155 SetPortAllocatorFlags();
4156 SetUpNetworkInterfaces();
4157 caller()->AddAudioVideoTracks();
4158 caller()->CreateAndSetAndSignalOffer();
4159
4160 // According to RFC7675, if there is no response within 30 seconds then the
4161 // peer should consider the other side to have rejected the connection. This
4162 // is signaled by the state transitioning to "failed".
4163 constexpr int kConsentTimeout = 30000;
4164 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4165 caller()->standardized_ice_connection_state(),
4166 kConsentTimeout, FakeClock());
4167 }
4168
4169 // Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4170 // and that the statistics in the metric observers are updated correctly.
TEST_P(PeerConnectionIntegrationIceStatesTest,VerifyBestConnection)4171 TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4172 ASSERT_TRUE(CreatePeerConnectionWrappers());
4173 ConnectFakeSignaling();
4174 SetPortAllocatorFlags();
4175 SetUpNetworkInterfaces();
4176 caller()->AddAudioVideoTracks();
4177 callee()->AddAudioVideoTracks();
4178 caller()->CreateAndSetAndSignalOffer();
4179
4180 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4181 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4182 caller()->ice_connection_state(), kDefaultTimeout);
4183 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4184 callee()->ice_connection_state(), kDefaultTimeout);
4185
4186 // TODO(bugs.webrtc.org/9456): Fix it.
4187 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4188 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4189 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4190 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
4191 if (TestIPv6()) {
4192 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4193 // connection.
4194 EXPECT_METRIC_EQ(0, num_best_ipv4);
4195 EXPECT_METRIC_EQ(1, num_best_ipv6);
4196 } else {
4197 EXPECT_METRIC_EQ(1, num_best_ipv4);
4198 EXPECT_METRIC_EQ(0, num_best_ipv6);
4199 }
4200
4201 EXPECT_METRIC_EQ(0, webrtc::metrics::NumEvents(
4202 "WebRTC.PeerConnection.CandidatePairType_UDP",
4203 webrtc::kIceCandidatePairHostHost));
4204 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4205 "WebRTC.PeerConnection.CandidatePairType_UDP",
4206 webrtc::kIceCandidatePairHostPublicHostPublic));
4207 }
4208
4209 constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4210 cricket::PORTALLOCATOR_DISABLE_STUN |
4211 cricket::PORTALLOCATOR_DISABLE_RELAY;
4212 constexpr uint32_t kFlagsIPv6NoStun =
4213 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4214 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4215 constexpr uint32_t kFlagsIPv4Stun =
4216 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4217
4218 INSTANTIATE_TEST_SUITE_P(
4219 PeerConnectionIntegrationTest,
4220 PeerConnectionIntegrationIceStatesTest,
4221 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4222 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4223 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4224 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
4225
4226 INSTANTIATE_TEST_SUITE_P(
4227 PeerConnectionIntegrationTest,
4228 PeerConnectionIntegrationIceStatesTestWithFakeClock,
4229 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4230 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4231 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4232 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
4233
4234 // This test sets up a call between two parties with audio and video.
4235 // During the call, the caller restarts ICE and the test verifies that
4236 // new ICE candidates are generated and audio and video still can flow, and the
4237 // ICE state reaches completed again.
TEST_P(PeerConnectionIntegrationTest,MediaContinuesFlowingAfterIceRestart)4238 TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
4239 ASSERT_TRUE(CreatePeerConnectionWrappers());
4240 ConnectFakeSignaling();
4241 // Do normal offer/answer and wait for ICE to complete.
4242 caller()->AddAudioVideoTracks();
4243 callee()->AddAudioVideoTracks();
4244 caller()->CreateAndSetAndSignalOffer();
4245 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4246 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4247 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4248 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4249 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4250
4251 // To verify that the ICE restart actually occurs, get
4252 // ufrag/password/candidates before and after restart.
4253 // Create an SDP string of the first audio candidate for both clients.
4254 const webrtc::IceCandidateCollection* audio_candidates_caller =
4255 caller()->pc()->local_description()->candidates(0);
4256 const webrtc::IceCandidateCollection* audio_candidates_callee =
4257 callee()->pc()->local_description()->candidates(0);
4258 ASSERT_GT(audio_candidates_caller->count(), 0u);
4259 ASSERT_GT(audio_candidates_callee->count(), 0u);
4260 std::string caller_candidate_pre_restart;
4261 ASSERT_TRUE(
4262 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4263 std::string callee_candidate_pre_restart;
4264 ASSERT_TRUE(
4265 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4266 const cricket::SessionDescription* desc =
4267 caller()->pc()->local_description()->description();
4268 std::string caller_ufrag_pre_restart =
4269 desc->transport_infos()[0].description.ice_ufrag;
4270 desc = callee()->pc()->local_description()->description();
4271 std::string callee_ufrag_pre_restart =
4272 desc->transport_infos()[0].description.ice_ufrag;
4273
4274 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
4275 // Have the caller initiate an ICE restart.
4276 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4277 caller()->CreateAndSetAndSignalOffer();
4278 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4279 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4280 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4281 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4282 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4283
4284 // Grab the ufrags/candidates again.
4285 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4286 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4287 ASSERT_GT(audio_candidates_caller->count(), 0u);
4288 ASSERT_GT(audio_candidates_callee->count(), 0u);
4289 std::string caller_candidate_post_restart;
4290 ASSERT_TRUE(
4291 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4292 std::string callee_candidate_post_restart;
4293 ASSERT_TRUE(
4294 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4295 desc = caller()->pc()->local_description()->description();
4296 std::string caller_ufrag_post_restart =
4297 desc->transport_infos()[0].description.ice_ufrag;
4298 desc = callee()->pc()->local_description()->description();
4299 std::string callee_ufrag_post_restart =
4300 desc->transport_infos()[0].description.ice_ufrag;
4301 // Sanity check that an ICE restart was actually negotiated in SDP.
4302 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4303 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4304 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4305 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
4306 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
4307
4308 // Ensure that additional frames are received after the ICE restart.
4309 MediaExpectations media_expectations;
4310 media_expectations.ExpectBidirectionalAudioAndVideo();
4311 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4312 }
4313
4314 // Verify that audio/video can be received end-to-end when ICE renomination is
4315 // enabled.
TEST_P(PeerConnectionIntegrationTest,EndToEndCallWithIceRenomination)4316 TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
4317 PeerConnectionInterface::RTCConfiguration config;
4318 config.enable_ice_renomination = true;
4319 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4320 ConnectFakeSignaling();
4321 // Do normal offer/answer and wait for some frames to be received in each
4322 // direction.
4323 caller()->AddAudioVideoTracks();
4324 callee()->AddAudioVideoTracks();
4325 caller()->CreateAndSetAndSignalOffer();
4326 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4327 // Sanity check that ICE renomination was actually negotiated.
4328 const cricket::SessionDescription* desc =
4329 caller()->pc()->local_description()->description();
4330 for (const cricket::TransportInfo& info : desc->transport_infos()) {
4331 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
4332 }
4333 desc = callee()->pc()->local_description()->description();
4334 for (const cricket::TransportInfo& info : desc->transport_infos()) {
4335 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
4336 }
4337 MediaExpectations media_expectations;
4338 media_expectations.ExpectBidirectionalAudioAndVideo();
4339 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4340 }
4341
4342 // With a max bundle policy and RTCP muxing, adding a new media description to
4343 // the connection should not affect ICE at all because the new media will use
4344 // the existing connection.
TEST_P(PeerConnectionIntegrationTest,AddMediaToConnectedBundleDoesNotRestartIce)4345 TEST_P(PeerConnectionIntegrationTest,
4346 AddMediaToConnectedBundleDoesNotRestartIce) {
4347 PeerConnectionInterface::RTCConfiguration config;
4348 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4349 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4350 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4351 config, PeerConnectionInterface::RTCConfiguration()));
4352 ConnectFakeSignaling();
4353
4354 caller()->AddAudioTrack();
4355 caller()->CreateAndSetAndSignalOffer();
4356 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4357 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4358 caller()->ice_connection_state(), kDefaultTimeout);
4359
4360 caller()->clear_ice_connection_state_history();
4361
4362 caller()->AddVideoTrack();
4363 caller()->CreateAndSetAndSignalOffer();
4364 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4365
4366 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4367 }
4368
4369 // This test sets up a call between two parties with audio and video. It then
4370 // renegotiates setting the video m-line to "port 0", then later renegotiates
4371 // again, enabling video.
TEST_P(PeerConnectionIntegrationTest,VideoFlowsAfterMediaSectionIsRejectedAndRecycled)4372 TEST_P(PeerConnectionIntegrationTest,
4373 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4374 ASSERT_TRUE(CreatePeerConnectionWrappers());
4375 ConnectFakeSignaling();
4376
4377 // Do initial negotiation, only sending media from the caller. Will result in
4378 // video and audio recvonly "m=" sections.
4379 caller()->AddAudioVideoTracks();
4380 caller()->CreateAndSetAndSignalOffer();
4381 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4382
4383 // Negotiate again, disabling the video "m=" section (the callee will set the
4384 // port to 0 due to offer_to_receive_video = 0).
4385 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4386 PeerConnectionInterface::RTCOfferAnswerOptions options;
4387 options.offer_to_receive_video = 0;
4388 callee()->SetOfferAnswerOptions(options);
4389 } else {
4390 callee()->SetRemoteOfferHandler([this] {
4391 callee()
4392 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
4393 ->StopInternal();
4394 });
4395 }
4396 caller()->CreateAndSetAndSignalOffer();
4397 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4398 // Sanity check that video "m=" section was actually rejected.
4399 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4400 callee()->pc()->local_description()->description());
4401 ASSERT_NE(nullptr, answer_video_content);
4402 ASSERT_TRUE(answer_video_content->rejected);
4403
4404 // Enable video and do negotiation again, making sure video is received
4405 // end-to-end, also adding media stream to callee.
4406 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4407 PeerConnectionInterface::RTCOfferAnswerOptions options;
4408 options.offer_to_receive_video = 1;
4409 callee()->SetOfferAnswerOptions(options);
4410 } else {
4411 // The caller's transceiver is stopped, so we need to add another track.
4412 auto caller_transceiver =
4413 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4414 EXPECT_EQ(nullptr, caller_transceiver.get());
4415 caller()->AddVideoTrack();
4416 }
4417 callee()->AddVideoTrack();
4418 callee()->SetRemoteOfferHandler(nullptr);
4419 caller()->CreateAndSetAndSignalOffer();
4420 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4421
4422 // Verify the caller receives frames from the newly added stream, and the
4423 // callee receives additional frames from the re-enabled video m= section.
4424 MediaExpectations media_expectations;
4425 media_expectations.CalleeExpectsSomeAudio();
4426 media_expectations.ExpectBidirectionalVideo();
4427 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4428 }
4429
4430 // This tests that if we negotiate after calling CreateSender but before we
4431 // have a track, then set a track later, frames from the newly-set track are
4432 // received end-to-end.
TEST_F(PeerConnectionIntegrationTestPlanB,MediaFlowsAfterEarlyWarmupWithCreateSender)4433 TEST_F(PeerConnectionIntegrationTestPlanB,
4434 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4435 ASSERT_TRUE(CreatePeerConnectionWrappers());
4436 ConnectFakeSignaling();
4437 auto caller_audio_sender =
4438 caller()->pc()->CreateSender("audio", "caller_stream");
4439 auto caller_video_sender =
4440 caller()->pc()->CreateSender("video", "caller_stream");
4441 auto callee_audio_sender =
4442 callee()->pc()->CreateSender("audio", "callee_stream");
4443 auto callee_video_sender =
4444 callee()->pc()->CreateSender("video", "callee_stream");
4445 caller()->CreateAndSetAndSignalOffer();
4446 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4447 // Wait for ICE to complete, without any tracks being set.
4448 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4449 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4450 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4451 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4452 // Now set the tracks, and expect frames to immediately start flowing.
4453 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4454 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4455 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4456 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4457 MediaExpectations media_expectations;
4458 media_expectations.ExpectBidirectionalAudioAndVideo();
4459 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4460 }
4461
4462 // This tests that if we negotiate after calling AddTransceiver but before we
4463 // have a track, then set a track later, frames from the newly-set tracks are
4464 // received end-to-end.
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,MediaFlowsAfterEarlyWarmupWithAddTransceiver)4465 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4466 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4467 ASSERT_TRUE(CreatePeerConnectionWrappers());
4468 ConnectFakeSignaling();
4469 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4470 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4471 auto caller_audio_sender = audio_result.MoveValue()->sender();
4472 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4473 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4474 auto caller_video_sender = video_result.MoveValue()->sender();
4475 callee()->SetRemoteOfferHandler([this] {
4476 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4477 callee()->pc()->GetTransceivers()[0]->SetDirectionWithError(
4478 RtpTransceiverDirection::kSendRecv);
4479 callee()->pc()->GetTransceivers()[1]->SetDirectionWithError(
4480 RtpTransceiverDirection::kSendRecv);
4481 });
4482 caller()->CreateAndSetAndSignalOffer();
4483 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4484 // Wait for ICE to complete, without any tracks being set.
4485 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4486 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4487 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4488 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4489 // Now set the tracks, and expect frames to immediately start flowing.
4490 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4491 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4492 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4493 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4494 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4495 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4496 MediaExpectations media_expectations;
4497 media_expectations.ExpectBidirectionalAudioAndVideo();
4498 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4499 }
4500
4501 // This test verifies that a remote video track can be added via AddStream,
4502 // and sent end-to-end. For this particular test, it's simply echoed back
4503 // from the caller to the callee, rather than being forwarded to a third
4504 // PeerConnection.
TEST_F(PeerConnectionIntegrationTestPlanB,CanSendRemoteVideoTrack)4505 TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
4506 ASSERT_TRUE(CreatePeerConnectionWrappers());
4507 ConnectFakeSignaling();
4508 // Just send a video track from the caller.
4509 caller()->AddVideoTrack();
4510 caller()->CreateAndSetAndSignalOffer();
4511 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4512 ASSERT_EQ(1U, callee()->remote_streams()->count());
4513
4514 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4515 // time).
4516 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4517 callee()->CreateAndSetAndSignalOffer();
4518 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4519
4520 MediaExpectations media_expectations;
4521 media_expectations.ExpectBidirectionalVideo();
4522 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4523 }
4524
4525 // Test that we achieve the expected end-to-end connection time, using a
4526 // fake clock and simulated latency on the media and signaling paths.
4527 // We use a TURN<->TURN connection because this is usually the quickest to
4528 // set up initially, especially when we're confident the connection will work
4529 // and can start sending media before we get a STUN response.
4530 //
4531 // With various optimizations enabled, here are the network delays we expect to
4532 // be on the critical path:
4533 // 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4534 // signaling answer (with DTLS fingerprint).
4535 // 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4536 // using TURN<->TURN pair, and DTLS exchange is 4 packets,
4537 // the first of which should have arrived before the answer.
TEST_P(PeerConnectionIntegrationTestWithFakeClock,EndToEndConnectionTimeWithTurnTurnPair)4538 TEST_P(PeerConnectionIntegrationTestWithFakeClock,
4539 EndToEndConnectionTimeWithTurnTurnPair) {
4540 static constexpr int media_hop_delay_ms = 50;
4541 static constexpr int signaling_trip_delay_ms = 500;
4542 // For explanation of these values, see comment above.
4543 static constexpr int required_media_hops = 9;
4544 static constexpr int required_signaling_trips = 2;
4545 // For internal delays (such as posting an event asychronously).
4546 static constexpr int allowed_internal_delay_ms = 20;
4547 static constexpr int total_connection_time_ms =
4548 media_hop_delay_ms * required_media_hops +
4549 signaling_trip_delay_ms * required_signaling_trips +
4550 allowed_internal_delay_ms;
4551
4552 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4553 3478};
4554 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4555 0};
4556 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4557 3478};
4558 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4559 0};
4560 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4561 turn_server_1_internal_address, turn_server_1_external_address);
4562
4563 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4564 turn_server_2_internal_address, turn_server_2_external_address);
4565 // Bypass permission check on received packets so media can be sent before
4566 // the candidate is signaled.
4567 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4568 turn_server_1->set_enable_permission_checks(false);
4569 });
4570 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4571 turn_server_2->set_enable_permission_checks(false);
4572 });
4573
4574 PeerConnectionInterface::RTCConfiguration client_1_config;
4575 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4576 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4577 ice_server_1.username = "test";
4578 ice_server_1.password = "test";
4579 client_1_config.servers.push_back(ice_server_1);
4580 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4581 client_1_config.presume_writable_when_fully_relayed = true;
4582
4583 PeerConnectionInterface::RTCConfiguration client_2_config;
4584 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4585 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4586 ice_server_2.username = "test";
4587 ice_server_2.password = "test";
4588 client_2_config.servers.push_back(ice_server_2);
4589 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4590 client_2_config.presume_writable_when_fully_relayed = true;
4591
4592 ASSERT_TRUE(
4593 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4594 // Set up the simulated delays.
4595 SetSignalingDelayMs(signaling_trip_delay_ms);
4596 ConnectFakeSignaling();
4597 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4598 virtual_socket_server()->UpdateDelayDistribution();
4599
4600 // Set "offer to receive audio/video" without adding any tracks, so we just
4601 // set up ICE/DTLS with no media.
4602 PeerConnectionInterface::RTCOfferAnswerOptions options;
4603 options.offer_to_receive_audio = 1;
4604 options.offer_to_receive_video = 1;
4605 caller()->SetOfferAnswerOptions(options);
4606 caller()->CreateAndSetAndSignalOffer();
4607 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4608 FakeClock());
4609 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4610 // If this is not done a DCHECK can be hit in ports.cc, because a large
4611 // negative number is calculated for the rtt due to the global clock changing.
4612 ClosePeerConnections();
4613 }
4614
4615 // Verify that a TurnCustomizer passed in through RTCConfiguration
4616 // is actually used by the underlying TURN candidate pair.
4617 // Note that turnport_unittest.cc contains more detailed, lower-level tests.
TEST_P(PeerConnectionIntegrationTest,TurnCustomizerUsedForTurnConnections)4618 TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
4619 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4620 3478};
4621 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4622 0};
4623 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4624 3478};
4625 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4626 0};
4627 CreateTurnServer(turn_server_1_internal_address,
4628 turn_server_1_external_address);
4629 CreateTurnServer(turn_server_2_internal_address,
4630 turn_server_2_external_address);
4631
4632 PeerConnectionInterface::RTCConfiguration client_1_config;
4633 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4634 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4635 ice_server_1.username = "test";
4636 ice_server_1.password = "test";
4637 client_1_config.servers.push_back(ice_server_1);
4638 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4639 auto* customizer1 = CreateTurnCustomizer();
4640 client_1_config.turn_customizer = customizer1;
4641
4642 PeerConnectionInterface::RTCConfiguration client_2_config;
4643 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4644 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4645 ice_server_2.username = "test";
4646 ice_server_2.password = "test";
4647 client_2_config.servers.push_back(ice_server_2);
4648 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4649 auto* customizer2 = CreateTurnCustomizer();
4650 client_2_config.turn_customizer = customizer2;
4651
4652 ASSERT_TRUE(
4653 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4654 ConnectFakeSignaling();
4655
4656 // Set "offer to receive audio/video" without adding any tracks, so we just
4657 // set up ICE/DTLS with no media.
4658 PeerConnectionInterface::RTCOfferAnswerOptions options;
4659 options.offer_to_receive_audio = 1;
4660 options.offer_to_receive_video = 1;
4661 caller()->SetOfferAnswerOptions(options);
4662 caller()->CreateAndSetAndSignalOffer();
4663 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4664
4665 ExpectTurnCustomizerCountersIncremented(customizer1);
4666 ExpectTurnCustomizerCountersIncremented(customizer2);
4667 }
4668
4669 // Verifies that you can use TCP instead of UDP to connect to a TURN server and
4670 // send media between the caller and the callee.
TEST_P(PeerConnectionIntegrationTest,TCPUsedForTurnConnections)4671 TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4672 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4673 3478};
4674 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4675
4676 // Enable TCP for the fake turn server.
4677 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4678 cricket::PROTO_TCP);
4679
4680 webrtc::PeerConnectionInterface::IceServer ice_server;
4681 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4682 ice_server.username = "test";
4683 ice_server.password = "test";
4684
4685 PeerConnectionInterface::RTCConfiguration client_1_config;
4686 client_1_config.servers.push_back(ice_server);
4687 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4688
4689 PeerConnectionInterface::RTCConfiguration client_2_config;
4690 client_2_config.servers.push_back(ice_server);
4691 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4692
4693 ASSERT_TRUE(
4694 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4695
4696 // Do normal offer/answer and wait for ICE to complete.
4697 ConnectFakeSignaling();
4698 caller()->AddAudioVideoTracks();
4699 callee()->AddAudioVideoTracks();
4700 caller()->CreateAndSetAndSignalOffer();
4701 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4702 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4703 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4704
4705 MediaExpectations media_expectations;
4706 media_expectations.ExpectBidirectionalAudioAndVideo();
4707 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4708 }
4709
4710 // Verify that a SSLCertificateVerifier passed in through
4711 // PeerConnectionDependencies is actually used by the underlying SSL
4712 // implementation to determine whether a certificate presented by the TURN
4713 // server is accepted by the client. Note that openssladapter_unittest.cc
4714 // contains more detailed, lower-level tests.
TEST_P(PeerConnectionIntegrationTest,SSLCertificateVerifierUsedForTurnConnections)4715 TEST_P(PeerConnectionIntegrationTest,
4716 SSLCertificateVerifierUsedForTurnConnections) {
4717 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4718 3478};
4719 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4720
4721 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4722 // that host name verification passes on the fake certificate.
4723 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4724 cricket::PROTO_TLS, "88.88.88.0");
4725
4726 webrtc::PeerConnectionInterface::IceServer ice_server;
4727 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4728 ice_server.username = "test";
4729 ice_server.password = "test";
4730
4731 PeerConnectionInterface::RTCConfiguration client_1_config;
4732 client_1_config.servers.push_back(ice_server);
4733 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4734
4735 PeerConnectionInterface::RTCConfiguration client_2_config;
4736 client_2_config.servers.push_back(ice_server);
4737 // Setting the type to kRelay forces the connection to go through a TURN
4738 // server.
4739 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4740
4741 // Get a copy to the pointer so we can verify calls later.
4742 rtc::TestCertificateVerifier* client_1_cert_verifier =
4743 new rtc::TestCertificateVerifier();
4744 client_1_cert_verifier->verify_certificate_ = true;
4745 rtc::TestCertificateVerifier* client_2_cert_verifier =
4746 new rtc::TestCertificateVerifier();
4747 client_2_cert_verifier->verify_certificate_ = true;
4748
4749 // Create the dependencies with the test certificate verifier.
4750 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4751 client_1_deps.tls_cert_verifier =
4752 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4753 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4754 client_2_deps.tls_cert_verifier =
4755 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4756
4757 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4758 client_1_config, std::move(client_1_deps), client_2_config,
4759 std::move(client_2_deps)));
4760 ConnectFakeSignaling();
4761
4762 // Set "offer to receive audio/video" without adding any tracks, so we just
4763 // set up ICE/DTLS with no media.
4764 PeerConnectionInterface::RTCOfferAnswerOptions options;
4765 options.offer_to_receive_audio = 1;
4766 options.offer_to_receive_video = 1;
4767 caller()->SetOfferAnswerOptions(options);
4768 caller()->CreateAndSetAndSignalOffer();
4769 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4770
4771 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4772 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
4773 }
4774
TEST_P(PeerConnectionIntegrationTest,SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection)4775 TEST_P(PeerConnectionIntegrationTest,
4776 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4777 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4778 3478};
4779 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4780
4781 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4782 // that host name verification passes on the fake certificate.
4783 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4784 cricket::PROTO_TLS, "88.88.88.0");
4785
4786 webrtc::PeerConnectionInterface::IceServer ice_server;
4787 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4788 ice_server.username = "test";
4789 ice_server.password = "test";
4790
4791 PeerConnectionInterface::RTCConfiguration client_1_config;
4792 client_1_config.servers.push_back(ice_server);
4793 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4794
4795 PeerConnectionInterface::RTCConfiguration client_2_config;
4796 client_2_config.servers.push_back(ice_server);
4797 // Setting the type to kRelay forces the connection to go through a TURN
4798 // server.
4799 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4800
4801 // Get a copy to the pointer so we can verify calls later.
4802 rtc::TestCertificateVerifier* client_1_cert_verifier =
4803 new rtc::TestCertificateVerifier();
4804 client_1_cert_verifier->verify_certificate_ = false;
4805 rtc::TestCertificateVerifier* client_2_cert_verifier =
4806 new rtc::TestCertificateVerifier();
4807 client_2_cert_verifier->verify_certificate_ = false;
4808
4809 // Create the dependencies with the test certificate verifier.
4810 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4811 client_1_deps.tls_cert_verifier =
4812 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4813 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4814 client_2_deps.tls_cert_verifier =
4815 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4816
4817 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4818 client_1_config, std::move(client_1_deps), client_2_config,
4819 std::move(client_2_deps)));
4820 ConnectFakeSignaling();
4821
4822 // Set "offer to receive audio/video" without adding any tracks, so we just
4823 // set up ICE/DTLS with no media.
4824 PeerConnectionInterface::RTCOfferAnswerOptions options;
4825 options.offer_to_receive_audio = 1;
4826 options.offer_to_receive_video = 1;
4827 caller()->SetOfferAnswerOptions(options);
4828 caller()->CreateAndSetAndSignalOffer();
4829 bool wait_res = true;
4830 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4831 // properly, should be able to just wait for a state of "failed" instead of
4832 // waiting a fixed 10 seconds.
4833 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4834 ASSERT_FALSE(wait_res);
4835
4836 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4837 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
4838 }
4839
4840 // Test that the injected ICE transport factory is used to create ICE transports
4841 // for WebRTC connections.
TEST_P(PeerConnectionIntegrationTest,IceTransportFactoryUsedForConnections)4842 TEST_P(PeerConnectionIntegrationTest, IceTransportFactoryUsedForConnections) {
4843 PeerConnectionInterface::RTCConfiguration default_config;
4844 PeerConnectionDependencies dependencies(nullptr);
4845 auto ice_transport_factory = std::make_unique<MockIceTransportFactory>();
4846 EXPECT_CALL(*ice_transport_factory, RecordIceTransportCreated()).Times(1);
4847 dependencies.ice_transport_factory = std::move(ice_transport_factory);
4848 auto wrapper = CreatePeerConnectionWrapper("Caller", nullptr, &default_config,
4849 std::move(dependencies), nullptr,
4850 /*reset_encoder_factory=*/false,
4851 /*reset_decoder_factory=*/false);
4852 ASSERT_TRUE(wrapper);
4853 wrapper->CreateDataChannel();
4854 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
4855 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
4856 wrapper->pc()->SetLocalDescription(observer,
4857 wrapper->CreateOfferAndWait().release());
4858 }
4859
4860 // Test that audio and video flow end-to-end when codec names don't use the
4861 // expected casing, given that they're supposed to be case insensitive. To test
4862 // this, all but one codec is removed from each media description, and its
4863 // casing is changed.
4864 //
4865 // In the past, this has regressed and caused crashes/black video, due to the
4866 // fact that code at some layers was doing case-insensitive comparisons and
4867 // code at other layers was not.
TEST_P(PeerConnectionIntegrationTest,CodecNamesAreCaseInsensitive)4868 TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
4869 ASSERT_TRUE(CreatePeerConnectionWrappers());
4870 ConnectFakeSignaling();
4871 caller()->AddAudioVideoTracks();
4872 callee()->AddAudioVideoTracks();
4873
4874 // Remove all but one audio/video codec (opus and VP8), and change the
4875 // casing of the caller's generated offer.
4876 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4877 cricket::AudioContentDescription* audio =
4878 GetFirstAudioContentDescription(description);
4879 ASSERT_NE(nullptr, audio);
4880 auto audio_codecs = audio->codecs();
4881 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4882 [](const cricket::AudioCodec& codec) {
4883 return codec.name != "opus";
4884 }),
4885 audio_codecs.end());
4886 ASSERT_EQ(1u, audio_codecs.size());
4887 audio_codecs[0].name = "OpUs";
4888 audio->set_codecs(audio_codecs);
4889
4890 cricket::VideoContentDescription* video =
4891 GetFirstVideoContentDescription(description);
4892 ASSERT_NE(nullptr, video);
4893 auto video_codecs = video->codecs();
4894 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4895 [](const cricket::VideoCodec& codec) {
4896 return codec.name != "VP8";
4897 }),
4898 video_codecs.end());
4899 ASSERT_EQ(1u, video_codecs.size());
4900 video_codecs[0].name = "vP8";
4901 video->set_codecs(video_codecs);
4902 });
4903
4904 caller()->CreateAndSetAndSignalOffer();
4905 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4906
4907 // Verify frames are still received end-to-end.
4908 MediaExpectations media_expectations;
4909 media_expectations.ExpectBidirectionalAudioAndVideo();
4910 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4911 }
4912
TEST_P(PeerConnectionIntegrationTest,GetSourcesAudio)4913 TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
4914 ASSERT_TRUE(CreatePeerConnectionWrappers());
4915 ConnectFakeSignaling();
4916 caller()->AddAudioTrack();
4917 caller()->CreateAndSetAndSignalOffer();
4918 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4919 // Wait for one audio frame to be received by the callee.
4920 MediaExpectations media_expectations;
4921 media_expectations.CalleeExpectsSomeAudio(1);
4922 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4923 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4924 auto receiver = callee()->pc()->GetReceivers()[0];
4925 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
4926 auto sources = receiver->GetSources();
4927 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4928 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4929 sources[0].source_id());
4930 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4931 }
4932
TEST_P(PeerConnectionIntegrationTest,GetSourcesVideo)4933 TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4934 ASSERT_TRUE(CreatePeerConnectionWrappers());
4935 ConnectFakeSignaling();
4936 caller()->AddVideoTrack();
4937 caller()->CreateAndSetAndSignalOffer();
4938 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4939 // Wait for one video frame to be received by the callee.
4940 MediaExpectations media_expectations;
4941 media_expectations.CalleeExpectsSomeVideo(1);
4942 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4943 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4944 auto receiver = callee()->pc()->GetReceivers()[0];
4945 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4946 auto sources = receiver->GetSources();
4947 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4948 ASSERT_GT(sources.size(), 0u);
4949 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4950 sources[0].source_id());
4951 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4952 }
4953
4954 // Test that if a track is removed and added again with a different stream ID,
4955 // the new stream ID is successfully communicated in SDP and media continues to
4956 // flow end-to-end.
4957 // TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4958 // it will not reuse a transceiver that has already been sending. After creating
4959 // a new transceiver it tries to create an offer with two senders of the same
4960 // track ids and it fails.
TEST_F(PeerConnectionIntegrationTestPlanB,RemoveAndAddTrackWithNewStreamId)4961 TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
4962 ASSERT_TRUE(CreatePeerConnectionWrappers());
4963 ConnectFakeSignaling();
4964
4965 // Add track using stream 1, do offer/answer.
4966 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4967 caller()->CreateLocalAudioTrack();
4968 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
4969 caller()->AddTrack(track, {"stream_1"});
4970 caller()->CreateAndSetAndSignalOffer();
4971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4972 {
4973 MediaExpectations media_expectations;
4974 media_expectations.CalleeExpectsSomeAudio(1);
4975 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4976 }
4977 // Remove the sender, and create a new one with the new stream.
4978 caller()->pc()->RemoveTrack(sender);
4979 sender = caller()->AddTrack(track, {"stream_2"});
4980 caller()->CreateAndSetAndSignalOffer();
4981 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4982 // Wait for additional audio frames to be received by the callee.
4983 {
4984 MediaExpectations media_expectations;
4985 media_expectations.CalleeExpectsSomeAudio();
4986 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4987 }
4988 }
4989
TEST_P(PeerConnectionIntegrationTest,RtcEventLogOutputWriteCalled)4990 TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
4991 ASSERT_TRUE(CreatePeerConnectionWrappers());
4992 ConnectFakeSignaling();
4993
4994 auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
4995 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
4996 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
4997 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
4998 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4999 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
5000
5001 caller()->AddAudioVideoTracks();
5002 caller()->CreateAndSetAndSignalOffer();
5003 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5004 }
5005
5006 // Test that if candidates are only signaled by applying full session
5007 // descriptions (instead of using AddIceCandidate), the peers can connect to
5008 // each other and exchange media.
TEST_P(PeerConnectionIntegrationTest,MediaFlowsWhenCandidatesSetOnlyInSdp)5009 TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
5010 ASSERT_TRUE(CreatePeerConnectionWrappers());
5011 // Each side will signal the session descriptions but not candidates.
5012 ConnectFakeSignalingForSdpOnly();
5013
5014 // Add audio video track and exchange the initial offer/answer with media
5015 // information only. This will start ICE gathering on each side.
5016 caller()->AddAudioVideoTracks();
5017 callee()->AddAudioVideoTracks();
5018 caller()->CreateAndSetAndSignalOffer();
5019
5020 // Wait for all candidates to be gathered on both the caller and callee.
5021 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5022 caller()->ice_gathering_state(), kDefaultTimeout);
5023 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5024 callee()->ice_gathering_state(), kDefaultTimeout);
5025
5026 // The candidates will now be included in the session description, so
5027 // signaling them will start the ICE connection.
5028 caller()->CreateAndSetAndSignalOffer();
5029 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5030
5031 // Ensure that media flows in both directions.
5032 MediaExpectations media_expectations;
5033 media_expectations.ExpectBidirectionalAudioAndVideo();
5034 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5035 }
5036
5037 // Test that SetAudioPlayout can be used to disable audio playout from the
5038 // start, then later enable it. This may be useful, for example, if the caller
5039 // needs to play a local ringtone until some event occurs, after which it
5040 // switches to playing the received audio.
TEST_P(PeerConnectionIntegrationTest,DisableAndEnableAudioPlayout)5041 TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
5042 ASSERT_TRUE(CreatePeerConnectionWrappers());
5043 ConnectFakeSignaling();
5044
5045 // Set up audio-only call where audio playout is disabled on caller's side.
5046 caller()->pc()->SetAudioPlayout(false);
5047 caller()->AddAudioTrack();
5048 callee()->AddAudioTrack();
5049 caller()->CreateAndSetAndSignalOffer();
5050 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5051
5052 // Pump messages for a second.
5053 WAIT(false, 1000);
5054 // Since audio playout is disabled, the caller shouldn't have received
5055 // anything (at the playout level, at least).
5056 EXPECT_EQ(0, caller()->audio_frames_received());
5057 // As a sanity check, make sure the callee (for which playout isn't disabled)
5058 // did still see frames on its audio level.
5059 ASSERT_GT(callee()->audio_frames_received(), 0);
5060
5061 // Enable playout again, and ensure audio starts flowing.
5062 caller()->pc()->SetAudioPlayout(true);
5063 MediaExpectations media_expectations;
5064 media_expectations.ExpectBidirectionalAudio();
5065 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5066 }
5067
GetAudioEnergyStat(PeerConnectionWrapper * pc)5068 double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5069 auto report = pc->NewGetStats();
5070 auto track_stats_list =
5071 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5072 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5073 for (const auto* track_stats : track_stats_list) {
5074 if (track_stats->remote_source.is_defined() &&
5075 *track_stats->remote_source) {
5076 remote_track_stats = track_stats;
5077 break;
5078 }
5079 }
5080
5081 if (!remote_track_stats->total_audio_energy.is_defined()) {
5082 return 0.0;
5083 }
5084 return *remote_track_stats->total_audio_energy;
5085 }
5086
5087 // Test that if audio playout is disabled via the SetAudioPlayout() method, then
5088 // incoming audio is still processed and statistics are generated.
TEST_P(PeerConnectionIntegrationTest,DisableAudioPlayoutStillGeneratesAudioStats)5089 TEST_P(PeerConnectionIntegrationTest,
5090 DisableAudioPlayoutStillGeneratesAudioStats) {
5091 ASSERT_TRUE(CreatePeerConnectionWrappers());
5092 ConnectFakeSignaling();
5093
5094 // Set up audio-only call where playout is disabled but audio-processing is
5095 // still active.
5096 caller()->AddAudioTrack();
5097 callee()->AddAudioTrack();
5098 caller()->pc()->SetAudioPlayout(false);
5099
5100 caller()->CreateAndSetAndSignalOffer();
5101 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5102
5103 // Wait for the callee to receive audio stats.
5104 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5105 }
5106
5107 // Test that SetAudioRecording can be used to disable audio recording from the
5108 // start, then later enable it. This may be useful, for example, if the caller
5109 // wants to ensure that no audio resources are active before a certain state
5110 // is reached.
TEST_P(PeerConnectionIntegrationTest,DisableAndEnableAudioRecording)5111 TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
5112 ASSERT_TRUE(CreatePeerConnectionWrappers());
5113 ConnectFakeSignaling();
5114
5115 // Set up audio-only call where audio recording is disabled on caller's side.
5116 caller()->pc()->SetAudioRecording(false);
5117 caller()->AddAudioTrack();
5118 callee()->AddAudioTrack();
5119 caller()->CreateAndSetAndSignalOffer();
5120 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5121
5122 // Pump messages for a second.
5123 WAIT(false, 1000);
5124 // Since caller has disabled audio recording, the callee shouldn't have
5125 // received anything.
5126 EXPECT_EQ(0, callee()->audio_frames_received());
5127 // As a sanity check, make sure the caller did still see frames on its
5128 // audio level since audio recording is enabled on the calle side.
5129 ASSERT_GT(caller()->audio_frames_received(), 0);
5130
5131 // Enable audio recording again, and ensure audio starts flowing.
5132 caller()->pc()->SetAudioRecording(true);
5133 MediaExpectations media_expectations;
5134 media_expectations.ExpectBidirectionalAudio();
5135 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5136 }
5137
5138 // Test that after closing PeerConnections, they stop sending any packets (ICE,
5139 // DTLS, RTP...).
TEST_P(PeerConnectionIntegrationTest,ClosingConnectionStopsPacketFlow)5140 TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
5141 // Set up audio/video/data, wait for some frames to be received.
5142 ASSERT_TRUE(CreatePeerConnectionWrappers());
5143 ConnectFakeSignaling();
5144 caller()->AddAudioVideoTracks();
5145 #ifdef HAVE_SCTP
5146 caller()->CreateDataChannel();
5147 #endif
5148 caller()->CreateAndSetAndSignalOffer();
5149 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5150 MediaExpectations media_expectations;
5151 media_expectations.CalleeExpectsSomeAudioAndVideo();
5152 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5153 // Close PeerConnections.
5154 ClosePeerConnections();
5155 // Pump messages for a second, and ensure no new packets end up sent.
5156 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5157 WAIT(false, 1000);
5158 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5159 EXPECT_EQ(sent_packets_a, sent_packets_b);
5160 }
5161
5162 // Test that transport stats are generated by the RTCStatsCollector for a
5163 // connection that only involves data channels. This is a regression test for
5164 // crbug.com/826972.
5165 #ifdef HAVE_SCTP
TEST_P(PeerConnectionIntegrationTest,TransportStatsReportedForDataChannelOnlyConnection)5166 TEST_P(PeerConnectionIntegrationTest,
5167 TransportStatsReportedForDataChannelOnlyConnection) {
5168 ASSERT_TRUE(CreatePeerConnectionWrappers());
5169 ConnectFakeSignaling();
5170 caller()->CreateDataChannel();
5171
5172 caller()->CreateAndSetAndSignalOffer();
5173 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5174 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5175
5176 auto caller_report = caller()->NewGetStats();
5177 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5178 auto callee_report = callee()->NewGetStats();
5179 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5180 }
5181 #endif // HAVE_SCTP
5182
TEST_P(PeerConnectionIntegrationTest,IceEventsGeneratedAndLoggedInRtcEventLog)5183 TEST_P(PeerConnectionIntegrationTest,
5184 IceEventsGeneratedAndLoggedInRtcEventLog) {
5185 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5186 ConnectFakeSignaling();
5187 PeerConnectionInterface::RTCOfferAnswerOptions options;
5188 options.offer_to_receive_audio = 1;
5189 caller()->SetOfferAnswerOptions(options);
5190 caller()->CreateAndSetAndSignalOffer();
5191 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5192 ASSERT_NE(nullptr, caller()->event_log_factory());
5193 ASSERT_NE(nullptr, callee()->event_log_factory());
5194 webrtc::FakeRtcEventLog* caller_event_log =
5195 static_cast<webrtc::FakeRtcEventLog*>(
5196 caller()->event_log_factory()->last_log_created());
5197 webrtc::FakeRtcEventLog* callee_event_log =
5198 static_cast<webrtc::FakeRtcEventLog*>(
5199 callee()->event_log_factory()->last_log_created());
5200 ASSERT_NE(nullptr, caller_event_log);
5201 ASSERT_NE(nullptr, callee_event_log);
5202 int caller_ice_config_count = caller_event_log->GetEventCount(
5203 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5204 int caller_ice_event_count = caller_event_log->GetEventCount(
5205 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5206 int callee_ice_config_count = callee_event_log->GetEventCount(
5207 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5208 int callee_ice_event_count = callee_event_log->GetEventCount(
5209 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5210 EXPECT_LT(0, caller_ice_config_count);
5211 EXPECT_LT(0, caller_ice_event_count);
5212 EXPECT_LT(0, callee_ice_config_count);
5213 EXPECT_LT(0, callee_ice_event_count);
5214 }
5215
TEST_P(PeerConnectionIntegrationTest,RegatherAfterChangingIceTransportType)5216 TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
5217 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5218 3478};
5219 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5220
5221 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5222
5223 webrtc::PeerConnectionInterface::IceServer ice_server;
5224 ice_server.urls.push_back("turn:88.88.88.0:3478");
5225 ice_server.username = "test";
5226 ice_server.password = "test";
5227
5228 PeerConnectionInterface::RTCConfiguration caller_config;
5229 caller_config.servers.push_back(ice_server);
5230 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5231 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5232 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
5233
5234 PeerConnectionInterface::RTCConfiguration callee_config;
5235 callee_config.servers.push_back(ice_server);
5236 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5237 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5238 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
5239
5240 ASSERT_TRUE(
5241 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5242
5243 // Do normal offer/answer and wait for ICE to complete.
5244 ConnectFakeSignaling();
5245 caller()->AddAudioVideoTracks();
5246 callee()->AddAudioVideoTracks();
5247 caller()->CreateAndSetAndSignalOffer();
5248 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5249 // Since we are doing continual gathering, the ICE transport does not reach
5250 // kIceGatheringComplete (see
5251 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5252 // kIceConnectionComplete.
5253 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5254 caller()->ice_connection_state(), kDefaultTimeout);
5255 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5256 callee()->ice_connection_state(), kDefaultTimeout);
5257 // Note that we cannot use the metric
5258 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5259 // metric is only populated when we reach kIceConnectionComplete in the
5260 // current implementation.
5261 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5262 caller()->last_candidate_gathered().type());
5263 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5264 callee()->last_candidate_gathered().type());
5265
5266 // Loosen the caller's candidate filter.
5267 caller_config = caller()->pc()->GetConfiguration();
5268 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5269 caller()->pc()->SetConfiguration(caller_config);
5270 // We should have gathered a new host candidate.
5271 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5272 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5273
5274 // Loosen the callee's candidate filter.
5275 callee_config = callee()->pc()->GetConfiguration();
5276 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5277 callee()->pc()->SetConfiguration(callee_config);
5278 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5279 callee()->last_candidate_gathered().type(), kDefaultTimeout);
5280
5281 // Create an offer and verify that it does not contain an ICE restart (i.e new
5282 // ice credentials).
5283 std::string caller_ufrag_pre_offer = caller()
5284 ->pc()
5285 ->local_description()
5286 ->description()
5287 ->transport_infos()[0]
5288 .description.ice_ufrag;
5289 caller()->CreateAndSetAndSignalOffer();
5290 std::string caller_ufrag_post_offer = caller()
5291 ->pc()
5292 ->local_description()
5293 ->description()
5294 ->transport_infos()[0]
5295 .description.ice_ufrag;
5296 EXPECT_EQ(caller_ufrag_pre_offer, caller_ufrag_post_offer);
5297 }
5298
TEST_P(PeerConnectionIntegrationTest,OnIceCandidateError)5299 TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
5300 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5301 3478};
5302 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5303
5304 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5305
5306 webrtc::PeerConnectionInterface::IceServer ice_server;
5307 ice_server.urls.push_back("turn:88.88.88.0:3478");
5308 ice_server.username = "test";
5309 ice_server.password = "123";
5310
5311 PeerConnectionInterface::RTCConfiguration caller_config;
5312 caller_config.servers.push_back(ice_server);
5313 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5314 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5315
5316 PeerConnectionInterface::RTCConfiguration callee_config;
5317 callee_config.servers.push_back(ice_server);
5318 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5319 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5320
5321 ASSERT_TRUE(
5322 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5323
5324 // Do normal offer/answer and wait for ICE to complete.
5325 ConnectFakeSignaling();
5326 caller()->AddAudioVideoTracks();
5327 callee()->AddAudioVideoTracks();
5328 caller()->CreateAndSetAndSignalOffer();
5329 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5330 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5331 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5332 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
5333 EXPECT_NE(caller()->error_event().address, "");
5334 }
5335
TEST_P(PeerConnectionIntegrationTest,OnIceCandidateErrorWithEmptyAddress)5336 TEST_P(PeerConnectionIntegrationTest, OnIceCandidateErrorWithEmptyAddress) {
5337 webrtc::PeerConnectionInterface::IceServer ice_server;
5338 ice_server.urls.push_back("turn:127.0.0.1:3478?transport=tcp");
5339 ice_server.username = "test";
5340 ice_server.password = "test";
5341
5342 PeerConnectionInterface::RTCConfiguration caller_config;
5343 caller_config.servers.push_back(ice_server);
5344 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5345 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5346
5347 PeerConnectionInterface::RTCConfiguration callee_config;
5348 callee_config.servers.push_back(ice_server);
5349 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5350 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5351
5352 ASSERT_TRUE(
5353 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5354
5355 // Do normal offer/answer and wait for ICE to complete.
5356 ConnectFakeSignaling();
5357 caller()->AddAudioVideoTracks();
5358 callee()->AddAudioVideoTracks();
5359 caller()->CreateAndSetAndSignalOffer();
5360 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5361 EXPECT_EQ_WAIT(701, caller()->error_event().error_code, kDefaultTimeout);
5362 EXPECT_EQ(caller()->error_event().address, "");
5363 }
5364
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,AudioKeepsFlowingAfterImplicitRollback)5365 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5366 AudioKeepsFlowingAfterImplicitRollback) {
5367 PeerConnectionInterface::RTCConfiguration config;
5368 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5369 config.enable_implicit_rollback = true;
5370 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5371 ConnectFakeSignaling();
5372 caller()->AddAudioTrack();
5373 callee()->AddAudioTrack();
5374 caller()->CreateAndSetAndSignalOffer();
5375 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5376 MediaExpectations media_expectations;
5377 media_expectations.ExpectBidirectionalAudio();
5378 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5379 SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
5380 caller()->AddVideoTrack();
5381 callee()->AddVideoTrack();
5382 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5383 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5384 callee()->pc()->SetLocalDescription(observer,
5385 callee()->CreateOfferAndWait().release());
5386 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
5387 caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
5388 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5389 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5390 }
5391
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,ImplicitRollbackVisitsStableState)5392 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5393 ImplicitRollbackVisitsStableState) {
5394 RTCConfiguration config;
5395 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5396 config.enable_implicit_rollback = true;
5397
5398 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5399
5400 rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
5401 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5402 callee()->pc()->SetLocalDescription(sld_observer,
5403 callee()->CreateOfferAndWait().release());
5404 EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
5405 EXPECT_EQ(sld_observer->error(), "");
5406
5407 rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
5408 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5409 callee()->pc()->SetRemoteDescription(
5410 srd_observer, caller()->CreateOfferAndWait().release());
5411 EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
5412 EXPECT_EQ(srd_observer->error(), "");
5413
5414 EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
5415 ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
5416 PeerConnectionInterface::kStable,
5417 PeerConnectionInterface::kHaveRemoteOffer));
5418 }
5419
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,H264FmtpSpsPpsIdrInKeyframeParameterUsage)5420 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5421 H264FmtpSpsPpsIdrInKeyframeParameterUsage) {
5422 ASSERT_TRUE(CreatePeerConnectionWrappers());
5423 ConnectFakeSignaling();
5424 caller()->AddVideoTrack();
5425 callee()->AddVideoTrack();
5426 auto munger = [](cricket::SessionDescription* desc) {
5427 cricket::VideoContentDescription* video =
5428 GetFirstVideoContentDescription(desc);
5429 auto codecs = video->codecs();
5430 for (auto&& codec : codecs) {
5431 if (codec.name == "H264") {
5432 std::string value;
5433 // The parameter is not supposed to be present in SDP by default.
5434 EXPECT_FALSE(
5435 codec.GetParam(cricket::kH264FmtpSpsPpsIdrInKeyframe, &value));
5436 codec.SetParam(std::string(cricket::kH264FmtpSpsPpsIdrInKeyframe),
5437 std::string(""));
5438 }
5439 }
5440 video->set_codecs(codecs);
5441 };
5442 // Munge local offer for SLD.
5443 caller()->SetGeneratedSdpMunger(munger);
5444 // Munge remote answer for SRD.
5445 caller()->SetReceivedSdpMunger(munger);
5446 caller()->CreateAndSetAndSignalOffer();
5447 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5448 // Observe that after munging the parameter is present in generated SDP.
5449 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* desc) {
5450 cricket::VideoContentDescription* video =
5451 GetFirstVideoContentDescription(desc);
5452 for (auto&& codec : video->codecs()) {
5453 if (codec.name == "H264") {
5454 std::string value;
5455 EXPECT_TRUE(
5456 codec.GetParam(cricket::kH264FmtpSpsPpsIdrInKeyframe, &value));
5457 }
5458 }
5459 });
5460 caller()->CreateOfferAndWait();
5461 }
5462
5463 INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5464 PeerConnectionIntegrationTest,
5465 Values(SdpSemantics::kPlanB,
5466 SdpSemantics::kUnifiedPlan));
5467
5468 INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5469 PeerConnectionIntegrationTestWithFakeClock,
5470 Values(SdpSemantics::kPlanB,
5471 SdpSemantics::kUnifiedPlan));
5472
5473 // Tests that verify interoperability between Plan B and Unified Plan
5474 // PeerConnections.
5475 class PeerConnectionIntegrationInteropTest
5476 : public PeerConnectionIntegrationBaseTest,
5477 public ::testing::WithParamInterface<
5478 std::tuple<SdpSemantics, SdpSemantics>> {
5479 protected:
5480 // Setting the SdpSemantics for the base test to kDefault does not matter
5481 // because we specify not to use the test semantics when creating
5482 // PeerConnectionWrappers.
PeerConnectionIntegrationInteropTest()5483 PeerConnectionIntegrationInteropTest()
5484 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
5485 caller_semantics_(std::get<0>(GetParam())),
5486 callee_semantics_(std::get<1>(GetParam())) {}
5487
CreatePeerConnectionWrappersWithSemantics()5488 bool CreatePeerConnectionWrappersWithSemantics() {
5489 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5490 callee_semantics_);
5491 }
5492
5493 const SdpSemantics caller_semantics_;
5494 const SdpSemantics callee_semantics_;
5495 };
5496
TEST_P(PeerConnectionIntegrationInteropTest,NoMediaLocalToNoMediaRemote)5497 TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5498 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5499 ConnectFakeSignaling();
5500
5501 caller()->CreateAndSetAndSignalOffer();
5502 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5503 }
5504
TEST_P(PeerConnectionIntegrationInteropTest,OneAudioLocalToNoMediaRemote)5505 TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5506 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5507 ConnectFakeSignaling();
5508 auto audio_sender = caller()->AddAudioTrack();
5509
5510 caller()->CreateAndSetAndSignalOffer();
5511 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5512
5513 // Verify that one audio receiver has been created on the remote and that it
5514 // has the same track ID as the sending track.
5515 auto receivers = callee()->pc()->GetReceivers();
5516 ASSERT_EQ(1u, receivers.size());
5517 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5518 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5519
5520 MediaExpectations media_expectations;
5521 media_expectations.CalleeExpectsSomeAudio();
5522 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5523 }
5524
TEST_P(PeerConnectionIntegrationInteropTest,OneAudioOneVideoToNoMediaRemote)5525 TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5526 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5527 ConnectFakeSignaling();
5528 auto video_sender = caller()->AddVideoTrack();
5529 auto audio_sender = caller()->AddAudioTrack();
5530
5531 caller()->CreateAndSetAndSignalOffer();
5532 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5533
5534 // Verify that one audio and one video receiver have been created on the
5535 // remote and that they have the same track IDs as the sending tracks.
5536 auto audio_receivers =
5537 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5538 ASSERT_EQ(1u, audio_receivers.size());
5539 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5540 auto video_receivers =
5541 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5542 ASSERT_EQ(1u, video_receivers.size());
5543 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5544
5545 MediaExpectations media_expectations;
5546 media_expectations.CalleeExpectsSomeAudioAndVideo();
5547 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5548 }
5549
TEST_P(PeerConnectionIntegrationInteropTest,OneAudioOneVideoLocalToOneAudioOneVideoRemote)5550 TEST_P(PeerConnectionIntegrationInteropTest,
5551 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5552 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5553 ConnectFakeSignaling();
5554 caller()->AddAudioVideoTracks();
5555 callee()->AddAudioVideoTracks();
5556
5557 caller()->CreateAndSetAndSignalOffer();
5558 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5559
5560 MediaExpectations media_expectations;
5561 media_expectations.ExpectBidirectionalAudioAndVideo();
5562 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5563 }
5564
TEST_P(PeerConnectionIntegrationInteropTest,ReverseRolesOneAudioLocalToOneVideoRemote)5565 TEST_P(PeerConnectionIntegrationInteropTest,
5566 ReverseRolesOneAudioLocalToOneVideoRemote) {
5567 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5568 ConnectFakeSignaling();
5569 caller()->AddAudioTrack();
5570 callee()->AddVideoTrack();
5571
5572 caller()->CreateAndSetAndSignalOffer();
5573 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5574
5575 // Verify that only the audio track has been negotiated.
5576 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5577 // Might also check that the callee's NegotiationNeeded flag is set.
5578
5579 // Reverse roles.
5580 callee()->CreateAndSetAndSignalOffer();
5581 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5582
5583 MediaExpectations media_expectations;
5584 media_expectations.CallerExpectsSomeVideo();
5585 media_expectations.CalleeExpectsSomeAudio();
5586 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5587 }
5588
5589 INSTANTIATE_TEST_SUITE_P(
5590 PeerConnectionIntegrationTest,
5591 PeerConnectionIntegrationInteropTest,
5592 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5593 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5594
5595 // Test that if the Unified Plan side offers two video tracks then the Plan B
5596 // side will only see the first one and ignore the second.
TEST_F(PeerConnectionIntegrationTestPlanB,TwoVideoUnifiedPlanToNoMediaPlanB)5597 TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
5598 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5599 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
5600 ConnectFakeSignaling();
5601 auto first_sender = caller()->AddVideoTrack();
5602 caller()->AddVideoTrack();
5603
5604 caller()->CreateAndSetAndSignalOffer();
5605 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5606
5607 // Verify that there is only one receiver and it corresponds to the first
5608 // added track.
5609 auto receivers = callee()->pc()->GetReceivers();
5610 ASSERT_EQ(1u, receivers.size());
5611 EXPECT_TRUE(receivers[0]->track()->enabled());
5612 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5613
5614 MediaExpectations media_expectations;
5615 media_expectations.CalleeExpectsSomeVideo();
5616 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5617 }
5618
5619 // Test that if the initial offer tagged BUNDLE section is rejected due to its
5620 // associated RtpTransceiver being stopped and another transceiver is added,
5621 // then renegotiation causes the callee to receive the new video track without
5622 // error.
5623 // This is a regression test for bugs.webrtc.org/9954
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,ReOfferWithStoppedBundleTaggedTransceiver)5624 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5625 ReOfferWithStoppedBundleTaggedTransceiver) {
5626 RTCConfiguration config;
5627 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5628 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5629 ConnectFakeSignaling();
5630 auto audio_transceiver_or_error =
5631 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5632 ASSERT_TRUE(audio_transceiver_or_error.ok());
5633 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5634
5635 caller()->CreateAndSetAndSignalOffer();
5636 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5637 {
5638 MediaExpectations media_expectations;
5639 media_expectations.CalleeExpectsSomeAudio();
5640 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5641 }
5642
5643 audio_transceiver->StopInternal();
5644 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5645
5646 caller()->CreateAndSetAndSignalOffer();
5647 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5648 {
5649 MediaExpectations media_expectations;
5650 media_expectations.CalleeExpectsSomeVideo();
5651 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5652 }
5653 }
5654
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,StopTransceiverRemovesDtlsTransports)5655 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5656 StopTransceiverRemovesDtlsTransports) {
5657 RTCConfiguration config;
5658 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5659 ConnectFakeSignaling();
5660 auto audio_transceiver_or_error =
5661 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5662 ASSERT_TRUE(audio_transceiver_or_error.ok());
5663 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5664
5665 caller()->CreateAndSetAndSignalOffer();
5666 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5667
5668 audio_transceiver->StopStandard();
5669 caller()->CreateAndSetAndSignalOffer();
5670 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5671 ASSERT_EQ(0U, caller()->pc()->GetTransceivers().size());
5672 EXPECT_EQ(PeerConnectionInterface::kIceGatheringNew,
5673 caller()->pc()->ice_gathering_state());
5674 EXPECT_THAT(caller()->ice_gathering_state_history(),
5675 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
5676 PeerConnectionInterface::kIceGatheringComplete,
5677 PeerConnectionInterface::kIceGatheringNew));
5678 }
5679
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,StopTransceiverStopsAndRemovesTransceivers)5680 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5681 StopTransceiverStopsAndRemovesTransceivers) {
5682 RTCConfiguration config;
5683 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5684 ConnectFakeSignaling();
5685 auto audio_transceiver_or_error =
5686 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5687 ASSERT_TRUE(audio_transceiver_or_error.ok());
5688 auto caller_transceiver = audio_transceiver_or_error.MoveValue();
5689
5690 caller()->CreateAndSetAndSignalOffer();
5691 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5692 caller_transceiver->StopStandard();
5693
5694 auto callee_transceiver = callee()->pc()->GetTransceivers()[0];
5695 caller()->CreateAndSetAndSignalOffer();
5696 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5697 EXPECT_EQ(0U, caller()->pc()->GetTransceivers().size());
5698 EXPECT_EQ(0U, callee()->pc()->GetTransceivers().size());
5699 EXPECT_EQ(0U, caller()->pc()->GetSenders().size());
5700 EXPECT_EQ(0U, callee()->pc()->GetSenders().size());
5701 EXPECT_EQ(0U, caller()->pc()->GetReceivers().size());
5702 EXPECT_EQ(0U, callee()->pc()->GetReceivers().size());
5703 EXPECT_TRUE(caller_transceiver->stopped());
5704 EXPECT_TRUE(callee_transceiver->stopped());
5705 }
5706
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,StopTransceiverEndsIncomingAudioTrack)5707 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5708 StopTransceiverEndsIncomingAudioTrack) {
5709 RTCConfiguration config;
5710 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5711 ConnectFakeSignaling();
5712 auto audio_transceiver_or_error =
5713 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5714 ASSERT_TRUE(audio_transceiver_or_error.ok());
5715 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5716
5717 caller()->CreateAndSetAndSignalOffer();
5718 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5719 auto caller_track = audio_transceiver->receiver()->track();
5720 auto callee_track = callee()->pc()->GetReceivers()[0]->track();
5721 audio_transceiver->StopStandard();
5722 EXPECT_EQ(MediaStreamTrackInterface::TrackState::kEnded,
5723 caller_track->state());
5724 caller()->CreateAndSetAndSignalOffer();
5725 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5726 EXPECT_EQ(MediaStreamTrackInterface::TrackState::kEnded,
5727 callee_track->state());
5728 }
5729
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,StopTransceiverEndsIncomingVideoTrack)5730 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5731 StopTransceiverEndsIncomingVideoTrack) {
5732 RTCConfiguration config;
5733 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5734 ConnectFakeSignaling();
5735 auto audio_transceiver_or_error =
5736 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5737 ASSERT_TRUE(audio_transceiver_or_error.ok());
5738 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5739
5740 caller()->CreateAndSetAndSignalOffer();
5741 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5742 auto caller_track = audio_transceiver->receiver()->track();
5743 auto callee_track = callee()->pc()->GetReceivers()[0]->track();
5744 audio_transceiver->StopStandard();
5745 EXPECT_EQ(MediaStreamTrackInterface::TrackState::kEnded,
5746 caller_track->state());
5747 caller()->CreateAndSetAndSignalOffer();
5748 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5749 EXPECT_EQ(MediaStreamTrackInterface::TrackState::kEnded,
5750 callee_track->state());
5751 }
5752
5753 #ifdef HAVE_SCTP
5754
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,EndToEndCallWithBundledSctpDataChannel)5755 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5756 EndToEndCallWithBundledSctpDataChannel) {
5757 ASSERT_TRUE(CreatePeerConnectionWrappers());
5758 ConnectFakeSignaling();
5759 caller()->CreateDataChannel();
5760 caller()->AddAudioVideoTracks();
5761 callee()->AddAudioVideoTracks();
5762 caller()->CreateAndSetAndSignalOffer();
5763 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5764 ASSERT_EQ_WAIT(SctpTransportState::kConnected,
5765 caller()->pc()->GetSctpTransport()->Information().state(),
5766 kDefaultTimeout);
5767 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5768 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5769 }
5770
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,EndToEndCallWithDataChannelOnlyConnects)5771 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5772 EndToEndCallWithDataChannelOnlyConnects) {
5773 ASSERT_TRUE(CreatePeerConnectionWrappers());
5774 ConnectFakeSignaling();
5775 caller()->CreateDataChannel();
5776 caller()->CreateAndSetAndSignalOffer();
5777 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5778 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5779 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5780 ASSERT_TRUE(caller()->data_observer()->IsOpen());
5781 }
5782
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,DataChannelClosesWhenClosed)5783 TEST_F(PeerConnectionIntegrationTestUnifiedPlan, DataChannelClosesWhenClosed) {
5784 ASSERT_TRUE(CreatePeerConnectionWrappers());
5785 ConnectFakeSignaling();
5786 caller()->CreateDataChannel();
5787 caller()->CreateAndSetAndSignalOffer();
5788 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5789 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5790 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5791 caller()->data_channel()->Close();
5792 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
5793 }
5794
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,DataChannelClosesWhenClosedReverse)5795 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5796 DataChannelClosesWhenClosedReverse) {
5797 ASSERT_TRUE(CreatePeerConnectionWrappers());
5798 ConnectFakeSignaling();
5799 caller()->CreateDataChannel();
5800 caller()->CreateAndSetAndSignalOffer();
5801 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5802 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5803 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5804 callee()->data_channel()->Close();
5805 ASSERT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
5806 }
5807
TEST_F(PeerConnectionIntegrationTestUnifiedPlan,DataChannelClosesWhenPeerConnectionClosed)5808 TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5809 DataChannelClosesWhenPeerConnectionClosed) {
5810 ASSERT_TRUE(CreatePeerConnectionWrappers());
5811 ConnectFakeSignaling();
5812 caller()->CreateDataChannel();
5813 caller()->CreateAndSetAndSignalOffer();
5814 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5815 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5816 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5817 caller()->pc()->Close();
5818 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
5819 }
5820
5821 #endif // HAVE_SCTP
5822
5823 } // namespace
5824 } // namespace webrtc
5825
5826 #endif // if !defined(THREAD_SANITIZER)
5827