Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / app / webrtc / peerconnection_unittest.cc
1 /*
2  * libjingle
3  * Copyright 2012, Google Inc.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *  1. Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *  2. Redistributions in binary form must reproduce the above copyright notice,
11  *     this list of conditions and the following disclaimer in the documentation
12  *     and/or other materials provided with the distribution.
13  *  3. The name of the author may not be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include <stdio.h>
29
30 #include <algorithm>
31 #include <list>
32 #include <map>
33 #include <vector>
34
35 #include "talk/app/webrtc/dtmfsender.h"
36 #include "talk/app/webrtc/fakeportallocatorfactory.h"
37 #include "talk/app/webrtc/localaudiosource.h"
38 #include "talk/app/webrtc/mediastreaminterface.h"
39 #include "talk/app/webrtc/peerconnectionfactory.h"
40 #include "talk/app/webrtc/peerconnectioninterface.h"
41 #include "talk/app/webrtc/test/fakeaudiocapturemodule.h"
42 #include "talk/app/webrtc/test/fakeconstraints.h"
43 #include "talk/app/webrtc/test/fakedtlsidentityservice.h"
44 #include "talk/app/webrtc/test/fakeperiodicvideocapturer.h"
45 #include "talk/app/webrtc/test/fakevideotrackrenderer.h"
46 #include "talk/app/webrtc/test/mockpeerconnectionobservers.h"
47 #include "talk/app/webrtc/videosourceinterface.h"
48 #include "talk/media/webrtc/fakewebrtcvideoengine.h"
49 #include "webrtc/p2p/base/constants.h"
50 #include "webrtc/p2p/base/sessiondescription.h"
51 #include "talk/session/media/mediasession.h"
52 #include "webrtc/base/gunit.h"
53 #include "webrtc/base/scoped_ptr.h"
54 #include "webrtc/base/ssladapter.h"
55 #include "webrtc/base/sslstreamadapter.h"
56 #include "webrtc/base/thread.h"
57
58 #define MAYBE_SKIP_TEST(feature)                    \
59   if (!(feature())) {                               \
60     LOG(LS_INFO) << "Feature disabled... skipping"; \
61     return;                                         \
62   }
63
64 using cricket::ContentInfo;
65 using cricket::FakeWebRtcVideoDecoder;
66 using cricket::FakeWebRtcVideoDecoderFactory;
67 using cricket::FakeWebRtcVideoEncoder;
68 using cricket::FakeWebRtcVideoEncoderFactory;
69 using cricket::MediaContentDescription;
70 using webrtc::DataBuffer;
71 using webrtc::DataChannelInterface;
72 using webrtc::DtmfSender;
73 using webrtc::DtmfSenderInterface;
74 using webrtc::DtmfSenderObserverInterface;
75 using webrtc::FakeConstraints;
76 using webrtc::MediaConstraintsInterface;
77 using webrtc::MediaStreamTrackInterface;
78 using webrtc::MockCreateSessionDescriptionObserver;
79 using webrtc::MockDataChannelObserver;
80 using webrtc::MockSetSessionDescriptionObserver;
81 using webrtc::MockStatsObserver;
82 using webrtc::PeerConnectionInterface;
83 using webrtc::SessionDescriptionInterface;
84 using webrtc::StreamCollectionInterface;
85
86 static const int kMaxWaitMs = 2000;
87 // Disable for TSan v2, see
88 // https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
89 // This declaration is also #ifdef'd as it causes uninitialized-variable
90 // warnings.
91 #if !defined(THREAD_SANITIZER)
92 static const int kMaxWaitForStatsMs = 3000;
93 static const int kMaxWaitForRembMs = 5000;
94 #endif
95 static const int kMaxWaitForFramesMs = 10000;
96 static const int kEndAudioFrameCount = 3;
97 static const int kEndVideoFrameCount = 3;
98
99 static const char kStreamLabelBase[] = "stream_label";
100 static const char kVideoTrackLabelBase[] = "video_track";
101 static const char kAudioTrackLabelBase[] = "audio_track";
102 static const char kDataChannelLabel[] = "data_channel";
103
104 static void RemoveLinesFromSdp(const std::string& line_start,
105                                std::string* sdp) {
106   const char kSdpLineEnd[] = "\r\n";
107   size_t ssrc_pos = 0;
108   while ((ssrc_pos = sdp->find(line_start, ssrc_pos)) !=
109       std::string::npos) {
110     size_t end_ssrc = sdp->find(kSdpLineEnd, ssrc_pos);
111     sdp->erase(ssrc_pos, end_ssrc - ssrc_pos + strlen(kSdpLineEnd));
112   }
113 }
114
115 class SignalingMessageReceiver {
116  public:
117  protected:
118   SignalingMessageReceiver() {}
119   virtual ~SignalingMessageReceiver() {}
120 };
121
122 class JsepMessageReceiver : public SignalingMessageReceiver {
123  public:
124   virtual void ReceiveSdpMessage(const std::string& type,
125                                  std::string& msg) = 0;
126   virtual void ReceiveIceMessage(const std::string& sdp_mid,
127                                  int sdp_mline_index,
128                                  const std::string& msg) = 0;
129
130  protected:
131   JsepMessageReceiver() {}
132   virtual ~JsepMessageReceiver() {}
133 };
134
135 template <typename MessageReceiver>
136 class PeerConnectionTestClientBase
137     : public webrtc::PeerConnectionObserver,
138       public MessageReceiver {
139  public:
140   ~PeerConnectionTestClientBase() {
141     while (!fake_video_renderers_.empty()) {
142       RenderMap::iterator it = fake_video_renderers_.begin();
143       delete it->second;
144       fake_video_renderers_.erase(it);
145     }
146   }
147
148   virtual void Negotiate()  = 0;
149
150   virtual void Negotiate(bool audio, bool video)  = 0;
151
152   virtual void SetVideoConstraints(
153       const webrtc::FakeConstraints& video_constraint) {
154     video_constraints_ = video_constraint;
155   }
156
157   void AddMediaStream(bool audio, bool video) {
158     std::string stream_label = kStreamLabelBase +
159         rtc::ToString<int>(
160             static_cast<int>(peer_connection_->local_streams()->count()));
161     rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
162         peer_connection_factory_->CreateLocalMediaStream(stream_label);
163
164     if (audio && can_receive_audio()) {
165       FakeConstraints constraints;
166       // Disable highpass filter so that we can get all the test audio frames.
167       constraints.AddMandatory(
168           MediaConstraintsInterface::kHighpassFilter, false);
169       rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
170           peer_connection_factory_->CreateAudioSource(&constraints);
171       // TODO(perkj): Test audio source when it is implemented. Currently audio
172       // always use the default input.
173       std::string label = stream_label + kAudioTrackLabelBase;
174       rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
175           peer_connection_factory_->CreateAudioTrack(label, source));
176       stream->AddTrack(audio_track);
177     }
178     if (video && can_receive_video()) {
179       stream->AddTrack(CreateLocalVideoTrack(stream_label));
180     }
181
182     EXPECT_TRUE(peer_connection_->AddStream(stream));
183   }
184
185   size_t NumberOfLocalMediaStreams() {
186     return peer_connection_->local_streams()->count();
187   }
188
189   bool SessionActive() {
190     return peer_connection_->signaling_state() ==
191         webrtc::PeerConnectionInterface::kStable;
192   }
193
194   void set_signaling_message_receiver(
195       MessageReceiver* signaling_message_receiver) {
196     signaling_message_receiver_ = signaling_message_receiver;
197   }
198
199   void EnableVideoDecoderFactory() {
200     video_decoder_factory_enabled_ = true;
201     fake_video_decoder_factory_->AddSupportedVideoCodecType(
202         webrtc::kVideoCodecVP8);
203   }
204
205   bool AudioFramesReceivedCheck(int number_of_frames) const {
206     return number_of_frames <= fake_audio_capture_module_->frames_received();
207   }
208
209   bool VideoFramesReceivedCheck(int number_of_frames) {
210     if (video_decoder_factory_enabled_) {
211       const std::vector<FakeWebRtcVideoDecoder*>& decoders
212           = fake_video_decoder_factory_->decoders();
213       if (decoders.empty()) {
214         return number_of_frames <= 0;
215       }
216
217       for (std::vector<FakeWebRtcVideoDecoder*>::const_iterator
218            it = decoders.begin(); it != decoders.end(); ++it) {
219         if (number_of_frames > (*it)->GetNumFramesReceived()) {
220           return false;
221         }
222       }
223       return true;
224     } else {
225       if (fake_video_renderers_.empty()) {
226         return number_of_frames <= 0;
227       }
228
229       for (RenderMap::const_iterator it = fake_video_renderers_.begin();
230            it != fake_video_renderers_.end(); ++it) {
231         if (number_of_frames > it->second->num_rendered_frames()) {
232           return false;
233         }
234       }
235       return true;
236     }
237   }
238   // Verify the CreateDtmfSender interface
239   void VerifyDtmf() {
240     rtc::scoped_ptr<DummyDtmfObserver> observer(new DummyDtmfObserver());
241     rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender;
242
243     // We can't create a DTMF sender with an invalid audio track or a non local
244     // track.
245     EXPECT_TRUE(peer_connection_->CreateDtmfSender(NULL) == NULL);
246     rtc::scoped_refptr<webrtc::AudioTrackInterface> non_localtrack(
247         peer_connection_factory_->CreateAudioTrack("dummy_track",
248                                                    NULL));
249     EXPECT_TRUE(peer_connection_->CreateDtmfSender(non_localtrack) == NULL);
250
251     // We should be able to create a DTMF sender from a local track.
252     webrtc::AudioTrackInterface* localtrack =
253         peer_connection_->local_streams()->at(0)->GetAudioTracks()[0];
254     dtmf_sender = peer_connection_->CreateDtmfSender(localtrack);
255     EXPECT_TRUE(dtmf_sender.get() != NULL);
256     dtmf_sender->RegisterObserver(observer.get());
257
258     // Test the DtmfSender object just created.
259     EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
260     EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
261
262     // We don't need to verify that the DTMF tones are actually sent out because
263     // that is already covered by the tests of the lower level components.
264
265     EXPECT_TRUE_WAIT(observer->completed(), kMaxWaitMs);
266     std::vector<std::string> tones;
267     tones.push_back("1");
268     tones.push_back("a");
269     tones.push_back("");
270     observer->Verify(tones);
271
272     dtmf_sender->UnregisterObserver();
273   }
274
275   // Verifies that the SessionDescription have rejected the appropriate media
276   // content.
277   void VerifyRejectedMediaInSessionDescription() {
278     ASSERT_TRUE(peer_connection_->remote_description() != NULL);
279     ASSERT_TRUE(peer_connection_->local_description() != NULL);
280     const cricket::SessionDescription* remote_desc =
281         peer_connection_->remote_description()->description();
282     const cricket::SessionDescription* local_desc =
283         peer_connection_->local_description()->description();
284
285     const ContentInfo* remote_audio_content = GetFirstAudioContent(remote_desc);
286     if (remote_audio_content) {
287       const ContentInfo* audio_content =
288           GetFirstAudioContent(local_desc);
289       EXPECT_EQ(can_receive_audio(), !audio_content->rejected);
290     }
291
292     const ContentInfo* remote_video_content = GetFirstVideoContent(remote_desc);
293     if (remote_video_content) {
294       const ContentInfo* video_content =
295           GetFirstVideoContent(local_desc);
296       EXPECT_EQ(can_receive_video(), !video_content->rejected);
297     }
298   }
299
300   void SetExpectIceRestart(bool expect_restart) {
301     expect_ice_restart_ = expect_restart;
302   }
303
304   bool ExpectIceRestart() const { return expect_ice_restart_; }
305
306   void VerifyLocalIceUfragAndPassword() {
307     ASSERT_TRUE(peer_connection_->local_description() != NULL);
308     const cricket::SessionDescription* desc =
309         peer_connection_->local_description()->description();
310     const cricket::ContentInfos& contents = desc->contents();
311
312     for (size_t index = 0; index < contents.size(); ++index) {
313       if (contents[index].rejected)
314         continue;
315       const cricket::TransportDescription* transport_desc =
316           desc->GetTransportDescriptionByName(contents[index].name);
317
318       std::map<int, IceUfragPwdPair>::const_iterator ufragpair_it =
319           ice_ufrag_pwd_.find(static_cast<int>(index));
320       if (ufragpair_it == ice_ufrag_pwd_.end()) {
321         ASSERT_FALSE(ExpectIceRestart());
322         ice_ufrag_pwd_[static_cast<int>(index)] =
323             IceUfragPwdPair(transport_desc->ice_ufrag, transport_desc->ice_pwd);
324       } else if (ExpectIceRestart()) {
325         const IceUfragPwdPair& ufrag_pwd = ufragpair_it->second;
326         EXPECT_NE(ufrag_pwd.first, transport_desc->ice_ufrag);
327         EXPECT_NE(ufrag_pwd.second, transport_desc->ice_pwd);
328       } else {
329         const IceUfragPwdPair& ufrag_pwd = ufragpair_it->second;
330         EXPECT_EQ(ufrag_pwd.first, transport_desc->ice_ufrag);
331         EXPECT_EQ(ufrag_pwd.second, transport_desc->ice_pwd);
332       }
333     }
334   }
335
336   int GetAudioOutputLevelStats(webrtc::MediaStreamTrackInterface* track) {
337     rtc::scoped_refptr<MockStatsObserver>
338         observer(new rtc::RefCountedObject<MockStatsObserver>());
339     EXPECT_TRUE(peer_connection_->GetStats(
340         observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
341     EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
342     return observer->AudioOutputLevel();
343   }
344
345   int GetAudioInputLevelStats() {
346     rtc::scoped_refptr<MockStatsObserver>
347         observer(new rtc::RefCountedObject<MockStatsObserver>());
348     EXPECT_TRUE(peer_connection_->GetStats(
349         observer, NULL, PeerConnectionInterface::kStatsOutputLevelStandard));
350     EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
351     return observer->AudioInputLevel();
352   }
353
354   int GetBytesReceivedStats(webrtc::MediaStreamTrackInterface* track) {
355     rtc::scoped_refptr<MockStatsObserver>
356     observer(new rtc::RefCountedObject<MockStatsObserver>());
357     EXPECT_TRUE(peer_connection_->GetStats(
358         observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
359     EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
360     return observer->BytesReceived();
361   }
362
363   int GetBytesSentStats(webrtc::MediaStreamTrackInterface* track) {
364     rtc::scoped_refptr<MockStatsObserver>
365     observer(new rtc::RefCountedObject<MockStatsObserver>());
366     EXPECT_TRUE(peer_connection_->GetStats(
367         observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
368     EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
369     return observer->BytesSent();
370   }
371
372   int GetAvailableReceivedBandwidthStats() {
373     rtc::scoped_refptr<MockStatsObserver>
374         observer(new rtc::RefCountedObject<MockStatsObserver>());
375     EXPECT_TRUE(peer_connection_->GetStats(
376         observer, NULL, PeerConnectionInterface::kStatsOutputLevelStandard));
377     EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
378     int bw = observer->AvailableReceiveBandwidth();
379     return bw;
380   }
381
382   int rendered_width() {
383     EXPECT_FALSE(fake_video_renderers_.empty());
384     return fake_video_renderers_.empty() ? 1 :
385         fake_video_renderers_.begin()->second->width();
386   }
387
388   int rendered_height() {
389     EXPECT_FALSE(fake_video_renderers_.empty());
390     return fake_video_renderers_.empty() ? 1 :
391         fake_video_renderers_.begin()->second->height();
392   }
393
394   size_t number_of_remote_streams() {
395     if (!pc())
396       return 0;
397     return pc()->remote_streams()->count();
398   }
399
400   StreamCollectionInterface* remote_streams() {
401     if (!pc()) {
402       ADD_FAILURE();
403       return NULL;
404     }
405     return pc()->remote_streams();
406   }
407
408   StreamCollectionInterface* local_streams() {
409     if (!pc()) {
410       ADD_FAILURE();
411       return NULL;
412     }
413     return pc()->local_streams();
414   }
415
416   webrtc::PeerConnectionInterface::SignalingState signaling_state() {
417     return pc()->signaling_state();
418   }
419
420   webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
421     return pc()->ice_connection_state();
422   }
423
424   webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
425     return pc()->ice_gathering_state();
426   }
427
428   // PeerConnectionObserver callbacks.
429   virtual void OnMessage(const std::string&) {}
430   virtual void OnSignalingMessage(const std::string& /*msg*/) {}
431   virtual void OnSignalingChange(
432       webrtc::PeerConnectionInterface::SignalingState new_state) {
433     EXPECT_EQ(peer_connection_->signaling_state(), new_state);
434   }
435   virtual void OnAddStream(webrtc::MediaStreamInterface* media_stream) {
436     for (size_t i = 0; i < media_stream->GetVideoTracks().size(); ++i) {
437       const std::string id = media_stream->GetVideoTracks()[i]->id();
438       ASSERT_TRUE(fake_video_renderers_.find(id) ==
439           fake_video_renderers_.end());
440       fake_video_renderers_[id] = new webrtc::FakeVideoTrackRenderer(
441           media_stream->GetVideoTracks()[i]);
442     }
443   }
444   virtual void OnRemoveStream(webrtc::MediaStreamInterface* media_stream) {}
445   virtual void OnRenegotiationNeeded() {}
446   virtual void OnIceConnectionChange(
447       webrtc::PeerConnectionInterface::IceConnectionState new_state) {
448     EXPECT_EQ(peer_connection_->ice_connection_state(), new_state);
449   }
450   virtual void OnIceGatheringChange(
451       webrtc::PeerConnectionInterface::IceGatheringState new_state) {
452     EXPECT_EQ(peer_connection_->ice_gathering_state(), new_state);
453   }
454   virtual void OnIceCandidate(
455       const webrtc::IceCandidateInterface* /*candidate*/) {}
456
457   webrtc::PeerConnectionInterface* pc() {
458     return peer_connection_.get();
459   }
460   void StopVideoCapturers() {
461     for (std::vector<cricket::VideoCapturer*>::iterator it =
462         video_capturers_.begin(); it != video_capturers_.end(); ++it) {
463       (*it)->Stop();
464     }
465   }
466
467  protected:
468   explicit PeerConnectionTestClientBase(const std::string& id)
469       : id_(id),
470         expect_ice_restart_(false),
471         fake_video_decoder_factory_(NULL),
472         fake_video_encoder_factory_(NULL),
473         video_decoder_factory_enabled_(false),
474         signaling_message_receiver_(NULL) {
475   }
476   bool Init(const MediaConstraintsInterface* constraints) {
477     EXPECT_TRUE(!peer_connection_);
478     EXPECT_TRUE(!peer_connection_factory_);
479     allocator_factory_ = webrtc::FakePortAllocatorFactory::Create();
480     if (!allocator_factory_) {
481       return false;
482     }
483     fake_audio_capture_module_ = FakeAudioCaptureModule::Create(
484         rtc::Thread::Current());
485
486     if (fake_audio_capture_module_ == NULL) {
487       return false;
488     }
489     fake_video_decoder_factory_ = new FakeWebRtcVideoDecoderFactory();
490     fake_video_encoder_factory_ = new FakeWebRtcVideoEncoderFactory();
491     peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
492         rtc::Thread::Current(), rtc::Thread::Current(),
493         fake_audio_capture_module_, fake_video_encoder_factory_,
494         fake_video_decoder_factory_);
495     if (!peer_connection_factory_) {
496       return false;
497     }
498     peer_connection_ = CreatePeerConnection(allocator_factory_.get(),
499                                             constraints);
500     return peer_connection_.get() != NULL;
501   }
502   virtual rtc::scoped_refptr<webrtc::PeerConnectionInterface>
503       CreatePeerConnection(webrtc::PortAllocatorFactoryInterface* factory,
504                            const MediaConstraintsInterface* constraints) = 0;
505   MessageReceiver* signaling_message_receiver() {
506     return signaling_message_receiver_;
507   }
508   webrtc::PeerConnectionFactoryInterface* peer_connection_factory() {
509     return peer_connection_factory_.get();
510   }
511
512   virtual bool can_receive_audio() = 0;
513   virtual bool can_receive_video() = 0;
514   const std::string& id() const { return id_; }
515
516  private:
517   class DummyDtmfObserver : public DtmfSenderObserverInterface {
518    public:
519     DummyDtmfObserver() : completed_(false) {}
520
521     // Implements DtmfSenderObserverInterface.
522     void OnToneChange(const std::string& tone) {
523       tones_.push_back(tone);
524       if (tone.empty()) {
525         completed_ = true;
526       }
527     }
528
529     void Verify(const std::vector<std::string>& tones) const {
530       ASSERT_TRUE(tones_.size() == tones.size());
531       EXPECT_TRUE(std::equal(tones.begin(), tones.end(), tones_.begin()));
532     }
533
534     bool completed() const { return completed_; }
535
536    private:
537     bool completed_;
538     std::vector<std::string> tones_;
539   };
540
541   rtc::scoped_refptr<webrtc::VideoTrackInterface>
542   CreateLocalVideoTrack(const std::string stream_label) {
543     // Set max frame rate to 10fps to reduce the risk of the tests to be flaky.
544     FakeConstraints source_constraints = video_constraints_;
545     source_constraints.SetMandatoryMaxFrameRate(10);
546
547     cricket::FakeVideoCapturer* fake_capturer =
548         new webrtc::FakePeriodicVideoCapturer();
549     video_capturers_.push_back(fake_capturer);
550     rtc::scoped_refptr<webrtc::VideoSourceInterface> source =
551         peer_connection_factory_->CreateVideoSource(
552             fake_capturer, &source_constraints);
553     std::string label = stream_label + kVideoTrackLabelBase;
554     return peer_connection_factory_->CreateVideoTrack(label, source);
555   }
556
557   std::string id_;
558
559   rtc::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
560       allocator_factory_;
561   rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
562   rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
563       peer_connection_factory_;
564
565   typedef std::pair<std::string, std::string> IceUfragPwdPair;
566   std::map<int, IceUfragPwdPair> ice_ufrag_pwd_;
567   bool expect_ice_restart_;
568
569   // Needed to keep track of number of frames send.
570   rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
571   // Needed to keep track of number of frames received.
572   typedef std::map<std::string, webrtc::FakeVideoTrackRenderer*> RenderMap;
573   RenderMap fake_video_renderers_;
574   // Needed to keep track of number of frames received when external decoder
575   // used.
576   FakeWebRtcVideoDecoderFactory* fake_video_decoder_factory_;
577   FakeWebRtcVideoEncoderFactory* fake_video_encoder_factory_;
578   bool video_decoder_factory_enabled_;
579   webrtc::FakeConstraints video_constraints_;
580
581   // For remote peer communication.
582   MessageReceiver* signaling_message_receiver_;
583
584   // Store references to the video capturers we've created, so that we can stop
585   // them, if required.
586   std::vector<cricket::VideoCapturer*> video_capturers_;
587 };
588
589 class JsepTestClient
590     : public PeerConnectionTestClientBase<JsepMessageReceiver> {
591  public:
592   static JsepTestClient* CreateClient(
593       const std::string& id,
594       const MediaConstraintsInterface* constraints) {
595     JsepTestClient* client(new JsepTestClient(id));
596     if (!client->Init(constraints)) {
597       delete client;
598       return NULL;
599     }
600     return client;
601   }
602   ~JsepTestClient() {}
603
604   virtual void Negotiate() {
605     Negotiate(true, true);
606   }
607   virtual void Negotiate(bool audio, bool video) {
608     rtc::scoped_ptr<SessionDescriptionInterface> offer;
609     ASSERT_TRUE(DoCreateOffer(offer.use()));
610
611     if (offer->description()->GetContentByName("audio")) {
612       offer->description()->GetContentByName("audio")->rejected = !audio;
613     }
614     if (offer->description()->GetContentByName("video")) {
615       offer->description()->GetContentByName("video")->rejected = !video;
616     }
617
618     std::string sdp;
619     EXPECT_TRUE(offer->ToString(&sdp));
620     EXPECT_TRUE(DoSetLocalDescription(offer.release()));
621     signaling_message_receiver()->ReceiveSdpMessage(
622         webrtc::SessionDescriptionInterface::kOffer, sdp);
623   }
624   // JsepMessageReceiver callback.
625   virtual void ReceiveSdpMessage(const std::string& type,
626                                  std::string& msg) {
627     FilterIncomingSdpMessage(&msg);
628     if (type == webrtc::SessionDescriptionInterface::kOffer) {
629       HandleIncomingOffer(msg);
630     } else {
631       HandleIncomingAnswer(msg);
632     }
633   }
634   // JsepMessageReceiver callback.
635   virtual void ReceiveIceMessage(const std::string& sdp_mid,
636                                  int sdp_mline_index,
637                                  const std::string& msg) {
638     LOG(INFO) << id() << "ReceiveIceMessage";
639     rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate(
640         webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, NULL));
641     EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
642   }
643   // Implements PeerConnectionObserver functions needed by Jsep.
644   virtual void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) {
645     LOG(INFO) << id() << "OnIceCandidate";
646
647     std::string ice_sdp;
648     EXPECT_TRUE(candidate->ToString(&ice_sdp));
649     if (signaling_message_receiver() == NULL) {
650       // Remote party may be deleted.
651       return;
652     }
653     signaling_message_receiver()->ReceiveIceMessage(candidate->sdp_mid(),
654         candidate->sdp_mline_index(), ice_sdp);
655   }
656
657   void IceRestart() {
658     session_description_constraints_.SetMandatoryIceRestart(true);
659     SetExpectIceRestart(true);
660   }
661
662   void SetReceiveAudioVideo(bool audio, bool video) {
663     SetReceiveAudio(audio);
664     SetReceiveVideo(video);
665     ASSERT_EQ(audio, can_receive_audio());
666     ASSERT_EQ(video, can_receive_video());
667   }
668
669   void SetReceiveAudio(bool audio) {
670     if (audio && can_receive_audio())
671       return;
672     session_description_constraints_.SetMandatoryReceiveAudio(audio);
673   }
674
675   void SetReceiveVideo(bool video) {
676     if (video && can_receive_video())
677       return;
678     session_description_constraints_.SetMandatoryReceiveVideo(video);
679   }
680
681   void RemoveMsidFromReceivedSdp(bool remove) {
682     remove_msid_ = remove;
683   }
684
685   void RemoveSdesCryptoFromReceivedSdp(bool remove) {
686     remove_sdes_ = remove;
687   }
688
689   void RemoveBundleFromReceivedSdp(bool remove) {
690     remove_bundle_ = remove;
691   }
692
693   virtual bool can_receive_audio() {
694     bool value;
695     if (webrtc::FindConstraint(&session_description_constraints_,
696         MediaConstraintsInterface::kOfferToReceiveAudio, &value, NULL)) {
697       return value;
698     }
699     return true;
700   }
701
702   virtual bool can_receive_video() {
703     bool value;
704     if (webrtc::FindConstraint(&session_description_constraints_,
705         MediaConstraintsInterface::kOfferToReceiveVideo, &value, NULL)) {
706       return value;
707     }
708     return true;
709   }
710
711   virtual void OnIceComplete() {
712     LOG(INFO) << id() << "OnIceComplete";
713   }
714
715   virtual void OnDataChannel(DataChannelInterface* data_channel) {
716     LOG(INFO) << id() << "OnDataChannel";
717     data_channel_ = data_channel;
718     data_observer_.reset(new MockDataChannelObserver(data_channel));
719   }
720
721   void CreateDataChannel() {
722     data_channel_ = pc()->CreateDataChannel(kDataChannelLabel,
723                                                          NULL);
724     ASSERT_TRUE(data_channel_.get() != NULL);
725     data_observer_.reset(new MockDataChannelObserver(data_channel_));
726   }
727
728   DataChannelInterface* data_channel() { return data_channel_; }
729   const MockDataChannelObserver* data_observer() const {
730     return data_observer_.get();
731   }
732
733  protected:
734   explicit JsepTestClient(const std::string& id)
735       : PeerConnectionTestClientBase<JsepMessageReceiver>(id),
736         remove_msid_(false),
737         remove_bundle_(false),
738         remove_sdes_(false) {
739   }
740
741   virtual rtc::scoped_refptr<webrtc::PeerConnectionInterface>
742       CreatePeerConnection(webrtc::PortAllocatorFactoryInterface* factory,
743                            const MediaConstraintsInterface* constraints) {
744     // CreatePeerConnection with IceServers.
745     webrtc::PeerConnectionInterface::IceServers ice_servers;
746     webrtc::PeerConnectionInterface::IceServer ice_server;
747     ice_server.uri = "stun:stun.l.google.com:19302";
748     ice_servers.push_back(ice_server);
749
750     FakeIdentityService* dtls_service =
751         rtc::SSLStreamAdapter::HaveDtlsSrtp() ?
752             new FakeIdentityService() : NULL;
753     return peer_connection_factory()->CreatePeerConnection(
754         ice_servers, constraints, factory, dtls_service, this);
755   }
756
757   void HandleIncomingOffer(const std::string& msg) {
758     LOG(INFO) << id() << "HandleIncomingOffer ";
759     if (NumberOfLocalMediaStreams() == 0) {
760       // If we are not sending any streams ourselves it is time to add some.
761       AddMediaStream(true, true);
762     }
763     rtc::scoped_ptr<SessionDescriptionInterface> desc(
764          webrtc::CreateSessionDescription("offer", msg, NULL));
765     EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
766     rtc::scoped_ptr<SessionDescriptionInterface> answer;
767     EXPECT_TRUE(DoCreateAnswer(answer.use()));
768     std::string sdp;
769     EXPECT_TRUE(answer->ToString(&sdp));
770     EXPECT_TRUE(DoSetLocalDescription(answer.release()));
771     if (signaling_message_receiver()) {
772       signaling_message_receiver()->ReceiveSdpMessage(
773           webrtc::SessionDescriptionInterface::kAnswer, sdp);
774     }
775   }
776
777   void HandleIncomingAnswer(const std::string& msg) {
778     LOG(INFO) << id() << "HandleIncomingAnswer";
779     rtc::scoped_ptr<SessionDescriptionInterface> desc(
780          webrtc::CreateSessionDescription("answer", msg, NULL));
781     EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
782   }
783
784   bool DoCreateOfferAnswer(SessionDescriptionInterface** desc,
785                            bool offer) {
786     rtc::scoped_refptr<MockCreateSessionDescriptionObserver>
787         observer(new rtc::RefCountedObject<
788             MockCreateSessionDescriptionObserver>());
789     if (offer) {
790       pc()->CreateOffer(observer, &session_description_constraints_);
791     } else {
792       pc()->CreateAnswer(observer, &session_description_constraints_);
793     }
794     EXPECT_EQ_WAIT(true, observer->called(), kMaxWaitMs);
795     *desc = observer->release_desc();
796     if (observer->result() && ExpectIceRestart()) {
797       EXPECT_EQ(0u, (*desc)->candidates(0)->count());
798     }
799     return observer->result();
800   }
801
802   bool DoCreateOffer(SessionDescriptionInterface** desc) {
803     return DoCreateOfferAnswer(desc, true);
804   }
805
806   bool DoCreateAnswer(SessionDescriptionInterface** desc) {
807     return DoCreateOfferAnswer(desc, false);
808   }
809
810   bool DoSetLocalDescription(SessionDescriptionInterface* desc) {
811     rtc::scoped_refptr<MockSetSessionDescriptionObserver>
812             observer(new rtc::RefCountedObject<
813                 MockSetSessionDescriptionObserver>());
814     LOG(INFO) << id() << "SetLocalDescription ";
815     pc()->SetLocalDescription(observer, desc);
816     // Ignore the observer result. If we wait for the result with
817     // EXPECT_TRUE_WAIT, local ice candidates might be sent to the remote peer
818     // before the offer which is an error.
819     // The reason is that EXPECT_TRUE_WAIT uses
820     // rtc::Thread::Current()->ProcessMessages(1);
821     // ProcessMessages waits at least 1ms but processes all messages before
822     // returning. Since this test is synchronous and send messages to the remote
823     // peer whenever a callback is invoked, this can lead to messages being
824     // sent to the remote peer in the wrong order.
825     // TODO(perkj): Find a way to check the result without risking that the
826     // order of sent messages are changed. Ex- by posting all messages that are
827     // sent to the remote peer.
828     return true;
829   }
830
831   bool DoSetRemoteDescription(SessionDescriptionInterface* desc) {
832     rtc::scoped_refptr<MockSetSessionDescriptionObserver>
833         observer(new rtc::RefCountedObject<
834             MockSetSessionDescriptionObserver>());
835     LOG(INFO) << id() << "SetRemoteDescription ";
836     pc()->SetRemoteDescription(observer, desc);
837     EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
838     return observer->result();
839   }
840
841   // This modifies all received SDP messages before they are processed.
842   void FilterIncomingSdpMessage(std::string* sdp) {
843     if (remove_msid_) {
844       const char kSdpSsrcAttribute[] = "a=ssrc:";
845       RemoveLinesFromSdp(kSdpSsrcAttribute, sdp);
846       const char kSdpMsidSupportedAttribute[] = "a=msid-semantic:";
847       RemoveLinesFromSdp(kSdpMsidSupportedAttribute, sdp);
848     }
849     if (remove_bundle_) {
850       const char kSdpBundleAttribute[] = "a=group:BUNDLE";
851       RemoveLinesFromSdp(kSdpBundleAttribute, sdp);
852     }
853     if (remove_sdes_) {
854       const char kSdpSdesCryptoAttribute[] = "a=crypto";
855       RemoveLinesFromSdp(kSdpSdesCryptoAttribute, sdp);
856     }
857   }
858
859  private:
860   webrtc::FakeConstraints session_description_constraints_;
861   bool remove_msid_;  // True if MSID should be removed in received SDP.
862   bool remove_bundle_;  // True if bundle should be removed in received SDP.
863   bool remove_sdes_;  // True if a=crypto should be removed in received SDP.
864
865   rtc::scoped_refptr<DataChannelInterface> data_channel_;
866   rtc::scoped_ptr<MockDataChannelObserver> data_observer_;
867 };
868
869 template <typename SignalingClass>
870 class P2PTestConductor : public testing::Test {
871  public:
872   bool SessionActive() {
873     return initiating_client_->SessionActive() &&
874         receiving_client_->SessionActive();
875   }
876   // Return true if the number of frames provided have been received or it is
877   // known that that will never occur (e.g. no frames will be sent or
878   // captured).
879   bool FramesNotPending(int audio_frames_to_receive,
880                         int video_frames_to_receive) {
881     return VideoFramesReceivedCheck(video_frames_to_receive) &&
882         AudioFramesReceivedCheck(audio_frames_to_receive);
883   }
884   bool AudioFramesReceivedCheck(int frames_received) {
885     return initiating_client_->AudioFramesReceivedCheck(frames_received) &&
886         receiving_client_->AudioFramesReceivedCheck(frames_received);
887   }
888   bool VideoFramesReceivedCheck(int frames_received) {
889     return initiating_client_->VideoFramesReceivedCheck(frames_received) &&
890         receiving_client_->VideoFramesReceivedCheck(frames_received);
891   }
892   void VerifyDtmf() {
893     initiating_client_->VerifyDtmf();
894     receiving_client_->VerifyDtmf();
895   }
896
897   void TestUpdateOfferWithRejectedContent() {
898     initiating_client_->Negotiate(true, false);
899     EXPECT_TRUE_WAIT(
900         FramesNotPending(kEndAudioFrameCount * 2, kEndVideoFrameCount),
901         kMaxWaitForFramesMs);
902     // There shouldn't be any more video frame after the new offer is
903     // negotiated.
904     EXPECT_FALSE(VideoFramesReceivedCheck(kEndVideoFrameCount + 1));
905   }
906
907   void VerifyRenderedSize(int width, int height) {
908     EXPECT_EQ(width, receiving_client()->rendered_width());
909     EXPECT_EQ(height, receiving_client()->rendered_height());
910     EXPECT_EQ(width, initializing_client()->rendered_width());
911     EXPECT_EQ(height, initializing_client()->rendered_height());
912   }
913
914   void VerifySessionDescriptions() {
915     initiating_client_->VerifyRejectedMediaInSessionDescription();
916     receiving_client_->VerifyRejectedMediaInSessionDescription();
917     initiating_client_->VerifyLocalIceUfragAndPassword();
918     receiving_client_->VerifyLocalIceUfragAndPassword();
919   }
920
921   ~P2PTestConductor() {
922     if (initiating_client_) {
923       initiating_client_->set_signaling_message_receiver(NULL);
924     }
925     if (receiving_client_) {
926       receiving_client_->set_signaling_message_receiver(NULL);
927     }
928   }
929
930   bool CreateTestClients() {
931     return CreateTestClients(NULL, NULL);
932   }
933
934   bool CreateTestClients(MediaConstraintsInterface* init_constraints,
935                          MediaConstraintsInterface* recv_constraints) {
936     initiating_client_.reset(SignalingClass::CreateClient("Caller: ",
937                                                           init_constraints));
938     receiving_client_.reset(SignalingClass::CreateClient("Callee: ",
939                                                          recv_constraints));
940     if (!initiating_client_ || !receiving_client_) {
941       return false;
942     }
943     initiating_client_->set_signaling_message_receiver(receiving_client_.get());
944     receiving_client_->set_signaling_message_receiver(initiating_client_.get());
945     return true;
946   }
947
948   void SetVideoConstraints(const webrtc::FakeConstraints& init_constraints,
949                            const webrtc::FakeConstraints& recv_constraints) {
950     initiating_client_->SetVideoConstraints(init_constraints);
951     receiving_client_->SetVideoConstraints(recv_constraints);
952   }
953
954   void EnableVideoDecoderFactory() {
955     initiating_client_->EnableVideoDecoderFactory();
956     receiving_client_->EnableVideoDecoderFactory();
957   }
958
959   // This test sets up a call between two parties. Both parties send static
960   // frames to each other. Once the test is finished the number of sent frames
961   // is compared to the number of received frames.
962   void LocalP2PTest() {
963     if (initiating_client_->NumberOfLocalMediaStreams() == 0) {
964       initiating_client_->AddMediaStream(true, true);
965     }
966     initiating_client_->Negotiate();
967     const int kMaxWaitForActivationMs = 5000;
968     // Assert true is used here since next tests are guaranteed to fail and
969     // would eat up 5 seconds.
970     ASSERT_TRUE_WAIT(SessionActive(), kMaxWaitForActivationMs);
971     VerifySessionDescriptions();
972
973
974     int audio_frame_count = kEndAudioFrameCount;
975     // TODO(ronghuawu): Add test to cover the case of sendonly and recvonly.
976     if (!initiating_client_->can_receive_audio() ||
977         !receiving_client_->can_receive_audio()) {
978       audio_frame_count = -1;
979     }
980     int video_frame_count = kEndVideoFrameCount;
981     if (!initiating_client_->can_receive_video() ||
982         !receiving_client_->can_receive_video()) {
983       video_frame_count = -1;
984     }
985
986     if (audio_frame_count != -1 || video_frame_count != -1) {
987       // Audio or video is expected to flow, so both clients should reach the
988       // Connected state, and the offerer (ICE controller) should proceed to
989       // Completed.
990       // Note: These tests have been observed to fail under heavy load at
991       // shorter timeouts, so they may be flaky.
992       EXPECT_EQ_WAIT(
993           webrtc::PeerConnectionInterface::kIceConnectionCompleted,
994           initiating_client_->ice_connection_state(),
995           kMaxWaitForFramesMs);
996       EXPECT_EQ_WAIT(
997           webrtc::PeerConnectionInterface::kIceConnectionConnected,
998           receiving_client_->ice_connection_state(),
999           kMaxWaitForFramesMs);
1000     }
1001
1002     if (initiating_client_->can_receive_audio() ||
1003         initiating_client_->can_receive_video()) {
1004       // The initiating client can receive media, so it must produce candidates
1005       // that will serve as destinations for that media.
1006       // TODO(bemasc): Understand why the state is not already Complete here, as
1007       // seems to be the case for the receiving client. This may indicate a bug
1008       // in the ICE gathering system.
1009       EXPECT_NE(webrtc::PeerConnectionInterface::kIceGatheringNew,
1010                 initiating_client_->ice_gathering_state());
1011     }
1012     if (receiving_client_->can_receive_audio() ||
1013         receiving_client_->can_receive_video()) {
1014       EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
1015                      receiving_client_->ice_gathering_state(),
1016                      kMaxWaitForFramesMs);
1017     }
1018
1019     EXPECT_TRUE_WAIT(FramesNotPending(audio_frame_count, video_frame_count),
1020                      kMaxWaitForFramesMs);
1021   }
1022
1023   void SendRtpData(webrtc::DataChannelInterface* dc, const std::string& data) {
1024     // Messages may get lost on the unreliable DataChannel, so we send multiple
1025     // times to avoid test flakiness.
1026     static const size_t kSendAttempts = 5;
1027
1028     for (size_t i = 0; i < kSendAttempts; ++i) {
1029       dc->Send(DataBuffer(data));
1030     }
1031   }
1032
1033   // Wait until 'size' bytes of audio has been seen by the receiver, on the
1034   // first audio stream.
1035   void WaitForAudioData(int size) {
1036     const int kMaxWaitForAudioDataMs = 10000;
1037
1038     StreamCollectionInterface* local_streams =
1039         initializing_client()->local_streams();
1040     ASSERT_GT(local_streams->count(), 0u);
1041     ASSERT_GT(local_streams->at(0)->GetAudioTracks().size(), 0u);
1042     MediaStreamTrackInterface* local_audio_track =
1043         local_streams->at(0)->GetAudioTracks()[0];
1044
1045     // Wait until *any* audio has been received.
1046     EXPECT_TRUE_WAIT(
1047         receiving_client()->GetBytesReceivedStats(local_audio_track) > 0,
1048         kMaxWaitForAudioDataMs);
1049
1050     // Wait until 'size' number of bytes have been received.
1051     size += receiving_client()->GetBytesReceivedStats(local_audio_track);
1052     EXPECT_TRUE_WAIT(
1053         receiving_client()->GetBytesReceivedStats(local_audio_track) > size,
1054         kMaxWaitForAudioDataMs);
1055   }
1056
1057   SignalingClass* initializing_client() { return initiating_client_.get(); }
1058   SignalingClass* receiving_client() { return receiving_client_.get(); }
1059
1060  private:
1061   rtc::scoped_ptr<SignalingClass> initiating_client_;
1062   rtc::scoped_ptr<SignalingClass> receiving_client_;
1063 };
1064 typedef P2PTestConductor<JsepTestClient> JsepPeerConnectionP2PTestClient;
1065
1066 // Disable for TSan v2, see
1067 // https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
1068 #if !defined(THREAD_SANITIZER)
1069
1070 // This test sets up a Jsep call between two parties and test Dtmf.
1071 // TODO(holmer): Disabled due to sometimes crashing on buildbots.
1072 // See issue webrtc/2378.
1073 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestDtmf) {
1074   ASSERT_TRUE(CreateTestClients());
1075   LocalP2PTest();
1076   VerifyDtmf();
1077 }
1078
1079 // This test sets up a Jsep call between two parties and test that we can get a
1080 // video aspect ratio of 16:9.
1081 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTest16To9) {
1082   ASSERT_TRUE(CreateTestClients());
1083   FakeConstraints constraint;
1084   double requested_ratio = 640.0/360;
1085   constraint.SetMandatoryMinAspectRatio(requested_ratio);
1086   SetVideoConstraints(constraint, constraint);
1087   LocalP2PTest();
1088
1089   ASSERT_LE(0, initializing_client()->rendered_height());
1090   double initiating_video_ratio =
1091       static_cast<double>(initializing_client()->rendered_width()) /
1092       initializing_client()->rendered_height();
1093   EXPECT_LE(requested_ratio, initiating_video_ratio);
1094
1095   ASSERT_LE(0, receiving_client()->rendered_height());
1096   double receiving_video_ratio =
1097       static_cast<double>(receiving_client()->rendered_width()) /
1098       receiving_client()->rendered_height();
1099   EXPECT_LE(requested_ratio, receiving_video_ratio);
1100 }
1101
1102 // This test sets up a Jsep call between two parties and test that the
1103 // received video has a resolution of 1280*720.
1104 // TODO(mallinath): Enable when
1105 // http://code.google.com/p/webrtc/issues/detail?id=981 is fixed.
1106 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTest1280By720) {
1107   ASSERT_TRUE(CreateTestClients());
1108   FakeConstraints constraint;
1109   constraint.SetMandatoryMinWidth(1280);
1110   constraint.SetMandatoryMinHeight(720);
1111   SetVideoConstraints(constraint, constraint);
1112   LocalP2PTest();
1113   VerifyRenderedSize(1280, 720);
1114 }
1115
1116 // This test sets up a call between two endpoints that are configured to use
1117 // DTLS key agreement. As a result, DTLS is negotiated and used for transport.
1118 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDtls) {
1119   MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1120   FakeConstraints setup_constraints;
1121   setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1122                                  true);
1123   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1124   LocalP2PTest();
1125   VerifyRenderedSize(640, 480);
1126 }
1127
1128 // This test sets up a audio call initially and then upgrades to audio/video,
1129 // using DTLS.
1130 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDtlsRenegotiate) {
1131   MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1132   FakeConstraints setup_constraints;
1133   setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1134                                  true);
1135   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1136   receiving_client()->SetReceiveAudioVideo(true, false);
1137   LocalP2PTest();
1138   receiving_client()->SetReceiveAudioVideo(true, true);
1139   receiving_client()->Negotiate();
1140 }
1141
1142 // This test sets up a call between two endpoints that are configured to use
1143 // DTLS key agreement. The offerer don't support SDES. As a result, DTLS is
1144 // negotiated and used for transport.
1145 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestOfferDtlsButNotSdes) {
1146   MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1147   FakeConstraints setup_constraints;
1148   setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1149                                  true);
1150   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1151   receiving_client()->RemoveSdesCryptoFromReceivedSdp(true);
1152   LocalP2PTest();
1153   VerifyRenderedSize(640, 480);
1154 }
1155
1156 // This test sets up a Jsep call between two parties, and the callee only
1157 // accept to receive video.
1158 // BUG=https://code.google.com/p/webrtc/issues/detail?id=2288
1159 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestAnswerVideo) {
1160   ASSERT_TRUE(CreateTestClients());
1161   receiving_client()->SetReceiveAudioVideo(false, true);
1162   LocalP2PTest();
1163 }
1164
1165 // This test sets up a Jsep call between two parties, and the callee only
1166 // accept to receive audio.
1167 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestAnswerAudio) {
1168   ASSERT_TRUE(CreateTestClients());
1169   receiving_client()->SetReceiveAudioVideo(true, false);
1170   LocalP2PTest();
1171 }
1172
1173 // This test sets up a Jsep call between two parties, and the callee reject both
1174 // audio and video.
1175 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestAnswerNone) {
1176   ASSERT_TRUE(CreateTestClients());
1177   receiving_client()->SetReceiveAudioVideo(false, false);
1178   LocalP2PTest();
1179 }
1180
1181 // This test sets up an audio and video call between two parties. After the call
1182 // runs for a while (10 frames), the caller sends an update offer with video
1183 // being rejected. Once the re-negotiation is done, the video flow should stop
1184 // and the audio flow should continue.
1185 // Disabled due to b/14955157.
1186 TEST_F(JsepPeerConnectionP2PTestClient,
1187        DISABLED_UpdateOfferWithRejectedContent) {
1188   ASSERT_TRUE(CreateTestClients());
1189   LocalP2PTest();
1190   TestUpdateOfferWithRejectedContent();
1191 }
1192
1193 // This test sets up a Jsep call between two parties. The MSID is removed from
1194 // the SDP strings from the caller.
1195 // Disabled due to b/14955157.
1196 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestWithoutMsid) {
1197   ASSERT_TRUE(CreateTestClients());
1198   receiving_client()->RemoveMsidFromReceivedSdp(true);
1199   // TODO(perkj): Currently there is a bug that cause audio to stop playing if
1200   // audio and video is muxed when MSID is disabled. Remove
1201   // SetRemoveBundleFromSdp once
1202   // https://code.google.com/p/webrtc/issues/detail?id=1193 is fixed.
1203   receiving_client()->RemoveBundleFromReceivedSdp(true);
1204   LocalP2PTest();
1205 }
1206
1207 // This test sets up a Jsep call between two parties and the initiating peer
1208 // sends two steams.
1209 // TODO(perkj): Disabled due to
1210 // https://code.google.com/p/webrtc/issues/detail?id=1454
1211 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestTwoStreams) {
1212   ASSERT_TRUE(CreateTestClients());
1213   // Set optional video constraint to max 320pixels to decrease CPU usage.
1214   FakeConstraints constraint;
1215   constraint.SetOptionalMaxWidth(320);
1216   SetVideoConstraints(constraint, constraint);
1217   initializing_client()->AddMediaStream(true, true);
1218   initializing_client()->AddMediaStream(false, true);
1219   ASSERT_EQ(2u, initializing_client()->NumberOfLocalMediaStreams());
1220   LocalP2PTest();
1221   EXPECT_EQ(2u, receiving_client()->number_of_remote_streams());
1222 }
1223
1224 // Test that we can receive the audio output level from a remote audio track.
1225 TEST_F(JsepPeerConnectionP2PTestClient, GetAudioOutputLevelStats) {
1226   ASSERT_TRUE(CreateTestClients());
1227   LocalP2PTest();
1228
1229   StreamCollectionInterface* remote_streams =
1230       initializing_client()->remote_streams();
1231   ASSERT_GT(remote_streams->count(), 0u);
1232   ASSERT_GT(remote_streams->at(0)->GetAudioTracks().size(), 0u);
1233   MediaStreamTrackInterface* remote_audio_track =
1234       remote_streams->at(0)->GetAudioTracks()[0];
1235
1236   // Get the audio output level stats. Note that the level is not available
1237   // until a RTCP packet has been received.
1238   EXPECT_TRUE_WAIT(
1239       initializing_client()->GetAudioOutputLevelStats(remote_audio_track) > 0,
1240       kMaxWaitForStatsMs);
1241 }
1242
1243 // Test that an audio input level is reported.
1244 TEST_F(JsepPeerConnectionP2PTestClient, GetAudioInputLevelStats) {
1245   ASSERT_TRUE(CreateTestClients());
1246   LocalP2PTest();
1247
1248   // Get the audio input level stats.  The level should be available very
1249   // soon after the test starts.
1250   EXPECT_TRUE_WAIT(initializing_client()->GetAudioInputLevelStats() > 0,
1251       kMaxWaitForStatsMs);
1252 }
1253
1254 // Test that we can get incoming byte counts from both audio and video tracks.
1255 TEST_F(JsepPeerConnectionP2PTestClient, GetBytesReceivedStats) {
1256   ASSERT_TRUE(CreateTestClients());
1257   LocalP2PTest();
1258
1259   StreamCollectionInterface* remote_streams =
1260       initializing_client()->remote_streams();
1261   ASSERT_GT(remote_streams->count(), 0u);
1262   ASSERT_GT(remote_streams->at(0)->GetAudioTracks().size(), 0u);
1263   MediaStreamTrackInterface* remote_audio_track =
1264       remote_streams->at(0)->GetAudioTracks()[0];
1265   EXPECT_TRUE_WAIT(
1266       initializing_client()->GetBytesReceivedStats(remote_audio_track) > 0,
1267       kMaxWaitForStatsMs);
1268
1269   MediaStreamTrackInterface* remote_video_track =
1270       remote_streams->at(0)->GetVideoTracks()[0];
1271   EXPECT_TRUE_WAIT(
1272       initializing_client()->GetBytesReceivedStats(remote_video_track) > 0,
1273       kMaxWaitForStatsMs);
1274 }
1275
1276 // Test that we can get outgoing byte counts from both audio and video tracks.
1277 TEST_F(JsepPeerConnectionP2PTestClient, GetBytesSentStats) {
1278   ASSERT_TRUE(CreateTestClients());
1279   LocalP2PTest();
1280
1281   StreamCollectionInterface* local_streams =
1282       initializing_client()->local_streams();
1283   ASSERT_GT(local_streams->count(), 0u);
1284   ASSERT_GT(local_streams->at(0)->GetAudioTracks().size(), 0u);
1285   MediaStreamTrackInterface* local_audio_track =
1286       local_streams->at(0)->GetAudioTracks()[0];
1287   EXPECT_TRUE_WAIT(
1288       initializing_client()->GetBytesSentStats(local_audio_track) > 0,
1289       kMaxWaitForStatsMs);
1290
1291   MediaStreamTrackInterface* local_video_track =
1292       local_streams->at(0)->GetVideoTracks()[0];
1293   EXPECT_TRUE_WAIT(
1294       initializing_client()->GetBytesSentStats(local_video_track) > 0,
1295       kMaxWaitForStatsMs);
1296 }
1297
1298 // This test sets up a call between two parties with audio, video and data.
1299 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDataChannel) {
1300   FakeConstraints setup_constraints;
1301   setup_constraints.SetAllowRtpDataChannels();
1302   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1303   initializing_client()->CreateDataChannel();
1304   LocalP2PTest();
1305   ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1306   ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1307   EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1308                    kMaxWaitMs);
1309   EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(),
1310                    kMaxWaitMs);
1311
1312   std::string data = "hello world";
1313
1314   SendRtpData(initializing_client()->data_channel(), data);
1315   EXPECT_EQ_WAIT(data, receiving_client()->data_observer()->last_message(),
1316                  kMaxWaitMs);
1317
1318   SendRtpData(receiving_client()->data_channel(), data);
1319   EXPECT_EQ_WAIT(data, initializing_client()->data_observer()->last_message(),
1320                  kMaxWaitMs);
1321
1322   receiving_client()->data_channel()->Close();
1323   // Send new offer and answer.
1324   receiving_client()->Negotiate();
1325   EXPECT_FALSE(initializing_client()->data_observer()->IsOpen());
1326   EXPECT_FALSE(receiving_client()->data_observer()->IsOpen());
1327 }
1328
1329 // This test sets up a call between two parties and creates a data channel.
1330 // The test tests that received data is buffered unless an observer has been
1331 // registered.
1332 // Rtp data channels can receive data before the underlying
1333 // transport has detected that a channel is writable and thus data can be
1334 // received before the data channel state changes to open. That is hard to test
1335 // but the same buffering is used in that case.
1336 TEST_F(JsepPeerConnectionP2PTestClient, RegisterDataChannelObserver) {
1337   FakeConstraints setup_constraints;
1338   setup_constraints.SetAllowRtpDataChannels();
1339   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1340   initializing_client()->CreateDataChannel();
1341   initializing_client()->Negotiate();
1342
1343   ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1344   ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1345   EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1346                    kMaxWaitMs);
1347   EXPECT_EQ_WAIT(DataChannelInterface::kOpen,
1348                  receiving_client()->data_channel()->state(), kMaxWaitMs);
1349
1350   // Unregister the existing observer.
1351   receiving_client()->data_channel()->UnregisterObserver();
1352
1353   std::string data = "hello world";
1354   SendRtpData(initializing_client()->data_channel(), data);
1355
1356   // Wait a while to allow the sent data to arrive before an observer is
1357   // registered..
1358   rtc::Thread::Current()->ProcessMessages(100);
1359
1360   MockDataChannelObserver new_observer(receiving_client()->data_channel());
1361   EXPECT_EQ_WAIT(data, new_observer.last_message(), kMaxWaitMs);
1362 }
1363
1364 // This test sets up a call between two parties with audio, video and but only
1365 // the initiating client support data.
1366 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestReceiverDoesntSupportData) {
1367   FakeConstraints setup_constraints_1;
1368   setup_constraints_1.SetAllowRtpDataChannels();
1369   // Must disable DTLS to make negotiation succeed.
1370   setup_constraints_1.SetMandatory(
1371       MediaConstraintsInterface::kEnableDtlsSrtp, false);
1372   FakeConstraints setup_constraints_2;
1373   setup_constraints_2.SetMandatory(
1374       MediaConstraintsInterface::kEnableDtlsSrtp, false);
1375   ASSERT_TRUE(CreateTestClients(&setup_constraints_1, &setup_constraints_2));
1376   initializing_client()->CreateDataChannel();
1377   LocalP2PTest();
1378   EXPECT_TRUE(initializing_client()->data_channel() != NULL);
1379   EXPECT_FALSE(receiving_client()->data_channel());
1380   EXPECT_FALSE(initializing_client()->data_observer()->IsOpen());
1381 }
1382
1383 // This test sets up a call between two parties with audio, video. When audio
1384 // and video is setup and flowing and data channel is negotiated.
1385 TEST_F(JsepPeerConnectionP2PTestClient, AddDataChannelAfterRenegotiation) {
1386   FakeConstraints setup_constraints;
1387   setup_constraints.SetAllowRtpDataChannels();
1388   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1389   LocalP2PTest();
1390   initializing_client()->CreateDataChannel();
1391   // Send new offer and answer.
1392   initializing_client()->Negotiate();
1393   ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1394   ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1395   EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1396                    kMaxWaitMs);
1397   EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(),
1398                    kMaxWaitMs);
1399 }
1400
1401 // This test sets up a Jsep call with SCTP DataChannel and verifies the
1402 // negotiation is completed without error.
1403 #ifdef HAVE_SCTP
1404 TEST_F(JsepPeerConnectionP2PTestClient, CreateOfferWithSctpDataChannel) {
1405   MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1406   FakeConstraints constraints;
1407   constraints.SetMandatory(
1408       MediaConstraintsInterface::kEnableDtlsSrtp, true);
1409   ASSERT_TRUE(CreateTestClients(&constraints, &constraints));
1410   initializing_client()->CreateDataChannel();
1411   initializing_client()->Negotiate(false, false);
1412 }
1413 #endif
1414
1415 // This test sets up a call between two parties with audio, and video.
1416 // During the call, the initializing side restart ice and the test verifies that
1417 // new ice candidates are generated and audio and video still can flow.
1418 TEST_F(JsepPeerConnectionP2PTestClient, IceRestart) {
1419   ASSERT_TRUE(CreateTestClients());
1420
1421   // Negotiate and wait for ice completion and make sure audio and video plays.
1422   LocalP2PTest();
1423
1424   // Create a SDP string of the first audio candidate for both clients.
1425   const webrtc::IceCandidateCollection* audio_candidates_initiator =
1426       initializing_client()->pc()->local_description()->candidates(0);
1427   const webrtc::IceCandidateCollection* audio_candidates_receiver =
1428       receiving_client()->pc()->local_description()->candidates(0);
1429   ASSERT_GT(audio_candidates_initiator->count(), 0u);
1430   ASSERT_GT(audio_candidates_receiver->count(), 0u);
1431   std::string initiator_candidate;
1432   EXPECT_TRUE(
1433       audio_candidates_initiator->at(0)->ToString(&initiator_candidate));
1434   std::string receiver_candidate;
1435   EXPECT_TRUE(audio_candidates_receiver->at(0)->ToString(&receiver_candidate));
1436
1437   // Restart ice on the initializing client.
1438   receiving_client()->SetExpectIceRestart(true);
1439   initializing_client()->IceRestart();
1440
1441   // Negotiate and wait for ice completion again and make sure audio and video
1442   // plays.
1443   LocalP2PTest();
1444
1445   // Create a SDP string of the first audio candidate for both clients again.
1446   const webrtc::IceCandidateCollection* audio_candidates_initiator_restart =
1447       initializing_client()->pc()->local_description()->candidates(0);
1448   const webrtc::IceCandidateCollection* audio_candidates_reciever_restart =
1449       receiving_client()->pc()->local_description()->candidates(0);
1450   ASSERT_GT(audio_candidates_initiator_restart->count(), 0u);
1451   ASSERT_GT(audio_candidates_reciever_restart->count(), 0u);
1452   std::string initiator_candidate_restart;
1453   EXPECT_TRUE(audio_candidates_initiator_restart->at(0)->ToString(
1454       &initiator_candidate_restart));
1455   std::string receiver_candidate_restart;
1456   EXPECT_TRUE(audio_candidates_reciever_restart->at(0)->ToString(
1457       &receiver_candidate_restart));
1458
1459   // Verify that the first candidates in the local session descriptions has
1460   // changed.
1461   EXPECT_NE(initiator_candidate, initiator_candidate_restart);
1462   EXPECT_NE(receiver_candidate, receiver_candidate_restart);
1463 }
1464
1465
1466 // This test sets up a Jsep call between two parties with external
1467 // VideoDecoderFactory.
1468 // TODO(holmer): Disabled due to sometimes crashing on buildbots.
1469 // See issue webrtc/2378.
1470 TEST_F(JsepPeerConnectionP2PTestClient,
1471        DISABLED_LocalP2PTestWithVideoDecoderFactory) {
1472   ASSERT_TRUE(CreateTestClients());
1473   EnableVideoDecoderFactory();
1474   LocalP2PTest();
1475 }
1476
1477 // Test receive bandwidth stats with only audio enabled at receiver.
1478 TEST_F(JsepPeerConnectionP2PTestClient, ReceivedBweStatsAudio) {
1479   ASSERT_TRUE(CreateTestClients());
1480   receiving_client()->SetReceiveAudioVideo(true, false);
1481   LocalP2PTest();
1482
1483   // Wait until we have received some audio data. Following REMB shoud be zero.
1484   WaitForAudioData(10000);
1485   EXPECT_EQ_WAIT(
1486       receiving_client()->GetAvailableReceivedBandwidthStats(), 0,
1487       kMaxWaitForRembMs);
1488 }
1489
1490 // Test receive bandwidth stats with combined BWE.
1491 // Disabled due to https://code.google.com/p/webrtc/issues/detail?id=3871.
1492 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_ReceivedBweStatsCombined) {
1493   FakeConstraints setup_constraints;
1494   setup_constraints.AddOptional(
1495       MediaConstraintsInterface::kCombinedAudioVideoBwe, true);
1496   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1497   initializing_client()->AddMediaStream(true, true);
1498   initializing_client()->AddMediaStream(false, true);
1499   initializing_client()->AddMediaStream(false, true);
1500   initializing_client()->AddMediaStream(false, true);
1501   LocalP2PTest();
1502
1503   // Run until a non-zero bw is reported.
1504   EXPECT_TRUE_WAIT(receiving_client()->GetAvailableReceivedBandwidthStats() > 0,
1505                    kMaxWaitForRembMs);
1506
1507   // Halt video capturers, then run until we have gotten some audio. Following
1508   // REMB should be non-zero.
1509   initializing_client()->StopVideoCapturers();
1510   WaitForAudioData(10000);
1511   EXPECT_TRUE_WAIT(
1512       receiving_client()->GetAvailableReceivedBandwidthStats() > 0,
1513       kMaxWaitForRembMs);
1514 }
1515
1516 // Test receive bandwidth stats with 1 video, 3 audio streams but no combined
1517 // BWE.
1518 // Disabled due to https://code.google.com/p/webrtc/issues/detail?id=3871.
1519 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_ReceivedBweStatsNotCombined) {
1520   FakeConstraints setup_constraints;
1521   setup_constraints.AddOptional(
1522       MediaConstraintsInterface::kCombinedAudioVideoBwe, false);
1523   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1524   initializing_client()->AddMediaStream(true, true);
1525   initializing_client()->AddMediaStream(false, true);
1526   initializing_client()->AddMediaStream(false, true);
1527   initializing_client()->AddMediaStream(false, true);
1528   LocalP2PTest();
1529
1530   // Run until a non-zero bw is reported.
1531   EXPECT_TRUE_WAIT(receiving_client()->GetAvailableReceivedBandwidthStats() > 0,
1532                    kMaxWaitForRembMs);
1533
1534   // Halt video capturers, then run until we have gotten some audio. Following
1535   // REMB should be zero.
1536   initializing_client()->StopVideoCapturers();
1537   WaitForAudioData(10000);
1538   EXPECT_EQ_WAIT(
1539       receiving_client()->GetAvailableReceivedBandwidthStats(), 0,
1540       kMaxWaitForRembMs);
1541 }
1542
1543 #endif // if !defined(THREAD_SANITIZER)