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