Upstream version 6.35.121.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 = 1000;
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     // TODO(jiayl): we should always pass a FakeIdentityService so that DTLS
730     // is enabled by default like in Chrome (issue 2838).
731     FakeIdentityService* dtls_service = NULL;
732     bool dtls;
733     if (FindConstraint(constraints,
734                        MediaConstraintsInterface::kEnableDtlsSrtp,
735                        &dtls,
736                        NULL) && dtls) {
737       dtls_service = new FakeIdentityService();
738     }
739     return peer_connection_factory()->CreatePeerConnection(
740         ice_servers, constraints, factory, dtls_service, this);
741   }
742
743   void HandleIncomingOffer(const std::string& msg) {
744     LOG(INFO) << id() << "HandleIncomingOffer ";
745     if (NumberOfLocalMediaStreams() == 0) {
746       // If we are not sending any streams ourselves it is time to add some.
747       AddMediaStream(true, true);
748     }
749     talk_base::scoped_ptr<SessionDescriptionInterface> desc(
750          webrtc::CreateSessionDescription("offer", msg, NULL));
751     EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
752     talk_base::scoped_ptr<SessionDescriptionInterface> answer;
753     EXPECT_TRUE(DoCreateAnswer(answer.use()));
754     std::string sdp;
755     EXPECT_TRUE(answer->ToString(&sdp));
756     EXPECT_TRUE(DoSetLocalDescription(answer.release()));
757     if (signaling_message_receiver()) {
758       signaling_message_receiver()->ReceiveSdpMessage(
759           webrtc::SessionDescriptionInterface::kAnswer, sdp);
760     }
761   }
762
763   void HandleIncomingAnswer(const std::string& msg) {
764     LOG(INFO) << id() << "HandleIncomingAnswer";
765     talk_base::scoped_ptr<SessionDescriptionInterface> desc(
766          webrtc::CreateSessionDescription("answer", msg, NULL));
767     EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
768   }
769
770   bool DoCreateOfferAnswer(SessionDescriptionInterface** desc,
771                            bool offer) {
772     talk_base::scoped_refptr<MockCreateSessionDescriptionObserver>
773         observer(new talk_base::RefCountedObject<
774             MockCreateSessionDescriptionObserver>());
775     if (offer) {
776       pc()->CreateOffer(observer, &session_description_constraints_);
777     } else {
778       pc()->CreateAnswer(observer, &session_description_constraints_);
779     }
780     EXPECT_EQ_WAIT(true, observer->called(), kMaxWaitMs);
781     *desc = observer->release_desc();
782     if (observer->result() && ExpectIceRestart()) {
783       EXPECT_EQ(0u, (*desc)->candidates(0)->count());
784     }
785     return observer->result();
786   }
787
788   bool DoCreateOffer(SessionDescriptionInterface** desc) {
789     return DoCreateOfferAnswer(desc, true);
790   }
791
792   bool DoCreateAnswer(SessionDescriptionInterface** desc) {
793     return DoCreateOfferAnswer(desc, false);
794   }
795
796   bool DoSetLocalDescription(SessionDescriptionInterface* desc) {
797     talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
798             observer(new talk_base::RefCountedObject<
799                 MockSetSessionDescriptionObserver>());
800     LOG(INFO) << id() << "SetLocalDescription ";
801     pc()->SetLocalDescription(observer, desc);
802     // Ignore the observer result. If we wait for the result with
803     // EXPECT_TRUE_WAIT, local ice candidates might be sent to the remote peer
804     // before the offer which is an error.
805     // The reason is that EXPECT_TRUE_WAIT uses
806     // talk_base::Thread::Current()->ProcessMessages(1);
807     // ProcessMessages waits at least 1ms but processes all messages before
808     // returning. Since this test is synchronous and send messages to the remote
809     // peer whenever a callback is invoked, this can lead to messages being
810     // sent to the remote peer in the wrong order.
811     // TODO(perkj): Find a way to check the result without risking that the
812     // order of sent messages are changed. Ex- by posting all messages that are
813     // sent to the remote peer.
814     return true;
815   }
816
817   bool DoSetRemoteDescription(SessionDescriptionInterface* desc) {
818     talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
819         observer(new talk_base::RefCountedObject<
820             MockSetSessionDescriptionObserver>());
821     LOG(INFO) << id() << "SetRemoteDescription ";
822     pc()->SetRemoteDescription(observer, desc);
823     EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
824     return observer->result();
825   }
826
827   // This modifies all received SDP messages before they are processed.
828   void FilterIncomingSdpMessage(std::string* sdp) {
829     if (remove_msid_) {
830       const char kSdpSsrcAttribute[] = "a=ssrc:";
831       RemoveLinesFromSdp(kSdpSsrcAttribute, sdp);
832       const char kSdpMsidSupportedAttribute[] = "a=msid-semantic:";
833       RemoveLinesFromSdp(kSdpMsidSupportedAttribute, sdp);
834     }
835     if (remove_bundle_) {
836       const char kSdpBundleAttribute[] = "a=group:BUNDLE";
837       RemoveLinesFromSdp(kSdpBundleAttribute, sdp);
838     }
839     if (remove_sdes_) {
840       const char kSdpSdesCryptoAttribute[] = "a=crypto";
841       RemoveLinesFromSdp(kSdpSdesCryptoAttribute, sdp);
842     }
843   }
844
845  private:
846   webrtc::FakeConstraints session_description_constraints_;
847   bool remove_msid_;  // True if MSID should be removed in received SDP.
848   bool remove_bundle_;  // True if bundle should be removed in received SDP.
849   bool remove_sdes_;  // True if a=crypto should be removed in received SDP.
850
851   talk_base::scoped_refptr<DataChannelInterface> data_channel_;
852   talk_base::scoped_ptr<MockDataChannelObserver> data_observer_;
853 };
854
855 template <typename SignalingClass>
856 class P2PTestConductor : public testing::Test {
857  public:
858   bool SessionActive() {
859     return initiating_client_->SessionActive() &&
860         receiving_client_->SessionActive();
861   }
862   // Return true if the number of frames provided have been received or it is
863   // known that that will never occur (e.g. no frames will be sent or
864   // captured).
865   bool FramesNotPending(int audio_frames_to_receive,
866                         int video_frames_to_receive) {
867     return VideoFramesReceivedCheck(video_frames_to_receive) &&
868         AudioFramesReceivedCheck(audio_frames_to_receive);
869   }
870   bool AudioFramesReceivedCheck(int frames_received) {
871     return initiating_client_->AudioFramesReceivedCheck(frames_received) &&
872         receiving_client_->AudioFramesReceivedCheck(frames_received);
873   }
874   bool VideoFramesReceivedCheck(int frames_received) {
875     return initiating_client_->VideoFramesReceivedCheck(frames_received) &&
876         receiving_client_->VideoFramesReceivedCheck(frames_received);
877   }
878   void VerifyDtmf() {
879     initiating_client_->VerifyDtmf();
880     receiving_client_->VerifyDtmf();
881   }
882
883   void TestUpdateOfferWithRejectedContent() {
884     initiating_client_->Negotiate(true, false);
885     EXPECT_TRUE_WAIT(
886         FramesNotPending(kEndAudioFrameCount * 2, kEndVideoFrameCount),
887         kMaxWaitForFramesMs);
888     // There shouldn't be any more video frame after the new offer is
889     // negotiated.
890     EXPECT_FALSE(VideoFramesReceivedCheck(kEndVideoFrameCount + 1));
891   }
892
893   void VerifyRenderedSize(int width, int height) {
894     EXPECT_EQ(width, receiving_client()->rendered_width());
895     EXPECT_EQ(height, receiving_client()->rendered_height());
896     EXPECT_EQ(width, initializing_client()->rendered_width());
897     EXPECT_EQ(height, initializing_client()->rendered_height());
898   }
899
900   void VerifySessionDescriptions() {
901     initiating_client_->VerifyRejectedMediaInSessionDescription();
902     receiving_client_->VerifyRejectedMediaInSessionDescription();
903     initiating_client_->VerifyLocalIceUfragAndPassword();
904     receiving_client_->VerifyLocalIceUfragAndPassword();
905   }
906
907   P2PTestConductor() {
908     talk_base::InitializeSSL(NULL);
909   }
910   ~P2PTestConductor() {
911     if (initiating_client_) {
912       initiating_client_->set_signaling_message_receiver(NULL);
913     }
914     if (receiving_client_) {
915       receiving_client_->set_signaling_message_receiver(NULL);
916     }
917     talk_base::CleanupSSL();
918   }
919
920   bool CreateTestClients() {
921     return CreateTestClients(NULL, NULL);
922   }
923
924   bool CreateTestClients(MediaConstraintsInterface* init_constraints,
925                          MediaConstraintsInterface* recv_constraints) {
926     initiating_client_.reset(SignalingClass::CreateClient("Caller: ",
927                                                           init_constraints));
928     receiving_client_.reset(SignalingClass::CreateClient("Callee: ",
929                                                          recv_constraints));
930     if (!initiating_client_ || !receiving_client_) {
931       return false;
932     }
933     initiating_client_->set_signaling_message_receiver(receiving_client_.get());
934     receiving_client_->set_signaling_message_receiver(initiating_client_.get());
935     return true;
936   }
937
938   void SetVideoConstraints(const webrtc::FakeConstraints& init_constraints,
939                            const webrtc::FakeConstraints& recv_constraints) {
940     initiating_client_->SetVideoConstraints(init_constraints);
941     receiving_client_->SetVideoConstraints(recv_constraints);
942   }
943
944   void EnableVideoDecoderFactory() {
945     initiating_client_->EnableVideoDecoderFactory();
946     receiving_client_->EnableVideoDecoderFactory();
947   }
948
949   // This test sets up a call between two parties. Both parties send static
950   // frames to each other. Once the test is finished the number of sent frames
951   // is compared to the number of received frames.
952   void LocalP2PTest() {
953     if (initiating_client_->NumberOfLocalMediaStreams() == 0) {
954       initiating_client_->AddMediaStream(true, true);
955     }
956     initiating_client_->Negotiate();
957     const int kMaxWaitForActivationMs = 5000;
958     // Assert true is used here since next tests are guaranteed to fail and
959     // would eat up 5 seconds.
960     ASSERT_TRUE_WAIT(SessionActive(), kMaxWaitForActivationMs);
961     VerifySessionDescriptions();
962
963
964     int audio_frame_count = kEndAudioFrameCount;
965     // TODO(ronghuawu): Add test to cover the case of sendonly and recvonly.
966     if (!initiating_client_->can_receive_audio() ||
967         !receiving_client_->can_receive_audio()) {
968       audio_frame_count = -1;
969     }
970     int video_frame_count = kEndVideoFrameCount;
971     if (!initiating_client_->can_receive_video() ||
972         !receiving_client_->can_receive_video()) {
973       video_frame_count = -1;
974     }
975
976     if (audio_frame_count != -1 || video_frame_count != -1) {
977       // Audio or video is expected to flow, so both clients should reach the
978       // Connected state, and the offerer (ICE controller) should proceed to
979       // Completed.
980       // Note: These tests have been observed to fail under heavy load at
981       // shorter timeouts, so they may be flaky.
982       EXPECT_EQ_WAIT(
983           webrtc::PeerConnectionInterface::kIceConnectionCompleted,
984           initiating_client_->ice_connection_state(),
985           kMaxWaitForFramesMs);
986       EXPECT_EQ_WAIT(
987           webrtc::PeerConnectionInterface::kIceConnectionConnected,
988           receiving_client_->ice_connection_state(),
989           kMaxWaitForFramesMs);
990     }
991
992     if (initiating_client_->can_receive_audio() ||
993         initiating_client_->can_receive_video()) {
994       // The initiating client can receive media, so it must produce candidates
995       // that will serve as destinations for that media.
996       // TODO(bemasc): Understand why the state is not already Complete here, as
997       // seems to be the case for the receiving client. This may indicate a bug
998       // in the ICE gathering system.
999       EXPECT_NE(webrtc::PeerConnectionInterface::kIceGatheringNew,
1000                 initiating_client_->ice_gathering_state());
1001     }
1002     if (receiving_client_->can_receive_audio() ||
1003         receiving_client_->can_receive_video()) {
1004       EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
1005                      receiving_client_->ice_gathering_state(),
1006                      kMaxWaitForFramesMs);
1007     }
1008
1009     EXPECT_TRUE_WAIT(FramesNotPending(audio_frame_count, video_frame_count),
1010                      kMaxWaitForFramesMs);
1011   }
1012
1013   SignalingClass* initializing_client() { return initiating_client_.get(); }
1014   SignalingClass* receiving_client() { return receiving_client_.get(); }
1015
1016  private:
1017   talk_base::scoped_ptr<SignalingClass> initiating_client_;
1018   talk_base::scoped_ptr<SignalingClass> receiving_client_;
1019 };
1020 typedef P2PTestConductor<JsepTestClient> JsepPeerConnectionP2PTestClient;
1021
1022 // Disable for TSan v2, see
1023 // https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
1024 #if !defined(THREAD_SANITIZER)
1025
1026 // This test sets up a Jsep call between two parties and test Dtmf.
1027 // TODO(holmer): Disabled due to sometimes crashing on buildbots.
1028 // See issue webrtc/2378.
1029 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestDtmf) {
1030   ASSERT_TRUE(CreateTestClients());
1031   LocalP2PTest();
1032   VerifyDtmf();
1033 }
1034
1035 // This test sets up a Jsep call between two parties and test that we can get a
1036 // video aspect ratio of 16:9.
1037 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTest16To9) {
1038   ASSERT_TRUE(CreateTestClients());
1039   FakeConstraints constraint;
1040   double requested_ratio = 640.0/360;
1041   constraint.SetMandatoryMinAspectRatio(requested_ratio);
1042   SetVideoConstraints(constraint, constraint);
1043   LocalP2PTest();
1044
1045   ASSERT_LE(0, initializing_client()->rendered_height());
1046   double initiating_video_ratio =
1047       static_cast<double>(initializing_client()->rendered_width()) /
1048       initializing_client()->rendered_height();
1049   EXPECT_LE(requested_ratio, initiating_video_ratio);
1050
1051   ASSERT_LE(0, receiving_client()->rendered_height());
1052   double receiving_video_ratio =
1053       static_cast<double>(receiving_client()->rendered_width()) /
1054       receiving_client()->rendered_height();
1055   EXPECT_LE(requested_ratio, receiving_video_ratio);
1056 }
1057
1058 // This test sets up a Jsep call between two parties and test that the
1059 // received video has a resolution of 1280*720.
1060 // TODO(mallinath): Enable when
1061 // http://code.google.com/p/webrtc/issues/detail?id=981 is fixed.
1062 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTest1280By720) {
1063   ASSERT_TRUE(CreateTestClients());
1064   FakeConstraints constraint;
1065   constraint.SetMandatoryMinWidth(1280);
1066   constraint.SetMandatoryMinHeight(720);
1067   SetVideoConstraints(constraint, constraint);
1068   LocalP2PTest();
1069   VerifyRenderedSize(1280, 720);
1070 }
1071
1072 // This test sets up a call between two endpoints that are configured to use
1073 // DTLS key agreement. As a result, DTLS is negotiated and used for transport.
1074 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDtls) {
1075   MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
1076   FakeConstraints setup_constraints;
1077   setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1078                                  true);
1079   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1080   LocalP2PTest();
1081   VerifyRenderedSize(640, 480);
1082 }
1083
1084 // This test sets up a audio call initially and then upgrades to audio/video,
1085 // using DTLS.
1086 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDtlsRenegotiate) {
1087   MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
1088   FakeConstraints setup_constraints;
1089   setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1090                                  true);
1091   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1092   receiving_client()->SetReceiveAudioVideo(true, false);
1093   LocalP2PTest();
1094   receiving_client()->SetReceiveAudioVideo(true, true);
1095   receiving_client()->Negotiate();
1096 }
1097
1098 // This test sets up a call between two endpoints that are configured to use
1099 // DTLS key agreement. The offerer don't support SDES. As a result, DTLS is
1100 // negotiated and used for transport.
1101 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestOfferDtlsButNotSdes) {
1102   MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
1103   FakeConstraints setup_constraints;
1104   setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1105                                  true);
1106   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1107   receiving_client()->RemoveSdesCryptoFromReceivedSdp(true);
1108   LocalP2PTest();
1109   VerifyRenderedSize(640, 480);
1110 }
1111
1112 // This test sets up a Jsep call between two parties, and the callee only
1113 // accept to receive video.
1114 // BUG=https://code.google.com/p/webrtc/issues/detail?id=2288
1115 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestAnswerVideo) {
1116   ASSERT_TRUE(CreateTestClients());
1117   receiving_client()->SetReceiveAudioVideo(false, true);
1118   LocalP2PTest();
1119 }
1120
1121 // This test sets up a Jsep call between two parties, and the callee only
1122 // accept to receive audio.
1123 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestAnswerAudio) {
1124   ASSERT_TRUE(CreateTestClients());
1125   receiving_client()->SetReceiveAudioVideo(true, false);
1126   LocalP2PTest();
1127 }
1128
1129 // This test sets up a Jsep call between two parties, and the callee reject both
1130 // audio and video.
1131 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestAnswerNone) {
1132   ASSERT_TRUE(CreateTestClients());
1133   receiving_client()->SetReceiveAudioVideo(false, false);
1134   LocalP2PTest();
1135 }
1136
1137 // This test sets up an audio and video call between two parties. After the call
1138 // runs for a while (10 frames), the caller sends an update offer with video
1139 // being rejected. Once the re-negotiation is done, the video flow should stop
1140 // and the audio flow should continue.
1141 TEST_F(JsepPeerConnectionP2PTestClient, UpdateOfferWithRejectedContent) {
1142   ASSERT_TRUE(CreateTestClients());
1143   LocalP2PTest();
1144   TestUpdateOfferWithRejectedContent();
1145 }
1146
1147 // This test sets up a Jsep call between two parties. The MSID is removed from
1148 // the SDP strings from the caller.
1149 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestWithoutMsid) {
1150   ASSERT_TRUE(CreateTestClients());
1151   receiving_client()->RemoveMsidFromReceivedSdp(true);
1152   // TODO(perkj): Currently there is a bug that cause audio to stop playing if
1153   // audio and video is muxed when MSID is disabled. Remove
1154   // SetRemoveBundleFromSdp once
1155   // https://code.google.com/p/webrtc/issues/detail?id=1193 is fixed.
1156   receiving_client()->RemoveBundleFromReceivedSdp(true);
1157   LocalP2PTest();
1158 }
1159
1160 // This test sets up a Jsep call between two parties and the initiating peer
1161 // sends two steams.
1162 // TODO(perkj): Disabled due to
1163 // https://code.google.com/p/webrtc/issues/detail?id=1454
1164 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestTwoStreams) {
1165   ASSERT_TRUE(CreateTestClients());
1166   // Set optional video constraint to max 320pixels to decrease CPU usage.
1167   FakeConstraints constraint;
1168   constraint.SetOptionalMaxWidth(320);
1169   SetVideoConstraints(constraint, constraint);
1170   initializing_client()->AddMediaStream(true, true);
1171   initializing_client()->AddMediaStream(false, true);
1172   ASSERT_EQ(2u, initializing_client()->NumberOfLocalMediaStreams());
1173   LocalP2PTest();
1174   EXPECT_EQ(2u, receiving_client()->number_of_remote_streams());
1175 }
1176
1177 // Test that we can receive the audio output level from a remote audio track.
1178 TEST_F(JsepPeerConnectionP2PTestClient, GetAudioOutputLevelStats) {
1179   ASSERT_TRUE(CreateTestClients());
1180   LocalP2PTest();
1181
1182   StreamCollectionInterface* remote_streams =
1183       initializing_client()->remote_streams();
1184   ASSERT_GT(remote_streams->count(), 0u);
1185   ASSERT_GT(remote_streams->at(0)->GetAudioTracks().size(), 0u);
1186   MediaStreamTrackInterface* remote_audio_track =
1187       remote_streams->at(0)->GetAudioTracks()[0];
1188
1189   // Get the audio output level stats. Note that the level is not available
1190   // until a RTCP packet has been received.
1191   EXPECT_TRUE_WAIT(
1192       initializing_client()->GetAudioOutputLevelStats(remote_audio_track) > 0,
1193       kMaxWaitForStatsMs);
1194 }
1195
1196 // Test that an audio input level is reported.
1197 TEST_F(JsepPeerConnectionP2PTestClient, GetAudioInputLevelStats) {
1198   ASSERT_TRUE(CreateTestClients());
1199   LocalP2PTest();
1200
1201   // Get the audio input level stats.  The level should be available very
1202   // soon after the test starts.
1203   EXPECT_TRUE_WAIT(initializing_client()->GetAudioInputLevelStats() > 0,
1204       kMaxWaitForStatsMs);
1205 }
1206
1207 // Test that we can get incoming byte counts from both audio and video tracks.
1208 TEST_F(JsepPeerConnectionP2PTestClient, GetBytesReceivedStats) {
1209   ASSERT_TRUE(CreateTestClients());
1210   LocalP2PTest();
1211
1212   StreamCollectionInterface* remote_streams =
1213       initializing_client()->remote_streams();
1214   ASSERT_GT(remote_streams->count(), 0u);
1215   ASSERT_GT(remote_streams->at(0)->GetAudioTracks().size(), 0u);
1216   MediaStreamTrackInterface* remote_audio_track =
1217       remote_streams->at(0)->GetAudioTracks()[0];
1218   EXPECT_TRUE_WAIT(
1219       initializing_client()->GetBytesReceivedStats(remote_audio_track) > 0,
1220       kMaxWaitForStatsMs);
1221
1222   MediaStreamTrackInterface* remote_video_track =
1223       remote_streams->at(0)->GetVideoTracks()[0];
1224   EXPECT_TRUE_WAIT(
1225       initializing_client()->GetBytesReceivedStats(remote_video_track) > 0,
1226       kMaxWaitForStatsMs);
1227 }
1228
1229 // Test that we can get outgoing byte counts from both audio and video tracks.
1230 TEST_F(JsepPeerConnectionP2PTestClient, GetBytesSentStats) {
1231   ASSERT_TRUE(CreateTestClients());
1232   LocalP2PTest();
1233
1234   StreamCollectionInterface* local_streams =
1235       initializing_client()->local_streams();
1236   ASSERT_GT(local_streams->count(), 0u);
1237   ASSERT_GT(local_streams->at(0)->GetAudioTracks().size(), 0u);
1238   MediaStreamTrackInterface* local_audio_track =
1239       local_streams->at(0)->GetAudioTracks()[0];
1240   EXPECT_TRUE_WAIT(
1241       initializing_client()->GetBytesSentStats(local_audio_track) > 0,
1242       kMaxWaitForStatsMs);
1243
1244   MediaStreamTrackInterface* local_video_track =
1245       local_streams->at(0)->GetVideoTracks()[0];
1246   EXPECT_TRUE_WAIT(
1247       initializing_client()->GetBytesSentStats(local_video_track) > 0,
1248       kMaxWaitForStatsMs);
1249 }
1250
1251 // This test sets up a call between two parties with audio, video and data.
1252 // TODO(jiayl): fix the flakiness on Windows and reenable. Issue 2891.
1253 #if defined(WIN32)
1254 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestDataChannel) {
1255 #else
1256 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDataChannel) {
1257 #endif
1258   FakeConstraints setup_constraints;
1259   setup_constraints.SetAllowRtpDataChannels();
1260   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1261   initializing_client()->CreateDataChannel();
1262   LocalP2PTest();
1263   ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1264   ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1265   EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1266                    kMaxWaitMs);
1267   EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(),
1268                    kMaxWaitMs);
1269
1270   std::string data = "hello world";
1271   initializing_client()->data_channel()->Send(DataBuffer(data));
1272   EXPECT_EQ_WAIT(data, receiving_client()->data_observer()->last_message(),
1273                  kMaxWaitMs);
1274   receiving_client()->data_channel()->Send(DataBuffer(data));
1275   EXPECT_EQ_WAIT(data, initializing_client()->data_observer()->last_message(),
1276                  kMaxWaitMs);
1277
1278   receiving_client()->data_channel()->Close();
1279   // Send new offer and answer.
1280   receiving_client()->Negotiate();
1281   EXPECT_FALSE(initializing_client()->data_observer()->IsOpen());
1282   EXPECT_FALSE(receiving_client()->data_observer()->IsOpen());
1283 }
1284
1285 // This test sets up a call between two parties and creates a data channel.
1286 // The test tests that received data is buffered unless an observer has been
1287 // registered.
1288 // Rtp data channels can receive data before the underlying
1289 // transport has detected that a channel is writable and thus data can be
1290 // received before the data channel state changes to open. That is hard to test
1291 // but the same buffering is used in that case.
1292 TEST_F(JsepPeerConnectionP2PTestClient, RegisterDataChannelObserver) {
1293   FakeConstraints setup_constraints;
1294   setup_constraints.SetAllowRtpDataChannels();
1295   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1296   initializing_client()->CreateDataChannel();
1297   initializing_client()->Negotiate();
1298
1299   ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1300   ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1301   EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1302                    kMaxWaitMs);
1303   EXPECT_EQ_WAIT(DataChannelInterface::kOpen,
1304                  receiving_client()->data_channel()->state(), kMaxWaitMs);
1305
1306   // Unregister the existing observer.
1307   receiving_client()->data_channel()->UnregisterObserver();
1308   std::string data = "hello world";
1309   initializing_client()->data_channel()->Send(DataBuffer(data));
1310   // Wait a while to allow the sent data to arrive before an observer is
1311   // registered..
1312   talk_base::Thread::Current()->ProcessMessages(100);
1313
1314   MockDataChannelObserver new_observer(receiving_client()->data_channel());
1315   EXPECT_EQ_WAIT(data, new_observer.last_message(), kMaxWaitMs);
1316 }
1317
1318 // This test sets up a call between two parties with audio, video and but only
1319 // the initiating client support data.
1320 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestReceiverDoesntSupportData) {
1321   FakeConstraints setup_constraints;
1322   setup_constraints.SetAllowRtpDataChannels();
1323   ASSERT_TRUE(CreateTestClients(&setup_constraints, NULL));
1324   initializing_client()->CreateDataChannel();
1325   LocalP2PTest();
1326   EXPECT_TRUE(initializing_client()->data_channel() != NULL);
1327   EXPECT_FALSE(receiving_client()->data_channel());
1328   EXPECT_FALSE(initializing_client()->data_observer()->IsOpen());
1329 }
1330
1331 // This test sets up a call between two parties with audio, video. When audio
1332 // and video is setup and flowing and data channel is negotiated.
1333 TEST_F(JsepPeerConnectionP2PTestClient, AddDataChannelAfterRenegotiation) {
1334   FakeConstraints setup_constraints;
1335   setup_constraints.SetAllowRtpDataChannels();
1336   ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1337   LocalP2PTest();
1338   initializing_client()->CreateDataChannel();
1339   // Send new offer and answer.
1340   initializing_client()->Negotiate();
1341   ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1342   ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1343   EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1344                    kMaxWaitMs);
1345   EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(),
1346                    kMaxWaitMs);
1347 }
1348
1349 // This test sets up a call between two parties with audio, and video.
1350 // During the call, the initializing side restart ice and the test verifies that
1351 // new ice candidates are generated and audio and video still can flow.
1352 TEST_F(JsepPeerConnectionP2PTestClient, IceRestart) {
1353   ASSERT_TRUE(CreateTestClients());
1354
1355   // Negotiate and wait for ice completion and make sure audio and video plays.
1356   LocalP2PTest();
1357
1358   // Create a SDP string of the first audio candidate for both clients.
1359   const webrtc::IceCandidateCollection* audio_candidates_initiator =
1360       initializing_client()->pc()->local_description()->candidates(0);
1361   const webrtc::IceCandidateCollection* audio_candidates_receiver =
1362       receiving_client()->pc()->local_description()->candidates(0);
1363   ASSERT_GT(audio_candidates_initiator->count(), 0u);
1364   ASSERT_GT(audio_candidates_receiver->count(), 0u);
1365   std::string initiator_candidate;
1366   EXPECT_TRUE(
1367       audio_candidates_initiator->at(0)->ToString(&initiator_candidate));
1368   std::string receiver_candidate;
1369   EXPECT_TRUE(audio_candidates_receiver->at(0)->ToString(&receiver_candidate));
1370
1371   // Restart ice on the initializing client.
1372   receiving_client()->SetExpectIceRestart(true);
1373   initializing_client()->IceRestart();
1374
1375   // Negotiate and wait for ice completion again and make sure audio and video
1376   // plays.
1377   LocalP2PTest();
1378
1379   // Create a SDP string of the first audio candidate for both clients again.
1380   const webrtc::IceCandidateCollection* audio_candidates_initiator_restart =
1381       initializing_client()->pc()->local_description()->candidates(0);
1382   const webrtc::IceCandidateCollection* audio_candidates_reciever_restart =
1383       receiving_client()->pc()->local_description()->candidates(0);
1384   ASSERT_GT(audio_candidates_initiator_restart->count(), 0u);
1385   ASSERT_GT(audio_candidates_reciever_restart->count(), 0u);
1386   std::string initiator_candidate_restart;
1387   EXPECT_TRUE(audio_candidates_initiator_restart->at(0)->ToString(
1388       &initiator_candidate_restart));
1389   std::string receiver_candidate_restart;
1390   EXPECT_TRUE(audio_candidates_reciever_restart->at(0)->ToString(
1391       &receiver_candidate_restart));
1392
1393   // Verify that the first candidates in the local session descriptions has
1394   // changed.
1395   EXPECT_NE(initiator_candidate, initiator_candidate_restart);
1396   EXPECT_NE(receiver_candidate, receiver_candidate_restart);
1397 }
1398
1399
1400 // This test sets up a Jsep call between two parties with external
1401 // VideoDecoderFactory.
1402 // TODO(holmer): Disabled due to sometimes crashing on buildbots.
1403 // See issue webrtc/2378.
1404 TEST_F(JsepPeerConnectionP2PTestClient,
1405        DISABLED_LocalP2PTestWithVideoDecoderFactory) {
1406   ASSERT_TRUE(CreateTestClients());
1407   EnableVideoDecoderFactory();
1408   LocalP2PTest();
1409 }
1410
1411 #endif // if !defined(THREAD_SANITIZER)
1412