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