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