Home | History | Annotate | Download | only in webrtc
      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 <string>
     29 
     30 #include "talk/app/webrtc/fakeportallocatorfactory.h"
     31 #include "talk/app/webrtc/jsepsessiondescription.h"
     32 #include "talk/app/webrtc/localvideosource.h"
     33 #include "talk/app/webrtc/mediastreaminterface.h"
     34 #include "talk/app/webrtc/peerconnectioninterface.h"
     35 #include "talk/app/webrtc/test/fakeconstraints.h"
     36 #include "talk/app/webrtc/test/mockpeerconnectionobservers.h"
     37 #include "talk/app/webrtc/test/testsdpstrings.h"
     38 #include "talk/base/gunit.h"
     39 #include "talk/base/scoped_ptr.h"
     40 #include "talk/base/sslstreamadapter.h"
     41 #include "talk/base/stringutils.h"
     42 #include "talk/base/thread.h"
     43 #include "talk/media/base/fakevideocapturer.h"
     44 #include "talk/session/media/mediasession.h"
     45 
     46 static const char kStreamLabel1[] = "local_stream_1";
     47 static const char kStreamLabel2[] = "local_stream_2";
     48 static const char kStreamLabel3[] = "local_stream_3";
     49 static const int kDefaultStunPort = 3478;
     50 static const char kStunAddressOnly[] = "stun:address";
     51 static const char kStunInvalidPort[] = "stun:address:-1";
     52 static const char kStunAddressPortAndMore1[] = "stun:address:port:more";
     53 static const char kStunAddressPortAndMore2[] = "stun:address:port more";
     54 static const char kTurnIceServerUri[] = "turn:user (at) turn.example.org";
     55 static const char kTurnUsername[] = "user";
     56 static const char kTurnPassword[] = "password";
     57 static const char kTurnHostname[] = "turn.example.org";
     58 static const uint32 kTimeout = 5000U;
     59 
     60 #define MAYBE_SKIP_TEST(feature)                    \
     61   if (!(feature())) {                               \
     62     LOG(LS_INFO) << "Feature disabled... skipping"; \
     63     return;                                         \
     64   }
     65 
     66 using talk_base::scoped_ptr;
     67 using talk_base::scoped_refptr;
     68 using webrtc::AudioSourceInterface;
     69 using webrtc::AudioTrackInterface;
     70 using webrtc::DataBuffer;
     71 using webrtc::DataChannelInterface;
     72 using webrtc::FakeConstraints;
     73 using webrtc::FakePortAllocatorFactory;
     74 using webrtc::IceCandidateInterface;
     75 using webrtc::MediaStreamInterface;
     76 using webrtc::MediaStreamTrackInterface;
     77 using webrtc::MockCreateSessionDescriptionObserver;
     78 using webrtc::MockDataChannelObserver;
     79 using webrtc::MockSetSessionDescriptionObserver;
     80 using webrtc::MockStatsObserver;
     81 using webrtc::PeerConnectionInterface;
     82 using webrtc::PeerConnectionObserver;
     83 using webrtc::PortAllocatorFactoryInterface;
     84 using webrtc::SdpParseError;
     85 using webrtc::SessionDescriptionInterface;
     86 using webrtc::VideoSourceInterface;
     87 using webrtc::VideoTrackInterface;
     88 
     89 namespace {
     90 
     91 // Gets the first ssrc of given content type from the ContentInfo.
     92 bool GetFirstSsrc(const cricket::ContentInfo* content_info, int* ssrc) {
     93   if (!content_info || !ssrc) {
     94     return false;
     95   }
     96   const cricket::MediaContentDescription* media_desc =
     97       static_cast<const cricket::MediaContentDescription*>(
     98           content_info->description);
     99   if (!media_desc || media_desc->streams().empty()) {
    100     return false;
    101   }
    102   *ssrc = media_desc->streams().begin()->first_ssrc();
    103   return true;
    104 }
    105 
    106 void SetSsrcToZero(std::string* sdp) {
    107   const char kSdpSsrcAtribute[] = "a=ssrc:";
    108   const char kSdpSsrcAtributeZero[] = "a=ssrc:0";
    109   size_t ssrc_pos = 0;
    110   while ((ssrc_pos = sdp->find(kSdpSsrcAtribute, ssrc_pos)) !=
    111       std::string::npos) {
    112     size_t end_ssrc = sdp->find(" ", ssrc_pos);
    113     sdp->replace(ssrc_pos, end_ssrc - ssrc_pos, kSdpSsrcAtributeZero);
    114     ssrc_pos = end_ssrc;
    115   }
    116 }
    117 
    118 class MockPeerConnectionObserver : public PeerConnectionObserver {
    119  public:
    120   MockPeerConnectionObserver()
    121       : renegotiation_needed_(false),
    122         ice_complete_(false) {
    123   }
    124   ~MockPeerConnectionObserver() {
    125   }
    126   void SetPeerConnectionInterface(PeerConnectionInterface* pc) {
    127     pc_ = pc;
    128     if (pc) {
    129       state_ = pc_->signaling_state();
    130     }
    131   }
    132   virtual void OnError() {}
    133   virtual void OnSignalingChange(
    134       PeerConnectionInterface::SignalingState new_state) {
    135     EXPECT_EQ(pc_->signaling_state(), new_state);
    136     state_ = new_state;
    137   }
    138   // TODO(bemasc): Remove this once callers transition to OnIceGatheringChange.
    139   virtual void OnStateChange(StateType state_changed) {
    140     if (pc_.get() == NULL)
    141       return;
    142     switch (state_changed) {
    143       case kSignalingState:
    144         // OnSignalingChange and OnStateChange(kSignalingState) should always
    145         // be called approximately simultaneously.  To ease testing, we require
    146         // that they always be called in that order.  This check verifies
    147         // that OnSignalingChange has just been called.
    148         EXPECT_EQ(pc_->signaling_state(), state_);
    149         break;
    150       case kIceState:
    151         ADD_FAILURE();
    152         break;
    153       default:
    154         ADD_FAILURE();
    155         break;
    156     }
    157   }
    158   virtual void OnAddStream(MediaStreamInterface* stream) {
    159     last_added_stream_ = stream;
    160   }
    161   virtual void OnRemoveStream(MediaStreamInterface* stream) {
    162     last_removed_stream_ = stream;
    163   }
    164   virtual void OnRenegotiationNeeded() {
    165     renegotiation_needed_ = true;
    166   }
    167   virtual void OnDataChannel(DataChannelInterface* data_channel) {
    168     last_datachannel_ = data_channel;
    169   }
    170 
    171   virtual void OnIceConnectionChange(
    172       PeerConnectionInterface::IceConnectionState new_state) {
    173     EXPECT_EQ(pc_->ice_connection_state(), new_state);
    174   }
    175   virtual void OnIceGatheringChange(
    176       PeerConnectionInterface::IceGatheringState new_state) {
    177     EXPECT_EQ(pc_->ice_gathering_state(), new_state);
    178   }
    179   virtual void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) {
    180     EXPECT_NE(PeerConnectionInterface::kIceGatheringNew,
    181               pc_->ice_gathering_state());
    182 
    183     std::string sdp;
    184     EXPECT_TRUE(candidate->ToString(&sdp));
    185     EXPECT_LT(0u, sdp.size());
    186     last_candidate_.reset(webrtc::CreateIceCandidate(candidate->sdp_mid(),
    187         candidate->sdp_mline_index(), sdp, NULL));
    188     EXPECT_TRUE(last_candidate_.get() != NULL);
    189   }
    190   // TODO(bemasc): Remove this once callers transition to OnSignalingChange.
    191   virtual void OnIceComplete() {
    192     ice_complete_ = true;
    193     // OnIceGatheringChange(IceGatheringCompleted) and OnIceComplete() should
    194     // be called approximately simultaneously.  For ease of testing, this
    195     // check additionally requires that they be called in the above order.
    196     EXPECT_EQ(PeerConnectionInterface::kIceGatheringComplete,
    197       pc_->ice_gathering_state());
    198   }
    199 
    200   // Returns the label of the last added stream.
    201   // Empty string if no stream have been added.
    202   std::string GetLastAddedStreamLabel() {
    203     if (last_added_stream_.get())
    204       return last_added_stream_->label();
    205     return "";
    206   }
    207   std::string GetLastRemovedStreamLabel() {
    208     if (last_removed_stream_.get())
    209       return last_removed_stream_->label();
    210     return "";
    211   }
    212 
    213   scoped_refptr<PeerConnectionInterface> pc_;
    214   PeerConnectionInterface::SignalingState state_;
    215   scoped_ptr<IceCandidateInterface> last_candidate_;
    216   scoped_refptr<DataChannelInterface> last_datachannel_;
    217   bool renegotiation_needed_;
    218   bool ice_complete_;
    219 
    220  private:
    221   scoped_refptr<MediaStreamInterface> last_added_stream_;
    222   scoped_refptr<MediaStreamInterface> last_removed_stream_;
    223 };
    224 
    225 }  // namespace
    226 class PeerConnectionInterfaceTest : public testing::Test {
    227  protected:
    228   virtual void SetUp() {
    229     pc_factory_ = webrtc::CreatePeerConnectionFactory(
    230         talk_base::Thread::Current(), talk_base::Thread::Current(), NULL, NULL,
    231         NULL);
    232     ASSERT_TRUE(pc_factory_.get() != NULL);
    233   }
    234 
    235   void CreatePeerConnection() {
    236     CreatePeerConnection("", "", NULL);
    237   }
    238 
    239   void CreatePeerConnection(webrtc::MediaConstraintsInterface* constraints) {
    240     CreatePeerConnection("", "", constraints);
    241   }
    242 
    243   void CreatePeerConnection(const std::string& uri,
    244                             const std::string& password,
    245                             webrtc::MediaConstraintsInterface* constraints) {
    246     PeerConnectionInterface::IceServer server;
    247     PeerConnectionInterface::IceServers servers;
    248     server.uri = uri;
    249     server.password = password;
    250     servers.push_back(server);
    251 
    252     port_allocator_factory_ = FakePortAllocatorFactory::Create();
    253     pc_ = pc_factory_->CreatePeerConnection(servers, constraints,
    254                                             port_allocator_factory_.get(),
    255                                             NULL,
    256                                             &observer_);
    257     ASSERT_TRUE(pc_.get() != NULL);
    258     observer_.SetPeerConnectionInterface(pc_.get());
    259     EXPECT_EQ(PeerConnectionInterface::kStable, observer_.state_);
    260   }
    261 
    262   void CreatePeerConnectionWithDifferentConfigurations() {
    263     CreatePeerConnection(kStunAddressOnly, "", NULL);
    264     EXPECT_EQ(1u, port_allocator_factory_->stun_configs().size());
    265     EXPECT_EQ(0u, port_allocator_factory_->turn_configs().size());
    266     EXPECT_EQ("address",
    267         port_allocator_factory_->stun_configs()[0].server.hostname());
    268     EXPECT_EQ(kDefaultStunPort,
    269         port_allocator_factory_->stun_configs()[0].server.port());
    270 
    271     CreatePeerConnection(kStunInvalidPort, "", NULL);
    272     EXPECT_EQ(0u, port_allocator_factory_->stun_configs().size());
    273     EXPECT_EQ(0u, port_allocator_factory_->turn_configs().size());
    274 
    275     CreatePeerConnection(kStunAddressPortAndMore1, "", NULL);
    276     EXPECT_EQ(0u, port_allocator_factory_->stun_configs().size());
    277     EXPECT_EQ(0u, port_allocator_factory_->turn_configs().size());
    278 
    279     CreatePeerConnection(kStunAddressPortAndMore2, "", NULL);
    280     EXPECT_EQ(0u, port_allocator_factory_->stun_configs().size());
    281     EXPECT_EQ(0u, port_allocator_factory_->turn_configs().size());
    282 
    283     CreatePeerConnection(kTurnIceServerUri, kTurnPassword, NULL);
    284     EXPECT_EQ(1u, port_allocator_factory_->stun_configs().size());
    285     EXPECT_EQ(1u, port_allocator_factory_->turn_configs().size());
    286     EXPECT_EQ(kTurnUsername,
    287               port_allocator_factory_->turn_configs()[0].username);
    288     EXPECT_EQ(kTurnPassword,
    289               port_allocator_factory_->turn_configs()[0].password);
    290     EXPECT_EQ(kTurnHostname,
    291               port_allocator_factory_->turn_configs()[0].server.hostname());
    292     EXPECT_EQ(kTurnHostname,
    293               port_allocator_factory_->stun_configs()[0].server.hostname());
    294   }
    295 
    296   void ReleasePeerConnection() {
    297     pc_ = NULL;
    298     observer_.SetPeerConnectionInterface(NULL);
    299   }
    300 
    301   void AddStream(const std::string& label) {
    302     // Create a local stream.
    303     scoped_refptr<MediaStreamInterface> stream(
    304         pc_factory_->CreateLocalMediaStream(label));
    305     scoped_refptr<VideoSourceInterface> video_source(
    306         pc_factory_->CreateVideoSource(new cricket::FakeVideoCapturer(), NULL));
    307     scoped_refptr<VideoTrackInterface> video_track(
    308         pc_factory_->CreateVideoTrack(label + "v0", video_source));
    309     stream->AddTrack(video_track.get());
    310     EXPECT_TRUE(pc_->AddStream(stream, NULL));
    311     EXPECT_TRUE_WAIT(observer_.renegotiation_needed_, kTimeout);
    312     observer_.renegotiation_needed_ = false;
    313   }
    314 
    315   void AddVoiceStream(const std::string& label) {
    316     // Create a local stream.
    317     scoped_refptr<MediaStreamInterface> stream(
    318         pc_factory_->CreateLocalMediaStream(label));
    319     scoped_refptr<AudioTrackInterface> audio_track(
    320         pc_factory_->CreateAudioTrack(label + "a0", NULL));
    321     stream->AddTrack(audio_track.get());
    322     EXPECT_TRUE(pc_->AddStream(stream, NULL));
    323     EXPECT_TRUE_WAIT(observer_.renegotiation_needed_, kTimeout);
    324     observer_.renegotiation_needed_ = false;
    325   }
    326 
    327   void AddAudioVideoStream(const std::string& stream_label,
    328                            const std::string& audio_track_label,
    329                            const std::string& video_track_label) {
    330     // Create a local stream.
    331     scoped_refptr<MediaStreamInterface> stream(
    332         pc_factory_->CreateLocalMediaStream(stream_label));
    333     scoped_refptr<AudioTrackInterface> audio_track(
    334         pc_factory_->CreateAudioTrack(
    335             audio_track_label, static_cast<AudioSourceInterface*>(NULL)));
    336     stream->AddTrack(audio_track.get());
    337     scoped_refptr<VideoTrackInterface> video_track(
    338         pc_factory_->CreateVideoTrack(video_track_label, NULL));
    339     stream->AddTrack(video_track.get());
    340     EXPECT_TRUE(pc_->AddStream(stream, NULL));
    341     EXPECT_TRUE_WAIT(observer_.renegotiation_needed_, kTimeout);
    342     observer_.renegotiation_needed_ = false;
    343   }
    344 
    345   bool DoCreateOfferAnswer(SessionDescriptionInterface** desc, bool offer) {
    346     talk_base::scoped_refptr<MockCreateSessionDescriptionObserver>
    347         observer(new talk_base::RefCountedObject<
    348             MockCreateSessionDescriptionObserver>());
    349     if (offer) {
    350       pc_->CreateOffer(observer, NULL);
    351     } else {
    352       pc_->CreateAnswer(observer, NULL);
    353     }
    354     EXPECT_EQ_WAIT(true, observer->called(), kTimeout);
    355     *desc = observer->release_desc();
    356     return observer->result();
    357   }
    358 
    359   bool DoCreateOffer(SessionDescriptionInterface** desc) {
    360     return DoCreateOfferAnswer(desc, true);
    361   }
    362 
    363   bool DoCreateAnswer(SessionDescriptionInterface** desc) {
    364     return DoCreateOfferAnswer(desc, false);
    365   }
    366 
    367   bool DoSetSessionDescription(SessionDescriptionInterface* desc, bool local) {
    368     talk_base::scoped_refptr<MockSetSessionDescriptionObserver>
    369         observer(new talk_base::RefCountedObject<
    370             MockSetSessionDescriptionObserver>());
    371     if (local) {
    372       pc_->SetLocalDescription(observer, desc);
    373     } else {
    374       pc_->SetRemoteDescription(observer, desc);
    375     }
    376     EXPECT_EQ_WAIT(true, observer->called(), kTimeout);
    377     return observer->result();
    378   }
    379 
    380   bool DoSetLocalDescription(SessionDescriptionInterface* desc) {
    381     return DoSetSessionDescription(desc, true);
    382   }
    383 
    384   bool DoSetRemoteDescription(SessionDescriptionInterface* desc) {
    385     return DoSetSessionDescription(desc, false);
    386   }
    387 
    388   // Calls PeerConnection::GetStats and check the return value.
    389   // It does not verify the values in the StatReports since a RTCP packet might
    390   // be required.
    391   bool DoGetStats(MediaStreamTrackInterface* track) {
    392     talk_base::scoped_refptr<MockStatsObserver> observer(
    393         new talk_base::RefCountedObject<MockStatsObserver>());
    394     if (!pc_->GetStats(observer, track))
    395       return false;
    396     EXPECT_TRUE_WAIT(observer->called(), kTimeout);
    397     return observer->called();
    398   }
    399 
    400   void InitiateCall() {
    401     CreatePeerConnection();
    402     // Create a local stream with audio&video tracks.
    403     AddAudioVideoStream(kStreamLabel1, "audio_label", "video_label");
    404     CreateOfferReceiveAnswer();
    405   }
    406 
    407   // Verify that RTP Header extensions has been negotiated for audio and video.
    408   void VerifyRemoteRtpHeaderExtensions() {
    409     const cricket::MediaContentDescription* desc =
    410         cricket::GetFirstAudioContentDescription(
    411             pc_->remote_description()->description());
    412     ASSERT_TRUE(desc != NULL);
    413     EXPECT_GT(desc->rtp_header_extensions().size(), 0u);
    414 
    415     desc = cricket::GetFirstVideoContentDescription(
    416         pc_->remote_description()->description());
    417     ASSERT_TRUE(desc != NULL);
    418     EXPECT_GT(desc->rtp_header_extensions().size(), 0u);
    419   }
    420 
    421   void CreateOfferAsRemoteDescription() {
    422     talk_base::scoped_ptr<SessionDescriptionInterface> offer;
    423     EXPECT_TRUE(DoCreateOffer(offer.use()));
    424     std::string sdp;
    425     EXPECT_TRUE(offer->ToString(&sdp));
    426     SessionDescriptionInterface* remote_offer =
    427         webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
    428                                          sdp, NULL);
    429     EXPECT_TRUE(DoSetRemoteDescription(remote_offer));
    430     EXPECT_EQ(PeerConnectionInterface::kHaveRemoteOffer, observer_.state_);
    431   }
    432 
    433   void CreateAnswerAsLocalDescription() {
    434     scoped_ptr<SessionDescriptionInterface> answer;
    435     EXPECT_TRUE(DoCreateAnswer(answer.use()));
    436 
    437     // TODO(perkj): Currently SetLocalDescription fails if any parameters in an
    438     // audio codec change, even if the parameter has nothing to do with
    439     // receiving. Not all parameters are serialized to SDP.
    440     // Since CreatePrAnswerAsLocalDescription serialize/deserialize
    441     // the SessionDescription, it is necessary to do that here to in order to
    442     // get ReceiveOfferCreatePrAnswerAndAnswer and RenegotiateAudioOnly to pass.
    443     // https://code.google.com/p/webrtc/issues/detail?id=1356
    444     std::string sdp;
    445     EXPECT_TRUE(answer->ToString(&sdp));
    446     SessionDescriptionInterface* new_answer =
    447         webrtc::CreateSessionDescription(SessionDescriptionInterface::kAnswer,
    448                                          sdp, NULL);
    449     EXPECT_TRUE(DoSetLocalDescription(new_answer));
    450     EXPECT_EQ(PeerConnectionInterface::kStable, observer_.state_);
    451   }
    452 
    453   void CreatePrAnswerAsLocalDescription() {
    454     scoped_ptr<SessionDescriptionInterface> answer;
    455     EXPECT_TRUE(DoCreateAnswer(answer.use()));
    456 
    457     std::string sdp;
    458     EXPECT_TRUE(answer->ToString(&sdp));
    459     SessionDescriptionInterface* pr_answer =
    460         webrtc::CreateSessionDescription(SessionDescriptionInterface::kPrAnswer,
    461                                          sdp, NULL);
    462     EXPECT_TRUE(DoSetLocalDescription(pr_answer));
    463     EXPECT_EQ(PeerConnectionInterface::kHaveLocalPrAnswer, observer_.state_);
    464   }
    465 
    466   void CreateOfferReceiveAnswer() {
    467     CreateOfferAsLocalDescription();
    468     std::string sdp;
    469     EXPECT_TRUE(pc_->local_description()->ToString(&sdp));
    470     CreateAnswerAsRemoteDescription(sdp);
    471   }
    472 
    473   void CreateOfferAsLocalDescription() {
    474     talk_base::scoped_ptr<SessionDescriptionInterface> offer;
    475     ASSERT_TRUE(DoCreateOffer(offer.use()));
    476     // TODO(perkj): Currently SetLocalDescription fails if any parameters in an
    477     // audio codec change, even if the parameter has nothing to do with
    478     // receiving. Not all parameters are serialized to SDP.
    479     // Since CreatePrAnswerAsLocalDescription serialize/deserialize
    480     // the SessionDescription, it is necessary to do that here to in order to
    481     // get ReceiveOfferCreatePrAnswerAndAnswer and RenegotiateAudioOnly to pass.
    482     // https://code.google.com/p/webrtc/issues/detail?id=1356
    483     std::string sdp;
    484     EXPECT_TRUE(offer->ToString(&sdp));
    485     SessionDescriptionInterface* new_offer =
    486             webrtc::CreateSessionDescription(
    487                 SessionDescriptionInterface::kOffer,
    488                 sdp, NULL);
    489 
    490     EXPECT_TRUE(DoSetLocalDescription(new_offer));
    491     EXPECT_EQ(PeerConnectionInterface::kHaveLocalOffer, observer_.state_);
    492   }
    493 
    494   void CreateAnswerAsRemoteDescription(const std::string& offer) {
    495     webrtc::JsepSessionDescription* answer = new webrtc::JsepSessionDescription(
    496         SessionDescriptionInterface::kAnswer);
    497     EXPECT_TRUE(answer->Initialize(offer, NULL));
    498     EXPECT_TRUE(DoSetRemoteDescription(answer));
    499     EXPECT_EQ(PeerConnectionInterface::kStable, observer_.state_);
    500   }
    501 
    502   void CreatePrAnswerAndAnswerAsRemoteDescription(const std::string& offer) {
    503     webrtc::JsepSessionDescription* pr_answer =
    504         new webrtc::JsepSessionDescription(
    505             SessionDescriptionInterface::kPrAnswer);
    506     EXPECT_TRUE(pr_answer->Initialize(offer, NULL));
    507     EXPECT_TRUE(DoSetRemoteDescription(pr_answer));
    508     EXPECT_EQ(PeerConnectionInterface::kHaveRemotePrAnswer, observer_.state_);
    509     webrtc::JsepSessionDescription* answer =
    510         new webrtc::JsepSessionDescription(
    511             SessionDescriptionInterface::kAnswer);
    512     EXPECT_TRUE(answer->Initialize(offer, NULL));
    513     EXPECT_TRUE(DoSetRemoteDescription(answer));
    514     EXPECT_EQ(PeerConnectionInterface::kStable, observer_.state_);
    515   }
    516 
    517   // Help function used for waiting until a the last signaled remote stream has
    518   // the same label as |stream_label|. In a few of the tests in this file we
    519   // answer with the same session description as we offer and thus we can
    520   // check if OnAddStream have been called with the same stream as we offer to
    521   // send.
    522   void WaitAndVerifyOnAddStream(const std::string& stream_label) {
    523     EXPECT_EQ_WAIT(stream_label, observer_.GetLastAddedStreamLabel(), kTimeout);
    524   }
    525 
    526   // Creates an offer and applies it as a local session description.
    527   // Creates an answer with the same SDP an the offer but removes all lines
    528   // that start with a:ssrc"
    529   void CreateOfferReceiveAnswerWithoutSsrc() {
    530     CreateOfferAsLocalDescription();
    531     std::string sdp;
    532     EXPECT_TRUE(pc_->local_description()->ToString(&sdp));
    533     SetSsrcToZero(&sdp);
    534     CreateAnswerAsRemoteDescription(sdp);
    535   }
    536 
    537   scoped_refptr<FakePortAllocatorFactory> port_allocator_factory_;
    538   scoped_refptr<webrtc::PeerConnectionFactoryInterface> pc_factory_;
    539   scoped_refptr<PeerConnectionInterface> pc_;
    540   MockPeerConnectionObserver observer_;
    541 };
    542 
    543 TEST_F(PeerConnectionInterfaceTest,
    544        CreatePeerConnectionWithDifferentConfigurations) {
    545   CreatePeerConnectionWithDifferentConfigurations();
    546 }
    547 
    548 TEST_F(PeerConnectionInterfaceTest, AddStreams) {
    549   CreatePeerConnection();
    550   AddStream(kStreamLabel1);
    551   AddVoiceStream(kStreamLabel2);
    552   ASSERT_EQ(2u, pc_->local_streams()->count());
    553 
    554   // Test we can add multiple local streams to one peerconnection.
    555   scoped_refptr<MediaStreamInterface> stream(
    556       pc_factory_->CreateLocalMediaStream(kStreamLabel3));
    557   scoped_refptr<AudioTrackInterface> audio_track(
    558       pc_factory_->CreateAudioTrack(
    559           kStreamLabel3, static_cast<AudioSourceInterface*>(NULL)));
    560   stream->AddTrack(audio_track.get());
    561   EXPECT_TRUE(pc_->AddStream(stream, NULL));
    562   EXPECT_EQ(3u, pc_->local_streams()->count());
    563 
    564   // Remove the third stream.
    565   pc_->RemoveStream(pc_->local_streams()->at(2));
    566   EXPECT_EQ(2u, pc_->local_streams()->count());
    567 
    568   // Remove the second stream.
    569   pc_->RemoveStream(pc_->local_streams()->at(1));
    570   EXPECT_EQ(1u, pc_->local_streams()->count());
    571 
    572   // Remove the first stream.
    573   pc_->RemoveStream(pc_->local_streams()->at(0));
    574   EXPECT_EQ(0u, pc_->local_streams()->count());
    575 }
    576 
    577 TEST_F(PeerConnectionInterfaceTest, RemoveStream) {
    578   CreatePeerConnection();
    579   AddStream(kStreamLabel1);
    580   ASSERT_EQ(1u, pc_->local_streams()->count());
    581   pc_->RemoveStream(pc_->local_streams()->at(0));
    582   EXPECT_EQ(0u, pc_->local_streams()->count());
    583 }
    584 
    585 TEST_F(PeerConnectionInterfaceTest, CreateOfferReceiveAnswer) {
    586   InitiateCall();
    587   WaitAndVerifyOnAddStream(kStreamLabel1);
    588   VerifyRemoteRtpHeaderExtensions();
    589 }
    590 
    591 TEST_F(PeerConnectionInterfaceTest, CreateOfferReceivePrAnswerAndAnswer) {
    592   CreatePeerConnection();
    593   AddStream(kStreamLabel1);
    594   CreateOfferAsLocalDescription();
    595   std::string offer;
    596   EXPECT_TRUE(pc_->local_description()->ToString(&offer));
    597   CreatePrAnswerAndAnswerAsRemoteDescription(offer);
    598   WaitAndVerifyOnAddStream(kStreamLabel1);
    599 }
    600 
    601 TEST_F(PeerConnectionInterfaceTest, ReceiveOfferCreateAnswer) {
    602   CreatePeerConnection();
    603   AddStream(kStreamLabel1);
    604 
    605   CreateOfferAsRemoteDescription();
    606   CreateAnswerAsLocalDescription();
    607 
    608   WaitAndVerifyOnAddStream(kStreamLabel1);
    609 }
    610 
    611 TEST_F(PeerConnectionInterfaceTest, ReceiveOfferCreatePrAnswerAndAnswer) {
    612   CreatePeerConnection();
    613   AddStream(kStreamLabel1);
    614 
    615   CreateOfferAsRemoteDescription();
    616   CreatePrAnswerAsLocalDescription();
    617   CreateAnswerAsLocalDescription();
    618 
    619   WaitAndVerifyOnAddStream(kStreamLabel1);
    620 }
    621 
    622 TEST_F(PeerConnectionInterfaceTest, Renegotiate) {
    623   InitiateCall();
    624   ASSERT_EQ(1u, pc_->remote_streams()->count());
    625   pc_->RemoveStream(pc_->local_streams()->at(0));
    626   CreateOfferReceiveAnswer();
    627   EXPECT_EQ(0u, pc_->remote_streams()->count());
    628   AddStream(kStreamLabel1);
    629   CreateOfferReceiveAnswer();
    630 }
    631 
    632 // Tests that after negotiating an audio only call, the respondent can perform a
    633 // renegotiation that removes the audio stream.
    634 TEST_F(PeerConnectionInterfaceTest, RenegotiateAudioOnly) {
    635   CreatePeerConnection();
    636   AddVoiceStream(kStreamLabel1);
    637   CreateOfferAsRemoteDescription();
    638   CreateAnswerAsLocalDescription();
    639 
    640   ASSERT_EQ(1u, pc_->remote_streams()->count());
    641   pc_->RemoveStream(pc_->local_streams()->at(0));
    642   CreateOfferReceiveAnswer();
    643   EXPECT_EQ(0u, pc_->remote_streams()->count());
    644 }
    645 
    646 // Test that candidates are generated and that we can parse our own candidates.
    647 TEST_F(PeerConnectionInterfaceTest, IceCandidates) {
    648   CreatePeerConnection();
    649 
    650   EXPECT_FALSE(pc_->AddIceCandidate(observer_.last_candidate_.get()));
    651   // SetRemoteDescription takes ownership of offer.
    652   SessionDescriptionInterface* offer = NULL;
    653   AddStream(kStreamLabel1);
    654   EXPECT_TRUE(DoCreateOffer(&offer));
    655   EXPECT_TRUE(DoSetRemoteDescription(offer));
    656 
    657   // SetLocalDescription takes ownership of answer.
    658   SessionDescriptionInterface* answer = NULL;
    659   EXPECT_TRUE(DoCreateAnswer(&answer));
    660   EXPECT_TRUE(DoSetLocalDescription(answer));
    661 
    662   EXPECT_TRUE_WAIT(observer_.last_candidate_.get() != NULL, kTimeout);
    663   EXPECT_TRUE_WAIT(observer_.ice_complete_, kTimeout);
    664 
    665   EXPECT_TRUE(pc_->AddIceCandidate(observer_.last_candidate_.get()));
    666 }
    667 
    668 // Test that the CreateOffer and CreatAnswer will fail if the track labels are
    669 // not unique.
    670 TEST_F(PeerConnectionInterfaceTest, CreateOfferAnswerWithInvalidStream) {
    671   CreatePeerConnection();
    672   // Create a regular offer for the CreateAnswer test later.
    673   SessionDescriptionInterface* offer = NULL;
    674   EXPECT_TRUE(DoCreateOffer(&offer));
    675   EXPECT_TRUE(offer != NULL);
    676   delete offer;
    677   offer = NULL;
    678 
    679   // Create a local stream with audio&video tracks having same label.
    680   AddAudioVideoStream(kStreamLabel1, "track_label", "track_label");
    681 
    682   // Test CreateOffer
    683   EXPECT_FALSE(DoCreateOffer(&offer));
    684 
    685   // Test CreateAnswer
    686   SessionDescriptionInterface* answer = NULL;
    687   EXPECT_FALSE(DoCreateAnswer(&answer));
    688 }
    689 
    690 // Test that we will get different SSRCs for each tracks in the offer and answer
    691 // we created.
    692 TEST_F(PeerConnectionInterfaceTest, SsrcInOfferAnswer) {
    693   CreatePeerConnection();
    694   // Create a local stream with audio&video tracks having different labels.
    695   AddAudioVideoStream(kStreamLabel1, "audio_label", "video_label");
    696 
    697   // Test CreateOffer
    698   scoped_ptr<SessionDescriptionInterface> offer;
    699   EXPECT_TRUE(DoCreateOffer(offer.use()));
    700   int audio_ssrc = 0;
    701   int video_ssrc = 0;
    702   EXPECT_TRUE(GetFirstSsrc(GetFirstAudioContent(offer->description()),
    703                            &audio_ssrc));
    704   EXPECT_TRUE(GetFirstSsrc(GetFirstVideoContent(offer->description()),
    705                            &video_ssrc));
    706   EXPECT_NE(audio_ssrc, video_ssrc);
    707 
    708   // Test CreateAnswer
    709   EXPECT_TRUE(DoSetRemoteDescription(offer.release()));
    710   scoped_ptr<SessionDescriptionInterface> answer;
    711   EXPECT_TRUE(DoCreateAnswer(answer.use()));
    712   audio_ssrc = 0;
    713   video_ssrc = 0;
    714   EXPECT_TRUE(GetFirstSsrc(GetFirstAudioContent(answer->description()),
    715                            &audio_ssrc));
    716   EXPECT_TRUE(GetFirstSsrc(GetFirstVideoContent(answer->description()),
    717                            &video_ssrc));
    718   EXPECT_NE(audio_ssrc, video_ssrc);
    719 }
    720 
    721 // Test that we can specify a certain track that we want statistics about.
    722 TEST_F(PeerConnectionInterfaceTest, GetStatsForSpecificTrack) {
    723   InitiateCall();
    724   ASSERT_LT(0u, pc_->remote_streams()->count());
    725   ASSERT_LT(0u, pc_->remote_streams()->at(0)->GetAudioTracks().size());
    726   scoped_refptr<MediaStreamTrackInterface> remote_audio =
    727       pc_->remote_streams()->at(0)->GetAudioTracks()[0];
    728   EXPECT_TRUE(DoGetStats(remote_audio));
    729 
    730   // Remove the stream. Since we are sending to our selves the local
    731   // and the remote stream is the same.
    732   pc_->RemoveStream(pc_->local_streams()->at(0));
    733   // Do a re-negotiation.
    734   CreateOfferReceiveAnswer();
    735 
    736   ASSERT_EQ(0u, pc_->remote_streams()->count());
    737 
    738   // Test that we still can get statistics for the old track. Even if it is not
    739   // sent any longer.
    740   EXPECT_TRUE(DoGetStats(remote_audio));
    741 }
    742 
    743 // Test that we can get stats on a video track.
    744 TEST_F(PeerConnectionInterfaceTest, GetStatsForVideoTrack) {
    745   InitiateCall();
    746   ASSERT_LT(0u, pc_->remote_streams()->count());
    747   ASSERT_LT(0u, pc_->remote_streams()->at(0)->GetVideoTracks().size());
    748   scoped_refptr<MediaStreamTrackInterface> remote_video =
    749       pc_->remote_streams()->at(0)->GetVideoTracks()[0];
    750   EXPECT_TRUE(DoGetStats(remote_video));
    751 }
    752 
    753 // Test that we don't get statistics for an invalid track.
    754 TEST_F(PeerConnectionInterfaceTest, GetStatsForInvalidTrack) {
    755   InitiateCall();
    756   scoped_refptr<AudioTrackInterface> unknown_audio_track(
    757       pc_factory_->CreateAudioTrack("unknown track", NULL));
    758   EXPECT_FALSE(DoGetStats(unknown_audio_track));
    759 }
    760 
    761 // This test setup two RTP data channels in loop back.
    762 #ifdef WIN32
    763 // TODO(perkj): Investigate why the transport channel sometimes don't become
    764 // writable on Windows when we try to connect in loop back.
    765 TEST_F(PeerConnectionInterfaceTest, DISABLED_TestDataChannel) {
    766 #else
    767 TEST_F(PeerConnectionInterfaceTest, TestDataChannel) {
    768 #endif
    769   FakeConstraints constraints;
    770   constraints.SetAllowRtpDataChannels();
    771   CreatePeerConnection(&constraints);
    772   scoped_refptr<DataChannelInterface> data1  =
    773       pc_->CreateDataChannel("test1", NULL);
    774   scoped_refptr<DataChannelInterface> data2  =
    775       pc_->CreateDataChannel("test2", NULL);
    776   ASSERT_TRUE(data1 != NULL);
    777   talk_base::scoped_ptr<MockDataChannelObserver> observer1(
    778       new MockDataChannelObserver(data1));
    779   talk_base::scoped_ptr<MockDataChannelObserver> observer2(
    780       new MockDataChannelObserver(data2));
    781 
    782   EXPECT_EQ(DataChannelInterface::kConnecting, data1->state());
    783   EXPECT_EQ(DataChannelInterface::kConnecting, data2->state());
    784   std::string data_to_send1 = "testing testing";
    785   std::string data_to_send2 = "testing something else";
    786   EXPECT_FALSE(data1->Send(DataBuffer(data_to_send1)));
    787 
    788   CreateOfferReceiveAnswer();
    789   EXPECT_TRUE_WAIT(observer1->IsOpen(), kTimeout);
    790   EXPECT_TRUE_WAIT(observer2->IsOpen(), kTimeout);
    791 
    792   EXPECT_EQ(DataChannelInterface::kOpen, data1->state());
    793   EXPECT_EQ(DataChannelInterface::kOpen, data2->state());
    794   EXPECT_TRUE(data1->Send(DataBuffer(data_to_send1)));
    795   EXPECT_TRUE(data2->Send(DataBuffer(data_to_send2)));
    796 
    797   EXPECT_EQ_WAIT(data_to_send1, observer1->last_message(), kTimeout);
    798   EXPECT_EQ_WAIT(data_to_send2, observer2->last_message(), kTimeout);
    799 
    800   data1->Close();
    801   EXPECT_EQ(DataChannelInterface::kClosing, data1->state());
    802   CreateOfferReceiveAnswer();
    803   EXPECT_FALSE(observer1->IsOpen());
    804   EXPECT_EQ(DataChannelInterface::kClosed, data1->state());
    805   EXPECT_TRUE(observer2->IsOpen());
    806 
    807   data_to_send2 = "testing something else again";
    808   EXPECT_TRUE(data2->Send(DataBuffer(data_to_send2)));
    809 
    810   EXPECT_EQ_WAIT(data_to_send2, observer2->last_message(), kTimeout);
    811 }
    812 
    813 // This test verifies that sendnig binary data over RTP data channels should
    814 // fail.
    815 #ifdef WIN32
    816 // TODO(perkj): Investigate why the transport channel sometimes don't become
    817 // writable on Windows when we try to connect in loop back.
    818 TEST_F(PeerConnectionInterfaceTest, DISABLED_TestSendBinaryOnRtpDataChannel) {
    819 #else
    820 TEST_F(PeerConnectionInterfaceTest, TestSendBinaryOnRtpDataChannel) {
    821 #endif
    822   FakeConstraints constraints;
    823   constraints.SetAllowRtpDataChannels();
    824   CreatePeerConnection(&constraints);
    825   scoped_refptr<DataChannelInterface> data1  =
    826       pc_->CreateDataChannel("test1", NULL);
    827   scoped_refptr<DataChannelInterface> data2  =
    828       pc_->CreateDataChannel("test2", NULL);
    829   ASSERT_TRUE(data1 != NULL);
    830   talk_base::scoped_ptr<MockDataChannelObserver> observer1(
    831       new MockDataChannelObserver(data1));
    832   talk_base::scoped_ptr<MockDataChannelObserver> observer2(
    833       new MockDataChannelObserver(data2));
    834 
    835   EXPECT_EQ(DataChannelInterface::kConnecting, data1->state());
    836   EXPECT_EQ(DataChannelInterface::kConnecting, data2->state());
    837 
    838   CreateOfferReceiveAnswer();
    839   EXPECT_TRUE_WAIT(observer1->IsOpen(), kTimeout);
    840   EXPECT_TRUE_WAIT(observer2->IsOpen(), kTimeout);
    841 
    842   EXPECT_EQ(DataChannelInterface::kOpen, data1->state());
    843   EXPECT_EQ(DataChannelInterface::kOpen, data2->state());
    844 
    845   talk_base::Buffer buffer("test", 4);
    846   EXPECT_FALSE(data1->Send(DataBuffer(buffer, true)));
    847 }
    848 
    849 // This test setup a RTP data channels in loop back and test that a channel is
    850 // opened even if the remote end answer with a zero SSRC.
    851 #ifdef WIN32
    852 // TODO(perkj): Investigate why the transport channel sometimes don't become
    853 // writable on Windows when we try to connect in loop back.
    854 TEST_F(PeerConnectionInterfaceTest, DISABLED_TestSendOnlyDataChannel) {
    855 #else
    856 TEST_F(PeerConnectionInterfaceTest, TestSendOnlyDataChannel) {
    857 #endif
    858   FakeConstraints constraints;
    859   constraints.SetAllowRtpDataChannels();
    860   CreatePeerConnection(&constraints);
    861   scoped_refptr<DataChannelInterface> data1  =
    862       pc_->CreateDataChannel("test1", NULL);
    863   talk_base::scoped_ptr<MockDataChannelObserver> observer1(
    864       new MockDataChannelObserver(data1));
    865 
    866   CreateOfferReceiveAnswerWithoutSsrc();
    867 
    868   EXPECT_TRUE_WAIT(observer1->IsOpen(), kTimeout);
    869 
    870   data1->Close();
    871   EXPECT_EQ(DataChannelInterface::kClosing, data1->state());
    872   CreateOfferReceiveAnswerWithoutSsrc();
    873   EXPECT_EQ(DataChannelInterface::kClosed, data1->state());
    874   EXPECT_FALSE(observer1->IsOpen());
    875 }
    876 
    877 // This test that if a data channel is added in an answer a receive only channel
    878 // channel is created.
    879 TEST_F(PeerConnectionInterfaceTest, TestReceiveOnlyDataChannel) {
    880   FakeConstraints constraints;
    881   constraints.SetAllowRtpDataChannels();
    882   CreatePeerConnection(&constraints);
    883 
    884   std::string offer_label = "offer_channel";
    885   scoped_refptr<DataChannelInterface> offer_channel  =
    886       pc_->CreateDataChannel(offer_label, NULL);
    887 
    888   CreateOfferAsLocalDescription();
    889 
    890   // Replace the data channel label in the offer and apply it as an answer.
    891   std::string receive_label = "answer_channel";
    892   std::string sdp;
    893   EXPECT_TRUE(pc_->local_description()->ToString(&sdp));
    894   talk_base::replace_substrs(offer_label.c_str(), offer_label.length(),
    895                              receive_label.c_str(), receive_label.length(),
    896                              &sdp);
    897   CreateAnswerAsRemoteDescription(sdp);
    898 
    899   // Verify that a new incoming data channel has been created and that
    900   // it is open but can't we written to.
    901   ASSERT_TRUE(observer_.last_datachannel_ != NULL);
    902   DataChannelInterface* received_channel = observer_.last_datachannel_;
    903   EXPECT_EQ(DataChannelInterface::kConnecting, received_channel->state());
    904   EXPECT_EQ(receive_label, received_channel->label());
    905   EXPECT_FALSE(received_channel->Send(DataBuffer("something")));
    906 
    907   // Verify that the channel we initially offered has been rejected.
    908   EXPECT_EQ(DataChannelInterface::kClosed, offer_channel->state());
    909 
    910   // Do another offer / answer exchange and verify that the data channel is
    911   // opened.
    912   CreateOfferReceiveAnswer();
    913   EXPECT_EQ_WAIT(DataChannelInterface::kOpen, received_channel->state(),
    914                  kTimeout);
    915 }
    916 
    917 // This test that no data channel is returned if a reliable channel is
    918 // requested.
    919 // TODO(perkj): Remove this test once reliable channels are implemented.
    920 TEST_F(PeerConnectionInterfaceTest, CreateReliableRtpDataChannelShouldFail) {
    921   FakeConstraints constraints;
    922   constraints.SetAllowRtpDataChannels();
    923   CreatePeerConnection(&constraints);
    924 
    925   std::string label = "test";
    926   webrtc::DataChannelInit config;
    927   config.reliable = true;
    928   scoped_refptr<DataChannelInterface> channel  =
    929       pc_->CreateDataChannel(label, &config);
    930   EXPECT_TRUE(channel == NULL);
    931 }
    932 
    933 // This tests that a SCTP data channel is returned using different
    934 // DataChannelInit configurations.
    935 TEST_F(PeerConnectionInterfaceTest, CreateSctpDataChannel) {
    936   FakeConstraints constraints;
    937   constraints.SetAllowDtlsSctpDataChannels();
    938   CreatePeerConnection(&constraints);
    939 
    940   webrtc::DataChannelInit config;
    941 
    942   scoped_refptr<DataChannelInterface> channel =
    943       pc_->CreateDataChannel("1", &config);
    944   EXPECT_TRUE(channel != NULL);
    945   EXPECT_TRUE(channel->reliable());
    946 
    947   config.ordered = false;
    948   channel = pc_->CreateDataChannel("2", &config);
    949   EXPECT_TRUE(channel != NULL);
    950   EXPECT_TRUE(channel->reliable());
    951 
    952   config.ordered = true;
    953   config.maxRetransmits = 0;
    954   channel = pc_->CreateDataChannel("3", &config);
    955   EXPECT_TRUE(channel != NULL);
    956   EXPECT_FALSE(channel->reliable());
    957 
    958   config.maxRetransmits = -1;
    959   config.maxRetransmitTime = 0;
    960   channel = pc_->CreateDataChannel("4", &config);
    961   EXPECT_TRUE(channel != NULL);
    962   EXPECT_FALSE(channel->reliable());
    963 }
    964 
    965 // This tests that no data channel is returned if both maxRetransmits and
    966 // maxRetransmitTime are set for SCTP data channels.
    967 TEST_F(PeerConnectionInterfaceTest,
    968        CreateSctpDataChannelShouldFailForInvalidConfig) {
    969   FakeConstraints constraints;
    970   constraints.SetAllowDtlsSctpDataChannels();
    971   CreatePeerConnection(&constraints);
    972 
    973   std::string label = "test";
    974   webrtc::DataChannelInit config;
    975   config.maxRetransmits = 0;
    976   config.maxRetransmitTime = 0;
    977 
    978   scoped_refptr<DataChannelInterface> channel =
    979       pc_->CreateDataChannel(label, &config);
    980   EXPECT_TRUE(channel == NULL);
    981 }
    982 
    983 // The test verifies that the first id not used by existing data channels is
    984 // assigned to a new data channel if no id is specified.
    985 TEST_F(PeerConnectionInterfaceTest, AssignSctpDataChannelId) {
    986   FakeConstraints constraints;
    987   constraints.SetAllowDtlsSctpDataChannels();
    988   CreatePeerConnection(&constraints);
    989 
    990   webrtc::DataChannelInit config;
    991 
    992   scoped_refptr<DataChannelInterface> channel =
    993       pc_->CreateDataChannel("1", &config);
    994   EXPECT_TRUE(channel != NULL);
    995   EXPECT_EQ(1, channel->id());
    996 
    997   config.id = 4;
    998   channel = pc_->CreateDataChannel("4", &config);
    999   EXPECT_TRUE(channel != NULL);
   1000   EXPECT_EQ(config.id, channel->id());
   1001 
   1002   config.id = -1;
   1003   channel = pc_->CreateDataChannel("2", &config);
   1004   EXPECT_TRUE(channel != NULL);
   1005   EXPECT_EQ(2, channel->id());
   1006 }
   1007 
   1008 // The test verifies that creating a SCTP data channel with an id already in use
   1009 // or out of range should fail.
   1010 TEST_F(PeerConnectionInterfaceTest,
   1011        CreateSctpDataChannelWithInvalidIdShouldFail) {
   1012   FakeConstraints constraints;
   1013   constraints.SetAllowDtlsSctpDataChannels();
   1014   CreatePeerConnection(&constraints);
   1015 
   1016   webrtc::DataChannelInit config;
   1017 
   1018   scoped_refptr<DataChannelInterface> channel =
   1019       pc_->CreateDataChannel("1", &config);
   1020   EXPECT_TRUE(channel != NULL);
   1021   EXPECT_EQ(1, channel->id());
   1022 
   1023   config.id = 1;
   1024   channel = pc_->CreateDataChannel("x", &config);
   1025   EXPECT_TRUE(channel == NULL);
   1026 
   1027   config.id = cricket::kMaxSctpSid;
   1028   channel = pc_->CreateDataChannel("max", &config);
   1029   EXPECT_TRUE(channel != NULL);
   1030   EXPECT_EQ(config.id, channel->id());
   1031 
   1032   config.id = cricket::kMaxSctpSid + 1;
   1033   channel = pc_->CreateDataChannel("x", &config);
   1034   EXPECT_TRUE(channel == NULL);
   1035 }
   1036 
   1037 // This test that a data channel closes when a PeerConnection is deleted/closed.
   1038 #ifdef WIN32
   1039 // TODO(perkj): Investigate why the transport channel sometimes don't become
   1040 // writable on Windows when we try to connect in loop back.
   1041 TEST_F(PeerConnectionInterfaceTest,
   1042        DISABLED_DataChannelCloseWhenPeerConnectionClose) {
   1043 #else
   1044 TEST_F(PeerConnectionInterfaceTest, DataChannelCloseWhenPeerConnectionClose) {
   1045 #endif
   1046   FakeConstraints constraints;
   1047   constraints.SetAllowRtpDataChannels();
   1048   CreatePeerConnection(&constraints);
   1049 
   1050   scoped_refptr<DataChannelInterface> data1  =
   1051       pc_->CreateDataChannel("test1", NULL);
   1052   scoped_refptr<DataChannelInterface> data2  =
   1053       pc_->CreateDataChannel("test2", NULL);
   1054   ASSERT_TRUE(data1 != NULL);
   1055   talk_base::scoped_ptr<MockDataChannelObserver> observer1(
   1056       new MockDataChannelObserver(data1));
   1057   talk_base::scoped_ptr<MockDataChannelObserver> observer2(
   1058       new MockDataChannelObserver(data2));
   1059 
   1060   CreateOfferReceiveAnswer();
   1061   EXPECT_TRUE_WAIT(observer1->IsOpen(), kTimeout);
   1062   EXPECT_TRUE_WAIT(observer2->IsOpen(), kTimeout);
   1063 
   1064   ReleasePeerConnection();
   1065   EXPECT_EQ(DataChannelInterface::kClosed, data1->state());
   1066   EXPECT_EQ(DataChannelInterface::kClosed, data2->state());
   1067 }
   1068 
   1069 // This test that data channels can be rejected in an answer.
   1070 TEST_F(PeerConnectionInterfaceTest, TestRejectDataChannelInAnswer) {
   1071   FakeConstraints constraints;
   1072   constraints.SetAllowRtpDataChannels();
   1073   CreatePeerConnection(&constraints);
   1074 
   1075   scoped_refptr<DataChannelInterface> offer_channel(
   1076       pc_->CreateDataChannel("offer_channel", NULL));
   1077 
   1078   CreateOfferAsLocalDescription();
   1079 
   1080   // Create an answer where the m-line for data channels are rejected.
   1081   std::string sdp;
   1082   EXPECT_TRUE(pc_->local_description()->ToString(&sdp));
   1083   webrtc::JsepSessionDescription* answer = new webrtc::JsepSessionDescription(
   1084       SessionDescriptionInterface::kAnswer);
   1085   EXPECT_TRUE(answer->Initialize(sdp, NULL));
   1086   cricket::ContentInfo* data_info =
   1087       answer->description()->GetContentByName("data");
   1088   data_info->rejected = true;
   1089 
   1090   DoSetRemoteDescription(answer);
   1091   EXPECT_EQ(DataChannelInterface::kClosed, offer_channel->state());
   1092 }
   1093 
   1094 // Test that we can create a session description from an SDP string from
   1095 // FireFox, use it as a remote session description, generate an answer and use
   1096 // the answer as a local description.
   1097 TEST_F(PeerConnectionInterfaceTest, ReceiveFireFoxOffer) {
   1098   MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp);
   1099   FakeConstraints constraints;
   1100   constraints.AddMandatory(webrtc::MediaConstraintsInterface::kEnableDtlsSrtp,
   1101                            true);
   1102   CreatePeerConnection(&constraints);
   1103   AddAudioVideoStream(kStreamLabel1, "audio_label", "video_label");
   1104   SessionDescriptionInterface* desc =
   1105       webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
   1106                                        webrtc::kFireFoxSdpOffer);
   1107   EXPECT_TRUE(DoSetSessionDescription(desc, false));
   1108   CreateAnswerAsLocalDescription();
   1109   ASSERT_TRUE(pc_->local_description() != NULL);
   1110   ASSERT_TRUE(pc_->remote_description() != NULL);
   1111 
   1112   const cricket::ContentInfo* content =
   1113       cricket::GetFirstAudioContent(pc_->local_description()->description());
   1114   ASSERT_TRUE(content != NULL);
   1115   EXPECT_FALSE(content->rejected);
   1116 
   1117   content =
   1118       cricket::GetFirstVideoContent(pc_->local_description()->description());
   1119   ASSERT_TRUE(content != NULL);
   1120   EXPECT_FALSE(content->rejected);
   1121 
   1122   content =
   1123       cricket::GetFirstDataContent(pc_->local_description()->description());
   1124   ASSERT_TRUE(content != NULL);
   1125   EXPECT_TRUE(content->rejected);
   1126 }
   1127 
   1128 // Test that we can create an audio only offer and receive an answer with a
   1129 // limited set of audio codecs and receive an updated offer with more audio
   1130 // codecs, where the added codecs are not supported.
   1131 TEST_F(PeerConnectionInterfaceTest, ReceiveUpdatedAudioOfferWithBadCodecs) {
   1132   CreatePeerConnection();
   1133   AddVoiceStream("audio_label");
   1134   CreateOfferAsLocalDescription();
   1135 
   1136   SessionDescriptionInterface* answer =
   1137       webrtc::CreateSessionDescription(SessionDescriptionInterface::kAnswer,
   1138                                        webrtc::kAudioSdp);
   1139   EXPECT_TRUE(DoSetSessionDescription(answer, false));
   1140 
   1141   SessionDescriptionInterface* updated_offer =
   1142       webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
   1143                                        webrtc::kAudioSdpWithUnsupportedCodecs);
   1144   EXPECT_TRUE(DoSetSessionDescription(updated_offer, false));
   1145   CreateAnswerAsLocalDescription();
   1146 }
   1147 
   1148 // Test that PeerConnection::Close changes the states to closed and all remote
   1149 // tracks change state to ended.
   1150 TEST_F(PeerConnectionInterfaceTest, CloseAndTestStreamsAndStates) {
   1151   // Initialize a PeerConnection and negotiate local and remote session
   1152   // description.
   1153   InitiateCall();
   1154   ASSERT_EQ(1u, pc_->local_streams()->count());
   1155   ASSERT_EQ(1u, pc_->remote_streams()->count());
   1156 
   1157   pc_->Close();
   1158 
   1159   EXPECT_EQ(PeerConnectionInterface::kClosed, pc_->signaling_state());
   1160   EXPECT_EQ(PeerConnectionInterface::kIceConnectionClosed,
   1161             pc_->ice_connection_state());
   1162   EXPECT_EQ(PeerConnectionInterface::kIceGatheringComplete,
   1163             pc_->ice_gathering_state());
   1164 
   1165   EXPECT_EQ(1u, pc_->local_streams()->count());
   1166   EXPECT_EQ(1u, pc_->remote_streams()->count());
   1167 
   1168   scoped_refptr<MediaStreamInterface> remote_stream =
   1169           pc_->remote_streams()->at(0);
   1170   EXPECT_EQ(MediaStreamTrackInterface::kEnded,
   1171             remote_stream->GetVideoTracks()[0]->state());
   1172   EXPECT_EQ(MediaStreamTrackInterface::kEnded,
   1173             remote_stream->GetAudioTracks()[0]->state());
   1174 }
   1175 
   1176 // Test that PeerConnection methods fails gracefully after
   1177 // PeerConnection::Close has been called.
   1178 TEST_F(PeerConnectionInterfaceTest, CloseAndTestMethods) {
   1179   CreatePeerConnection();
   1180   AddAudioVideoStream(kStreamLabel1, "audio_label", "video_label");
   1181   CreateOfferAsRemoteDescription();
   1182   CreateAnswerAsLocalDescription();
   1183 
   1184   ASSERT_EQ(1u, pc_->local_streams()->count());
   1185   scoped_refptr<MediaStreamInterface> local_stream =
   1186       pc_->local_streams()->at(0);
   1187 
   1188   pc_->Close();
   1189 
   1190   pc_->RemoveStream(local_stream);
   1191   EXPECT_FALSE(pc_->AddStream(local_stream, NULL));
   1192 
   1193   ASSERT_FALSE(local_stream->GetAudioTracks().empty());
   1194   talk_base::scoped_refptr<webrtc::DtmfSenderInterface> dtmf_sender(
   1195       pc_->CreateDtmfSender(local_stream->GetAudioTracks()[0]));
   1196   EXPECT_FALSE(dtmf_sender->CanInsertDtmf());
   1197 
   1198   EXPECT_TRUE(pc_->CreateDataChannel("test", NULL) == NULL);
   1199 
   1200   EXPECT_TRUE(pc_->local_description() != NULL);
   1201   EXPECT_TRUE(pc_->remote_description() != NULL);
   1202 
   1203   talk_base::scoped_ptr<SessionDescriptionInterface> offer;
   1204   EXPECT_TRUE(DoCreateOffer(offer.use()));
   1205   talk_base::scoped_ptr<SessionDescriptionInterface> answer;
   1206   EXPECT_TRUE(DoCreateAnswer(answer.use()));
   1207 
   1208   std::string sdp;
   1209   ASSERT_TRUE(pc_->remote_description()->ToString(&sdp));
   1210   SessionDescriptionInterface* remote_offer =
   1211       webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
   1212                                        sdp, NULL);
   1213   EXPECT_FALSE(DoSetRemoteDescription(remote_offer));
   1214 
   1215   ASSERT_TRUE(pc_->local_description()->ToString(&sdp));
   1216   SessionDescriptionInterface* local_offer =
   1217         webrtc::CreateSessionDescription(SessionDescriptionInterface::kOffer,
   1218                                          sdp, NULL);
   1219   EXPECT_FALSE(DoSetLocalDescription(local_offer));
   1220 }
   1221 
   1222 // Test that GetStats can still be called after PeerConnection::Close.
   1223 TEST_F(PeerConnectionInterfaceTest, CloseAndGetStats) {
   1224   InitiateCall();
   1225   pc_->Close();
   1226   DoGetStats(NULL);
   1227 }
   1228