3 * Copyright 2012, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
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"
58 #define MAYBE_SKIP_TEST(feature) \
60 LOG(LS_INFO) << "Feature disabled... skipping"; \
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;
86 static const int kMaxWaitMs = 2000;
87 static const int kMaxWaitForStatsMs = 3000;
88 static const int kMaxWaitForFramesMs = 5000;
89 static const int kEndAudioFrameCount = 3;
90 static const int kEndVideoFrameCount = 3;
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";
97 static void RemoveLinesFromSdp(const std::string& line_start,
99 const char kSdpLineEnd[] = "\r\n";
101 while ((ssrc_pos = sdp->find(line_start, ssrc_pos)) !=
103 size_t end_ssrc = sdp->find(kSdpLineEnd, ssrc_pos);
104 sdp->erase(ssrc_pos, end_ssrc - ssrc_pos + strlen(kSdpLineEnd));
108 class SignalingMessageReceiver {
111 SignalingMessageReceiver() {}
112 virtual ~SignalingMessageReceiver() {}
115 class JsepMessageReceiver : public SignalingMessageReceiver {
117 virtual void ReceiveSdpMessage(const std::string& type,
118 std::string& msg) = 0;
119 virtual void ReceiveIceMessage(const std::string& sdp_mid,
121 const std::string& msg) = 0;
124 JsepMessageReceiver() {}
125 virtual ~JsepMessageReceiver() {}
128 template <typename MessageReceiver>
129 class PeerConnectionTestClientBase
130 : public webrtc::PeerConnectionObserver,
131 public MessageReceiver {
133 ~PeerConnectionTestClientBase() {
134 while (!fake_video_renderers_.empty()) {
135 RenderMap::iterator it = fake_video_renderers_.begin();
137 fake_video_renderers_.erase(it);
141 virtual void Negotiate() = 0;
143 virtual void Negotiate(bool audio, bool video) = 0;
145 virtual void SetVideoConstraints(
146 const webrtc::FakeConstraints& video_constraint) {
147 video_constraints_ = video_constraint;
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);
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,
169 stream->AddTrack(audio_track);
171 if (video && can_receive_video()) {
172 stream->AddTrack(CreateLocalVideoTrack(label));
175 EXPECT_TRUE(peer_connection_->AddStream(stream, NULL));
178 size_t NumberOfLocalMediaStreams() {
179 return peer_connection_->local_streams()->count();
182 bool SessionActive() {
183 return peer_connection_->signaling_state() ==
184 webrtc::PeerConnectionInterface::kStable;
187 void set_signaling_message_receiver(
188 MessageReceiver* signaling_message_receiver) {
189 signaling_message_receiver_ = signaling_message_receiver;
192 void EnableVideoDecoderFactory() {
193 video_decoder_factory_enabled_ = true;
194 fake_video_decoder_factory_->AddSupportedVideoCodecType(
195 webrtc::kVideoCodecVP8);
198 bool AudioFramesReceivedCheck(int number_of_frames) const {
199 return number_of_frames <= fake_audio_capture_module_->frames_received();
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;
210 for (std::vector<FakeWebRtcVideoDecoder*>::const_iterator
211 it = decoders.begin(); it != decoders.end(); ++it) {
212 if (number_of_frames > (*it)->GetNumFramesReceived()) {
218 if (fake_video_renderers_.empty()) {
219 return number_of_frames <= 0;
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()) {
231 // Verify the CreateDtmfSender interface
233 talk_base::scoped_ptr<DummyDtmfObserver> observer(new DummyDtmfObserver());
234 talk_base::scoped_refptr<DtmfSenderInterface> dtmf_sender;
236 // We can't create a DTMF sender with an invalid audio track or a non local
238 EXPECT_TRUE(peer_connection_->CreateDtmfSender(NULL) == NULL);
239 talk_base::scoped_refptr<webrtc::AudioTrackInterface> non_localtrack(
240 peer_connection_factory_->CreateAudioTrack("dummy_track",
242 EXPECT_TRUE(peer_connection_->CreateDtmfSender(non_localtrack) == NULL);
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());
251 // Test the DtmfSender object just created.
252 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
253 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
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.
258 EXPECT_TRUE_WAIT(observer->completed(), kMaxWaitMs);
259 std::vector<std::string> tones;
260 tones.push_back("1");
261 tones.push_back("a");
263 observer->Verify(tones);
265 dtmf_sender->UnregisterObserver();
268 // Verifies that the SessionDescription have rejected the appropriate media
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();
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);
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);
293 void SetExpectIceRestart(bool expect_restart) {
294 expect_ice_restart_ = expect_restart;
297 bool ExpectIceRestart() const { return expect_ice_restart_; }
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();
305 for (size_t index = 0; index < contents.size(); ++index) {
306 if (contents[index].rejected)
308 const cricket::TransportDescription* transport_desc =
309 desc->GetTransportDescriptionByName(contents[index].name);
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);
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);
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();
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();
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();
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();
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();
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();
377 size_t number_of_remote_streams() {
380 return pc()->remote_streams()->count();
383 StreamCollectionInterface* remote_streams() {
388 return pc()->remote_streams();
391 StreamCollectionInterface* local_streams() {
396 return pc()->local_streams();
399 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
400 return pc()->signaling_state();
403 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
404 return pc()->ice_connection_state();
407 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
408 return pc()->ice_gathering_state();
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);
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]);
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);
434 virtual void OnIceGatheringChange(
435 webrtc::PeerConnectionInterface::IceGatheringState new_state) {
436 EXPECT_EQ(peer_connection_->ice_gathering_state(), new_state);
438 virtual void OnIceCandidate(
439 const webrtc::IceCandidateInterface* /*candidate*/) {}
441 webrtc::PeerConnectionInterface* pc() {
442 return peer_connection_.get();
446 explicit PeerConnectionTestClientBase(const std::string& 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) {
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_) {
461 audio_thread_.Start();
462 fake_audio_capture_module_ = FakeAudioCaptureModule::Create(
465 if (fake_audio_capture_module_ == NULL) {
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_) {
477 peer_connection_ = CreatePeerConnection(allocator_factory_.get(),
479 return peer_connection_.get() != NULL;
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_;
487 webrtc::PeerConnectionFactoryInterface* peer_connection_factory() {
488 return peer_connection_factory_.get();
491 virtual bool can_receive_audio() = 0;
492 virtual bool can_receive_video() = 0;
493 const std::string& id() const { return id_; }
496 class DummyDtmfObserver : public DtmfSenderObserverInterface {
498 DummyDtmfObserver() : completed_(false) {}
500 // Implements DtmfSenderObserverInterface.
501 void OnToneChange(const std::string& tone) {
502 tones_.push_back(tone);
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()));
513 bool completed() const { return completed_; }
517 std::vector<std::string> tones_;
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);
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);
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_;
542 talk_base::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
544 talk_base::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
545 talk_base::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
546 peer_connection_factory_;
548 typedef std::pair<std::string, std::string> IceUfragPwdPair;
549 std::map<int, IceUfragPwdPair> ice_ufrag_pwd_;
550 bool expect_ice_restart_;
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
559 FakeWebRtcVideoDecoderFactory* fake_video_decoder_factory_;
560 FakeWebRtcVideoEncoderFactory* fake_video_encoder_factory_;
561 bool video_decoder_factory_enabled_;
562 webrtc::FakeConstraints video_constraints_;
564 // For remote peer communication.
565 MessageReceiver* signaling_message_receiver_;
569 : public PeerConnectionTestClientBase<JsepMessageReceiver> {
571 static JsepTestClient* CreateClient(
572 const std::string& id,
573 const MediaConstraintsInterface* constraints) {
574 JsepTestClient* client(new JsepTestClient(id));
575 if (!client->Init(constraints)) {
583 virtual void Negotiate() {
584 Negotiate(true, true);
586 virtual void Negotiate(bool audio, bool video) {
587 talk_base::scoped_ptr<SessionDescriptionInterface> offer;
588 EXPECT_TRUE(DoCreateOffer(offer.use()));
590 if (offer->description()->GetContentByName("audio")) {
591 offer->description()->GetContentByName("audio")->rejected = !audio;
593 if (offer->description()->GetContentByName("video")) {
594 offer->description()->GetContentByName("video")->rejected = !video;
598 EXPECT_TRUE(offer->ToString(&sdp));
599 EXPECT_TRUE(DoSetLocalDescription(offer.release()));
600 signaling_message_receiver()->ReceiveSdpMessage(
601 webrtc::SessionDescriptionInterface::kOffer, sdp);
603 // JsepMessageReceiver callback.
604 virtual void ReceiveSdpMessage(const std::string& type,
606 FilterIncomingSdpMessage(&msg);
607 if (type == webrtc::SessionDescriptionInterface::kOffer) {
608 HandleIncomingOffer(msg);
610 HandleIncomingAnswer(msg);
613 // JsepMessageReceiver callback.
614 virtual void ReceiveIceMessage(const std::string& sdp_mid,
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()));
622 // Implements PeerConnectionObserver functions needed by Jsep.
623 virtual void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) {
624 LOG(INFO) << id() << "OnIceCandidate";
627 EXPECT_TRUE(candidate->ToString(&ice_sdp));
628 if (signaling_message_receiver() == NULL) {
629 // Remote party may be deleted.
632 signaling_message_receiver()->ReceiveIceMessage(candidate->sdp_mid(),
633 candidate->sdp_mline_index(), ice_sdp);
637 session_description_constraints_.SetMandatoryIceRestart(true);
638 SetExpectIceRestart(true);
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());
648 void SetReceiveAudio(bool audio) {
649 if (audio && can_receive_audio())
651 session_description_constraints_.SetMandatoryReceiveAudio(audio);
654 void SetReceiveVideo(bool video) {
655 if (video && can_receive_video())
657 session_description_constraints_.SetMandatoryReceiveVideo(video);
660 void RemoveMsidFromReceivedSdp(bool remove) {
661 remove_msid_ = remove;
664 void RemoveSdesCryptoFromReceivedSdp(bool remove) {
665 remove_sdes_ = remove;
668 void RemoveBundleFromReceivedSdp(bool remove) {
669 remove_bundle_ = remove;
672 virtual bool can_receive_audio() {
674 if (webrtc::FindConstraint(&session_description_constraints_,
675 MediaConstraintsInterface::kOfferToReceiveAudio, &value, NULL)) {
681 virtual bool can_receive_video() {
683 if (webrtc::FindConstraint(&session_description_constraints_,
684 MediaConstraintsInterface::kOfferToReceiveVideo, &value, NULL)) {
690 virtual void OnIceComplete() {
691 LOG(INFO) << id() << "OnIceComplete";
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));
700 void CreateDataChannel() {
701 data_channel_ = pc()->CreateDataChannel(kDataChannelLabel,
703 ASSERT_TRUE(data_channel_.get() != NULL);
704 data_observer_.reset(new MockDataChannelObserver(data_channel_));
707 DataChannelInterface* data_channel() { return data_channel_; }
708 const MockDataChannelObserver* data_observer() const {
709 return data_observer_.get();
713 explicit JsepTestClient(const std::string& id)
714 : PeerConnectionTestClientBase<JsepMessageReceiver>(id),
716 remove_bundle_(false),
717 remove_sdes_(false) {
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);
729 FakeIdentityService* dtls_service =
730 talk_base::SSLStreamAdapter::HaveDtlsSrtp() ?
731 new FakeIdentityService() : NULL;
732 return peer_connection_factory()->CreatePeerConnection(
733 ice_servers, constraints, factory, dtls_service, this);
736 void HandleIncomingOffer(const std::string& msg) {
737 LOG(INFO) << id() << "HandleIncomingOffer ";
738 if (NumberOfLocalMediaStreams() == 0) {
739 // If we are not sending any streams ourselves it is time to add some.
740 AddMediaStream(true, true);
742 talk_base::scoped_ptr<SessionDescriptionInterface> desc(
743 webrtc::CreateSessionDescription("offer", msg, NULL));
744 EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
745 talk_base::scoped_ptr<SessionDescriptionInterface> answer;
746 EXPECT_TRUE(DoCreateAnswer(answer.use()));
748 EXPECT_TRUE(answer->ToString(&sdp));
749 EXPECT_TRUE(DoSetLocalDescription(answer.release()));
750 if (signaling_message_receiver()) {
751 signaling_message_receiver()->ReceiveSdpMessage(
752 webrtc::SessionDescriptionInterface::kAnswer, sdp);
756 void HandleIncomingAnswer(const std::string& msg) {
757 LOG(INFO) << id() << "HandleIncomingAnswer";
758 talk_base::scoped_ptr<SessionDescriptionInterface> desc(
759 webrtc::CreateSessionDescription("answer", msg, NULL));
760 EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
763 bool DoCreateOfferAnswer(SessionDescriptionInterface** desc,
765 talk_base::scoped_refptr<MockCreateSessionDescriptionObserver>
766 observer(new talk_base::RefCountedObject<
767 MockCreateSessionDescriptionObserver>());
769 pc()->CreateOffer(observer, &session_description_constraints_);
771 pc()->CreateAnswer(observer, &session_description_constraints_);
773 EXPECT_EQ_WAIT(true, observer->called(), kMaxWaitMs);
774 *desc = observer->release_desc();
775 if (observer->result() && ExpectIceRestart()) {
776 EXPECT_EQ(0u, (*desc)->candidates(0)->count());
778 return observer->result();
781 bool DoCreateOffer(SessionDescriptionInterface** desc) {
782 return DoCreateOfferAnswer(desc, true);
785 bool DoCreateAnswer(SessionDescriptionInterface** desc) {
786 return DoCreateOfferAnswer(desc, false);
789 bool DoSetLocalDescription(SessionDescriptionInterface* desc) {
790 talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
791 observer(new talk_base::RefCountedObject<
792 MockSetSessionDescriptionObserver>());
793 LOG(INFO) << id() << "SetLocalDescription ";
794 pc()->SetLocalDescription(observer, desc);
795 // Ignore the observer result. If we wait for the result with
796 // EXPECT_TRUE_WAIT, local ice candidates might be sent to the remote peer
797 // before the offer which is an error.
798 // The reason is that EXPECT_TRUE_WAIT uses
799 // talk_base::Thread::Current()->ProcessMessages(1);
800 // ProcessMessages waits at least 1ms but processes all messages before
801 // returning. Since this test is synchronous and send messages to the remote
802 // peer whenever a callback is invoked, this can lead to messages being
803 // sent to the remote peer in the wrong order.
804 // TODO(perkj): Find a way to check the result without risking that the
805 // order of sent messages are changed. Ex- by posting all messages that are
806 // sent to the remote peer.
810 bool DoSetRemoteDescription(SessionDescriptionInterface* desc) {
811 talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
812 observer(new talk_base::RefCountedObject<
813 MockSetSessionDescriptionObserver>());
814 LOG(INFO) << id() << "SetRemoteDescription ";
815 pc()->SetRemoteDescription(observer, desc);
816 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
817 return observer->result();
820 // This modifies all received SDP messages before they are processed.
821 void FilterIncomingSdpMessage(std::string* sdp) {
823 const char kSdpSsrcAttribute[] = "a=ssrc:";
824 RemoveLinesFromSdp(kSdpSsrcAttribute, sdp);
825 const char kSdpMsidSupportedAttribute[] = "a=msid-semantic:";
826 RemoveLinesFromSdp(kSdpMsidSupportedAttribute, sdp);
828 if (remove_bundle_) {
829 const char kSdpBundleAttribute[] = "a=group:BUNDLE";
830 RemoveLinesFromSdp(kSdpBundleAttribute, sdp);
833 const char kSdpSdesCryptoAttribute[] = "a=crypto";
834 RemoveLinesFromSdp(kSdpSdesCryptoAttribute, sdp);
839 webrtc::FakeConstraints session_description_constraints_;
840 bool remove_msid_; // True if MSID should be removed in received SDP.
841 bool remove_bundle_; // True if bundle should be removed in received SDP.
842 bool remove_sdes_; // True if a=crypto should be removed in received SDP.
844 talk_base::scoped_refptr<DataChannelInterface> data_channel_;
845 talk_base::scoped_ptr<MockDataChannelObserver> data_observer_;
848 template <typename SignalingClass>
849 class P2PTestConductor : public testing::Test {
851 bool SessionActive() {
852 return initiating_client_->SessionActive() &&
853 receiving_client_->SessionActive();
855 // Return true if the number of frames provided have been received or it is
856 // known that that will never occur (e.g. no frames will be sent or
858 bool FramesNotPending(int audio_frames_to_receive,
859 int video_frames_to_receive) {
860 return VideoFramesReceivedCheck(video_frames_to_receive) &&
861 AudioFramesReceivedCheck(audio_frames_to_receive);
863 bool AudioFramesReceivedCheck(int frames_received) {
864 return initiating_client_->AudioFramesReceivedCheck(frames_received) &&
865 receiving_client_->AudioFramesReceivedCheck(frames_received);
867 bool VideoFramesReceivedCheck(int frames_received) {
868 return initiating_client_->VideoFramesReceivedCheck(frames_received) &&
869 receiving_client_->VideoFramesReceivedCheck(frames_received);
872 initiating_client_->VerifyDtmf();
873 receiving_client_->VerifyDtmf();
876 void TestUpdateOfferWithRejectedContent() {
877 initiating_client_->Negotiate(true, false);
879 FramesNotPending(kEndAudioFrameCount * 2, kEndVideoFrameCount),
880 kMaxWaitForFramesMs);
881 // There shouldn't be any more video frame after the new offer is
883 EXPECT_FALSE(VideoFramesReceivedCheck(kEndVideoFrameCount + 1));
886 void VerifyRenderedSize(int width, int height) {
887 EXPECT_EQ(width, receiving_client()->rendered_width());
888 EXPECT_EQ(height, receiving_client()->rendered_height());
889 EXPECT_EQ(width, initializing_client()->rendered_width());
890 EXPECT_EQ(height, initializing_client()->rendered_height());
893 void VerifySessionDescriptions() {
894 initiating_client_->VerifyRejectedMediaInSessionDescription();
895 receiving_client_->VerifyRejectedMediaInSessionDescription();
896 initiating_client_->VerifyLocalIceUfragAndPassword();
897 receiving_client_->VerifyLocalIceUfragAndPassword();
901 talk_base::InitializeSSL(NULL);
903 ~P2PTestConductor() {
904 if (initiating_client_) {
905 initiating_client_->set_signaling_message_receiver(NULL);
907 if (receiving_client_) {
908 receiving_client_->set_signaling_message_receiver(NULL);
910 talk_base::CleanupSSL();
913 bool CreateTestClients() {
914 return CreateTestClients(NULL, NULL);
917 bool CreateTestClients(MediaConstraintsInterface* init_constraints,
918 MediaConstraintsInterface* recv_constraints) {
919 initiating_client_.reset(SignalingClass::CreateClient("Caller: ",
921 receiving_client_.reset(SignalingClass::CreateClient("Callee: ",
923 if (!initiating_client_ || !receiving_client_) {
926 initiating_client_->set_signaling_message_receiver(receiving_client_.get());
927 receiving_client_->set_signaling_message_receiver(initiating_client_.get());
931 void SetVideoConstraints(const webrtc::FakeConstraints& init_constraints,
932 const webrtc::FakeConstraints& recv_constraints) {
933 initiating_client_->SetVideoConstraints(init_constraints);
934 receiving_client_->SetVideoConstraints(recv_constraints);
937 void EnableVideoDecoderFactory() {
938 initiating_client_->EnableVideoDecoderFactory();
939 receiving_client_->EnableVideoDecoderFactory();
942 // This test sets up a call between two parties. Both parties send static
943 // frames to each other. Once the test is finished the number of sent frames
944 // is compared to the number of received frames.
945 void LocalP2PTest() {
946 if (initiating_client_->NumberOfLocalMediaStreams() == 0) {
947 initiating_client_->AddMediaStream(true, true);
949 initiating_client_->Negotiate();
950 const int kMaxWaitForActivationMs = 5000;
951 // Assert true is used here since next tests are guaranteed to fail and
952 // would eat up 5 seconds.
953 ASSERT_TRUE_WAIT(SessionActive(), kMaxWaitForActivationMs);
954 VerifySessionDescriptions();
957 int audio_frame_count = kEndAudioFrameCount;
958 // TODO(ronghuawu): Add test to cover the case of sendonly and recvonly.
959 if (!initiating_client_->can_receive_audio() ||
960 !receiving_client_->can_receive_audio()) {
961 audio_frame_count = -1;
963 int video_frame_count = kEndVideoFrameCount;
964 if (!initiating_client_->can_receive_video() ||
965 !receiving_client_->can_receive_video()) {
966 video_frame_count = -1;
969 if (audio_frame_count != -1 || video_frame_count != -1) {
970 // Audio or video is expected to flow, so both clients should reach the
971 // Connected state, and the offerer (ICE controller) should proceed to
973 // Note: These tests have been observed to fail under heavy load at
974 // shorter timeouts, so they may be flaky.
976 webrtc::PeerConnectionInterface::kIceConnectionCompleted,
977 initiating_client_->ice_connection_state(),
978 kMaxWaitForFramesMs);
980 webrtc::PeerConnectionInterface::kIceConnectionConnected,
981 receiving_client_->ice_connection_state(),
982 kMaxWaitForFramesMs);
985 if (initiating_client_->can_receive_audio() ||
986 initiating_client_->can_receive_video()) {
987 // The initiating client can receive media, so it must produce candidates
988 // that will serve as destinations for that media.
989 // TODO(bemasc): Understand why the state is not already Complete here, as
990 // seems to be the case for the receiving client. This may indicate a bug
991 // in the ICE gathering system.
992 EXPECT_NE(webrtc::PeerConnectionInterface::kIceGatheringNew,
993 initiating_client_->ice_gathering_state());
995 if (receiving_client_->can_receive_audio() ||
996 receiving_client_->can_receive_video()) {
997 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
998 receiving_client_->ice_gathering_state(),
999 kMaxWaitForFramesMs);
1002 EXPECT_TRUE_WAIT(FramesNotPending(audio_frame_count, video_frame_count),
1003 kMaxWaitForFramesMs);
1006 SignalingClass* initializing_client() { return initiating_client_.get(); }
1007 SignalingClass* receiving_client() { return receiving_client_.get(); }
1010 talk_base::scoped_ptr<SignalingClass> initiating_client_;
1011 talk_base::scoped_ptr<SignalingClass> receiving_client_;
1013 typedef P2PTestConductor<JsepTestClient> JsepPeerConnectionP2PTestClient;
1015 // Disable for TSan v2, see
1016 // https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
1017 #if !defined(THREAD_SANITIZER)
1019 // This test sets up a Jsep call between two parties and test Dtmf.
1020 // TODO(holmer): Disabled due to sometimes crashing on buildbots.
1021 // See issue webrtc/2378.
1022 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestDtmf) {
1023 ASSERT_TRUE(CreateTestClients());
1028 // This test sets up a Jsep call between two parties and test that we can get a
1029 // video aspect ratio of 16:9.
1030 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTest16To9) {
1031 ASSERT_TRUE(CreateTestClients());
1032 FakeConstraints constraint;
1033 double requested_ratio = 640.0/360;
1034 constraint.SetMandatoryMinAspectRatio(requested_ratio);
1035 SetVideoConstraints(constraint, constraint);
1038 ASSERT_LE(0, initializing_client()->rendered_height());
1039 double initiating_video_ratio =
1040 static_cast<double>(initializing_client()->rendered_width()) /
1041 initializing_client()->rendered_height();
1042 EXPECT_LE(requested_ratio, initiating_video_ratio);
1044 ASSERT_LE(0, receiving_client()->rendered_height());
1045 double receiving_video_ratio =
1046 static_cast<double>(receiving_client()->rendered_width()) /
1047 receiving_client()->rendered_height();
1048 EXPECT_LE(requested_ratio, receiving_video_ratio);
1051 // This test sets up a Jsep call between two parties and test that the
1052 // received video has a resolution of 1280*720.
1053 // TODO(mallinath): Enable when
1054 // http://code.google.com/p/webrtc/issues/detail?id=981 is fixed.
1055 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTest1280By720) {
1056 ASSERT_TRUE(CreateTestClients());
1057 FakeConstraints constraint;
1058 constraint.SetMandatoryMinWidth(1280);
1059 constraint.SetMandatoryMinHeight(720);
1060 SetVideoConstraints(constraint, constraint);
1062 VerifyRenderedSize(1280, 720);
1065 // This test sets up a call between two endpoints that are configured to use
1066 // DTLS key agreement. As a result, DTLS is negotiated and used for transport.
1067 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDtls) {
1068 MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
1069 FakeConstraints setup_constraints;
1070 setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1072 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1074 VerifyRenderedSize(640, 480);
1077 // This test sets up a audio call initially and then upgrades to audio/video,
1079 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDtlsRenegotiate) {
1080 MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
1081 FakeConstraints setup_constraints;
1082 setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1084 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1085 receiving_client()->SetReceiveAudioVideo(true, false);
1087 receiving_client()->SetReceiveAudioVideo(true, true);
1088 receiving_client()->Negotiate();
1091 // This test sets up a call between two endpoints that are configured to use
1092 // DTLS key agreement. The offerer don't support SDES. As a result, DTLS is
1093 // negotiated and used for transport.
1094 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestOfferDtlsButNotSdes) {
1095 MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
1096 FakeConstraints setup_constraints;
1097 setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1099 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1100 receiving_client()->RemoveSdesCryptoFromReceivedSdp(true);
1102 VerifyRenderedSize(640, 480);
1105 // This test sets up a Jsep call between two parties, and the callee only
1106 // accept to receive video.
1107 // BUG=https://code.google.com/p/webrtc/issues/detail?id=2288
1108 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestAnswerVideo) {
1109 ASSERT_TRUE(CreateTestClients());
1110 receiving_client()->SetReceiveAudioVideo(false, true);
1114 // This test sets up a Jsep call between two parties, and the callee only
1115 // accept to receive audio.
1116 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestAnswerAudio) {
1117 ASSERT_TRUE(CreateTestClients());
1118 receiving_client()->SetReceiveAudioVideo(true, false);
1122 // This test sets up a Jsep call between two parties, and the callee reject both
1124 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestAnswerNone) {
1125 ASSERT_TRUE(CreateTestClients());
1126 receiving_client()->SetReceiveAudioVideo(false, false);
1130 // This test sets up an audio and video call between two parties. After the call
1131 // runs for a while (10 frames), the caller sends an update offer with video
1132 // being rejected. Once the re-negotiation is done, the video flow should stop
1133 // and the audio flow should continue.
1134 TEST_F(JsepPeerConnectionP2PTestClient, UpdateOfferWithRejectedContent) {
1135 ASSERT_TRUE(CreateTestClients());
1137 TestUpdateOfferWithRejectedContent();
1140 // This test sets up a Jsep call between two parties. The MSID is removed from
1141 // the SDP strings from the caller.
1142 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestWithoutMsid) {
1143 ASSERT_TRUE(CreateTestClients());
1144 receiving_client()->RemoveMsidFromReceivedSdp(true);
1145 // TODO(perkj): Currently there is a bug that cause audio to stop playing if
1146 // audio and video is muxed when MSID is disabled. Remove
1147 // SetRemoveBundleFromSdp once
1148 // https://code.google.com/p/webrtc/issues/detail?id=1193 is fixed.
1149 receiving_client()->RemoveBundleFromReceivedSdp(true);
1153 // This test sets up a Jsep call between two parties and the initiating peer
1154 // sends two steams.
1155 // TODO(perkj): Disabled due to
1156 // https://code.google.com/p/webrtc/issues/detail?id=1454
1157 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestTwoStreams) {
1158 ASSERT_TRUE(CreateTestClients());
1159 // Set optional video constraint to max 320pixels to decrease CPU usage.
1160 FakeConstraints constraint;
1161 constraint.SetOptionalMaxWidth(320);
1162 SetVideoConstraints(constraint, constraint);
1163 initializing_client()->AddMediaStream(true, true);
1164 initializing_client()->AddMediaStream(false, true);
1165 ASSERT_EQ(2u, initializing_client()->NumberOfLocalMediaStreams());
1167 EXPECT_EQ(2u, receiving_client()->number_of_remote_streams());
1170 // Test that we can receive the audio output level from a remote audio track.
1171 TEST_F(JsepPeerConnectionP2PTestClient, GetAudioOutputLevelStats) {
1172 ASSERT_TRUE(CreateTestClients());
1175 StreamCollectionInterface* remote_streams =
1176 initializing_client()->remote_streams();
1177 ASSERT_GT(remote_streams->count(), 0u);
1178 ASSERT_GT(remote_streams->at(0)->GetAudioTracks().size(), 0u);
1179 MediaStreamTrackInterface* remote_audio_track =
1180 remote_streams->at(0)->GetAudioTracks()[0];
1182 // Get the audio output level stats. Note that the level is not available
1183 // until a RTCP packet has been received.
1185 initializing_client()->GetAudioOutputLevelStats(remote_audio_track) > 0,
1186 kMaxWaitForStatsMs);
1189 // Test that an audio input level is reported.
1190 TEST_F(JsepPeerConnectionP2PTestClient, GetAudioInputLevelStats) {
1191 ASSERT_TRUE(CreateTestClients());
1194 // Get the audio input level stats. The level should be available very
1195 // soon after the test starts.
1196 EXPECT_TRUE_WAIT(initializing_client()->GetAudioInputLevelStats() > 0,
1197 kMaxWaitForStatsMs);
1200 // Test that we can get incoming byte counts from both audio and video tracks.
1201 TEST_F(JsepPeerConnectionP2PTestClient, GetBytesReceivedStats) {
1202 ASSERT_TRUE(CreateTestClients());
1205 StreamCollectionInterface* remote_streams =
1206 initializing_client()->remote_streams();
1207 ASSERT_GT(remote_streams->count(), 0u);
1208 ASSERT_GT(remote_streams->at(0)->GetAudioTracks().size(), 0u);
1209 MediaStreamTrackInterface* remote_audio_track =
1210 remote_streams->at(0)->GetAudioTracks()[0];
1212 initializing_client()->GetBytesReceivedStats(remote_audio_track) > 0,
1213 kMaxWaitForStatsMs);
1215 MediaStreamTrackInterface* remote_video_track =
1216 remote_streams->at(0)->GetVideoTracks()[0];
1218 initializing_client()->GetBytesReceivedStats(remote_video_track) > 0,
1219 kMaxWaitForStatsMs);
1222 // Test that we can get outgoing byte counts from both audio and video tracks.
1223 TEST_F(JsepPeerConnectionP2PTestClient, GetBytesSentStats) {
1224 ASSERT_TRUE(CreateTestClients());
1227 StreamCollectionInterface* local_streams =
1228 initializing_client()->local_streams();
1229 ASSERT_GT(local_streams->count(), 0u);
1230 ASSERT_GT(local_streams->at(0)->GetAudioTracks().size(), 0u);
1231 MediaStreamTrackInterface* local_audio_track =
1232 local_streams->at(0)->GetAudioTracks()[0];
1234 initializing_client()->GetBytesSentStats(local_audio_track) > 0,
1235 kMaxWaitForStatsMs);
1237 MediaStreamTrackInterface* local_video_track =
1238 local_streams->at(0)->GetVideoTracks()[0];
1240 initializing_client()->GetBytesSentStats(local_video_track) > 0,
1241 kMaxWaitForStatsMs);
1244 // This test sets up a call between two parties with audio, video and data.
1245 // TODO(jiayl): fix the flakiness on Windows and reenable. Issue 2891.
1247 TEST_F(JsepPeerConnectionP2PTestClient, DISABLED_LocalP2PTestDataChannel) {
1249 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestDataChannel) {
1251 FakeConstraints setup_constraints;
1252 setup_constraints.SetAllowRtpDataChannels();
1253 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1254 initializing_client()->CreateDataChannel();
1256 ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1257 ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1258 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1260 EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(),
1263 std::string data = "hello world";
1264 initializing_client()->data_channel()->Send(DataBuffer(data));
1265 EXPECT_EQ_WAIT(data, receiving_client()->data_observer()->last_message(),
1267 receiving_client()->data_channel()->Send(DataBuffer(data));
1268 EXPECT_EQ_WAIT(data, initializing_client()->data_observer()->last_message(),
1271 receiving_client()->data_channel()->Close();
1272 // Send new offer and answer.
1273 receiving_client()->Negotiate();
1274 EXPECT_FALSE(initializing_client()->data_observer()->IsOpen());
1275 EXPECT_FALSE(receiving_client()->data_observer()->IsOpen());
1278 // This test sets up a call between two parties and creates a data channel.
1279 // The test tests that received data is buffered unless an observer has been
1281 // Rtp data channels can receive data before the underlying
1282 // transport has detected that a channel is writable and thus data can be
1283 // received before the data channel state changes to open. That is hard to test
1284 // but the same buffering is used in that case.
1285 TEST_F(JsepPeerConnectionP2PTestClient, RegisterDataChannelObserver) {
1286 FakeConstraints setup_constraints;
1287 setup_constraints.SetAllowRtpDataChannels();
1288 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1289 initializing_client()->CreateDataChannel();
1290 initializing_client()->Negotiate();
1292 ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1293 ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1294 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1296 EXPECT_EQ_WAIT(DataChannelInterface::kOpen,
1297 receiving_client()->data_channel()->state(), kMaxWaitMs);
1299 // Unregister the existing observer.
1300 receiving_client()->data_channel()->UnregisterObserver();
1301 std::string data = "hello world";
1302 initializing_client()->data_channel()->Send(DataBuffer(data));
1303 // Wait a while to allow the sent data to arrive before an observer is
1305 talk_base::Thread::Current()->ProcessMessages(100);
1307 MockDataChannelObserver new_observer(receiving_client()->data_channel());
1308 EXPECT_EQ_WAIT(data, new_observer.last_message(), kMaxWaitMs);
1311 // This test sets up a call between two parties with audio, video and but only
1312 // the initiating client support data.
1313 TEST_F(JsepPeerConnectionP2PTestClient, LocalP2PTestReceiverDoesntSupportData) {
1314 FakeConstraints setup_constraints_1;
1315 setup_constraints_1.SetAllowRtpDataChannels();
1316 // Must disable DTLS to make negotiation succeed.
1317 setup_constraints_1.SetMandatory(
1318 MediaConstraintsInterface::kEnableDtlsSrtp, false);
1319 FakeConstraints setup_constraints_2;
1320 setup_constraints_2.SetMandatory(
1321 MediaConstraintsInterface::kEnableDtlsSrtp, false);
1322 ASSERT_TRUE(CreateTestClients(&setup_constraints_1, &setup_constraints_2));
1323 initializing_client()->CreateDataChannel();
1325 EXPECT_TRUE(initializing_client()->data_channel() != NULL);
1326 EXPECT_FALSE(receiving_client()->data_channel());
1327 EXPECT_FALSE(initializing_client()->data_observer()->IsOpen());
1330 // This test sets up a call between two parties with audio, video. When audio
1331 // and video is setup and flowing and data channel is negotiated.
1332 TEST_F(JsepPeerConnectionP2PTestClient, AddDataChannelAfterRenegotiation) {
1333 FakeConstraints setup_constraints;
1334 setup_constraints.SetAllowRtpDataChannels();
1335 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1337 initializing_client()->CreateDataChannel();
1338 // Send new offer and answer.
1339 initializing_client()->Negotiate();
1340 ASSERT_TRUE(initializing_client()->data_channel() != NULL);
1341 ASSERT_TRUE(receiving_client()->data_channel() != NULL);
1342 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
1344 EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(),
1348 // This test sets up a Jsep call with SCTP DataChannel and verifies the
1349 // negotiation is completed without error.
1351 TEST_F(JsepPeerConnectionP2PTestClient, CreateOfferWithSctpDataChannel) {
1352 MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
1353 FakeConstraints constraints;
1354 constraints.SetMandatory(
1355 MediaConstraintsInterface::kEnableDtlsSrtp, true);
1356 ASSERT_TRUE(CreateTestClients(&constraints, &constraints));
1357 initializing_client()->CreateDataChannel();
1358 initializing_client()->Negotiate(false, false);
1362 // This test sets up a call between two parties with audio, and video.
1363 // During the call, the initializing side restart ice and the test verifies that
1364 // new ice candidates are generated and audio and video still can flow.
1365 TEST_F(JsepPeerConnectionP2PTestClient, IceRestart) {
1366 ASSERT_TRUE(CreateTestClients());
1368 // Negotiate and wait for ice completion and make sure audio and video plays.
1371 // Create a SDP string of the first audio candidate for both clients.
1372 const webrtc::IceCandidateCollection* audio_candidates_initiator =
1373 initializing_client()->pc()->local_description()->candidates(0);
1374 const webrtc::IceCandidateCollection* audio_candidates_receiver =
1375 receiving_client()->pc()->local_description()->candidates(0);
1376 ASSERT_GT(audio_candidates_initiator->count(), 0u);
1377 ASSERT_GT(audio_candidates_receiver->count(), 0u);
1378 std::string initiator_candidate;
1380 audio_candidates_initiator->at(0)->ToString(&initiator_candidate));
1381 std::string receiver_candidate;
1382 EXPECT_TRUE(audio_candidates_receiver->at(0)->ToString(&receiver_candidate));
1384 // Restart ice on the initializing client.
1385 receiving_client()->SetExpectIceRestart(true);
1386 initializing_client()->IceRestart();
1388 // Negotiate and wait for ice completion again and make sure audio and video
1392 // Create a SDP string of the first audio candidate for both clients again.
1393 const webrtc::IceCandidateCollection* audio_candidates_initiator_restart =
1394 initializing_client()->pc()->local_description()->candidates(0);
1395 const webrtc::IceCandidateCollection* audio_candidates_reciever_restart =
1396 receiving_client()->pc()->local_description()->candidates(0);
1397 ASSERT_GT(audio_candidates_initiator_restart->count(), 0u);
1398 ASSERT_GT(audio_candidates_reciever_restart->count(), 0u);
1399 std::string initiator_candidate_restart;
1400 EXPECT_TRUE(audio_candidates_initiator_restart->at(0)->ToString(
1401 &initiator_candidate_restart));
1402 std::string receiver_candidate_restart;
1403 EXPECT_TRUE(audio_candidates_reciever_restart->at(0)->ToString(
1404 &receiver_candidate_restart));
1406 // Verify that the first candidates in the local session descriptions has
1408 EXPECT_NE(initiator_candidate, initiator_candidate_restart);
1409 EXPECT_NE(receiver_candidate, receiver_candidate_restart);
1413 // This test sets up a Jsep call between two parties with external
1414 // VideoDecoderFactory.
1415 // TODO(holmer): Disabled due to sometimes crashing on buildbots.
1416 // See issue webrtc/2378.
1417 TEST_F(JsepPeerConnectionP2PTestClient,
1418 DISABLED_LocalP2PTestWithVideoDecoderFactory) {
1419 ASSERT_TRUE(CreateTestClients());
1420 EnableVideoDecoderFactory();
1423 #endif // if !defined(THREAD_SANITIZER)