xref: /aosp_15_r20/external/webrtc/pc/peer_connection_end_to_end_unittest.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2013 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 #include <stdint.h>
12 
13 #include <cstddef>
14 #include <limits>
15 #include <memory>
16 #include <string>
17 #include <type_traits>
18 #include <utility>
19 #include <vector>
20 
21 #include "absl/strings/match.h"
22 #include "absl/types/optional.h"
23 #include "api/audio_codecs/L16/audio_decoder_L16.h"
24 #include "api/audio_codecs/L16/audio_encoder_L16.h"
25 #include "api/audio_codecs/audio_codec_pair_id.h"
26 #include "api/audio_codecs/audio_decoder.h"
27 #include "api/audio_codecs/audio_decoder_factory.h"
28 #include "api/audio_codecs/audio_decoder_factory_template.h"
29 #include "api/audio_codecs/audio_encoder.h"
30 #include "api/audio_codecs/audio_encoder_factory.h"
31 #include "api/audio_codecs/audio_encoder_factory_template.h"
32 #include "api/audio_codecs/audio_format.h"
33 #include "api/audio_codecs/opus_audio_decoder_factory.h"
34 #include "api/audio_codecs/opus_audio_encoder_factory.h"
35 #include "api/audio_options.h"
36 #include "api/data_channel_interface.h"
37 #include "api/media_stream_interface.h"
38 #include "api/peer_connection_interface.h"
39 #include "api/rtc_error.h"
40 #include "api/scoped_refptr.h"
41 #include "media/sctp/sctp_transport_internal.h"
42 #include "rtc_base/checks.h"
43 #include "rtc_base/copy_on_write_buffer.h"
44 #include "rtc_base/gunit.h"
45 #include "rtc_base/physical_socket_server.h"
46 #include "rtc_base/third_party/sigslot/sigslot.h"
47 #include "rtc_base/thread.h"
48 #include "test/gmock.h"
49 #include "test/gtest.h"
50 
51 #ifdef WEBRTC_ANDROID
52 #include "pc/test/android_test_initializer.h"
53 #endif
54 #include "pc/test/peer_connection_test_wrapper.h"
55 // Notice that mockpeerconnectionobservers.h must be included after the above!
56 #include "pc/test/mock_peer_connection_observers.h"
57 #include "test/mock_audio_decoder.h"
58 #include "test/mock_audio_decoder_factory.h"
59 #include "test/mock_audio_encoder_factory.h"
60 
61 using ::testing::_;
62 using ::testing::AtLeast;
63 using ::testing::Invoke;
64 using ::testing::StrictMock;
65 using ::testing::Values;
66 
67 using webrtc::DataChannelInterface;
68 using webrtc::MediaStreamInterface;
69 using webrtc::PeerConnectionInterface;
70 using webrtc::SdpSemantics;
71 
72 namespace {
73 
74 const int kMaxWait = 25000;
75 
76 }  // namespace
77 
78 class PeerConnectionEndToEndBaseTest : public sigslot::has_slots<>,
79                                        public ::testing::Test {
80  public:
81   typedef std::vector<rtc::scoped_refptr<DataChannelInterface>> DataChannelList;
82 
PeerConnectionEndToEndBaseTest(SdpSemantics sdp_semantics)83   explicit PeerConnectionEndToEndBaseTest(SdpSemantics sdp_semantics)
84       : network_thread_(std::make_unique<rtc::Thread>(&pss_)),
85         worker_thread_(rtc::Thread::Create()) {
86     RTC_CHECK(network_thread_->Start());
87     RTC_CHECK(worker_thread_->Start());
88     caller_ = rtc::make_ref_counted<PeerConnectionTestWrapper>(
89         "caller", &pss_, network_thread_.get(), worker_thread_.get());
90     callee_ = rtc::make_ref_counted<PeerConnectionTestWrapper>(
91         "callee", &pss_, network_thread_.get(), worker_thread_.get());
92     webrtc::PeerConnectionInterface::IceServer ice_server;
93     ice_server.uri = "stun:stun.l.google.com:19302";
94     config_.servers.push_back(ice_server);
95     config_.sdp_semantics = sdp_semantics;
96 
97 #ifdef WEBRTC_ANDROID
98     webrtc::InitializeAndroidObjects();
99 #endif
100   }
101 
CreatePcs(rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory1,rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory1,rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory2,rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory2)102   void CreatePcs(
103       rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory1,
104       rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory1,
105       rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory2,
106       rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory2) {
107     EXPECT_TRUE(caller_->CreatePc(config_, audio_encoder_factory1,
108                                   audio_decoder_factory1));
109     EXPECT_TRUE(callee_->CreatePc(config_, audio_encoder_factory2,
110                                   audio_decoder_factory2));
111     PeerConnectionTestWrapper::Connect(caller_.get(), callee_.get());
112 
113     caller_->SignalOnDataChannel.connect(
114         this, &PeerConnectionEndToEndBaseTest::OnCallerAddedDataChanel);
115     callee_->SignalOnDataChannel.connect(
116         this, &PeerConnectionEndToEndBaseTest::OnCalleeAddedDataChannel);
117   }
118 
CreatePcs(rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory,rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory)119   void CreatePcs(
120       rtc::scoped_refptr<webrtc::AudioEncoderFactory> audio_encoder_factory,
121       rtc::scoped_refptr<webrtc::AudioDecoderFactory> audio_decoder_factory) {
122     CreatePcs(audio_encoder_factory, audio_decoder_factory,
123               audio_encoder_factory, audio_decoder_factory);
124   }
125 
GetAndAddUserMedia()126   void GetAndAddUserMedia() {
127     cricket::AudioOptions audio_options;
128     GetAndAddUserMedia(true, audio_options, true);
129   }
130 
GetAndAddUserMedia(bool audio,const cricket::AudioOptions & audio_options,bool video)131   void GetAndAddUserMedia(bool audio,
132                           const cricket::AudioOptions& audio_options,
133                           bool video) {
134     caller_->GetAndAddUserMedia(audio, audio_options, video);
135     callee_->GetAndAddUserMedia(audio, audio_options, video);
136   }
137 
Negotiate()138   void Negotiate() {
139     caller_->CreateOffer(
140         webrtc::PeerConnectionInterface::RTCOfferAnswerOptions());
141   }
142 
WaitForCallEstablished()143   void WaitForCallEstablished() {
144     caller_->WaitForCallEstablished();
145     callee_->WaitForCallEstablished();
146   }
147 
WaitForConnection()148   void WaitForConnection() {
149     caller_->WaitForConnection();
150     callee_->WaitForConnection();
151   }
152 
OnCallerAddedDataChanel(DataChannelInterface * dc)153   void OnCallerAddedDataChanel(DataChannelInterface* dc) {
154     caller_signaled_data_channels_.push_back(
155         rtc::scoped_refptr<DataChannelInterface>(dc));
156   }
157 
OnCalleeAddedDataChannel(DataChannelInterface * dc)158   void OnCalleeAddedDataChannel(DataChannelInterface* dc) {
159     callee_signaled_data_channels_.push_back(
160         rtc::scoped_refptr<DataChannelInterface>(dc));
161   }
162 
163   // Tests that `dc1` and `dc2` can send to and receive from each other.
TestDataChannelSendAndReceive(DataChannelInterface * dc1,DataChannelInterface * dc2,size_t size=6)164   void TestDataChannelSendAndReceive(DataChannelInterface* dc1,
165                                      DataChannelInterface* dc2,
166                                      size_t size = 6) {
167     std::unique_ptr<webrtc::MockDataChannelObserver> dc1_observer(
168         new webrtc::MockDataChannelObserver(dc1));
169 
170     std::unique_ptr<webrtc::MockDataChannelObserver> dc2_observer(
171         new webrtc::MockDataChannelObserver(dc2));
172 
173     static const std::string kDummyData =
174         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
175     webrtc::DataBuffer buffer("");
176 
177     size_t sizeLeft = size;
178     while (sizeLeft > 0) {
179       size_t chunkSize =
180           sizeLeft > kDummyData.length() ? kDummyData.length() : sizeLeft;
181       buffer.data.AppendData(kDummyData.data(), chunkSize);
182       sizeLeft -= chunkSize;
183     }
184 
185     EXPECT_TRUE(dc1->Send(buffer));
186     EXPECT_EQ_WAIT(buffer.data,
187                    rtc::CopyOnWriteBuffer(dc2_observer->last_message()),
188                    kMaxWait);
189 
190     EXPECT_TRUE(dc2->Send(buffer));
191     EXPECT_EQ_WAIT(buffer.data,
192                    rtc::CopyOnWriteBuffer(dc1_observer->last_message()),
193                    kMaxWait);
194 
195     EXPECT_EQ(1U, dc1_observer->received_message_count());
196     EXPECT_EQ(size, dc1_observer->last_message().length());
197     EXPECT_EQ(1U, dc2_observer->received_message_count());
198     EXPECT_EQ(size, dc2_observer->last_message().length());
199   }
200 
WaitForDataChannelsToOpen(DataChannelInterface * local_dc,const DataChannelList & remote_dc_list,size_t remote_dc_index)201   void WaitForDataChannelsToOpen(DataChannelInterface* local_dc,
202                                  const DataChannelList& remote_dc_list,
203                                  size_t remote_dc_index) {
204     EXPECT_EQ_WAIT(DataChannelInterface::kOpen, local_dc->state(), kMaxWait);
205 
206     ASSERT_TRUE_WAIT(remote_dc_list.size() > remote_dc_index, kMaxWait);
207     EXPECT_EQ_WAIT(DataChannelInterface::kOpen,
208                    remote_dc_list[remote_dc_index]->state(), kMaxWait);
209     EXPECT_EQ(local_dc->id(), remote_dc_list[remote_dc_index]->id());
210   }
211 
CloseDataChannels(DataChannelInterface * local_dc,const DataChannelList & remote_dc_list,size_t remote_dc_index)212   void CloseDataChannels(DataChannelInterface* local_dc,
213                          const DataChannelList& remote_dc_list,
214                          size_t remote_dc_index) {
215     local_dc->Close();
216     EXPECT_EQ_WAIT(DataChannelInterface::kClosed, local_dc->state(), kMaxWait);
217     EXPECT_EQ_WAIT(DataChannelInterface::kClosed,
218                    remote_dc_list[remote_dc_index]->state(), kMaxWait);
219   }
220 
221  protected:
222   rtc::AutoThread main_thread_;
223   rtc::PhysicalSocketServer pss_;
224   std::unique_ptr<rtc::Thread> network_thread_;
225   std::unique_ptr<rtc::Thread> worker_thread_;
226   rtc::scoped_refptr<PeerConnectionTestWrapper> caller_;
227   rtc::scoped_refptr<PeerConnectionTestWrapper> callee_;
228   DataChannelList caller_signaled_data_channels_;
229   DataChannelList callee_signaled_data_channels_;
230   webrtc::PeerConnectionInterface::RTCConfiguration config_;
231 };
232 
233 class PeerConnectionEndToEndTest
234     : public PeerConnectionEndToEndBaseTest,
235       public ::testing::WithParamInterface<SdpSemantics> {
236  protected:
PeerConnectionEndToEndTest()237   PeerConnectionEndToEndTest() : PeerConnectionEndToEndBaseTest(GetParam()) {}
238 };
239 
240 namespace {
241 
CreateForwardingMockDecoder(std::unique_ptr<webrtc::AudioDecoder> real_decoder)242 std::unique_ptr<webrtc::AudioDecoder> CreateForwardingMockDecoder(
243     std::unique_ptr<webrtc::AudioDecoder> real_decoder) {
244   class ForwardingMockDecoder : public StrictMock<webrtc::MockAudioDecoder> {
245    public:
246     explicit ForwardingMockDecoder(std::unique_ptr<AudioDecoder> decoder)
247         : decoder_(std::move(decoder)) {}
248 
249    private:
250     std::unique_ptr<AudioDecoder> decoder_;
251   };
252 
253   const auto dec = real_decoder.get();  // For lambda capturing.
254   auto mock_decoder =
255       std::make_unique<ForwardingMockDecoder>(std::move(real_decoder));
256   EXPECT_CALL(*mock_decoder, Channels())
257       .Times(AtLeast(1))
258       .WillRepeatedly(Invoke([dec] { return dec->Channels(); }));
259   EXPECT_CALL(*mock_decoder, DecodeInternal(_, _, _, _, _))
260       .Times(AtLeast(1))
261       .WillRepeatedly(
262           Invoke([dec](const uint8_t* encoded, size_t encoded_len,
263                        int sample_rate_hz, int16_t* decoded,
264                        webrtc::AudioDecoder::SpeechType* speech_type) {
265             return dec->Decode(encoded, encoded_len, sample_rate_hz,
266                                std::numeric_limits<size_t>::max(), decoded,
267                                speech_type);
268           }));
269   EXPECT_CALL(*mock_decoder, Die());
270   EXPECT_CALL(*mock_decoder, HasDecodePlc()).WillRepeatedly(Invoke([dec] {
271     return dec->HasDecodePlc();
272   }));
273   EXPECT_CALL(*mock_decoder, PacketDuration(_, _))
274       .Times(AtLeast(1))
275       .WillRepeatedly(Invoke([dec](const uint8_t* encoded, size_t encoded_len) {
276         return dec->PacketDuration(encoded, encoded_len);
277       }));
278   EXPECT_CALL(*mock_decoder, SampleRateHz())
279       .Times(AtLeast(1))
280       .WillRepeatedly(Invoke([dec] { return dec->SampleRateHz(); }));
281 
282   return std::move(mock_decoder);
283 }
284 
285 rtc::scoped_refptr<webrtc::AudioDecoderFactory>
CreateForwardingMockDecoderFactory(webrtc::AudioDecoderFactory * real_decoder_factory)286 CreateForwardingMockDecoderFactory(
287     webrtc::AudioDecoderFactory* real_decoder_factory) {
288   rtc::scoped_refptr<webrtc::MockAudioDecoderFactory> mock_decoder_factory =
289       rtc::make_ref_counted<StrictMock<webrtc::MockAudioDecoderFactory>>();
290   EXPECT_CALL(*mock_decoder_factory, GetSupportedDecoders())
291       .Times(AtLeast(1))
292       .WillRepeatedly(Invoke([real_decoder_factory] {
293         return real_decoder_factory->GetSupportedDecoders();
294       }));
295   EXPECT_CALL(*mock_decoder_factory, IsSupportedDecoder(_))
296       .Times(AtLeast(1))
297       .WillRepeatedly(
298           Invoke([real_decoder_factory](const webrtc::SdpAudioFormat& format) {
299             return real_decoder_factory->IsSupportedDecoder(format);
300           }));
301   EXPECT_CALL(*mock_decoder_factory, MakeAudioDecoderMock(_, _, _))
302       .Times(AtLeast(2))
303       .WillRepeatedly(
304           Invoke([real_decoder_factory](
305                      const webrtc::SdpAudioFormat& format,
306                      absl::optional<webrtc::AudioCodecPairId> codec_pair_id,
307                      std::unique_ptr<webrtc::AudioDecoder>* return_value) {
308             auto real_decoder =
309                 real_decoder_factory->MakeAudioDecoder(format, codec_pair_id);
310             *return_value =
311                 real_decoder
312                     ? CreateForwardingMockDecoder(std::move(real_decoder))
313                     : nullptr;
314           }));
315   return mock_decoder_factory;
316 }
317 
318 struct AudioEncoderUnicornSparklesRainbow {
319   using Config = webrtc::AudioEncoderL16::Config;
SdpToConfig__anonbf9c431b0211::AudioEncoderUnicornSparklesRainbow320   static absl::optional<Config> SdpToConfig(webrtc::SdpAudioFormat format) {
321     if (absl::EqualsIgnoreCase(format.name, "UnicornSparklesRainbow")) {
322       const webrtc::SdpAudioFormat::Parameters expected_params = {
323           {"num_horns", "1"}};
324       EXPECT_EQ(expected_params, format.parameters);
325       format.parameters.clear();
326       format.name = "L16";
327       return webrtc::AudioEncoderL16::SdpToConfig(format);
328     } else {
329       return absl::nullopt;
330     }
331   }
AppendSupportedEncoders__anonbf9c431b0211::AudioEncoderUnicornSparklesRainbow332   static void AppendSupportedEncoders(
333       std::vector<webrtc::AudioCodecSpec>* specs) {
334     std::vector<webrtc::AudioCodecSpec> new_specs;
335     webrtc::AudioEncoderL16::AppendSupportedEncoders(&new_specs);
336     for (auto& spec : new_specs) {
337       spec.format.name = "UnicornSparklesRainbow";
338       EXPECT_TRUE(spec.format.parameters.empty());
339       spec.format.parameters.emplace("num_horns", "1");
340       specs->push_back(spec);
341     }
342   }
QueryAudioEncoder__anonbf9c431b0211::AudioEncoderUnicornSparklesRainbow343   static webrtc::AudioCodecInfo QueryAudioEncoder(const Config& config) {
344     return webrtc::AudioEncoderL16::QueryAudioEncoder(config);
345   }
MakeAudioEncoder__anonbf9c431b0211::AudioEncoderUnicornSparklesRainbow346   static std::unique_ptr<webrtc::AudioEncoder> MakeAudioEncoder(
347       const Config& config,
348       int payload_type,
349       absl::optional<webrtc::AudioCodecPairId> codec_pair_id = absl::nullopt) {
350     return webrtc::AudioEncoderL16::MakeAudioEncoder(config, payload_type,
351                                                      codec_pair_id);
352   }
353 };
354 
355 struct AudioDecoderUnicornSparklesRainbow {
356   using Config = webrtc::AudioDecoderL16::Config;
SdpToConfig__anonbf9c431b0211::AudioDecoderUnicornSparklesRainbow357   static absl::optional<Config> SdpToConfig(webrtc::SdpAudioFormat format) {
358     if (absl::EqualsIgnoreCase(format.name, "UnicornSparklesRainbow")) {
359       const webrtc::SdpAudioFormat::Parameters expected_params = {
360           {"num_horns", "1"}};
361       EXPECT_EQ(expected_params, format.parameters);
362       format.parameters.clear();
363       format.name = "L16";
364       return webrtc::AudioDecoderL16::SdpToConfig(format);
365     } else {
366       return absl::nullopt;
367     }
368   }
AppendSupportedDecoders__anonbf9c431b0211::AudioDecoderUnicornSparklesRainbow369   static void AppendSupportedDecoders(
370       std::vector<webrtc::AudioCodecSpec>* specs) {
371     std::vector<webrtc::AudioCodecSpec> new_specs;
372     webrtc::AudioDecoderL16::AppendSupportedDecoders(&new_specs);
373     for (auto& spec : new_specs) {
374       spec.format.name = "UnicornSparklesRainbow";
375       EXPECT_TRUE(spec.format.parameters.empty());
376       spec.format.parameters.emplace("num_horns", "1");
377       specs->push_back(spec);
378     }
379   }
MakeAudioDecoder__anonbf9c431b0211::AudioDecoderUnicornSparklesRainbow380   static std::unique_ptr<webrtc::AudioDecoder> MakeAudioDecoder(
381       const Config& config,
382       absl::optional<webrtc::AudioCodecPairId> codec_pair_id = absl::nullopt) {
383     return webrtc::AudioDecoderL16::MakeAudioDecoder(config, codec_pair_id);
384   }
385 };
386 
387 }  // namespace
388 
TEST_P(PeerConnectionEndToEndTest,Call)389 TEST_P(PeerConnectionEndToEndTest, Call) {
390   rtc::scoped_refptr<webrtc::AudioDecoderFactory> real_decoder_factory =
391       webrtc::CreateOpusAudioDecoderFactory();
392   CreatePcs(webrtc::CreateOpusAudioEncoderFactory(),
393             CreateForwardingMockDecoderFactory(real_decoder_factory.get()));
394   GetAndAddUserMedia();
395   Negotiate();
396   WaitForCallEstablished();
397 }
398 
399 #if defined(IS_FUCHSIA)
TEST_P(PeerConnectionEndToEndTest,CallWithSdesKeyNegotiation)400 TEST_P(PeerConnectionEndToEndTest, CallWithSdesKeyNegotiation) {
401   config_.enable_dtls_srtp = false;
402   CreatePcs(webrtc::CreateOpusAudioEncoderFactory(),
403             webrtc::CreateOpusAudioDecoderFactory());
404   GetAndAddUserMedia();
405   Negotiate();
406   WaitForCallEstablished();
407 }
408 #endif
409 
TEST_P(PeerConnectionEndToEndTest,CallWithCustomCodec)410 TEST_P(PeerConnectionEndToEndTest, CallWithCustomCodec) {
411   class IdLoggingAudioEncoderFactory : public webrtc::AudioEncoderFactory {
412    public:
413     IdLoggingAudioEncoderFactory(
414         rtc::scoped_refptr<AudioEncoderFactory> real_factory,
415         std::vector<webrtc::AudioCodecPairId>* const codec_ids)
416         : fact_(real_factory), codec_ids_(codec_ids) {}
417     std::vector<webrtc::AudioCodecSpec> GetSupportedEncoders() override {
418       return fact_->GetSupportedEncoders();
419     }
420     absl::optional<webrtc::AudioCodecInfo> QueryAudioEncoder(
421         const webrtc::SdpAudioFormat& format) override {
422       return fact_->QueryAudioEncoder(format);
423     }
424     std::unique_ptr<webrtc::AudioEncoder> MakeAudioEncoder(
425         int payload_type,
426         const webrtc::SdpAudioFormat& format,
427         absl::optional<webrtc::AudioCodecPairId> codec_pair_id) override {
428       EXPECT_TRUE(codec_pair_id.has_value());
429       codec_ids_->push_back(*codec_pair_id);
430       return fact_->MakeAudioEncoder(payload_type, format, codec_pair_id);
431     }
432 
433    private:
434     const rtc::scoped_refptr<webrtc::AudioEncoderFactory> fact_;
435     std::vector<webrtc::AudioCodecPairId>* const codec_ids_;
436   };
437 
438   class IdLoggingAudioDecoderFactory : public webrtc::AudioDecoderFactory {
439    public:
440     IdLoggingAudioDecoderFactory(
441         rtc::scoped_refptr<AudioDecoderFactory> real_factory,
442         std::vector<webrtc::AudioCodecPairId>* const codec_ids)
443         : fact_(real_factory), codec_ids_(codec_ids) {}
444     std::vector<webrtc::AudioCodecSpec> GetSupportedDecoders() override {
445       return fact_->GetSupportedDecoders();
446     }
447     bool IsSupportedDecoder(const webrtc::SdpAudioFormat& format) override {
448       return fact_->IsSupportedDecoder(format);
449     }
450     std::unique_ptr<webrtc::AudioDecoder> MakeAudioDecoder(
451         const webrtc::SdpAudioFormat& format,
452         absl::optional<webrtc::AudioCodecPairId> codec_pair_id) override {
453       EXPECT_TRUE(codec_pair_id.has_value());
454       codec_ids_->push_back(*codec_pair_id);
455       return fact_->MakeAudioDecoder(format, codec_pair_id);
456     }
457 
458    private:
459     const rtc::scoped_refptr<webrtc::AudioDecoderFactory> fact_;
460     std::vector<webrtc::AudioCodecPairId>* const codec_ids_;
461   };
462 
463   std::vector<webrtc::AudioCodecPairId> encoder_id1, encoder_id2, decoder_id1,
464       decoder_id2;
465   CreatePcs(rtc::make_ref_counted<IdLoggingAudioEncoderFactory>(
466                 webrtc::CreateAudioEncoderFactory<
467                     AudioEncoderUnicornSparklesRainbow>(),
468                 &encoder_id1),
469             rtc::make_ref_counted<IdLoggingAudioDecoderFactory>(
470                 webrtc::CreateAudioDecoderFactory<
471                     AudioDecoderUnicornSparklesRainbow>(),
472                 &decoder_id1),
473             rtc::make_ref_counted<IdLoggingAudioEncoderFactory>(
474                 webrtc::CreateAudioEncoderFactory<
475                     AudioEncoderUnicornSparklesRainbow>(),
476                 &encoder_id2),
477             rtc::make_ref_counted<IdLoggingAudioDecoderFactory>(
478                 webrtc::CreateAudioDecoderFactory<
479                     AudioDecoderUnicornSparklesRainbow>(),
480                 &decoder_id2));
481   GetAndAddUserMedia();
482   Negotiate();
483   WaitForCallEstablished();
484 
485   // Each codec factory has been used to create one codec. The first pair got
486   // the same ID because they were passed to the same PeerConnectionFactory,
487   // and the second pair got the same ID---but these two IDs are not equal,
488   // because each PeerConnectionFactory has its own ID.
489   EXPECT_EQ(1U, encoder_id1.size());
490   EXPECT_EQ(1U, encoder_id2.size());
491   EXPECT_EQ(encoder_id1, decoder_id1);
492   EXPECT_EQ(encoder_id2, decoder_id2);
493   EXPECT_NE(encoder_id1, encoder_id2);
494 }
495 
496 #ifdef WEBRTC_HAVE_SCTP
497 // Verifies that a DataChannel created before the negotiation can transition to
498 // "OPEN" and transfer data.
TEST_P(PeerConnectionEndToEndTest,CreateDataChannelBeforeNegotiate)499 TEST_P(PeerConnectionEndToEndTest, CreateDataChannelBeforeNegotiate) {
500   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
501             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
502 
503   webrtc::DataChannelInit init;
504   rtc::scoped_refptr<DataChannelInterface> caller_dc(
505       caller_->CreateDataChannel("data", init));
506   rtc::scoped_refptr<DataChannelInterface> callee_dc(
507       callee_->CreateDataChannel("data", init));
508 
509   Negotiate();
510   WaitForConnection();
511 
512   WaitForDataChannelsToOpen(caller_dc.get(), callee_signaled_data_channels_, 0);
513   WaitForDataChannelsToOpen(callee_dc.get(), caller_signaled_data_channels_, 0);
514 
515   TestDataChannelSendAndReceive(caller_dc.get(),
516                                 callee_signaled_data_channels_[0].get());
517   TestDataChannelSendAndReceive(callee_dc.get(),
518                                 caller_signaled_data_channels_[0].get());
519 
520   CloseDataChannels(caller_dc.get(), callee_signaled_data_channels_, 0);
521   CloseDataChannels(callee_dc.get(), caller_signaled_data_channels_, 0);
522 }
523 
524 // Verifies that a DataChannel created after the negotiation can transition to
525 // "OPEN" and transfer data.
TEST_P(PeerConnectionEndToEndTest,CreateDataChannelAfterNegotiate)526 TEST_P(PeerConnectionEndToEndTest, CreateDataChannelAfterNegotiate) {
527   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
528             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
529 
530   webrtc::DataChannelInit init;
531 
532   // This DataChannel is for creating the data content in the negotiation.
533   rtc::scoped_refptr<DataChannelInterface> dummy(
534       caller_->CreateDataChannel("data", init));
535   Negotiate();
536   WaitForConnection();
537 
538   // Wait for the data channel created pre-negotiation to be opened.
539   WaitForDataChannelsToOpen(dummy.get(), callee_signaled_data_channels_, 0);
540 
541   // Create new DataChannels after the negotiation and verify their states.
542   rtc::scoped_refptr<DataChannelInterface> caller_dc(
543       caller_->CreateDataChannel("hello", init));
544   rtc::scoped_refptr<DataChannelInterface> callee_dc(
545       callee_->CreateDataChannel("hello", init));
546 
547   WaitForDataChannelsToOpen(caller_dc.get(), callee_signaled_data_channels_, 1);
548   WaitForDataChannelsToOpen(callee_dc.get(), caller_signaled_data_channels_, 0);
549 
550   TestDataChannelSendAndReceive(caller_dc.get(),
551                                 callee_signaled_data_channels_[1].get());
552   TestDataChannelSendAndReceive(callee_dc.get(),
553                                 caller_signaled_data_channels_[0].get());
554 
555   CloseDataChannels(caller_dc.get(), callee_signaled_data_channels_, 1);
556   CloseDataChannels(callee_dc.get(), caller_signaled_data_channels_, 0);
557 }
558 
559 // Verifies that a DataChannel created can transfer large messages.
TEST_P(PeerConnectionEndToEndTest,CreateDataChannelLargeTransfer)560 TEST_P(PeerConnectionEndToEndTest, CreateDataChannelLargeTransfer) {
561   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
562             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
563 
564   webrtc::DataChannelInit init;
565 
566   // This DataChannel is for creating the data content in the negotiation.
567   rtc::scoped_refptr<DataChannelInterface> dummy(
568       caller_->CreateDataChannel("data", init));
569   Negotiate();
570   WaitForConnection();
571 
572   // Wait for the data channel created pre-negotiation to be opened.
573   WaitForDataChannelsToOpen(dummy.get(), callee_signaled_data_channels_, 0);
574 
575   // Create new DataChannels after the negotiation and verify their states.
576   rtc::scoped_refptr<DataChannelInterface> caller_dc(
577       caller_->CreateDataChannel("hello", init));
578   rtc::scoped_refptr<DataChannelInterface> callee_dc(
579       callee_->CreateDataChannel("hello", init));
580 
581   WaitForDataChannelsToOpen(caller_dc.get(), callee_signaled_data_channels_, 1);
582   WaitForDataChannelsToOpen(callee_dc.get(), caller_signaled_data_channels_, 0);
583 
584   TestDataChannelSendAndReceive(
585       caller_dc.get(), callee_signaled_data_channels_[1].get(), 256 * 1024);
586   TestDataChannelSendAndReceive(
587       callee_dc.get(), caller_signaled_data_channels_[0].get(), 256 * 1024);
588 
589   CloseDataChannels(caller_dc.get(), callee_signaled_data_channels_, 1);
590   CloseDataChannels(callee_dc.get(), caller_signaled_data_channels_, 0);
591 }
592 
593 // Verifies that DataChannel IDs are even/odd based on the DTLS roles.
TEST_P(PeerConnectionEndToEndTest,DataChannelIdAssignment)594 TEST_P(PeerConnectionEndToEndTest, DataChannelIdAssignment) {
595   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
596             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
597 
598   webrtc::DataChannelInit init;
599   rtc::scoped_refptr<DataChannelInterface> caller_dc_1(
600       caller_->CreateDataChannel("data", init));
601   rtc::scoped_refptr<DataChannelInterface> callee_dc_1(
602       callee_->CreateDataChannel("data", init));
603 
604   Negotiate();
605   WaitForConnection();
606 
607   EXPECT_EQ(1, caller_dc_1->id() % 2);
608   EXPECT_EQ(0, callee_dc_1->id() % 2);
609 
610   rtc::scoped_refptr<DataChannelInterface> caller_dc_2(
611       caller_->CreateDataChannel("data", init));
612   rtc::scoped_refptr<DataChannelInterface> callee_dc_2(
613       callee_->CreateDataChannel("data", init));
614 
615   EXPECT_EQ(1, caller_dc_2->id() % 2);
616   EXPECT_EQ(0, callee_dc_2->id() % 2);
617 }
618 
619 // Verifies that the message is received by the right remote DataChannel when
620 // there are multiple DataChannels.
TEST_P(PeerConnectionEndToEndTest,MessageTransferBetweenTwoPairsOfDataChannels)621 TEST_P(PeerConnectionEndToEndTest,
622        MessageTransferBetweenTwoPairsOfDataChannels) {
623   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
624             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
625 
626   webrtc::DataChannelInit init;
627 
628   rtc::scoped_refptr<DataChannelInterface> caller_dc_1(
629       caller_->CreateDataChannel("data", init));
630   rtc::scoped_refptr<DataChannelInterface> caller_dc_2(
631       caller_->CreateDataChannel("data", init));
632 
633   Negotiate();
634   WaitForConnection();
635   WaitForDataChannelsToOpen(caller_dc_1.get(), callee_signaled_data_channels_,
636                             0);
637   WaitForDataChannelsToOpen(caller_dc_2.get(), callee_signaled_data_channels_,
638                             1);
639 
640   std::unique_ptr<webrtc::MockDataChannelObserver> dc_1_observer(
641       new webrtc::MockDataChannelObserver(
642           callee_signaled_data_channels_[0].get()));
643 
644   std::unique_ptr<webrtc::MockDataChannelObserver> dc_2_observer(
645       new webrtc::MockDataChannelObserver(
646           callee_signaled_data_channels_[1].get()));
647 
648   const std::string message_1 = "hello 1";
649   const std::string message_2 = "hello 2";
650 
651   caller_dc_1->Send(webrtc::DataBuffer(message_1));
652   EXPECT_EQ_WAIT(message_1, dc_1_observer->last_message(), kMaxWait);
653 
654   caller_dc_2->Send(webrtc::DataBuffer(message_2));
655   EXPECT_EQ_WAIT(message_2, dc_2_observer->last_message(), kMaxWait);
656 
657   EXPECT_EQ(1U, dc_1_observer->received_message_count());
658   EXPECT_EQ(1U, dc_2_observer->received_message_count());
659 }
660 
661 // Verifies that a DataChannel added from an OPEN message functions after
662 // a channel has been previously closed (webrtc issue 3778).
663 // This previously failed because the new channel re-used the ID of the closed
664 // channel, and the closed channel was incorrectly still assigned to the ID.
TEST_P(PeerConnectionEndToEndTest,DataChannelFromOpenWorksAfterPreviousChannelClosed)665 TEST_P(PeerConnectionEndToEndTest,
666        DataChannelFromOpenWorksAfterPreviousChannelClosed) {
667   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
668             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
669 
670   webrtc::DataChannelInit init;
671   rtc::scoped_refptr<DataChannelInterface> caller_dc(
672       caller_->CreateDataChannel("data", init));
673 
674   Negotiate();
675   WaitForConnection();
676 
677   WaitForDataChannelsToOpen(caller_dc.get(), callee_signaled_data_channels_, 0);
678   int first_channel_id = caller_dc->id();
679   // Wait for the local side to say it's closed, but not the remote side.
680   // Previously, the channel on which Close is called reported being closed
681   // prematurely, and this caused issues; see bugs.webrtc.org/4453.
682   caller_dc->Close();
683   EXPECT_EQ_WAIT(DataChannelInterface::kClosed, caller_dc->state(), kMaxWait);
684 
685   // Create a new channel and ensure it works after closing the previous one.
686   caller_dc = caller_->CreateDataChannel("data2", init);
687   WaitForDataChannelsToOpen(caller_dc.get(), callee_signaled_data_channels_, 1);
688   // Since the second channel was created after the first finished closing, it
689   // should be able to re-use the first one's ID.
690   EXPECT_EQ(first_channel_id, caller_dc->id());
691   TestDataChannelSendAndReceive(caller_dc.get(),
692                                 callee_signaled_data_channels_[1].get());
693 
694   CloseDataChannels(caller_dc.get(), callee_signaled_data_channels_, 1);
695 }
696 
697 // Similar to the above test, but don't wait for the first channel to finish
698 // closing before creating the second one.
TEST_P(PeerConnectionEndToEndTest,DataChannelFromOpenWorksWhilePreviousChannelClosing)699 TEST_P(PeerConnectionEndToEndTest,
700        DataChannelFromOpenWorksWhilePreviousChannelClosing) {
701   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
702             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
703 
704   webrtc::DataChannelInit init;
705   rtc::scoped_refptr<DataChannelInterface> caller_dc(
706       caller_->CreateDataChannel("data", init));
707 
708   Negotiate();
709   WaitForConnection();
710 
711   WaitForDataChannelsToOpen(caller_dc.get(), callee_signaled_data_channels_, 0);
712   int first_channel_id = caller_dc->id();
713   caller_dc->Close();
714 
715   // Immediately create a new channel, before waiting for the previous one to
716   // transition to "closed".
717   caller_dc = caller_->CreateDataChannel("data2", init);
718   WaitForDataChannelsToOpen(caller_dc.get(), callee_signaled_data_channels_, 1);
719   // Since the second channel was created while the first was still closing,
720   // it should have been assigned a different ID.
721   EXPECT_NE(first_channel_id, caller_dc->id());
722   TestDataChannelSendAndReceive(caller_dc.get(),
723                                 callee_signaled_data_channels_[1].get());
724 
725   CloseDataChannels(caller_dc.get(), callee_signaled_data_channels_, 1);
726 }
727 
728 // This tests that if a data channel is closed remotely while not referenced
729 // by the application (meaning only the PeerConnection contributes to its
730 // reference count), no memory access violation will occur.
731 // See: https://code.google.com/p/chromium/issues/detail?id=565048
TEST_P(PeerConnectionEndToEndTest,CloseDataChannelRemotelyWhileNotReferenced)732 TEST_P(PeerConnectionEndToEndTest, CloseDataChannelRemotelyWhileNotReferenced) {
733   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
734             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
735 
736   webrtc::DataChannelInit init;
737   rtc::scoped_refptr<DataChannelInterface> caller_dc(
738       caller_->CreateDataChannel("data", init));
739 
740   Negotiate();
741   WaitForConnection();
742 
743   WaitForDataChannelsToOpen(caller_dc.get(), callee_signaled_data_channels_, 0);
744   // This removes the reference to the remote data channel that we hold.
745   callee_signaled_data_channels_.clear();
746   caller_dc->Close();
747   EXPECT_EQ_WAIT(DataChannelInterface::kClosed, caller_dc->state(), kMaxWait);
748 
749   // Wait for a bit longer so the remote data channel will receive the
750   // close message and be destroyed.
751   rtc::Thread::Current()->ProcessMessages(100);
752 }
753 
754 // Test behavior of creating too many datachannels.
TEST_P(PeerConnectionEndToEndTest,TooManyDataChannelsOpenedBeforeConnecting)755 TEST_P(PeerConnectionEndToEndTest, TooManyDataChannelsOpenedBeforeConnecting) {
756   CreatePcs(webrtc::MockAudioEncoderFactory::CreateEmptyFactory(),
757             webrtc::MockAudioDecoderFactory::CreateEmptyFactory());
758 
759   webrtc::DataChannelInit init;
760   std::vector<rtc::scoped_refptr<DataChannelInterface>> channels;
761   for (int i = 0; i <= cricket::kMaxSctpStreams / 2; i++) {
762     rtc::scoped_refptr<DataChannelInterface> caller_dc(
763         caller_->CreateDataChannel("data", init));
764     channels.push_back(std::move(caller_dc));
765   }
766   Negotiate();
767   WaitForConnection();
768   EXPECT_EQ_WAIT(callee_signaled_data_channels_.size(),
769                  static_cast<size_t>(cricket::kMaxSctpStreams / 2), kMaxWait);
770   EXPECT_EQ(DataChannelInterface::kOpen,
771             channels[(cricket::kMaxSctpStreams / 2) - 1]->state());
772   EXPECT_EQ(DataChannelInterface::kClosed,
773             channels[cricket::kMaxSctpStreams / 2]->state());
774 }
775 
776 #endif  // WEBRTC_HAVE_SCTP
777 
TEST_P(PeerConnectionEndToEndTest,CanRestartIce)778 TEST_P(PeerConnectionEndToEndTest, CanRestartIce) {
779   rtc::scoped_refptr<webrtc::AudioDecoderFactory> real_decoder_factory =
780       webrtc::CreateOpusAudioDecoderFactory();
781   CreatePcs(webrtc::CreateOpusAudioEncoderFactory(),
782             CreateForwardingMockDecoderFactory(real_decoder_factory.get()));
783   GetAndAddUserMedia();
784   Negotiate();
785   WaitForCallEstablished();
786   // Cause ICE restart to be requested.
787   auto config = caller_->pc()->GetConfiguration();
788   ASSERT_NE(PeerConnectionInterface::kRelay, config.type);
789   config.type = PeerConnectionInterface::kRelay;
790   ASSERT_TRUE(caller_->pc()->SetConfiguration(config).ok());
791   // When solving https://crbug.com/webrtc/10504, all we need to check
792   // is that we do not crash. We should also be testing that restart happens.
793 }
794 
795 INSTANTIATE_TEST_SUITE_P(PeerConnectionEndToEndTest,
796                          PeerConnectionEndToEndTest,
797                          Values(SdpSemantics::kPlanB_DEPRECATED,
798                                 SdpSemantics::kUnifiedPlan));
799