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.
28 #include "talk/app/webrtc/mediastreamsignaling.h"
32 #include "talk/app/webrtc/audiotrack.h"
33 #include "talk/app/webrtc/mediastreamproxy.h"
34 #include "talk/app/webrtc/mediaconstraintsinterface.h"
35 #include "talk/app/webrtc/mediastreamtrackproxy.h"
36 #include "talk/app/webrtc/remoteaudiosource.h"
37 #include "talk/app/webrtc/remotevideocapturer.h"
38 #include "talk/app/webrtc/sctputils.h"
39 #include "talk/app/webrtc/videosource.h"
40 #include "talk/app/webrtc/videotrack.h"
41 #include "talk/base/bytebuffer.h"
42 #include "talk/base/stringutils.h"
43 #include "talk/media/sctp/sctpdataengine.h"
45 static const char kDefaultStreamLabel[] = "default";
46 static const char kDefaultAudioTrackLabel[] = "defaulta0";
47 static const char kDefaultVideoTrackLabel[] = "defaultv0";
51 using talk_base::scoped_ptr;
52 using talk_base::scoped_refptr;
54 static bool ParseConstraints(
55 const MediaConstraintsInterface* constraints,
56 cricket::MediaSessionOptions* options, bool is_answer) {
58 size_t mandatory_constraints_satisfied = 0;
60 if (FindConstraint(constraints,
61 MediaConstraintsInterface::kOfferToReceiveAudio,
62 &value, &mandatory_constraints_satisfied)) {
63 // |options-|has_audio| can only change from false to
64 // true, but never change from true to false. This is to make sure
65 // CreateOffer / CreateAnswer doesn't remove a media content
66 // description that has been created.
67 options->has_audio |= value;
69 // kOfferToReceiveAudio defaults to true according to spec.
70 options->has_audio = true;
73 if (FindConstraint(constraints,
74 MediaConstraintsInterface::kOfferToReceiveVideo,
75 &value, &mandatory_constraints_satisfied)) {
76 // |options->has_video| can only change from false to
77 // true, but never change from true to false. This is to make sure
78 // CreateOffer / CreateAnswer doesn't remove a media content
79 // description that has been created.
80 options->has_video |= value;
82 // kOfferToReceiveVideo defaults to false according to spec. But
83 // if it is an answer and video is offered, we should still accept video
85 options->has_video |= is_answer;
88 if (FindConstraint(constraints,
89 MediaConstraintsInterface::kVoiceActivityDetection,
90 &value, &mandatory_constraints_satisfied)) {
91 options->vad_enabled = value;
94 if (FindConstraint(constraints,
95 MediaConstraintsInterface::kUseRtpMux,
96 &value, &mandatory_constraints_satisfied)) {
97 options->bundle_enabled = value;
99 // kUseRtpMux defaults to true according to spec.
100 options->bundle_enabled = true;
102 if (FindConstraint(constraints,
103 MediaConstraintsInterface::kIceRestart,
104 &value, &mandatory_constraints_satisfied)) {
105 options->transport_options.ice_restart = value;
107 // kIceRestart defaults to false according to spec.
108 options->transport_options.ice_restart = false;
114 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
117 // Returns true if if at least one media content is present and
118 // |options.bundle_enabled| is true.
119 // Bundle will be enabled by default if at least one media content is present
120 // and the constraint kUseRtpMux has not disabled bundle.
121 static bool EvaluateNeedForBundle(const cricket::MediaSessionOptions& options) {
122 return options.bundle_enabled &&
123 (options.has_audio || options.has_video || options.has_data());
126 // Factory class for creating remote MediaStreams and MediaStreamTracks.
127 class RemoteMediaStreamFactory {
129 explicit RemoteMediaStreamFactory(talk_base::Thread* signaling_thread,
130 cricket::ChannelManager* channel_manager)
131 : signaling_thread_(signaling_thread),
132 channel_manager_(channel_manager) {
135 talk_base::scoped_refptr<MediaStreamInterface> CreateMediaStream(
136 const std::string& stream_label) {
137 return MediaStreamProxy::Create(
138 signaling_thread_, MediaStream::Create(stream_label));
141 AudioTrackInterface* AddAudioTrack(webrtc::MediaStreamInterface* stream,
142 const std::string& track_id) {
143 return AddTrack<AudioTrackInterface, AudioTrack, AudioTrackProxy>(
144 stream, track_id, RemoteAudioSource::Create().get());
147 VideoTrackInterface* AddVideoTrack(webrtc::MediaStreamInterface* stream,
148 const std::string& track_id) {
149 return AddTrack<VideoTrackInterface, VideoTrack, VideoTrackProxy>(
150 stream, track_id, VideoSource::Create(channel_manager_,
151 new RemoteVideoCapturer(),
156 template <typename TI, typename T, typename TP, typename S>
157 TI* AddTrack(MediaStreamInterface* stream, const std::string& track_id,
159 talk_base::scoped_refptr<TI> track(
160 TP::Create(signaling_thread_, T::Create(track_id, source)));
161 track->set_state(webrtc::MediaStreamTrackInterface::kLive);
162 if (stream->AddTrack(track)) {
168 talk_base::Thread* signaling_thread_;
169 cricket::ChannelManager* channel_manager_;
172 MediaStreamSignaling::MediaStreamSignaling(
173 talk_base::Thread* signaling_thread,
174 MediaStreamSignalingObserver* stream_observer,
175 cricket::ChannelManager* channel_manager)
176 : signaling_thread_(signaling_thread),
177 data_channel_factory_(NULL),
178 stream_observer_(stream_observer),
179 local_streams_(StreamCollection::Create()),
180 remote_streams_(StreamCollection::Create()),
181 remote_stream_factory_(new RemoteMediaStreamFactory(signaling_thread,
183 last_allocated_sctp_even_sid_(-2),
184 last_allocated_sctp_odd_sid_(-1) {
185 options_.has_video = false;
186 options_.has_audio = false;
189 MediaStreamSignaling::~MediaStreamSignaling() {
192 void MediaStreamSignaling::TearDown() {
193 OnAudioChannelClose();
194 OnVideoChannelClose();
195 OnDataChannelClose();
198 bool MediaStreamSignaling::IsSctpSidAvailable(int sid) const {
199 if (sid < 0 || sid > static_cast<int>(cricket::kMaxSctpSid))
201 for (SctpDataChannels::const_iterator iter = sctp_data_channels_.begin();
202 iter != sctp_data_channels_.end();
204 if ((*iter)->id() == sid) {
211 // Gets the first unused odd/even id based on the DTLS role. If |role| is
212 // SSL_CLIENT, the allocated id starts from 0 and takes even numbers; otherwise,
213 // the id starts from 1 and takes odd numbers. Returns false if no id can be
215 bool MediaStreamSignaling::AllocateSctpSid(talk_base::SSLRole role, int* sid) {
216 int& last_id = (role == talk_base::SSL_CLIENT) ?
217 last_allocated_sctp_even_sid_ : last_allocated_sctp_odd_sid_;
221 } while (last_id <= static_cast<int>(cricket::kMaxSctpSid) &&
222 !IsSctpSidAvailable(last_id));
224 if (last_id > static_cast<int>(cricket::kMaxSctpSid)) {
232 bool MediaStreamSignaling::HasDataChannels() const {
233 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
236 bool MediaStreamSignaling::AddDataChannel(DataChannel* data_channel) {
237 ASSERT(data_channel != NULL);
238 if (data_channel->data_channel_type() == cricket::DCT_RTP) {
239 if (rtp_data_channels_.find(data_channel->label()) !=
240 rtp_data_channels_.end()) {
241 LOG(LS_ERROR) << "DataChannel with label " << data_channel->label()
242 << " already exists.";
245 rtp_data_channels_[data_channel->label()] = data_channel;
247 ASSERT(data_channel->data_channel_type() == cricket::DCT_SCTP);
248 sctp_data_channels_.push_back(data_channel);
253 bool MediaStreamSignaling::AddDataChannelFromOpenMessage(
254 const cricket::ReceiveDataParams& params,
255 const talk_base::Buffer& payload) {
256 if (!data_channel_factory_) {
257 LOG(LS_WARNING) << "Remote peer requested a DataChannel but DataChannels "
258 << "are not supported.";
263 InternalDataChannelInit config;
264 config.id = params.ssrc;
265 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
266 LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
270 config.open_handshake_role = InternalDataChannelInit::kAcker;
272 scoped_refptr<DataChannel> channel(
273 data_channel_factory_->CreateDataChannel(label, &config));
274 if (!channel.get()) {
275 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
278 sctp_data_channels_.push_back(channel);
279 stream_observer_->OnAddDataChannel(channel);
283 bool MediaStreamSignaling::AddLocalStream(MediaStreamInterface* local_stream) {
284 if (local_streams_->find(local_stream->label()) != NULL) {
285 LOG(LS_WARNING) << "MediaStream with label " << local_stream->label()
289 local_streams_->AddStream(local_stream);
291 // Find tracks that has already been configured in SDP. This can occur if a
292 // local session description that contains the MSID of these tracks is set
293 // before AddLocalStream is called. It can also occur if the local session
294 // description is not changed and RemoveLocalStream
295 // is called and later AddLocalStream is called again with the same stream.
296 AudioTrackVector audio_tracks = local_stream->GetAudioTracks();
297 for (AudioTrackVector::const_iterator it = audio_tracks.begin();
298 it != audio_tracks.end(); ++it) {
299 const TrackInfo* track_info = FindTrackInfo(local_audio_tracks_,
300 local_stream->label(),
303 OnLocalTrackSeen(track_info->stream_label, track_info->track_id,
304 track_info->ssrc, cricket::MEDIA_TYPE_AUDIO);
308 VideoTrackVector video_tracks = local_stream->GetVideoTracks();
309 for (VideoTrackVector::const_iterator it = video_tracks.begin();
310 it != video_tracks.end(); ++it) {
311 const TrackInfo* track_info = FindTrackInfo(local_video_tracks_,
312 local_stream->label(),
315 OnLocalTrackSeen(track_info->stream_label, track_info->track_id,
316 track_info->ssrc, cricket::MEDIA_TYPE_VIDEO);
322 void MediaStreamSignaling::RemoveLocalStream(
323 MediaStreamInterface* local_stream) {
324 AudioTrackVector audio_tracks = local_stream->GetAudioTracks();
325 for (AudioTrackVector::const_iterator it = audio_tracks.begin();
326 it != audio_tracks.end(); ++it) {
327 const TrackInfo* track_info = FindTrackInfo(local_audio_tracks_,
328 local_stream->label(),
331 stream_observer_->OnRemoveLocalAudioTrack(local_stream, *it,
335 VideoTrackVector video_tracks = local_stream->GetVideoTracks();
336 for (VideoTrackVector::const_iterator it = video_tracks.begin();
337 it != video_tracks.end(); ++it) {
338 const TrackInfo* track_info = FindTrackInfo(local_video_tracks_,
339 local_stream->label(),
342 stream_observer_->OnRemoveLocalVideoTrack(local_stream, *it);
346 local_streams_->RemoveStream(local_stream);
347 stream_observer_->OnRemoveLocalStream(local_stream);
350 bool MediaStreamSignaling::GetOptionsForOffer(
351 const MediaConstraintsInterface* constraints,
352 cricket::MediaSessionOptions* options) {
353 UpdateSessionOptions();
354 if (!ParseConstraints(constraints, &options_, false)) {
357 options_.bundle_enabled = EvaluateNeedForBundle(options_);
362 bool MediaStreamSignaling::GetOptionsForAnswer(
363 const MediaConstraintsInterface* constraints,
364 cricket::MediaSessionOptions* options) {
365 UpdateSessionOptions();
367 // Copy the |options_| to not let the flag MediaSessionOptions::has_audio and
368 // MediaSessionOptions::has_video affect subsequent offers.
369 cricket::MediaSessionOptions current_options = options_;
370 if (!ParseConstraints(constraints, ¤t_options, true)) {
373 current_options.bundle_enabled = EvaluateNeedForBundle(current_options);
374 *options = current_options;
378 // Updates or creates remote MediaStream objects given a
379 // remote SessionDesription.
380 // If the remote SessionDesription contains new remote MediaStreams
381 // the observer OnAddStream method is called. If a remote MediaStream is missing
382 // from the remote SessionDescription OnRemoveStream is called.
383 void MediaStreamSignaling::OnRemoteDescriptionChanged(
384 const SessionDescriptionInterface* desc) {
385 const cricket::SessionDescription* remote_desc = desc->description();
386 talk_base::scoped_refptr<StreamCollection> new_streams(
387 StreamCollection::Create());
389 // Find all audio rtp streams and create corresponding remote AudioTracks
391 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
393 const cricket::AudioContentDescription* desc =
394 static_cast<const cricket::AudioContentDescription*>(
395 audio_content->description);
396 UpdateRemoteStreamsList(desc->streams(), desc->type(), new_streams);
397 remote_info_.default_audio_track_needed =
398 desc->direction() == cricket::MD_SENDRECV && desc->streams().empty();
401 // Find all video rtp streams and create corresponding remote VideoTracks
403 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
405 const cricket::VideoContentDescription* desc =
406 static_cast<const cricket::VideoContentDescription*>(
407 video_content->description);
408 UpdateRemoteStreamsList(desc->streams(), desc->type(), new_streams);
409 remote_info_.default_video_track_needed =
410 desc->direction() == cricket::MD_SENDRECV && desc->streams().empty();
413 // Update the DataChannels with the information from the remote peer.
414 const cricket::ContentInfo* data_content = GetFirstDataContent(remote_desc);
416 const cricket::DataContentDescription* data_desc =
417 static_cast<const cricket::DataContentDescription*>(
418 data_content->description);
419 if (talk_base::starts_with(
420 data_desc->protocol().data(), cricket::kMediaProtocolRtpPrefix)) {
421 UpdateRemoteRtpDataChannels(data_desc->streams());
425 // Iterate new_streams and notify the observer about new MediaStreams.
426 for (size_t i = 0; i < new_streams->count(); ++i) {
427 MediaStreamInterface* new_stream = new_streams->at(i);
428 stream_observer_->OnAddRemoteStream(new_stream);
431 // Find removed MediaStreams.
432 if (remote_info_.IsDefaultMediaStreamNeeded() &&
433 remote_streams_->find(kDefaultStreamLabel) != NULL) {
434 // The default media stream already exists. No need to do anything.
436 UpdateEndedRemoteMediaStreams();
437 remote_info_.msid_supported |= remote_streams_->count() > 0;
439 MaybeCreateDefaultStream();
442 void MediaStreamSignaling::OnLocalDescriptionChanged(
443 const SessionDescriptionInterface* desc) {
444 const cricket::ContentInfo* audio_content =
445 GetFirstAudioContent(desc->description());
447 if (audio_content->rejected) {
448 RejectRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
450 const cricket::AudioContentDescription* audio_desc =
451 static_cast<const cricket::AudioContentDescription*>(
452 audio_content->description);
453 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
456 const cricket::ContentInfo* video_content =
457 GetFirstVideoContent(desc->description());
459 if (video_content->rejected) {
460 RejectRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
462 const cricket::VideoContentDescription* video_desc =
463 static_cast<const cricket::VideoContentDescription*>(
464 video_content->description);
465 UpdateLocalTracks(video_desc->streams(), video_desc->type());
468 const cricket::ContentInfo* data_content =
469 GetFirstDataContent(desc->description());
471 const cricket::DataContentDescription* data_desc =
472 static_cast<const cricket::DataContentDescription*>(
473 data_content->description);
474 if (talk_base::starts_with(
475 data_desc->protocol().data(), cricket::kMediaProtocolRtpPrefix)) {
476 UpdateLocalRtpDataChannels(data_desc->streams());
481 void MediaStreamSignaling::OnAudioChannelClose() {
482 RejectRemoteTracks(cricket::MEDIA_TYPE_AUDIO);
485 void MediaStreamSignaling::OnVideoChannelClose() {
486 RejectRemoteTracks(cricket::MEDIA_TYPE_VIDEO);
489 void MediaStreamSignaling::OnDataChannelClose() {
490 RtpDataChannels::iterator it1 = rtp_data_channels_.begin();
491 for (; it1 != rtp_data_channels_.end(); ++it1) {
492 it1->second->OnDataEngineClose();
494 SctpDataChannels::iterator it2 = sctp_data_channels_.begin();
495 for (; it2 != sctp_data_channels_.end(); ++it2) {
496 (*it2)->OnDataEngineClose();
500 void MediaStreamSignaling::UpdateSessionOptions() {
501 options_.streams.clear();
502 if (local_streams_ != NULL) {
503 for (size_t i = 0; i < local_streams_->count(); ++i) {
504 MediaStreamInterface* stream = local_streams_->at(i);
506 AudioTrackVector audio_tracks(stream->GetAudioTracks());
507 if (!audio_tracks.empty()) {
508 options_.has_audio = true;
511 // For each audio track in the stream, add it to the MediaSessionOptions.
512 for (size_t j = 0; j < audio_tracks.size(); ++j) {
513 scoped_refptr<MediaStreamTrackInterface> track(audio_tracks[j]);
514 options_.AddStream(cricket::MEDIA_TYPE_AUDIO, track->id(),
518 VideoTrackVector video_tracks(stream->GetVideoTracks());
519 if (!video_tracks.empty()) {
520 options_.has_video = true;
522 // For each video track in the stream, add it to the MediaSessionOptions.
523 for (size_t j = 0; j < video_tracks.size(); ++j) {
524 scoped_refptr<MediaStreamTrackInterface> track(video_tracks[j]);
525 options_.AddStream(cricket::MEDIA_TYPE_VIDEO, track->id(),
531 // Check for data channels.
532 RtpDataChannels::const_iterator data_channel_it = rtp_data_channels_.begin();
533 for (; data_channel_it != rtp_data_channels_.end(); ++data_channel_it) {
534 const DataChannel* channel = data_channel_it->second;
535 if (channel->state() == DataChannel::kConnecting ||
536 channel->state() == DataChannel::kOpen) {
537 // |streamid| and |sync_label| are both set to the DataChannel label
538 // here so they can be signaled the same way as MediaStreams and Tracks.
539 // For MediaStreams, the sync_label is the MediaStream label and the
540 // track label is the same as |streamid|.
541 const std::string& streamid = channel->label();
542 const std::string& sync_label = channel->label();
543 options_.AddStream(cricket::MEDIA_TYPE_DATA, streamid, sync_label);
548 void MediaStreamSignaling::UpdateRemoteStreamsList(
549 const cricket::StreamParamsVec& streams,
550 cricket::MediaType media_type,
551 StreamCollection* new_streams) {
552 TrackInfos* current_tracks = GetRemoteTracks(media_type);
554 // Find removed tracks. Ie tracks where the track id or ssrc don't match the
556 TrackInfos::iterator track_it = current_tracks->begin();
557 while (track_it != current_tracks->end()) {
558 const TrackInfo& info = *track_it;
559 cricket::StreamParams params;
560 if (!cricket::GetStreamBySsrc(streams, info.ssrc, ¶ms) ||
561 params.id != info.track_id) {
562 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
563 track_it = current_tracks->erase(track_it);
569 // Find new and active tracks.
570 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
571 it != streams.end(); ++it) {
572 // The sync_label is the MediaStream label and the |stream.id| is the
574 const std::string& stream_label = it->sync_label;
575 const std::string& track_id = it->id;
576 uint32 ssrc = it->first_ssrc();
578 talk_base::scoped_refptr<MediaStreamInterface> stream =
579 remote_streams_->find(stream_label);
581 // This is a new MediaStream. Create a new remote MediaStream.
582 stream = remote_stream_factory_->CreateMediaStream(stream_label);
583 remote_streams_->AddStream(stream);
584 new_streams->AddStream(stream);
587 const TrackInfo* track_info = FindTrackInfo(*current_tracks, stream_label,
590 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
591 OnRemoteTrackSeen(stream_label, track_id, it->first_ssrc(), media_type);
596 void MediaStreamSignaling::OnRemoteTrackSeen(const std::string& stream_label,
597 const std::string& track_id,
599 cricket::MediaType media_type) {
600 MediaStreamInterface* stream = remote_streams_->find(stream_label);
602 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
603 AudioTrackInterface* audio_track =
604 remote_stream_factory_->AddAudioTrack(stream, track_id);
605 stream_observer_->OnAddRemoteAudioTrack(stream, audio_track, ssrc);
606 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
607 VideoTrackInterface* video_track =
608 remote_stream_factory_->AddVideoTrack(stream, track_id);
609 stream_observer_->OnAddRemoteVideoTrack(stream, video_track, ssrc);
611 ASSERT(false && "Invalid media type");
615 void MediaStreamSignaling::OnRemoteTrackRemoved(
616 const std::string& stream_label,
617 const std::string& track_id,
618 cricket::MediaType media_type) {
619 MediaStreamInterface* stream = remote_streams_->find(stream_label);
621 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
622 talk_base::scoped_refptr<AudioTrackInterface> audio_track =
623 stream->FindAudioTrack(track_id);
625 audio_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
626 stream->RemoveTrack(audio_track);
627 stream_observer_->OnRemoveRemoteAudioTrack(stream, audio_track);
629 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
630 talk_base::scoped_refptr<VideoTrackInterface> video_track =
631 stream->FindVideoTrack(track_id);
633 video_track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
634 stream->RemoveTrack(video_track);
635 stream_observer_->OnRemoveRemoteVideoTrack(stream, video_track);
638 ASSERT(false && "Invalid media type");
642 void MediaStreamSignaling::RejectRemoteTracks(cricket::MediaType media_type) {
643 TrackInfos* current_tracks = GetRemoteTracks(media_type);
644 for (TrackInfos::iterator track_it = current_tracks->begin();
645 track_it != current_tracks->end(); ++track_it) {
646 const TrackInfo& info = *track_it;
647 MediaStreamInterface* stream = remote_streams_->find(info.stream_label);
648 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
649 AudioTrackInterface* track = stream->FindAudioTrack(info.track_id);
650 // There's no guarantee the track is still available, e.g. the track may
651 // have been removed from the stream by javascript.
653 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
656 if (media_type == cricket::MEDIA_TYPE_VIDEO) {
657 VideoTrackInterface* track = stream->FindVideoTrack(info.track_id);
658 // There's no guarantee the track is still available, e.g. the track may
659 // have been removed from the stream by javascript.
661 track->set_state(webrtc::MediaStreamTrackInterface::kEnded);
667 void MediaStreamSignaling::UpdateEndedRemoteMediaStreams() {
668 std::vector<scoped_refptr<MediaStreamInterface> > streams_to_remove;
669 for (size_t i = 0; i < remote_streams_->count(); ++i) {
670 MediaStreamInterface*stream = remote_streams_->at(i);
671 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
672 streams_to_remove.push_back(stream);
676 std::vector<scoped_refptr<MediaStreamInterface> >::const_iterator it;
677 for (it = streams_to_remove.begin(); it != streams_to_remove.end(); ++it) {
678 remote_streams_->RemoveStream(*it);
679 stream_observer_->OnRemoveRemoteStream(*it);
683 void MediaStreamSignaling::MaybeCreateDefaultStream() {
684 if (!remote_info_.IsDefaultMediaStreamNeeded())
687 bool default_created = false;
689 scoped_refptr<MediaStreamInterface> default_remote_stream =
690 remote_streams_->find(kDefaultStreamLabel);
691 if (default_remote_stream == NULL) {
692 default_created = true;
693 default_remote_stream =
694 remote_stream_factory_->CreateMediaStream(kDefaultStreamLabel);
695 remote_streams_->AddStream(default_remote_stream);
697 if (remote_info_.default_audio_track_needed &&
698 default_remote_stream->GetAudioTracks().size() == 0) {
699 remote_audio_tracks_.push_back(TrackInfo(kDefaultStreamLabel,
700 kDefaultAudioTrackLabel, 0));
702 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultAudioTrackLabel, 0,
703 cricket::MEDIA_TYPE_AUDIO);
705 if (remote_info_.default_video_track_needed &&
706 default_remote_stream->GetVideoTracks().size() == 0) {
707 remote_video_tracks_.push_back(TrackInfo(kDefaultStreamLabel,
708 kDefaultVideoTrackLabel, 0));
709 OnRemoteTrackSeen(kDefaultStreamLabel, kDefaultVideoTrackLabel, 0,
710 cricket::MEDIA_TYPE_VIDEO);
712 if (default_created) {
713 stream_observer_->OnAddRemoteStream(default_remote_stream);
717 MediaStreamSignaling::TrackInfos* MediaStreamSignaling::GetRemoteTracks(
718 cricket::MediaType type) {
719 if (type == cricket::MEDIA_TYPE_AUDIO)
720 return &remote_audio_tracks_;
721 else if (type == cricket::MEDIA_TYPE_VIDEO)
722 return &remote_video_tracks_;
723 ASSERT(false && "Unknown MediaType");
727 MediaStreamSignaling::TrackInfos* MediaStreamSignaling::GetLocalTracks(
728 cricket::MediaType media_type) {
729 ASSERT(media_type == cricket::MEDIA_TYPE_AUDIO ||
730 media_type == cricket::MEDIA_TYPE_VIDEO);
732 return (media_type == cricket::MEDIA_TYPE_AUDIO) ?
733 &local_audio_tracks_ : &local_video_tracks_;
736 void MediaStreamSignaling::UpdateLocalTracks(
737 const std::vector<cricket::StreamParams>& streams,
738 cricket::MediaType media_type) {
739 TrackInfos* current_tracks = GetLocalTracks(media_type);
741 // Find removed tracks. Ie tracks where the track id, stream label or ssrc
742 // don't match the new StreamParam.
743 TrackInfos::iterator track_it = current_tracks->begin();
744 while (track_it != current_tracks->end()) {
745 const TrackInfo& info = *track_it;
746 cricket::StreamParams params;
747 if (!cricket::GetStreamBySsrc(streams, info.ssrc, ¶ms) ||
748 params.id != info.track_id || params.sync_label != info.stream_label) {
749 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
751 track_it = current_tracks->erase(track_it);
757 // Find new and active tracks.
758 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
759 it != streams.end(); ++it) {
760 // The sync_label is the MediaStream label and the |stream.id| is the
762 const std::string& stream_label = it->sync_label;
763 const std::string& track_id = it->id;
764 uint32 ssrc = it->first_ssrc();
765 const TrackInfo* track_info = FindTrackInfo(*current_tracks,
769 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
770 OnLocalTrackSeen(stream_label, track_id, it->first_ssrc(),
776 void MediaStreamSignaling::OnLocalTrackSeen(
777 const std::string& stream_label,
778 const std::string& track_id,
780 cricket::MediaType media_type) {
781 MediaStreamInterface* stream = local_streams_->find(stream_label);
783 LOG(LS_WARNING) << "An unknown local MediaStream with label "
784 << stream_label << " has been configured.";
788 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
789 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
791 LOG(LS_WARNING) << "An unknown local AudioTrack with id , "
792 << track_id << " has been configured.";
795 stream_observer_->OnAddLocalAudioTrack(stream, audio_track, ssrc);
796 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
797 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
799 LOG(LS_WARNING) << "An unknown local VideoTrack with id , "
800 << track_id << " has been configured.";
803 stream_observer_->OnAddLocalVideoTrack(stream, video_track, ssrc);
805 ASSERT(false && "Invalid media type");
809 void MediaStreamSignaling::OnLocalTrackRemoved(
810 const std::string& stream_label,
811 const std::string& track_id,
813 cricket::MediaType media_type) {
814 MediaStreamInterface* stream = local_streams_->find(stream_label);
816 // This is the normal case. Ie RemoveLocalStream has been called and the
817 // SessionDescriptions has been renegotiated.
820 // A track has been removed from the SessionDescription but the MediaStream
821 // is still associated with MediaStreamSignaling. This only occurs if the SDP
822 // doesn't match with the calls to AddLocalStream and RemoveLocalStream.
824 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
825 AudioTrackInterface* audio_track = stream->FindAudioTrack(track_id);
829 stream_observer_->OnRemoveLocalAudioTrack(stream, audio_track, ssrc);
830 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
831 VideoTrackInterface* video_track = stream->FindVideoTrack(track_id);
835 stream_observer_->OnRemoveLocalVideoTrack(stream, video_track);
837 ASSERT(false && "Invalid media type.");
841 void MediaStreamSignaling::UpdateLocalRtpDataChannels(
842 const cricket::StreamParamsVec& streams) {
843 std::vector<std::string> existing_channels;
845 // Find new and active data channels.
846 for (cricket::StreamParamsVec::const_iterator it =streams.begin();
847 it != streams.end(); ++it) {
848 // |it->sync_label| is actually the data channel label. The reason is that
849 // we use the same naming of data channels as we do for
850 // MediaStreams and Tracks.
851 // For MediaStreams, the sync_label is the MediaStream label and the
852 // track label is the same as |streamid|.
853 const std::string& channel_label = it->sync_label;
854 RtpDataChannels::iterator data_channel_it =
855 rtp_data_channels_.find(channel_label);
856 if (!VERIFY(data_channel_it != rtp_data_channels_.end())) {
859 // Set the SSRC the data channel should use for sending.
860 data_channel_it->second->SetSendSsrc(it->first_ssrc());
861 existing_channels.push_back(data_channel_it->first);
864 UpdateClosingDataChannels(existing_channels, true);
867 void MediaStreamSignaling::UpdateRemoteRtpDataChannels(
868 const cricket::StreamParamsVec& streams) {
869 std::vector<std::string> existing_channels;
871 // Find new and active data channels.
872 for (cricket::StreamParamsVec::const_iterator it = streams.begin();
873 it != streams.end(); ++it) {
874 // The data channel label is either the mslabel or the SSRC if the mslabel
875 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
876 std::string label = it->sync_label.empty() ?
877 talk_base::ToString(it->first_ssrc()) : it->sync_label;
878 RtpDataChannels::iterator data_channel_it =
879 rtp_data_channels_.find(label);
880 if (data_channel_it == rtp_data_channels_.end()) {
881 // This is a new data channel.
882 CreateRemoteDataChannel(label, it->first_ssrc());
884 data_channel_it->second->SetReceiveSsrc(it->first_ssrc());
886 existing_channels.push_back(label);
889 UpdateClosingDataChannels(existing_channels, false);
892 void MediaStreamSignaling::UpdateClosingDataChannels(
893 const std::vector<std::string>& active_channels, bool is_local_update) {
894 RtpDataChannels::iterator it = rtp_data_channels_.begin();
895 while (it != rtp_data_channels_.end()) {
896 DataChannel* data_channel = it->second;
897 if (std::find(active_channels.begin(), active_channels.end(),
898 data_channel->label()) != active_channels.end()) {
904 data_channel->SetSendSsrc(0);
906 data_channel->RemotePeerRequestClose();
908 if (data_channel->state() == DataChannel::kClosed) {
909 rtp_data_channels_.erase(it);
910 it = rtp_data_channels_.begin();
917 void MediaStreamSignaling::CreateRemoteDataChannel(const std::string& label,
918 uint32 remote_ssrc) {
919 if (!data_channel_factory_) {
920 LOG(LS_WARNING) << "Remote peer requested a DataChannel but DataChannels "
921 << "are not supported.";
924 scoped_refptr<DataChannel> channel(
925 data_channel_factory_->CreateDataChannel(label, NULL));
926 if (!channel.get()) {
927 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
928 << "CreateDataChannel failed.";
931 channel->SetReceiveSsrc(remote_ssrc);
932 stream_observer_->OnAddDataChannel(channel);
935 void MediaStreamSignaling::OnDataTransportCreatedForSctp() {
936 SctpDataChannels::iterator it = sctp_data_channels_.begin();
937 for (; it != sctp_data_channels_.end(); ++it) {
938 (*it)->OnTransportChannelCreated();
942 void MediaStreamSignaling::OnDtlsRoleReadyForSctp(talk_base::SSLRole role) {
943 SctpDataChannels::iterator it = sctp_data_channels_.begin();
944 for (; it != sctp_data_channels_.end(); ++it) {
945 if ((*it)->id() < 0) {
947 if (!AllocateSctpSid(role, &sid)) {
948 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
951 (*it)->SetSctpSid(sid);
956 const MediaStreamSignaling::TrackInfo*
957 MediaStreamSignaling::FindTrackInfo(
958 const MediaStreamSignaling::TrackInfos& infos,
959 const std::string& stream_label,
960 const std::string track_id) const {
962 for (TrackInfos::const_iterator it = infos.begin();
963 it != infos.end(); ++it) {
964 if (it->stream_label == stream_label && it->track_id == track_id)
970 } // namespace webrtc