3 * Copyright 2004 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/session/media/channel.h"
30 #include "talk/base/bind.h"
31 #include "talk/base/buffer.h"
32 #include "talk/base/byteorder.h"
33 #include "talk/base/common.h"
34 #include "talk/base/dscp.h"
35 #include "talk/base/logging.h"
36 #include "talk/media/base/rtputils.h"
37 #include "talk/p2p/base/transportchannel.h"
38 #include "talk/session/media/channelmanager.h"
39 #include "talk/session/media/mediamessages.h"
40 #include "talk/session/media/rtcpmuxfilter.h"
41 #include "talk/session/media/typingmonitor.h"
46 using talk_base::Bind;
49 MSG_EARLYMEDIATIMEOUT = 1,
50 MSG_SCREENCASTWINDOWEVENT,
56 MSG_FIRSTPACKETRECEIVED,
59 // Value specified in RFC 5764.
60 static const char kDtlsSrtpExporterLabel[] = "EXTRACTOR-dtls_srtp";
62 static const int kAgcMinus10db = -10;
64 static void SetSessionError(BaseSession* session, BaseSession::Error error,
65 const std::string& error_desc) {
66 session->SetError(error, error_desc);
69 static void SafeSetError(const std::string& message, std::string* error_desc) {
71 *error_desc = message;
75 // TODO(hellner): use the device manager for creation of screen capturers when
76 // the cl enabling it has landed.
77 class NullScreenCapturerFactory : public VideoChannel::ScreenCapturerFactory {
79 VideoCapturer* CreateScreenCapturer(const ScreencastId& window) {
85 VideoChannel::ScreenCapturerFactory* CreateScreenCapturerFactory() {
86 return new NullScreenCapturerFactory();
89 struct PacketMessageData : public talk_base::MessageData {
90 talk_base::Buffer packet;
91 talk_base::DiffServCodePoint dscp;
94 struct ScreencastEventMessageData : public talk_base::MessageData {
95 ScreencastEventMessageData(uint32 s, talk_base::WindowEvent we)
100 talk_base::WindowEvent event;
103 struct VoiceChannelErrorMessageData : public talk_base::MessageData {
104 VoiceChannelErrorMessageData(uint32 in_ssrc,
105 VoiceMediaChannel::Error in_error)
110 VoiceMediaChannel::Error error;
113 struct VideoChannelErrorMessageData : public talk_base::MessageData {
114 VideoChannelErrorMessageData(uint32 in_ssrc,
115 VideoMediaChannel::Error in_error)
120 VideoMediaChannel::Error error;
123 struct DataChannelErrorMessageData : public talk_base::MessageData {
124 DataChannelErrorMessageData(uint32 in_ssrc,
125 DataMediaChannel::Error in_error)
129 DataMediaChannel::Error error;
133 struct VideoChannel::ScreencastDetailsData {
134 explicit ScreencastDetailsData(uint32 s)
135 : ssrc(s), fps(0), screencast_max_pixels(0) {
139 int screencast_max_pixels;
142 static const char* PacketType(bool rtcp) {
143 return (!rtcp) ? "RTP" : "RTCP";
146 static bool ValidPacket(bool rtcp, const talk_base::Buffer* packet) {
147 // Check the packet size. We could check the header too if needed.
149 packet->length() >= (!rtcp ? kMinRtpPacketLen : kMinRtcpPacketLen) &&
150 packet->length() <= kMaxRtpPacketLen);
153 static bool IsReceiveContentDirection(MediaContentDirection direction) {
154 return direction == MD_SENDRECV || direction == MD_RECVONLY;
157 static bool IsSendContentDirection(MediaContentDirection direction) {
158 return direction == MD_SENDRECV || direction == MD_SENDONLY;
161 static const MediaContentDescription* GetContentDescription(
162 const ContentInfo* cinfo) {
165 return static_cast<const MediaContentDescription*>(cinfo->description);
168 BaseChannel::BaseChannel(talk_base::Thread* thread,
169 MediaEngineInterface* media_engine,
170 MediaChannel* media_channel, BaseSession* session,
171 const std::string& content_name, bool rtcp)
172 : worker_thread_(thread),
173 media_engine_(media_engine),
175 media_channel_(media_channel),
176 content_name_(content_name),
178 transport_channel_(NULL),
179 rtcp_transport_channel_(NULL),
182 rtp_ready_to_send_(false),
183 rtcp_ready_to_send_(false),
184 was_ever_writable_(false),
185 local_content_direction_(MD_INACTIVE),
186 remote_content_direction_(MD_INACTIVE),
187 has_received_packet_(false),
189 secure_required_(false) {
190 ASSERT(worker_thread_ == talk_base::Thread::Current());
191 LOG(LS_INFO) << "Created channel for " << content_name;
194 BaseChannel::~BaseChannel() {
195 ASSERT(worker_thread_ == talk_base::Thread::Current());
197 StopConnectionMonitor();
198 FlushRtcpMessages(); // Send any outstanding RTCP packets.
199 worker_thread_->Clear(this); // eats any outstanding messages or packets
200 // We must destroy the media channel before the transport channel, otherwise
201 // the media channel may try to send on the dead transport channel. NULLing
202 // is not an effective strategy since the sends will come on another thread.
203 delete media_channel_;
204 set_rtcp_transport_channel(NULL);
205 if (transport_channel_ != NULL)
206 session_->DestroyChannel(content_name_, transport_channel_->component());
207 LOG(LS_INFO) << "Destroyed channel";
210 bool BaseChannel::Init(TransportChannel* transport_channel,
211 TransportChannel* rtcp_transport_channel) {
212 if (transport_channel == NULL) {
215 if (rtcp() && rtcp_transport_channel == NULL) {
218 transport_channel_ = transport_channel;
220 if (!SetDtlsSrtpCiphers(transport_channel_, false)) {
224 transport_channel_->SignalWritableState.connect(
225 this, &BaseChannel::OnWritableState);
226 transport_channel_->SignalReadPacket.connect(
227 this, &BaseChannel::OnChannelRead);
228 transport_channel_->SignalReadyToSend.connect(
229 this, &BaseChannel::OnReadyToSend);
231 session_->SignalNewLocalDescription.connect(
232 this, &BaseChannel::OnNewLocalDescription);
233 session_->SignalNewRemoteDescription.connect(
234 this, &BaseChannel::OnNewRemoteDescription);
236 set_rtcp_transport_channel(rtcp_transport_channel);
237 // Both RTP and RTCP channels are set, we can call SetInterface on
238 // media channel and it can set network options.
239 media_channel_->SetInterface(this);
243 void BaseChannel::Deinit() {
244 media_channel_->SetInterface(NULL);
247 bool BaseChannel::Enable(bool enable) {
248 worker_thread_->Invoke<void>(Bind(
249 enable ? &BaseChannel::EnableMedia_w : &BaseChannel::DisableMedia_w,
254 bool BaseChannel::MuteStream(uint32 ssrc, bool mute) {
255 return InvokeOnWorker(Bind(&BaseChannel::MuteStream_w, this, ssrc, mute));
258 bool BaseChannel::IsStreamMuted(uint32 ssrc) {
259 return InvokeOnWorker(Bind(&BaseChannel::IsStreamMuted_w, this, ssrc));
262 bool BaseChannel::AddRecvStream(const StreamParams& sp) {
263 return InvokeOnWorker(Bind(&BaseChannel::AddRecvStream_w, this, sp));
266 bool BaseChannel::RemoveRecvStream(uint32 ssrc) {
267 return InvokeOnWorker(Bind(&BaseChannel::RemoveRecvStream_w, this, ssrc));
270 bool BaseChannel::AddSendStream(const StreamParams& sp) {
271 return InvokeOnWorker(
272 Bind(&MediaChannel::AddSendStream, media_channel(), sp));
275 bool BaseChannel::RemoveSendStream(uint32 ssrc) {
276 return InvokeOnWorker(
277 Bind(&MediaChannel::RemoveSendStream, media_channel(), ssrc));
280 bool BaseChannel::SetLocalContent(const MediaContentDescription* content,
281 ContentAction action,
282 std::string* error_desc) {
283 return InvokeOnWorker(Bind(&BaseChannel::SetLocalContent_w,
284 this, content, action, error_desc));
287 bool BaseChannel::SetRemoteContent(const MediaContentDescription* content,
288 ContentAction action,
289 std::string* error_desc) {
290 return InvokeOnWorker(Bind(&BaseChannel::SetRemoteContent_w,
291 this, content, action, error_desc));
294 void BaseChannel::StartConnectionMonitor(int cms) {
295 socket_monitor_.reset(new SocketMonitor(transport_channel_,
297 talk_base::Thread::Current()));
298 socket_monitor_->SignalUpdate.connect(
299 this, &BaseChannel::OnConnectionMonitorUpdate);
300 socket_monitor_->Start(cms);
303 void BaseChannel::StopConnectionMonitor() {
304 if (socket_monitor_) {
305 socket_monitor_->Stop();
306 socket_monitor_.reset();
310 void BaseChannel::set_rtcp_transport_channel(TransportChannel* channel) {
311 if (rtcp_transport_channel_ != channel) {
312 if (rtcp_transport_channel_) {
313 session_->DestroyChannel(
314 content_name_, rtcp_transport_channel_->component());
316 rtcp_transport_channel_ = channel;
317 if (rtcp_transport_channel_) {
318 // TODO(juberti): Propagate this error code
319 VERIFY(SetDtlsSrtpCiphers(rtcp_transport_channel_, true));
320 rtcp_transport_channel_->SignalWritableState.connect(
321 this, &BaseChannel::OnWritableState);
322 rtcp_transport_channel_->SignalReadPacket.connect(
323 this, &BaseChannel::OnChannelRead);
324 rtcp_transport_channel_->SignalReadyToSend.connect(
325 this, &BaseChannel::OnReadyToSend);
330 bool BaseChannel::IsReadyToReceive() const {
331 // Receive data if we are enabled and have local content,
332 return enabled() && IsReceiveContentDirection(local_content_direction_);
335 bool BaseChannel::IsReadyToSend() const {
336 // Send outgoing data if we are enabled, have local and remote content,
337 // and we have had some form of connectivity.
339 IsReceiveContentDirection(remote_content_direction_) &&
340 IsSendContentDirection(local_content_direction_) &&
344 bool BaseChannel::SendPacket(talk_base::Buffer* packet,
345 talk_base::DiffServCodePoint dscp) {
346 return SendPacket(false, packet, dscp);
349 bool BaseChannel::SendRtcp(talk_base::Buffer* packet,
350 talk_base::DiffServCodePoint dscp) {
351 return SendPacket(true, packet, dscp);
354 int BaseChannel::SetOption(SocketType type, talk_base::Socket::Option opt,
356 TransportChannel* channel = NULL;
359 channel = transport_channel_;
362 channel = rtcp_transport_channel_;
365 return channel ? channel->SetOption(opt, value) : -1;
368 void BaseChannel::OnWritableState(TransportChannel* channel) {
369 ASSERT(channel == transport_channel_ || channel == rtcp_transport_channel_);
370 if (transport_channel_->writable()
371 && (!rtcp_transport_channel_ || rtcp_transport_channel_->writable())) {
374 ChannelNotWritable_w();
378 void BaseChannel::OnChannelRead(TransportChannel* channel,
379 const char* data, size_t len,
380 const talk_base::PacketTime& packet_time,
382 // OnChannelRead gets called from P2PSocket; now pass data to MediaEngine
383 ASSERT(worker_thread_ == talk_base::Thread::Current());
385 // When using RTCP multiplexing we might get RTCP packets on the RTP
386 // transport. We feed RTP traffic into the demuxer to determine if it is RTCP.
387 bool rtcp = PacketIsRtcp(channel, data, len);
388 talk_base::Buffer packet(data, len);
389 HandlePacket(rtcp, &packet, packet_time);
392 void BaseChannel::OnReadyToSend(TransportChannel* channel) {
393 SetReadyToSend(channel, true);
396 void BaseChannel::SetReadyToSend(TransportChannel* channel, bool ready) {
397 ASSERT(channel == transport_channel_ || channel == rtcp_transport_channel_);
398 if (channel == transport_channel_) {
399 rtp_ready_to_send_ = ready;
401 if (channel == rtcp_transport_channel_) {
402 rtcp_ready_to_send_ = ready;
406 // Notify the MediaChannel when either rtp or rtcp channel can't send.
407 media_channel_->OnReadyToSend(false);
408 } else if (rtp_ready_to_send_ &&
409 // In the case of rtcp mux |rtcp_transport_channel_| will be null.
410 (rtcp_ready_to_send_ || !rtcp_transport_channel_)) {
411 // Notify the MediaChannel when both rtp and rtcp channel can send.
412 media_channel_->OnReadyToSend(true);
416 bool BaseChannel::PacketIsRtcp(const TransportChannel* channel,
417 const char* data, size_t len) {
418 return (channel == rtcp_transport_channel_ ||
419 rtcp_mux_filter_.DemuxRtcp(data, static_cast<int>(len)));
422 bool BaseChannel::SendPacket(bool rtcp, talk_base::Buffer* packet,
423 talk_base::DiffServCodePoint dscp) {
424 // SendPacket gets called from MediaEngine, typically on an encoder thread.
425 // If the thread is not our worker thread, we will post to our worker
426 // so that the real work happens on our worker. This avoids us having to
427 // synchronize access to all the pieces of the send path, including
428 // SRTP and the inner workings of the transport channels.
429 // The only downside is that we can't return a proper failure code if
430 // needed. Since UDP is unreliable anyway, this should be a non-issue.
431 if (talk_base::Thread::Current() != worker_thread_) {
432 // Avoid a copy by transferring the ownership of the packet data.
433 int message_id = (!rtcp) ? MSG_RTPPACKET : MSG_RTCPPACKET;
434 PacketMessageData* data = new PacketMessageData;
435 packet->TransferTo(&data->packet);
437 worker_thread_->Post(this, message_id, data);
441 // Now that we are on the correct thread, ensure we have a place to send this
442 // packet before doing anything. (We might get RTCP packets that we don't
443 // intend to send.) If we've negotiated RTCP mux, send RTCP over the RTP
445 TransportChannel* channel = (!rtcp || rtcp_mux_filter_.IsActive()) ?
446 transport_channel_ : rtcp_transport_channel_;
447 if (!channel || !channel->writable()) {
451 // Protect ourselves against crazy data.
452 if (!ValidPacket(rtcp, packet)) {
453 LOG(LS_ERROR) << "Dropping outgoing " << content_name_ << " "
454 << PacketType(rtcp) << " packet: wrong size="
459 // Signal to the media sink before protecting the packet.
461 talk_base::CritScope cs(&signal_send_packet_cs_);
462 SignalSendPacketPreCrypto(packet->data(), packet->length(), rtcp);
465 // Protect if needed.
466 if (srtp_filter_.IsActive()) {
468 char* data = packet->data();
469 int len = static_cast<int>(packet->length());
471 res = srtp_filter_.ProtectRtp(data, len,
472 static_cast<int>(packet->capacity()), &len);
476 GetRtpSeqNum(data, len, &seq_num);
477 GetRtpSsrc(data, len, &ssrc);
478 LOG(LS_ERROR) << "Failed to protect " << content_name_
479 << " RTP packet: size=" << len
480 << ", seqnum=" << seq_num << ", SSRC=" << ssrc;
484 res = srtp_filter_.ProtectRtcp(data, len,
485 static_cast<int>(packet->capacity()),
489 GetRtcpType(data, len, &type);
490 LOG(LS_ERROR) << "Failed to protect " << content_name_
491 << " RTCP packet: size=" << len << ", type=" << type;
496 // Update the length of the packet now that we've added the auth tag.
497 packet->SetLength(len);
498 } else if (secure_required_) {
499 // This is a double check for something that supposedly can't happen.
500 LOG(LS_ERROR) << "Can't send outgoing " << PacketType(rtcp)
501 << " packet when SRTP is inactive and crypto is required";
507 // Signal to the media sink after protecting the packet.
509 talk_base::CritScope cs(&signal_send_packet_cs_);
510 SignalSendPacketPostCrypto(packet->data(), packet->length(), rtcp);
514 talk_base::PacketOptions options(dscp);
515 int ret = channel->SendPacket(packet->data(), packet->length(), options,
516 (secure() && secure_dtls()) ? PF_SRTP_BYPASS : 0);
517 if (ret != static_cast<int>(packet->length())) {
518 if (channel->GetError() == EWOULDBLOCK) {
519 LOG(LS_WARNING) << "Got EWOULDBLOCK from socket.";
520 SetReadyToSend(channel, false);
527 bool BaseChannel::WantsPacket(bool rtcp, talk_base::Buffer* packet) {
528 // Protect ourselves against crazy data.
529 if (!ValidPacket(rtcp, packet)) {
530 LOG(LS_ERROR) << "Dropping incoming " << content_name_ << " "
531 << PacketType(rtcp) << " packet: wrong size="
535 // If this channel is suppose to handle RTP data, that is determined by
536 // checking against ssrc filter. This is necessary to do it here to avoid
537 // double decryption.
538 if (ssrc_filter_.IsActive() &&
539 !ssrc_filter_.DemuxPacket(packet->data(), packet->length(), rtcp)) {
546 void BaseChannel::HandlePacket(bool rtcp, talk_base::Buffer* packet,
547 const talk_base::PacketTime& packet_time) {
548 if (!WantsPacket(rtcp, packet)) {
552 if (!has_received_packet_) {
553 has_received_packet_ = true;
554 signaling_thread()->Post(this, MSG_FIRSTPACKETRECEIVED);
557 // Signal to the media sink before unprotecting the packet.
559 talk_base::CritScope cs(&signal_recv_packet_cs_);
560 SignalRecvPacketPostCrypto(packet->data(), packet->length(), rtcp);
563 // Unprotect the packet, if needed.
564 if (srtp_filter_.IsActive()) {
565 char* data = packet->data();
566 int len = static_cast<int>(packet->length());
569 res = srtp_filter_.UnprotectRtp(data, len, &len);
573 GetRtpSeqNum(data, len, &seq_num);
574 GetRtpSsrc(data, len, &ssrc);
575 LOG(LS_ERROR) << "Failed to unprotect " << content_name_
576 << " RTP packet: size=" << len
577 << ", seqnum=" << seq_num << ", SSRC=" << ssrc;
581 res = srtp_filter_.UnprotectRtcp(data, len, &len);
584 GetRtcpType(data, len, &type);
585 LOG(LS_ERROR) << "Failed to unprotect " << content_name_
586 << " RTCP packet: size=" << len << ", type=" << type;
591 packet->SetLength(len);
592 } else if (secure_required_) {
593 // Our session description indicates that SRTP is required, but we got a
594 // packet before our SRTP filter is active. This means either that
595 // a) we got SRTP packets before we received the SDES keys, in which case
596 // we can't decrypt it anyway, or
597 // b) we got SRTP packets before DTLS completed on both the RTP and RTCP
598 // channels, so we haven't yet extracted keys, even if DTLS did complete
599 // on the channel that the packets are being sent on. It's really good
600 // practice to wait for both RTP and RTCP to be good to go before sending
601 // media, to prevent weird failure modes, so it's fine for us to just eat
602 // packets here. This is all sidestepped if RTCP mux is used anyway.
603 LOG(LS_WARNING) << "Can't process incoming " << PacketType(rtcp)
604 << " packet when SRTP is inactive and crypto is required";
608 // Signal to the media sink after unprotecting the packet.
610 talk_base::CritScope cs(&signal_recv_packet_cs_);
611 SignalRecvPacketPreCrypto(packet->data(), packet->length(), rtcp);
614 // Push it down to the media channel.
616 media_channel_->OnPacketReceived(packet, packet_time);
618 media_channel_->OnRtcpReceived(packet, packet_time);
622 void BaseChannel::OnNewLocalDescription(
623 BaseSession* session, ContentAction action) {
624 const ContentInfo* content_info =
625 GetFirstContent(session->local_description());
626 const MediaContentDescription* content_desc =
627 GetContentDescription(content_info);
628 std::string error_desc;
629 if (content_desc && content_info && !content_info->rejected &&
630 !SetLocalContent(content_desc, action, &error_desc)) {
631 SetSessionError(session_, BaseSession::ERROR_CONTENT, error_desc);
632 LOG(LS_ERROR) << "Failure in SetLocalContent with action " << action;
636 void BaseChannel::OnNewRemoteDescription(
637 BaseSession* session, ContentAction action) {
638 const ContentInfo* content_info =
639 GetFirstContent(session->remote_description());
640 const MediaContentDescription* content_desc =
641 GetContentDescription(content_info);
642 std::string error_desc;
643 if (content_desc && content_info && !content_info->rejected &&
644 !SetRemoteContent(content_desc, action, &error_desc)) {
645 SetSessionError(session_, BaseSession::ERROR_CONTENT, error_desc);
646 LOG(LS_ERROR) << "Failure in SetRemoteContent with action " << action;
650 void BaseChannel::EnableMedia_w() {
651 ASSERT(worker_thread_ == talk_base::Thread::Current());
655 LOG(LS_INFO) << "Channel enabled";
660 void BaseChannel::DisableMedia_w() {
661 ASSERT(worker_thread_ == talk_base::Thread::Current());
665 LOG(LS_INFO) << "Channel disabled";
670 bool BaseChannel::MuteStream_w(uint32 ssrc, bool mute) {
671 ASSERT(worker_thread_ == talk_base::Thread::Current());
672 bool ret = media_channel()->MuteStream(ssrc, mute);
675 muted_streams_.insert(ssrc);
677 muted_streams_.erase(ssrc);
682 bool BaseChannel::IsStreamMuted_w(uint32 ssrc) {
683 ASSERT(worker_thread_ == talk_base::Thread::Current());
684 return muted_streams_.find(ssrc) != muted_streams_.end();
687 void BaseChannel::ChannelWritable_w() {
688 ASSERT(worker_thread_ == talk_base::Thread::Current());
692 LOG(LS_INFO) << "Channel socket writable ("
693 << transport_channel_->content_name() << ", "
694 << transport_channel_->component() << ")"
695 << (was_ever_writable_ ? "" : " for the first time");
697 std::vector<ConnectionInfo> infos;
698 transport_channel_->GetStats(&infos);
699 for (std::vector<ConnectionInfo>::const_iterator it = infos.begin();
700 it != infos.end(); ++it) {
701 if (it->best_connection) {
702 LOG(LS_INFO) << "Using " << it->local_candidate.ToSensitiveString()
703 << "->" << it->remote_candidate.ToSensitiveString();
708 // If we're doing DTLS-SRTP, now is the time.
709 if (!was_ever_writable_ && ShouldSetupDtlsSrtp()) {
710 if (!SetupDtlsSrtp(false)) {
711 const std::string error_desc =
712 "Couldn't set up DTLS-SRTP on RTP channel.";
713 // Sent synchronously.
714 signaling_thread()->Invoke<void>(Bind(
717 BaseSession::ERROR_TRANSPORT,
722 if (rtcp_transport_channel_) {
723 if (!SetupDtlsSrtp(true)) {
724 const std::string error_desc =
725 "Couldn't set up DTLS-SRTP on RTCP channel";
726 // Sent synchronously.
727 signaling_thread()->Invoke<void>(Bind(
730 BaseSession::ERROR_TRANSPORT,
737 was_ever_writable_ = true;
742 bool BaseChannel::SetDtlsSrtpCiphers(TransportChannel *tc, bool rtcp) {
743 std::vector<std::string> ciphers;
744 // We always use the default SRTP ciphers for RTCP, but we may use different
745 // ciphers for RTP depending on the media type.
747 GetSrtpCiphers(&ciphers);
749 GetSupportedDefaultCryptoSuites(&ciphers);
751 return tc->SetSrtpCiphers(ciphers);
754 bool BaseChannel::ShouldSetupDtlsSrtp() const {
758 // This function returns true if either DTLS-SRTP is not in use
759 // *or* DTLS-SRTP is successfully set up.
760 bool BaseChannel::SetupDtlsSrtp(bool rtcp_channel) {
763 TransportChannel *channel = rtcp_channel ?
764 rtcp_transport_channel_ : transport_channel_;
767 if (!channel->IsDtlsActive())
770 std::string selected_cipher;
772 if (!channel->GetSrtpCipher(&selected_cipher)) {
773 LOG(LS_ERROR) << "No DTLS-SRTP selected cipher";
777 LOG(LS_INFO) << "Installing keys from DTLS-SRTP on "
778 << content_name() << " "
779 << PacketType(rtcp_channel);
781 // OK, we're now doing DTLS (RFC 5764)
782 std::vector<unsigned char> dtls_buffer(SRTP_MASTER_KEY_KEY_LEN * 2 +
783 SRTP_MASTER_KEY_SALT_LEN * 2);
785 // RFC 5705 exporter using the RFC 5764 parameters
786 if (!channel->ExportKeyingMaterial(
787 kDtlsSrtpExporterLabel,
789 &dtls_buffer[0], dtls_buffer.size())) {
790 LOG(LS_WARNING) << "DTLS-SRTP key export failed";
791 ASSERT(false); // This should never happen
795 // Sync up the keys with the DTLS-SRTP interface
796 std::vector<unsigned char> client_write_key(SRTP_MASTER_KEY_KEY_LEN +
797 SRTP_MASTER_KEY_SALT_LEN);
798 std::vector<unsigned char> server_write_key(SRTP_MASTER_KEY_KEY_LEN +
799 SRTP_MASTER_KEY_SALT_LEN);
801 memcpy(&client_write_key[0], &dtls_buffer[offset],
802 SRTP_MASTER_KEY_KEY_LEN);
803 offset += SRTP_MASTER_KEY_KEY_LEN;
804 memcpy(&server_write_key[0], &dtls_buffer[offset],
805 SRTP_MASTER_KEY_KEY_LEN);
806 offset += SRTP_MASTER_KEY_KEY_LEN;
807 memcpy(&client_write_key[SRTP_MASTER_KEY_KEY_LEN],
808 &dtls_buffer[offset], SRTP_MASTER_KEY_SALT_LEN);
809 offset += SRTP_MASTER_KEY_SALT_LEN;
810 memcpy(&server_write_key[SRTP_MASTER_KEY_KEY_LEN],
811 &dtls_buffer[offset], SRTP_MASTER_KEY_SALT_LEN);
813 std::vector<unsigned char> *send_key, *recv_key;
814 talk_base::SSLRole role;
815 if (!channel->GetSslRole(&role)) {
816 LOG(LS_WARNING) << "GetSslRole failed";
820 if (role == talk_base::SSL_SERVER) {
821 send_key = &server_write_key;
822 recv_key = &client_write_key;
824 send_key = &client_write_key;
825 recv_key = &server_write_key;
829 ret = srtp_filter_.SetRtcpParams(
832 static_cast<int>(send_key->size()),
835 static_cast<int>(recv_key->size()));
837 ret = srtp_filter_.SetRtpParams(
840 static_cast<int>(send_key->size()),
843 static_cast<int>(recv_key->size()));
847 LOG(LS_WARNING) << "DTLS-SRTP key installation failed";
854 void BaseChannel::ChannelNotWritable_w() {
855 ASSERT(worker_thread_ == talk_base::Thread::Current());
859 LOG(LS_INFO) << "Channel socket not writable ("
860 << transport_channel_->content_name() << ", "
861 << transport_channel_->component() << ")";
866 // |dtls| will be set to true if DTLS is active for transport channel and
868 bool BaseChannel::CheckSrtpConfig(const std::vector<CryptoParams>& cryptos,
870 std::string* error_desc) {
871 *dtls = transport_channel_->IsDtlsActive();
872 if (*dtls && !cryptos.empty()) {
873 SafeSetError("Cryptos must be empty when DTLS is active.",
880 bool BaseChannel::SetSrtp_w(const std::vector<CryptoParams>& cryptos,
881 ContentAction action,
883 std::string* error_desc) {
884 if (action == CA_UPDATE) {
890 ret = CheckSrtpConfig(cryptos, &dtls, error_desc);
896 // If DTLS is already active on the channel, we could be renegotiating
897 // here. We don't update the srtp filter.
899 ret = srtp_filter_.SetOffer(cryptos, src);
903 // If we're doing DTLS-SRTP, we don't want to update the filter
904 // with an answer, because we already have SRTP parameters.
906 ret = srtp_filter_.SetProvisionalAnswer(cryptos, src);
910 // If we're doing DTLS-SRTP, we don't want to update the filter
911 // with an answer, because we already have SRTP parameters.
913 ret = srtp_filter_.SetAnswer(cryptos, src);
920 SafeSetError("Failed to setup SRTP filter.", error_desc);
926 bool BaseChannel::SetRtcpMux_w(bool enable, ContentAction action,
928 std::string* error_desc) {
932 ret = rtcp_mux_filter_.SetOffer(enable, src);
935 ret = rtcp_mux_filter_.SetProvisionalAnswer(enable, src);
938 ret = rtcp_mux_filter_.SetAnswer(enable, src);
939 if (ret && rtcp_mux_filter_.IsActive()) {
940 // We activated RTCP mux, close down the RTCP transport.
941 set_rtcp_transport_channel(NULL);
951 SafeSetError("Failed to setup RTCP mux filter.", error_desc);
954 // |rtcp_mux_filter_| can be active if |action| is CA_PRANSWER or
955 // CA_ANSWER, but we only want to tear down the RTCP transport channel if we
956 // received a final answer.
957 if (rtcp_mux_filter_.IsActive()) {
958 // If the RTP transport is already writable, then so are we.
959 if (transport_channel_->writable()) {
967 bool BaseChannel::AddRecvStream_w(const StreamParams& sp) {
968 ASSERT(worker_thread() == talk_base::Thread::Current());
969 if (!media_channel()->AddRecvStream(sp))
972 return ssrc_filter_.AddStream(sp);
975 bool BaseChannel::RemoveRecvStream_w(uint32 ssrc) {
976 ASSERT(worker_thread() == talk_base::Thread::Current());
977 ssrc_filter_.RemoveStream(ssrc);
978 return media_channel()->RemoveRecvStream(ssrc);
981 bool BaseChannel::UpdateLocalStreams_w(const std::vector<StreamParams>& streams,
982 ContentAction action,
983 std::string* error_desc) {
984 if (!VERIFY(action == CA_OFFER || action == CA_ANSWER ||
985 action == CA_PRANSWER || action == CA_UPDATE))
988 // If this is an update, streams only contain streams that have changed.
989 if (action == CA_UPDATE) {
990 for (StreamParamsVec::const_iterator it = streams.begin();
991 it != streams.end(); ++it) {
992 StreamParams existing_stream;
993 bool stream_exist = GetStreamByIds(local_streams_, it->groupid,
994 it->id, &existing_stream);
995 if (!stream_exist && it->has_ssrcs()) {
996 if (media_channel()->AddSendStream(*it)) {
997 local_streams_.push_back(*it);
998 LOG(LS_INFO) << "Add send stream ssrc: " << it->first_ssrc();
1000 std::ostringstream desc;
1001 desc << "Failed to add send stream ssrc: " << it->first_ssrc();
1002 SafeSetError(desc.str(), error_desc);
1005 } else if (stream_exist && !it->has_ssrcs()) {
1006 if (!media_channel()->RemoveSendStream(existing_stream.first_ssrc())) {
1007 std::ostringstream desc;
1008 desc << "Failed to remove send stream with ssrc "
1009 << it->first_ssrc() << ".";
1010 SafeSetError(desc.str(), error_desc);
1013 RemoveStreamBySsrc(&local_streams_, existing_stream.first_ssrc());
1015 LOG(LS_WARNING) << "Ignore unsupported stream update";
1020 // Else streams are all the streams we want to send.
1022 // Check for streams that have been removed.
1024 for (StreamParamsVec::const_iterator it = local_streams_.begin();
1025 it != local_streams_.end(); ++it) {
1026 if (!GetStreamBySsrc(streams, it->first_ssrc(), NULL)) {
1027 if (!media_channel()->RemoveSendStream(it->first_ssrc())) {
1028 std::ostringstream desc;
1029 desc << "Failed to remove send stream with ssrc "
1030 << it->first_ssrc() << ".";
1031 SafeSetError(desc.str(), error_desc);
1036 // Check for new streams.
1037 for (StreamParamsVec::const_iterator it = streams.begin();
1038 it != streams.end(); ++it) {
1039 if (!GetStreamBySsrc(local_streams_, it->first_ssrc(), NULL)) {
1040 if (media_channel()->AddSendStream(*it)) {
1041 LOG(LS_INFO) << "Add send ssrc: " << it->ssrcs[0];
1043 std::ostringstream desc;
1044 desc << "Failed to add send stream ssrc: " << it->first_ssrc();
1045 SafeSetError(desc.str(), error_desc);
1050 local_streams_ = streams;
1054 bool BaseChannel::UpdateRemoteStreams_w(
1055 const std::vector<StreamParams>& streams,
1056 ContentAction action,
1057 std::string* error_desc) {
1058 if (!VERIFY(action == CA_OFFER || action == CA_ANSWER ||
1059 action == CA_PRANSWER || action == CA_UPDATE))
1062 // If this is an update, streams only contain streams that have changed.
1063 if (action == CA_UPDATE) {
1064 for (StreamParamsVec::const_iterator it = streams.begin();
1065 it != streams.end(); ++it) {
1066 StreamParams existing_stream;
1067 bool stream_exists = GetStreamByIds(remote_streams_, it->groupid,
1068 it->id, &existing_stream);
1069 if (!stream_exists && it->has_ssrcs()) {
1070 if (AddRecvStream_w(*it)) {
1071 remote_streams_.push_back(*it);
1072 LOG(LS_INFO) << "Add remote stream ssrc: " << it->first_ssrc();
1074 std::ostringstream desc;
1075 desc << "Failed to add remote stream ssrc: " << it->first_ssrc();
1076 SafeSetError(desc.str(), error_desc);
1079 } else if (stream_exists && !it->has_ssrcs()) {
1080 if (!RemoveRecvStream_w(existing_stream.first_ssrc())) {
1081 std::ostringstream desc;
1082 desc << "Failed to remove remote stream with ssrc "
1083 << it->first_ssrc() << ".";
1084 SafeSetError(desc.str(), error_desc);
1087 RemoveStreamBySsrc(&remote_streams_, existing_stream.first_ssrc());
1089 LOG(LS_WARNING) << "Ignore unsupported stream update."
1090 << " Stream exists? " << stream_exists
1091 << " existing stream = " << existing_stream.ToString()
1092 << " new stream = " << it->ToString();
1097 // Else streams are all the streams we want to receive.
1099 // Check for streams that have been removed.
1101 for (StreamParamsVec::const_iterator it = remote_streams_.begin();
1102 it != remote_streams_.end(); ++it) {
1103 if (!GetStreamBySsrc(streams, it->first_ssrc(), NULL)) {
1104 if (!RemoveRecvStream_w(it->first_ssrc())) {
1105 std::ostringstream desc;
1106 desc << "Failed to remove remote stream with ssrc "
1107 << it->first_ssrc() << ".";
1108 SafeSetError(desc.str(), error_desc);
1113 // Check for new streams.
1114 for (StreamParamsVec::const_iterator it = streams.begin();
1115 it != streams.end(); ++it) {
1116 if (!GetStreamBySsrc(remote_streams_, it->first_ssrc(), NULL)) {
1117 if (AddRecvStream_w(*it)) {
1118 LOG(LS_INFO) << "Add remote ssrc: " << it->ssrcs[0];
1120 std::ostringstream desc;
1121 desc << "Failed to add remote stream ssrc: " << it->first_ssrc();
1122 SafeSetError(desc.str(), error_desc);
1127 remote_streams_ = streams;
1131 bool BaseChannel::SetBaseLocalContent_w(const MediaContentDescription* content,
1132 ContentAction action,
1133 std::string* error_desc) {
1134 // Cache secure_required_ for belt and suspenders check on SendPacket
1135 secure_required_ = content->crypto_required();
1136 bool ret = UpdateLocalStreams_w(content->streams(), action, error_desc);
1137 // Set local SRTP parameters (what we will encrypt with).
1138 ret &= SetSrtp_w(content->cryptos(), action, CS_LOCAL, error_desc);
1139 // Set local RTCP mux parameters.
1140 ret &= SetRtcpMux_w(content->rtcp_mux(), action, CS_LOCAL, error_desc);
1141 // Set local RTP header extensions.
1142 if (content->rtp_header_extensions_set()) {
1143 if (!media_channel()->SetRecvRtpHeaderExtensions(
1144 content->rtp_header_extensions())) {
1145 std::ostringstream desc;
1146 desc << "Failed to set receive rtp header extensions for "
1147 << MediaTypeToString(content->type()) << " content.";
1148 SafeSetError(desc.str(), error_desc);
1152 set_local_content_direction(content->direction());
1156 bool BaseChannel::SetBaseRemoteContent_w(const MediaContentDescription* content,
1157 ContentAction action,
1158 std::string* error_desc) {
1159 bool ret = UpdateRemoteStreams_w(content->streams(), action, error_desc);
1160 // Set remote SRTP parameters (what the other side will encrypt with).
1161 ret &= SetSrtp_w(content->cryptos(), action, CS_REMOTE, error_desc);
1162 // Set remote RTCP mux parameters.
1163 ret &= SetRtcpMux_w(content->rtcp_mux(), action, CS_REMOTE, error_desc);
1164 // Set remote RTP header extensions.
1165 if (content->rtp_header_extensions_set()) {
1166 if (!media_channel()->SetSendRtpHeaderExtensions(
1167 content->rtp_header_extensions())) {
1168 std::ostringstream desc;
1169 desc << "Failed to set send rtp header extensions for "
1170 << MediaTypeToString(content->type()) << " content.";
1171 SafeSetError(desc.str(), error_desc);
1176 if (!media_channel()->SetMaxSendBandwidth(content->bandwidth())) {
1177 std::ostringstream desc;
1178 desc << "Failed to set max send bandwidth for "
1179 << MediaTypeToString(content->type()) << " content.";
1180 SafeSetError(desc.str(), error_desc);
1183 set_remote_content_direction(content->direction());
1187 void BaseChannel::OnMessage(talk_base::Message *pmsg) {
1188 switch (pmsg->message_id) {
1190 case MSG_RTCPPACKET: {
1191 PacketMessageData* data = static_cast<PacketMessageData*>(pmsg->pdata);
1192 SendPacket(pmsg->message_id == MSG_RTCPPACKET, &data->packet, data->dscp);
1193 delete data; // because it is Posted
1196 case MSG_FIRSTPACKETRECEIVED: {
1197 SignalFirstPacketReceived(this);
1203 void BaseChannel::FlushRtcpMessages() {
1204 // Flush all remaining RTCP messages. This should only be called in
1206 ASSERT(talk_base::Thread::Current() == worker_thread_);
1207 talk_base::MessageList rtcp_messages;
1208 worker_thread_->Clear(this, MSG_RTCPPACKET, &rtcp_messages);
1209 for (talk_base::MessageList::iterator it = rtcp_messages.begin();
1210 it != rtcp_messages.end(); ++it) {
1211 worker_thread_->Send(this, MSG_RTCPPACKET, it->pdata);
1215 VoiceChannel::VoiceChannel(talk_base::Thread* thread,
1216 MediaEngineInterface* media_engine,
1217 VoiceMediaChannel* media_channel,
1218 BaseSession* session,
1219 const std::string& content_name,
1221 : BaseChannel(thread, media_engine, media_channel, session, content_name,
1223 received_media_(false) {
1226 VoiceChannel::~VoiceChannel() {
1229 // this can't be done in the base class, since it calls a virtual
1234 bool VoiceChannel::Init() {
1235 TransportChannel* rtcp_channel = rtcp() ? session()->CreateChannel(
1236 content_name(), "rtcp", ICE_CANDIDATE_COMPONENT_RTCP) : NULL;
1237 if (!BaseChannel::Init(session()->CreateChannel(
1238 content_name(), "rtp", ICE_CANDIDATE_COMPONENT_RTP),
1242 media_channel()->SignalMediaError.connect(
1243 this, &VoiceChannel::OnVoiceChannelError);
1244 srtp_filter()->SignalSrtpError.connect(
1245 this, &VoiceChannel::OnSrtpError);
1249 bool VoiceChannel::SetRemoteRenderer(uint32 ssrc, AudioRenderer* renderer) {
1250 return InvokeOnWorker(Bind(&VoiceMediaChannel::SetRemoteRenderer,
1251 media_channel(), ssrc, renderer));
1254 bool VoiceChannel::SetLocalRenderer(uint32 ssrc, AudioRenderer* renderer) {
1255 return InvokeOnWorker(Bind(&VoiceMediaChannel::SetLocalRenderer,
1256 media_channel(), ssrc, renderer));
1259 bool VoiceChannel::SetRingbackTone(const void* buf, int len) {
1260 return InvokeOnWorker(Bind(&VoiceChannel::SetRingbackTone_w, this, buf, len));
1263 // TODO(juberti): Handle early media the right way. We should get an explicit
1264 // ringing message telling us to start playing local ringback, which we cancel
1265 // if any early media actually arrives. For now, we do the opposite, which is
1266 // to wait 1 second for early media, and start playing local ringback if none
1268 void VoiceChannel::SetEarlyMedia(bool enable) {
1270 // Start the early media timeout
1271 worker_thread()->PostDelayed(kEarlyMediaTimeout, this,
1272 MSG_EARLYMEDIATIMEOUT);
1274 // Stop the timeout if currently going.
1275 worker_thread()->Clear(this, MSG_EARLYMEDIATIMEOUT);
1279 bool VoiceChannel::PlayRingbackTone(uint32 ssrc, bool play, bool loop) {
1280 return InvokeOnWorker(Bind(&VoiceChannel::PlayRingbackTone_w,
1281 this, ssrc, play, loop));
1284 bool VoiceChannel::PressDTMF(int digit, bool playout) {
1285 int flags = DF_SEND;
1289 int duration_ms = 160;
1290 return InsertDtmf(0, digit, duration_ms, flags);
1293 bool VoiceChannel::CanInsertDtmf() {
1294 return InvokeOnWorker(Bind(&VoiceMediaChannel::CanInsertDtmf,
1298 bool VoiceChannel::InsertDtmf(uint32 ssrc, int event_code, int duration,
1300 return InvokeOnWorker(Bind(&VoiceChannel::InsertDtmf_w, this,
1301 ssrc, event_code, duration, flags));
1304 bool VoiceChannel::SetOutputScaling(uint32 ssrc, double left, double right) {
1305 return InvokeOnWorker(Bind(&VoiceMediaChannel::SetOutputScaling,
1306 media_channel(), ssrc, left, right));
1309 bool VoiceChannel::GetStats(VoiceMediaInfo* stats) {
1310 return InvokeOnWorker(Bind(&VoiceMediaChannel::GetStats,
1311 media_channel(), stats));
1314 void VoiceChannel::StartMediaMonitor(int cms) {
1315 media_monitor_.reset(new VoiceMediaMonitor(media_channel(), worker_thread(),
1316 talk_base::Thread::Current()));
1317 media_monitor_->SignalUpdate.connect(
1318 this, &VoiceChannel::OnMediaMonitorUpdate);
1319 media_monitor_->Start(cms);
1322 void VoiceChannel::StopMediaMonitor() {
1323 if (media_monitor_) {
1324 media_monitor_->Stop();
1325 media_monitor_->SignalUpdate.disconnect(this);
1326 media_monitor_.reset();
1330 void VoiceChannel::StartAudioMonitor(int cms) {
1331 audio_monitor_.reset(new AudioMonitor(this, talk_base::Thread::Current()));
1333 ->SignalUpdate.connect(this, &VoiceChannel::OnAudioMonitorUpdate);
1334 audio_monitor_->Start(cms);
1337 void VoiceChannel::StopAudioMonitor() {
1338 if (audio_monitor_) {
1339 audio_monitor_->Stop();
1340 audio_monitor_.reset();
1344 bool VoiceChannel::IsAudioMonitorRunning() const {
1345 return (audio_monitor_.get() != NULL);
1348 void VoiceChannel::StartTypingMonitor(const TypingMonitorOptions& settings) {
1349 typing_monitor_.reset(new TypingMonitor(this, worker_thread(), settings));
1350 SignalAutoMuted.repeat(typing_monitor_->SignalMuted);
1353 void VoiceChannel::StopTypingMonitor() {
1354 typing_monitor_.reset();
1357 bool VoiceChannel::IsTypingMonitorRunning() const {
1358 return typing_monitor_;
1361 bool VoiceChannel::MuteStream_w(uint32 ssrc, bool mute) {
1362 bool ret = BaseChannel::MuteStream_w(ssrc, mute);
1363 if (typing_monitor_ && mute)
1364 typing_monitor_->OnChannelMuted();
1368 int VoiceChannel::GetInputLevel_w() {
1369 return media_engine()->GetInputLevel();
1372 int VoiceChannel::GetOutputLevel_w() {
1373 return media_channel()->GetOutputLevel();
1376 void VoiceChannel::GetActiveStreams_w(AudioInfo::StreamList* actives) {
1377 media_channel()->GetActiveStreams(actives);
1380 void VoiceChannel::OnChannelRead(TransportChannel* channel,
1381 const char* data, size_t len,
1382 const talk_base::PacketTime& packet_time,
1384 BaseChannel::OnChannelRead(channel, data, len, packet_time, flags);
1386 // Set a flag when we've received an RTP packet. If we're waiting for early
1387 // media, this will disable the timeout.
1388 if (!received_media_ && !PacketIsRtcp(channel, data, len)) {
1389 received_media_ = true;
1393 void VoiceChannel::ChangeState() {
1394 // Render incoming data if we're the active call, and we have the local
1395 // content. We receive data on the default channel and multiplexed streams.
1396 bool recv = IsReadyToReceive();
1397 if (!media_channel()->SetPlayout(recv)) {
1398 SendLastMediaError();
1401 // Send outgoing data if we're the active call, we have the remote content,
1402 // and we have had some form of connectivity.
1403 bool send = IsReadyToSend();
1404 SendFlags send_flag = send ? SEND_MICROPHONE : SEND_NOTHING;
1405 if (!media_channel()->SetSend(send_flag)) {
1406 LOG(LS_ERROR) << "Failed to SetSend " << send_flag << " on voice channel";
1407 SendLastMediaError();
1410 LOG(LS_INFO) << "Changing voice state, recv=" << recv << " send=" << send;
1413 const ContentInfo* VoiceChannel::GetFirstContent(
1414 const SessionDescription* sdesc) {
1415 return GetFirstAudioContent(sdesc);
1418 bool VoiceChannel::SetLocalContent_w(const MediaContentDescription* content,
1419 ContentAction action,
1420 std::string* error_desc) {
1421 ASSERT(worker_thread() == talk_base::Thread::Current());
1422 LOG(LS_INFO) << "Setting local voice description";
1424 const AudioContentDescription* audio =
1425 static_cast<const AudioContentDescription*>(content);
1426 ASSERT(audio != NULL);
1428 SafeSetError("Can't find audio content in local description.", error_desc);
1432 bool ret = SetBaseLocalContent_w(content, action, error_desc);
1433 // Set local audio codecs (what we want to receive).
1434 // TODO(whyuan): Change action != CA_UPDATE to !audio->partial() when partial
1436 if (action != CA_UPDATE || audio->has_codecs()) {
1437 if (!media_channel()->SetRecvCodecs(audio->codecs())) {
1438 SafeSetError("Failed to set audio receive codecs.", error_desc);
1443 // If everything worked, see if we can start receiving.
1447 LOG(LS_WARNING) << "Failed to set local voice description";
1452 bool VoiceChannel::SetRemoteContent_w(const MediaContentDescription* content,
1453 ContentAction action,
1454 std::string* error_desc) {
1455 ASSERT(worker_thread() == talk_base::Thread::Current());
1456 LOG(LS_INFO) << "Setting remote voice description";
1458 const AudioContentDescription* audio =
1459 static_cast<const AudioContentDescription*>(content);
1460 ASSERT(audio != NULL);
1462 SafeSetError("Can't find audio content in remote description.", error_desc);
1467 // Set remote video codecs (what the other side wants to receive).
1468 if (action != CA_UPDATE || audio->has_codecs()) {
1469 if (!media_channel()->SetSendCodecs(audio->codecs())) {
1470 SafeSetError("Failed to set audio send codecs.", error_desc);
1475 ret &= SetBaseRemoteContent_w(content, action, error_desc);
1477 if (action != CA_UPDATE) {
1478 // Tweak our audio processing settings, if needed.
1479 AudioOptions audio_options;
1480 if (!media_channel()->GetOptions(&audio_options)) {
1481 LOG(LS_WARNING) << "Can not set audio options from on remote content.";
1483 if (audio->conference_mode()) {
1484 audio_options.conference_mode.Set(true);
1486 if (audio->agc_minus_10db()) {
1487 audio_options.adjust_agc_delta.Set(kAgcMinus10db);
1489 if (!media_channel()->SetOptions(audio_options)) {
1490 // Log an error on failure, but don't abort the call.
1491 LOG(LS_ERROR) << "Failed to set voice channel options";
1496 // If everything worked, see if we can start sending.
1500 LOG(LS_WARNING) << "Failed to set remote voice description";
1505 bool VoiceChannel::SetRingbackTone_w(const void* buf, int len) {
1506 ASSERT(worker_thread() == talk_base::Thread::Current());
1507 return media_channel()->SetRingbackTone(static_cast<const char*>(buf), len);
1510 bool VoiceChannel::PlayRingbackTone_w(uint32 ssrc, bool play, bool loop) {
1511 ASSERT(worker_thread() == talk_base::Thread::Current());
1513 LOG(LS_INFO) << "Playing ringback tone, loop=" << loop;
1515 LOG(LS_INFO) << "Stopping ringback tone";
1517 return media_channel()->PlayRingbackTone(ssrc, play, loop);
1520 void VoiceChannel::HandleEarlyMediaTimeout() {
1521 // This occurs on the main thread, not the worker thread.
1522 if (!received_media_) {
1523 LOG(LS_INFO) << "No early media received before timeout";
1524 SignalEarlyMediaTimeout(this);
1528 bool VoiceChannel::InsertDtmf_w(uint32 ssrc, int event, int duration,
1534 return media_channel()->InsertDtmf(ssrc, event, duration, flags);
1537 bool VoiceChannel::SetChannelOptions(const AudioOptions& options) {
1538 return InvokeOnWorker(Bind(&VoiceMediaChannel::SetOptions,
1539 media_channel(), options));
1542 void VoiceChannel::OnMessage(talk_base::Message *pmsg) {
1543 switch (pmsg->message_id) {
1544 case MSG_EARLYMEDIATIMEOUT:
1545 HandleEarlyMediaTimeout();
1547 case MSG_CHANNEL_ERROR: {
1548 VoiceChannelErrorMessageData* data =
1549 static_cast<VoiceChannelErrorMessageData*>(pmsg->pdata);
1550 SignalMediaError(this, data->ssrc, data->error);
1555 BaseChannel::OnMessage(pmsg);
1560 void VoiceChannel::OnConnectionMonitorUpdate(
1561 SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos) {
1562 SignalConnectionMonitor(this, infos);
1565 void VoiceChannel::OnMediaMonitorUpdate(
1566 VoiceMediaChannel* media_channel, const VoiceMediaInfo& info) {
1567 ASSERT(media_channel == this->media_channel());
1568 SignalMediaMonitor(this, info);
1571 void VoiceChannel::OnAudioMonitorUpdate(AudioMonitor* monitor,
1572 const AudioInfo& info) {
1573 SignalAudioMonitor(this, info);
1576 void VoiceChannel::OnVoiceChannelError(
1577 uint32 ssrc, VoiceMediaChannel::Error err) {
1578 VoiceChannelErrorMessageData* data = new VoiceChannelErrorMessageData(
1580 signaling_thread()->Post(this, MSG_CHANNEL_ERROR, data);
1583 void VoiceChannel::OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode,
1584 SrtpFilter::Error error) {
1586 case SrtpFilter::ERROR_FAIL:
1587 OnVoiceChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
1588 VoiceMediaChannel::ERROR_REC_SRTP_ERROR :
1589 VoiceMediaChannel::ERROR_PLAY_SRTP_ERROR);
1591 case SrtpFilter::ERROR_AUTH:
1592 OnVoiceChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
1593 VoiceMediaChannel::ERROR_REC_SRTP_AUTH_FAILED :
1594 VoiceMediaChannel::ERROR_PLAY_SRTP_AUTH_FAILED);
1596 case SrtpFilter::ERROR_REPLAY:
1597 // Only receving channel should have this error.
1598 ASSERT(mode == SrtpFilter::UNPROTECT);
1599 OnVoiceChannelError(ssrc, VoiceMediaChannel::ERROR_PLAY_SRTP_REPLAY);
1606 void VoiceChannel::GetSrtpCiphers(std::vector<std::string>* ciphers) const {
1607 GetSupportedAudioCryptoSuites(ciphers);
1610 VideoChannel::VideoChannel(talk_base::Thread* thread,
1611 MediaEngineInterface* media_engine,
1612 VideoMediaChannel* media_channel,
1613 BaseSession* session,
1614 const std::string& content_name,
1616 VoiceChannel* voice_channel)
1617 : BaseChannel(thread, media_engine, media_channel, session, content_name,
1619 voice_channel_(voice_channel),
1621 screencapture_factory_(CreateScreenCapturerFactory()),
1622 previous_we_(talk_base::WE_CLOSE) {
1625 bool VideoChannel::Init() {
1626 TransportChannel* rtcp_channel = rtcp() ? session()->CreateChannel(
1627 content_name(), "video_rtcp", ICE_CANDIDATE_COMPONENT_RTCP) : NULL;
1628 if (!BaseChannel::Init(session()->CreateChannel(
1629 content_name(), "video_rtp", ICE_CANDIDATE_COMPONENT_RTP),
1633 media_channel()->SignalMediaError.connect(
1634 this, &VideoChannel::OnVideoChannelError);
1635 srtp_filter()->SignalSrtpError.connect(
1636 this, &VideoChannel::OnSrtpError);
1640 void VoiceChannel::SendLastMediaError() {
1642 VoiceMediaChannel::Error error;
1643 media_channel()->GetLastMediaError(&ssrc, &error);
1644 SignalMediaError(this, ssrc, error);
1647 VideoChannel::~VideoChannel() {
1648 std::vector<uint32> screencast_ssrcs;
1649 ScreencastMap::iterator iter;
1650 while (!screencast_capturers_.empty()) {
1651 if (!RemoveScreencast(screencast_capturers_.begin()->first)) {
1652 LOG(LS_ERROR) << "Unable to delete screencast with ssrc "
1653 << screencast_capturers_.begin()->first;
1660 // this can't be done in the base class, since it calls a virtual
1666 bool VideoChannel::SetRenderer(uint32 ssrc, VideoRenderer* renderer) {
1667 worker_thread()->Invoke<void>(Bind(
1668 &VideoMediaChannel::SetRenderer, media_channel(), ssrc, renderer));
1672 bool VideoChannel::ApplyViewRequest(const ViewRequest& request) {
1673 return InvokeOnWorker(Bind(&VideoChannel::ApplyViewRequest_w, this, request));
1676 VideoCapturer* VideoChannel::AddScreencast(
1677 uint32 ssrc, const ScreencastId& id) {
1678 return worker_thread()->Invoke<VideoCapturer*>(Bind(
1679 &VideoChannel::AddScreencast_w, this, ssrc, id));
1682 bool VideoChannel::SetCapturer(uint32 ssrc, VideoCapturer* capturer) {
1683 return InvokeOnWorker(Bind(&VideoMediaChannel::SetCapturer,
1684 media_channel(), ssrc, capturer));
1687 bool VideoChannel::RemoveScreencast(uint32 ssrc) {
1688 return InvokeOnWorker(Bind(&VideoChannel::RemoveScreencast_w, this, ssrc));
1691 bool VideoChannel::IsScreencasting() {
1692 return InvokeOnWorker(Bind(&VideoChannel::IsScreencasting_w, this));
1695 int VideoChannel::GetScreencastFps(uint32 ssrc) {
1696 ScreencastDetailsData data(ssrc);
1697 worker_thread()->Invoke<void>(Bind(
1698 &VideoChannel::GetScreencastDetails_w, this, &data));
1702 int VideoChannel::GetScreencastMaxPixels(uint32 ssrc) {
1703 ScreencastDetailsData data(ssrc);
1704 worker_thread()->Invoke<void>(Bind(
1705 &VideoChannel::GetScreencastDetails_w, this, &data));
1706 return data.screencast_max_pixels;
1709 bool VideoChannel::SendIntraFrame() {
1710 worker_thread()->Invoke<void>(Bind(
1711 &VideoMediaChannel::SendIntraFrame, media_channel()));
1715 bool VideoChannel::RequestIntraFrame() {
1716 worker_thread()->Invoke<void>(Bind(
1717 &VideoMediaChannel::RequestIntraFrame, media_channel()));
1721 void VideoChannel::SetScreenCaptureFactory(
1722 ScreenCapturerFactory* screencapture_factory) {
1723 worker_thread()->Invoke<void>(Bind(
1724 &VideoChannel::SetScreenCaptureFactory_w,
1725 this, screencapture_factory));
1728 void VideoChannel::ChangeState() {
1729 // Render incoming data if we're the active call, and we have the local
1730 // content. We receive data on the default channel and multiplexed streams.
1731 bool recv = IsReadyToReceive();
1732 if (!media_channel()->SetRender(recv)) {
1733 LOG(LS_ERROR) << "Failed to SetRender on video channel";
1734 // TODO(gangji): Report error back to server.
1737 // Send outgoing data if we're the active call, we have the remote content,
1738 // and we have had some form of connectivity.
1739 bool send = IsReadyToSend();
1740 if (!media_channel()->SetSend(send)) {
1741 LOG(LS_ERROR) << "Failed to SetSend on video channel";
1742 // TODO(gangji): Report error back to server.
1745 LOG(LS_INFO) << "Changing video state, recv=" << recv << " send=" << send;
1748 bool VideoChannel::GetStats(
1749 const StatsOptions& options, VideoMediaInfo* stats) {
1750 return InvokeOnWorker(Bind(&VideoMediaChannel::GetStats,
1751 media_channel(), options, stats));
1754 void VideoChannel::StartMediaMonitor(int cms) {
1755 media_monitor_.reset(new VideoMediaMonitor(media_channel(), worker_thread(),
1756 talk_base::Thread::Current()));
1757 media_monitor_->SignalUpdate.connect(
1758 this, &VideoChannel::OnMediaMonitorUpdate);
1759 media_monitor_->Start(cms);
1762 void VideoChannel::StopMediaMonitor() {
1763 if (media_monitor_) {
1764 media_monitor_->Stop();
1765 media_monitor_.reset();
1769 const ContentInfo* VideoChannel::GetFirstContent(
1770 const SessionDescription* sdesc) {
1771 return GetFirstVideoContent(sdesc);
1774 bool VideoChannel::SetLocalContent_w(const MediaContentDescription* content,
1775 ContentAction action,
1776 std::string* error_desc) {
1777 ASSERT(worker_thread() == talk_base::Thread::Current());
1778 LOG(LS_INFO) << "Setting local video description";
1780 const VideoContentDescription* video =
1781 static_cast<const VideoContentDescription*>(content);
1782 ASSERT(video != NULL);
1784 SafeSetError("Can't find video content in local description.", error_desc);
1788 bool ret = SetBaseLocalContent_w(content, action, error_desc);
1789 // Set local video codecs (what we want to receive).
1790 if (action != CA_UPDATE || video->has_codecs()) {
1791 if (!media_channel()->SetRecvCodecs(video->codecs())) {
1792 SafeSetError("Failed to set video receive codecs.", error_desc);
1797 if (action != CA_UPDATE) {
1798 VideoOptions video_options;
1799 media_channel()->GetOptions(&video_options);
1800 video_options.buffered_mode_latency.Set(video->buffered_mode_latency());
1802 if (!media_channel()->SetOptions(video_options)) {
1803 // Log an error on failure, but don't abort the call.
1804 LOG(LS_ERROR) << "Failed to set video channel options";
1808 // If everything worked, see if we can start receiving.
1812 LOG(LS_WARNING) << "Failed to set local video description";
1817 bool VideoChannel::SetRemoteContent_w(const MediaContentDescription* content,
1818 ContentAction action,
1819 std::string* error_desc) {
1820 ASSERT(worker_thread() == talk_base::Thread::Current());
1821 LOG(LS_INFO) << "Setting remote video description";
1823 const VideoContentDescription* video =
1824 static_cast<const VideoContentDescription*>(content);
1825 ASSERT(video != NULL);
1827 SafeSetError("Can't find video content in remote description.", error_desc);
1832 // Set remote video codecs (what the other side wants to receive).
1833 if (action != CA_UPDATE || video->has_codecs()) {
1834 if (!media_channel()->SetSendCodecs(video->codecs())) {
1835 SafeSetError("Failed to set video send codecs.", error_desc);
1840 ret &= SetBaseRemoteContent_w(content, action, error_desc);
1842 if (action != CA_UPDATE) {
1843 // Tweak our video processing settings, if needed.
1844 VideoOptions video_options;
1845 media_channel()->GetOptions(&video_options);
1846 if (video->conference_mode()) {
1847 video_options.conference_mode.Set(true);
1849 video_options.buffered_mode_latency.Set(video->buffered_mode_latency());
1851 if (!media_channel()->SetOptions(video_options)) {
1852 // Log an error on failure, but don't abort the call.
1853 LOG(LS_ERROR) << "Failed to set video channel options";
1857 // If everything worked, see if we can start sending.
1861 LOG(LS_WARNING) << "Failed to set remote video description";
1866 bool VideoChannel::ApplyViewRequest_w(const ViewRequest& request) {
1868 // Set the send format for each of the local streams. If the view request
1869 // does not contain a local stream, set its send format to 0x0, which will
1871 for (std::vector<StreamParams>::const_iterator it = local_streams().begin();
1872 it != local_streams().end(); ++it) {
1873 VideoFormat format(0, 0, 0, cricket::FOURCC_I420);
1874 StaticVideoViews::const_iterator view;
1875 for (view = request.static_video_views.begin();
1876 view != request.static_video_views.end(); ++view) {
1877 if (view->selector.Matches(*it)) {
1878 format.width = view->width;
1879 format.height = view->height;
1880 format.interval = cricket::VideoFormat::FpsToInterval(view->framerate);
1885 ret &= media_channel()->SetSendStreamFormat(it->first_ssrc(), format);
1888 // Check if the view request has invalid streams.
1889 for (StaticVideoViews::const_iterator it = request.static_video_views.begin();
1890 it != request.static_video_views.end(); ++it) {
1891 if (!GetStream(local_streams(), it->selector, NULL)) {
1892 LOG(LS_WARNING) << "View request for ("
1893 << it->selector.ssrc << ", '"
1894 << it->selector.groupid << "', '"
1895 << it->selector.streamid << "'"
1896 << ") is not in the local streams.";
1903 VideoCapturer* VideoChannel::AddScreencast_w(
1904 uint32 ssrc, const ScreencastId& id) {
1905 if (screencast_capturers_.find(ssrc) != screencast_capturers_.end()) {
1908 VideoCapturer* screen_capturer =
1909 screencapture_factory_->CreateScreenCapturer(id);
1910 if (!screen_capturer) {
1913 screen_capturer->SignalStateChange.connect(this,
1914 &VideoChannel::OnStateChange);
1915 screencast_capturers_[ssrc] = screen_capturer;
1916 return screen_capturer;
1919 bool VideoChannel::RemoveScreencast_w(uint32 ssrc) {
1920 ScreencastMap::iterator iter = screencast_capturers_.find(ssrc);
1921 if (iter == screencast_capturers_.end()) {
1924 // Clean up VideoCapturer.
1925 delete iter->second;
1926 screencast_capturers_.erase(iter);
1930 bool VideoChannel::IsScreencasting_w() const {
1931 return !screencast_capturers_.empty();
1934 void VideoChannel::GetScreencastDetails_w(
1935 ScreencastDetailsData* data) const {
1936 ScreencastMap::const_iterator iter = screencast_capturers_.find(data->ssrc);
1937 if (iter == screencast_capturers_.end()) {
1940 VideoCapturer* capturer = iter->second;
1941 const VideoFormat* video_format = capturer->GetCaptureFormat();
1942 data->fps = VideoFormat::IntervalToFps(video_format->interval);
1943 data->screencast_max_pixels = capturer->screencast_max_pixels();
1946 void VideoChannel::SetScreenCaptureFactory_w(
1947 ScreenCapturerFactory* screencapture_factory) {
1948 if (screencapture_factory == NULL) {
1949 screencapture_factory_.reset(CreateScreenCapturerFactory());
1951 screencapture_factory_.reset(screencapture_factory);
1955 void VideoChannel::OnScreencastWindowEvent_s(uint32 ssrc,
1956 talk_base::WindowEvent we) {
1957 ASSERT(signaling_thread() == talk_base::Thread::Current());
1958 SignalScreencastWindowEvent(ssrc, we);
1961 bool VideoChannel::SetChannelOptions(const VideoOptions &options) {
1962 return InvokeOnWorker(Bind(&VideoMediaChannel::SetOptions,
1963 media_channel(), options));
1966 void VideoChannel::OnMessage(talk_base::Message *pmsg) {
1967 switch (pmsg->message_id) {
1968 case MSG_SCREENCASTWINDOWEVENT: {
1969 const ScreencastEventMessageData* data =
1970 static_cast<ScreencastEventMessageData*>(pmsg->pdata);
1971 OnScreencastWindowEvent_s(data->ssrc, data->event);
1975 case MSG_CHANNEL_ERROR: {
1976 const VideoChannelErrorMessageData* data =
1977 static_cast<VideoChannelErrorMessageData*>(pmsg->pdata);
1978 SignalMediaError(this, data->ssrc, data->error);
1983 BaseChannel::OnMessage(pmsg);
1988 void VideoChannel::OnConnectionMonitorUpdate(
1989 SocketMonitor *monitor, const std::vector<ConnectionInfo> &infos) {
1990 SignalConnectionMonitor(this, infos);
1993 // TODO(pthatcher): Look into removing duplicate code between
1994 // audio, video, and data, perhaps by using templates.
1995 void VideoChannel::OnMediaMonitorUpdate(
1996 VideoMediaChannel* media_channel, const VideoMediaInfo &info) {
1997 ASSERT(media_channel == this->media_channel());
1998 SignalMediaMonitor(this, info);
2001 void VideoChannel::OnScreencastWindowEvent(uint32 ssrc,
2002 talk_base::WindowEvent event) {
2003 ScreencastEventMessageData* pdata =
2004 new ScreencastEventMessageData(ssrc, event);
2005 signaling_thread()->Post(this, MSG_SCREENCASTWINDOWEVENT, pdata);
2008 void VideoChannel::OnStateChange(VideoCapturer* capturer, CaptureState ev) {
2009 // Map capturer events to window events. In the future we may want to simply
2010 // pass these events up directly.
2011 talk_base::WindowEvent we;
2012 if (ev == CS_STOPPED) {
2013 we = talk_base::WE_CLOSE;
2014 } else if (ev == CS_PAUSED) {
2015 we = talk_base::WE_MINIMIZE;
2016 } else if (ev == CS_RUNNING && previous_we_ == talk_base::WE_MINIMIZE) {
2017 we = talk_base::WE_RESTORE;
2024 if (!GetLocalSsrc(capturer, &ssrc)) {
2028 OnScreencastWindowEvent(ssrc, we);
2031 bool VideoChannel::GetLocalSsrc(const VideoCapturer* capturer, uint32* ssrc) {
2033 for (ScreencastMap::iterator iter = screencast_capturers_.begin();
2034 iter != screencast_capturers_.end(); ++iter) {
2035 if (iter->second == capturer) {
2036 *ssrc = iter->first;
2043 void VideoChannel::OnVideoChannelError(uint32 ssrc,
2044 VideoMediaChannel::Error error) {
2045 VideoChannelErrorMessageData* data = new VideoChannelErrorMessageData(
2047 signaling_thread()->Post(this, MSG_CHANNEL_ERROR, data);
2050 void VideoChannel::OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode,
2051 SrtpFilter::Error error) {
2053 case SrtpFilter::ERROR_FAIL:
2054 OnVideoChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
2055 VideoMediaChannel::ERROR_REC_SRTP_ERROR :
2056 VideoMediaChannel::ERROR_PLAY_SRTP_ERROR);
2058 case SrtpFilter::ERROR_AUTH:
2059 OnVideoChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
2060 VideoMediaChannel::ERROR_REC_SRTP_AUTH_FAILED :
2061 VideoMediaChannel::ERROR_PLAY_SRTP_AUTH_FAILED);
2063 case SrtpFilter::ERROR_REPLAY:
2064 // Only receving channel should have this error.
2065 ASSERT(mode == SrtpFilter::UNPROTECT);
2066 // TODO(gangji): Turn on the signaling of replay error once we have
2067 // switched to the new mechanism for doing video retransmissions.
2068 // OnVideoChannelError(ssrc, VideoMediaChannel::ERROR_PLAY_SRTP_REPLAY);
2076 void VideoChannel::GetSrtpCiphers(std::vector<std::string>* ciphers) const {
2077 GetSupportedVideoCryptoSuites(ciphers);
2080 DataChannel::DataChannel(talk_base::Thread* thread,
2081 DataMediaChannel* media_channel,
2082 BaseSession* session,
2083 const std::string& content_name,
2085 // MediaEngine is NULL
2086 : BaseChannel(thread, NULL, media_channel, session, content_name, rtcp),
2087 data_channel_type_(cricket::DCT_NONE),
2088 ready_to_send_data_(false) {
2091 DataChannel::~DataChannel() {
2093 // this can't be done in the base class, since it calls a virtual
2099 bool DataChannel::Init() {
2100 TransportChannel* rtcp_channel = rtcp() ? session()->CreateChannel(
2101 content_name(), "data_rtcp", ICE_CANDIDATE_COMPONENT_RTCP) : NULL;
2102 if (!BaseChannel::Init(session()->CreateChannel(
2103 content_name(), "data_rtp", ICE_CANDIDATE_COMPONENT_RTP),
2107 media_channel()->SignalDataReceived.connect(
2108 this, &DataChannel::OnDataReceived);
2109 media_channel()->SignalMediaError.connect(
2110 this, &DataChannel::OnDataChannelError);
2111 media_channel()->SignalReadyToSend.connect(
2112 this, &DataChannel::OnDataChannelReadyToSend);
2113 srtp_filter()->SignalSrtpError.connect(
2114 this, &DataChannel::OnSrtpError);
2118 bool DataChannel::SendData(const SendDataParams& params,
2119 const talk_base::Buffer& payload,
2120 SendDataResult* result) {
2121 return InvokeOnWorker(Bind(&DataMediaChannel::SendData,
2122 media_channel(), params, payload, result));
2125 const ContentInfo* DataChannel::GetFirstContent(
2126 const SessionDescription* sdesc) {
2127 return GetFirstDataContent(sdesc);
2131 static bool IsRtpPacket(const talk_base::Buffer* packet) {
2133 if (!GetRtpVersion(packet->data(), packet->length(), &version)) {
2137 return version == 2;
2140 bool DataChannel::WantsPacket(bool rtcp, talk_base::Buffer* packet) {
2141 if (data_channel_type_ == DCT_SCTP) {
2142 // TODO(pthatcher): Do this in a more robust way by checking for
2144 return !IsRtpPacket(packet);
2145 } else if (data_channel_type_ == DCT_RTP) {
2146 return BaseChannel::WantsPacket(rtcp, packet);
2151 bool DataChannel::SetDataChannelType(DataChannelType new_data_channel_type,
2152 std::string* error_desc) {
2153 // It hasn't been set before, so set it now.
2154 if (data_channel_type_ == DCT_NONE) {
2155 data_channel_type_ = new_data_channel_type;
2159 // It's been set before, but doesn't match. That's bad.
2160 if (data_channel_type_ != new_data_channel_type) {
2161 std::ostringstream desc;
2162 desc << "Data channel type mismatch."
2163 << " Expected " << data_channel_type_
2164 << " Got " << new_data_channel_type;
2165 SafeSetError(desc.str(), error_desc);
2169 // It's hasn't changed. Nothing to do.
2173 bool DataChannel::SetDataChannelTypeFromContent(
2174 const DataContentDescription* content,
2175 std::string* error_desc) {
2176 bool is_sctp = ((content->protocol() == kMediaProtocolSctp) ||
2177 (content->protocol() == kMediaProtocolDtlsSctp));
2178 DataChannelType data_channel_type = is_sctp ? DCT_SCTP : DCT_RTP;
2179 return SetDataChannelType(data_channel_type, error_desc);
2182 bool DataChannel::SetLocalContent_w(const MediaContentDescription* content,
2183 ContentAction action,
2184 std::string* error_desc) {
2185 ASSERT(worker_thread() == talk_base::Thread::Current());
2186 LOG(LS_INFO) << "Setting local data description";
2188 const DataContentDescription* data =
2189 static_cast<const DataContentDescription*>(content);
2190 ASSERT(data != NULL);
2192 SafeSetError("Can't find data content in local description.", error_desc);
2197 if (!SetDataChannelTypeFromContent(data, error_desc)) {
2201 if (data_channel_type_ == DCT_SCTP) {
2202 // SCTP data channels don't need the rest of the stuff.
2203 ret = UpdateLocalStreams_w(data->streams(), action, error_desc);
2205 set_local_content_direction(content->direction());
2206 // As in SetRemoteContent_w, make sure we set the local SCTP port
2207 // number as specified in our DataContentDescription.
2208 if (!media_channel()->SetRecvCodecs(data->codecs())) {
2209 SafeSetError("Failed to set data receive codecs.", error_desc);
2214 ret = SetBaseLocalContent_w(content, action, error_desc);
2216 if (action != CA_UPDATE || data->has_codecs()) {
2217 if (!media_channel()->SetRecvCodecs(data->codecs())) {
2218 SafeSetError("Failed to set data receive codecs.", error_desc);
2224 // If everything worked, see if we can start receiving.
2228 LOG(LS_WARNING) << "Failed to set local data description";
2233 bool DataChannel::SetRemoteContent_w(const MediaContentDescription* content,
2234 ContentAction action,
2235 std::string* error_desc) {
2236 ASSERT(worker_thread() == talk_base::Thread::Current());
2238 const DataContentDescription* data =
2239 static_cast<const DataContentDescription*>(content);
2240 ASSERT(data != NULL);
2242 SafeSetError("Can't find data content in remote description.", error_desc);
2247 if (!SetDataChannelTypeFromContent(data, error_desc)) {
2251 if (data_channel_type_ == DCT_SCTP) {
2252 LOG(LS_INFO) << "Setting SCTP remote data description";
2253 // SCTP data channels don't need the rest of the stuff.
2254 ret = UpdateRemoteStreams_w(content->streams(), action, error_desc);
2256 set_remote_content_direction(content->direction());
2257 // We send the SCTP port number (not to be confused with the underlying
2258 // UDP port number) as a codec parameter. Make sure it gets there.
2259 if (!media_channel()->SetSendCodecs(data->codecs())) {
2260 SafeSetError("Failed to set data send codecs.", error_desc);
2265 // If the remote data doesn't have codecs and isn't an update, it
2266 // must be empty, so ignore it.
2267 if (action != CA_UPDATE && !data->has_codecs()) {
2270 LOG(LS_INFO) << "Setting remote data description";
2272 // Set remote video codecs (what the other side wants to receive).
2273 if (action != CA_UPDATE || data->has_codecs()) {
2274 if (!media_channel()->SetSendCodecs(data->codecs())) {
2275 SafeSetError("Failed to set data send codecs.", error_desc);
2281 ret &= SetBaseRemoteContent_w(content, action, error_desc);
2284 if (action != CA_UPDATE) {
2285 int bandwidth_bps = data->bandwidth();
2286 if (!media_channel()->SetMaxSendBandwidth(bandwidth_bps)) {
2287 std::ostringstream desc;
2288 desc << "Failed to set max send bandwidth for data content.";
2289 SafeSetError(desc.str(), error_desc);
2295 // If everything worked, see if we can start sending.
2299 LOG(LS_WARNING) << "Failed to set remote data description";
2304 void DataChannel::ChangeState() {
2305 // Render incoming data if we're the active call, and we have the local
2306 // content. We receive data on the default channel and multiplexed streams.
2307 bool recv = IsReadyToReceive();
2308 if (!media_channel()->SetReceive(recv)) {
2309 LOG(LS_ERROR) << "Failed to SetReceive on data channel";
2312 // Send outgoing data if we're the active call, we have the remote content,
2313 // and we have had some form of connectivity.
2314 bool send = IsReadyToSend();
2315 if (!media_channel()->SetSend(send)) {
2316 LOG(LS_ERROR) << "Failed to SetSend on data channel";
2319 // Trigger SignalReadyToSendData asynchronously.
2320 OnDataChannelReadyToSend(send);
2322 LOG(LS_INFO) << "Changing data state, recv=" << recv << " send=" << send;
2325 void DataChannel::OnMessage(talk_base::Message *pmsg) {
2326 switch (pmsg->message_id) {
2327 case MSG_READYTOSENDDATA: {
2328 DataChannelReadyToSendMessageData* data =
2329 static_cast<DataChannelReadyToSendMessageData*>(pmsg->pdata);
2330 ready_to_send_data_ = data->data();
2331 SignalReadyToSendData(ready_to_send_data_);
2335 case MSG_DATARECEIVED: {
2336 DataReceivedMessageData* data =
2337 static_cast<DataReceivedMessageData*>(pmsg->pdata);
2338 SignalDataReceived(this, data->params, data->payload);
2342 case MSG_CHANNEL_ERROR: {
2343 const DataChannelErrorMessageData* data =
2344 static_cast<DataChannelErrorMessageData*>(pmsg->pdata);
2345 SignalMediaError(this, data->ssrc, data->error);
2350 BaseChannel::OnMessage(pmsg);
2355 void DataChannel::OnConnectionMonitorUpdate(
2356 SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos) {
2357 SignalConnectionMonitor(this, infos);
2360 void DataChannel::StartMediaMonitor(int cms) {
2361 media_monitor_.reset(new DataMediaMonitor(media_channel(), worker_thread(),
2362 talk_base::Thread::Current()));
2363 media_monitor_->SignalUpdate.connect(
2364 this, &DataChannel::OnMediaMonitorUpdate);
2365 media_monitor_->Start(cms);
2368 void DataChannel::StopMediaMonitor() {
2369 if (media_monitor_) {
2370 media_monitor_->Stop();
2371 media_monitor_->SignalUpdate.disconnect(this);
2372 media_monitor_.reset();
2376 void DataChannel::OnMediaMonitorUpdate(
2377 DataMediaChannel* media_channel, const DataMediaInfo& info) {
2378 ASSERT(media_channel == this->media_channel());
2379 SignalMediaMonitor(this, info);
2382 void DataChannel::OnDataReceived(
2383 const ReceiveDataParams& params, const char* data, size_t len) {
2384 DataReceivedMessageData* msg = new DataReceivedMessageData(
2386 signaling_thread()->Post(this, MSG_DATARECEIVED, msg);
2389 void DataChannel::OnDataChannelError(
2390 uint32 ssrc, DataMediaChannel::Error err) {
2391 DataChannelErrorMessageData* data = new DataChannelErrorMessageData(
2393 signaling_thread()->Post(this, MSG_CHANNEL_ERROR, data);
2396 void DataChannel::OnDataChannelReadyToSend(bool writable) {
2397 // This is usded for congestion control to indicate that the stream is ready
2398 // to send by the MediaChannel, as opposed to OnReadyToSend, which indicates
2399 // that the transport channel is ready.
2400 signaling_thread()->Post(this, MSG_READYTOSENDDATA,
2401 new DataChannelReadyToSendMessageData(writable));
2404 void DataChannel::OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode,
2405 SrtpFilter::Error error) {
2407 case SrtpFilter::ERROR_FAIL:
2408 OnDataChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
2409 DataMediaChannel::ERROR_SEND_SRTP_ERROR :
2410 DataMediaChannel::ERROR_RECV_SRTP_ERROR);
2412 case SrtpFilter::ERROR_AUTH:
2413 OnDataChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
2414 DataMediaChannel::ERROR_SEND_SRTP_AUTH_FAILED :
2415 DataMediaChannel::ERROR_RECV_SRTP_AUTH_FAILED);
2417 case SrtpFilter::ERROR_REPLAY:
2418 // Only receving channel should have this error.
2419 ASSERT(mode == SrtpFilter::UNPROTECT);
2420 OnDataChannelError(ssrc, DataMediaChannel::ERROR_RECV_SRTP_REPLAY);
2427 void DataChannel::GetSrtpCiphers(std::vector<std::string>* ciphers) const {
2428 GetSupportedDataCryptoSuites(ciphers);
2431 bool DataChannel::ShouldSetupDtlsSrtp() const {
2432 return (data_channel_type_ == DCT_RTP);
2435 } // namespace cricket