1 /*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #include "talk/session/media/channel.h"
29
30 #include "talk/media/base/constants.h"
31 #include "talk/media/base/rtputils.h"
32 #include "talk/p2p/base/transportchannel.h"
33 #include "talk/session/media/channelmanager.h"
34 #include "talk/session/media/mediamessages.h"
35 #include "talk/session/media/typingmonitor.h"
36 #include "webrtc/base/bind.h"
37 #include "webrtc/base/buffer.h"
38 #include "webrtc/base/byteorder.h"
39 #include "webrtc/base/common.h"
40 #include "webrtc/base/dscp.h"
41 #include "webrtc/base/logging.h"
42
43 namespace cricket {
44
45 using rtc::Bind;
46
47 enum {
48 MSG_EARLYMEDIATIMEOUT = 1,
49 MSG_SCREENCASTWINDOWEVENT,
50 MSG_RTPPACKET,
51 MSG_RTCPPACKET,
52 MSG_CHANNEL_ERROR,
53 MSG_READYTOSENDDATA,
54 MSG_DATARECEIVED,
55 MSG_FIRSTPACKETRECEIVED,
56 MSG_STREAMCLOSEDREMOTELY,
57 };
58
59 // Value specified in RFC 5764.
60 static const char kDtlsSrtpExporterLabel[] = "EXTRACTOR-dtls_srtp";
61
62 static const int kAgcMinus10db = -10;
63
SetSessionError(BaseSession * session,BaseSession::Error error,const std::string & error_desc)64 static void SetSessionError(BaseSession* session, BaseSession::Error error,
65 const std::string& error_desc) {
66 session->SetError(error, error_desc);
67 }
68
SafeSetError(const std::string & message,std::string * error_desc)69 static void SafeSetError(const std::string& message, std::string* error_desc) {
70 if (error_desc) {
71 *error_desc = message;
72 }
73 }
74
75 struct PacketMessageData : public rtc::MessageData {
76 rtc::Buffer packet;
77 rtc::DiffServCodePoint dscp;
78 };
79
80 struct ScreencastEventMessageData : public rtc::MessageData {
ScreencastEventMessageDatacricket::ScreencastEventMessageData81 ScreencastEventMessageData(uint32 s, rtc::WindowEvent we)
82 : ssrc(s),
83 event(we) {
84 }
85 uint32 ssrc;
86 rtc::WindowEvent event;
87 };
88
89 struct VoiceChannelErrorMessageData : public rtc::MessageData {
VoiceChannelErrorMessageDatacricket::VoiceChannelErrorMessageData90 VoiceChannelErrorMessageData(uint32 in_ssrc,
91 VoiceMediaChannel::Error in_error)
92 : ssrc(in_ssrc),
93 error(in_error) {
94 }
95 uint32 ssrc;
96 VoiceMediaChannel::Error error;
97 };
98
99 struct VideoChannelErrorMessageData : public rtc::MessageData {
VideoChannelErrorMessageDatacricket::VideoChannelErrorMessageData100 VideoChannelErrorMessageData(uint32 in_ssrc,
101 VideoMediaChannel::Error in_error)
102 : ssrc(in_ssrc),
103 error(in_error) {
104 }
105 uint32 ssrc;
106 VideoMediaChannel::Error error;
107 };
108
109 struct DataChannelErrorMessageData : public rtc::MessageData {
DataChannelErrorMessageDatacricket::DataChannelErrorMessageData110 DataChannelErrorMessageData(uint32 in_ssrc,
111 DataMediaChannel::Error in_error)
112 : ssrc(in_ssrc),
113 error(in_error) {}
114 uint32 ssrc;
115 DataMediaChannel::Error error;
116 };
117
118
119 struct VideoChannel::ScreencastDetailsData {
ScreencastDetailsDatacricket::VideoChannel::ScreencastDetailsData120 explicit ScreencastDetailsData(uint32 s)
121 : ssrc(s), fps(0), screencast_max_pixels(0) {
122 }
123 uint32 ssrc;
124 int fps;
125 int screencast_max_pixels;
126 };
127
PacketType(bool rtcp)128 static const char* PacketType(bool rtcp) {
129 return (!rtcp) ? "RTP" : "RTCP";
130 }
131
ValidPacket(bool rtcp,const rtc::Buffer * packet)132 static bool ValidPacket(bool rtcp, const rtc::Buffer* packet) {
133 // Check the packet size. We could check the header too if needed.
134 return (packet &&
135 packet->length() >= (!rtcp ? kMinRtpPacketLen : kMinRtcpPacketLen) &&
136 packet->length() <= kMaxRtpPacketLen);
137 }
138
IsReceiveContentDirection(MediaContentDirection direction)139 static bool IsReceiveContentDirection(MediaContentDirection direction) {
140 return direction == MD_SENDRECV || direction == MD_RECVONLY;
141 }
142
IsSendContentDirection(MediaContentDirection direction)143 static bool IsSendContentDirection(MediaContentDirection direction) {
144 return direction == MD_SENDRECV || direction == MD_SENDONLY;
145 }
146
GetContentDescription(const ContentInfo * cinfo)147 static const MediaContentDescription* GetContentDescription(
148 const ContentInfo* cinfo) {
149 if (cinfo == NULL)
150 return NULL;
151 return static_cast<const MediaContentDescription*>(cinfo->description);
152 }
153
BaseChannel(rtc::Thread * thread,MediaEngineInterface * media_engine,MediaChannel * media_channel,BaseSession * session,const std::string & content_name,bool rtcp)154 BaseChannel::BaseChannel(rtc::Thread* thread,
155 MediaEngineInterface* media_engine,
156 MediaChannel* media_channel, BaseSession* session,
157 const std::string& content_name, bool rtcp)
158 : worker_thread_(thread),
159 media_engine_(media_engine),
160 session_(session),
161 media_channel_(media_channel),
162 content_name_(content_name),
163 rtcp_(rtcp),
164 transport_channel_(NULL),
165 rtcp_transport_channel_(NULL),
166 enabled_(false),
167 writable_(false),
168 rtp_ready_to_send_(false),
169 rtcp_ready_to_send_(false),
170 was_ever_writable_(false),
171 local_content_direction_(MD_INACTIVE),
172 remote_content_direction_(MD_INACTIVE),
173 has_received_packet_(false),
174 dtls_keyed_(false),
175 secure_required_(false),
176 rtp_abs_sendtime_extn_id_(-1) {
177 ASSERT(worker_thread_ == rtc::Thread::Current());
178 LOG(LS_INFO) << "Created channel for " << content_name;
179 }
180
~BaseChannel()181 BaseChannel::~BaseChannel() {
182 ASSERT(worker_thread_ == rtc::Thread::Current());
183 Deinit();
184 StopConnectionMonitor();
185 FlushRtcpMessages(); // Send any outstanding RTCP packets.
186 worker_thread_->Clear(this); // eats any outstanding messages or packets
187 // We must destroy the media channel before the transport channel, otherwise
188 // the media channel may try to send on the dead transport channel. NULLing
189 // is not an effective strategy since the sends will come on another thread.
190 delete media_channel_;
191 set_rtcp_transport_channel(NULL);
192 if (transport_channel_ != NULL)
193 session_->DestroyChannel(content_name_, transport_channel_->component());
194 LOG(LS_INFO) << "Destroyed channel";
195 }
196
Init(TransportChannel * transport_channel,TransportChannel * rtcp_transport_channel)197 bool BaseChannel::Init(TransportChannel* transport_channel,
198 TransportChannel* rtcp_transport_channel) {
199 if (transport_channel == NULL) {
200 return false;
201 }
202 if (rtcp() && rtcp_transport_channel == NULL) {
203 return false;
204 }
205 transport_channel_ = transport_channel;
206
207 if (!SetDtlsSrtpCiphers(transport_channel_, false)) {
208 return false;
209 }
210
211 transport_channel_->SignalWritableState.connect(
212 this, &BaseChannel::OnWritableState);
213 transport_channel_->SignalReadPacket.connect(
214 this, &BaseChannel::OnChannelRead);
215 transport_channel_->SignalReadyToSend.connect(
216 this, &BaseChannel::OnReadyToSend);
217
218 session_->SignalNewLocalDescription.connect(
219 this, &BaseChannel::OnNewLocalDescription);
220 session_->SignalNewRemoteDescription.connect(
221 this, &BaseChannel::OnNewRemoteDescription);
222
223 set_rtcp_transport_channel(rtcp_transport_channel);
224 // Both RTP and RTCP channels are set, we can call SetInterface on
225 // media channel and it can set network options.
226 media_channel_->SetInterface(this);
227 return true;
228 }
229
Deinit()230 void BaseChannel::Deinit() {
231 media_channel_->SetInterface(NULL);
232 }
233
Enable(bool enable)234 bool BaseChannel::Enable(bool enable) {
235 worker_thread_->Invoke<void>(Bind(
236 enable ? &BaseChannel::EnableMedia_w : &BaseChannel::DisableMedia_w,
237 this));
238 return true;
239 }
240
MuteStream(uint32 ssrc,bool mute)241 bool BaseChannel::MuteStream(uint32 ssrc, bool mute) {
242 return InvokeOnWorker(Bind(&BaseChannel::MuteStream_w, this, ssrc, mute));
243 }
244
IsStreamMuted(uint32 ssrc)245 bool BaseChannel::IsStreamMuted(uint32 ssrc) {
246 return InvokeOnWorker(Bind(&BaseChannel::IsStreamMuted_w, this, ssrc));
247 }
248
AddRecvStream(const StreamParams & sp)249 bool BaseChannel::AddRecvStream(const StreamParams& sp) {
250 return InvokeOnWorker(Bind(&BaseChannel::AddRecvStream_w, this, sp));
251 }
252
RemoveRecvStream(uint32 ssrc)253 bool BaseChannel::RemoveRecvStream(uint32 ssrc) {
254 return InvokeOnWorker(Bind(&BaseChannel::RemoveRecvStream_w, this, ssrc));
255 }
256
AddSendStream(const StreamParams & sp)257 bool BaseChannel::AddSendStream(const StreamParams& sp) {
258 return InvokeOnWorker(
259 Bind(&MediaChannel::AddSendStream, media_channel(), sp));
260 }
261
RemoveSendStream(uint32 ssrc)262 bool BaseChannel::RemoveSendStream(uint32 ssrc) {
263 return InvokeOnWorker(
264 Bind(&MediaChannel::RemoveSendStream, media_channel(), ssrc));
265 }
266
SetLocalContent(const MediaContentDescription * content,ContentAction action,std::string * error_desc)267 bool BaseChannel::SetLocalContent(const MediaContentDescription* content,
268 ContentAction action,
269 std::string* error_desc) {
270 return InvokeOnWorker(Bind(&BaseChannel::SetLocalContent_w,
271 this, content, action, error_desc));
272 }
273
SetRemoteContent(const MediaContentDescription * content,ContentAction action,std::string * error_desc)274 bool BaseChannel::SetRemoteContent(const MediaContentDescription* content,
275 ContentAction action,
276 std::string* error_desc) {
277 return InvokeOnWorker(Bind(&BaseChannel::SetRemoteContent_w,
278 this, content, action, error_desc));
279 }
280
StartConnectionMonitor(int cms)281 void BaseChannel::StartConnectionMonitor(int cms) {
282 socket_monitor_.reset(new SocketMonitor(transport_channel_,
283 worker_thread(),
284 rtc::Thread::Current()));
285 socket_monitor_->SignalUpdate.connect(
286 this, &BaseChannel::OnConnectionMonitorUpdate);
287 socket_monitor_->Start(cms);
288 }
289
StopConnectionMonitor()290 void BaseChannel::StopConnectionMonitor() {
291 if (socket_monitor_) {
292 socket_monitor_->Stop();
293 socket_monitor_.reset();
294 }
295 }
296
set_rtcp_transport_channel(TransportChannel * channel)297 void BaseChannel::set_rtcp_transport_channel(TransportChannel* channel) {
298 if (rtcp_transport_channel_ != channel) {
299 if (rtcp_transport_channel_) {
300 session_->DestroyChannel(
301 content_name_, rtcp_transport_channel_->component());
302 }
303 rtcp_transport_channel_ = channel;
304 if (rtcp_transport_channel_) {
305 // TODO(juberti): Propagate this error code
306 VERIFY(SetDtlsSrtpCiphers(rtcp_transport_channel_, true));
307 rtcp_transport_channel_->SignalWritableState.connect(
308 this, &BaseChannel::OnWritableState);
309 rtcp_transport_channel_->SignalReadPacket.connect(
310 this, &BaseChannel::OnChannelRead);
311 rtcp_transport_channel_->SignalReadyToSend.connect(
312 this, &BaseChannel::OnReadyToSend);
313 }
314 }
315 }
316
IsReadyToReceive() const317 bool BaseChannel::IsReadyToReceive() const {
318 // Receive data if we are enabled and have local content,
319 return enabled() && IsReceiveContentDirection(local_content_direction_);
320 }
321
IsReadyToSend() const322 bool BaseChannel::IsReadyToSend() const {
323 // Send outgoing data if we are enabled, have local and remote content,
324 // and we have had some form of connectivity.
325 return enabled() &&
326 IsReceiveContentDirection(remote_content_direction_) &&
327 IsSendContentDirection(local_content_direction_) &&
328 was_ever_writable();
329 }
330
SendPacket(rtc::Buffer * packet,rtc::DiffServCodePoint dscp)331 bool BaseChannel::SendPacket(rtc::Buffer* packet,
332 rtc::DiffServCodePoint dscp) {
333 return SendPacket(false, packet, dscp);
334 }
335
SendRtcp(rtc::Buffer * packet,rtc::DiffServCodePoint dscp)336 bool BaseChannel::SendRtcp(rtc::Buffer* packet,
337 rtc::DiffServCodePoint dscp) {
338 return SendPacket(true, packet, dscp);
339 }
340
SetOption(SocketType type,rtc::Socket::Option opt,int value)341 int BaseChannel::SetOption(SocketType type, rtc::Socket::Option opt,
342 int value) {
343 TransportChannel* channel = NULL;
344 switch (type) {
345 case ST_RTP:
346 channel = transport_channel_;
347 break;
348 case ST_RTCP:
349 channel = rtcp_transport_channel_;
350 break;
351 }
352 return channel ? channel->SetOption(opt, value) : -1;
353 }
354
OnWritableState(TransportChannel * channel)355 void BaseChannel::OnWritableState(TransportChannel* channel) {
356 ASSERT(channel == transport_channel_ || channel == rtcp_transport_channel_);
357 if (transport_channel_->writable()
358 && (!rtcp_transport_channel_ || rtcp_transport_channel_->writable())) {
359 ChannelWritable_w();
360 } else {
361 ChannelNotWritable_w();
362 }
363 }
364
OnChannelRead(TransportChannel * channel,const char * data,size_t len,const rtc::PacketTime & packet_time,int flags)365 void BaseChannel::OnChannelRead(TransportChannel* channel,
366 const char* data, size_t len,
367 const rtc::PacketTime& packet_time,
368 int flags) {
369 // OnChannelRead gets called from P2PSocket; now pass data to MediaEngine
370 ASSERT(worker_thread_ == rtc::Thread::Current());
371
372 // When using RTCP multiplexing we might get RTCP packets on the RTP
373 // transport. We feed RTP traffic into the demuxer to determine if it is RTCP.
374 bool rtcp = PacketIsRtcp(channel, data, len);
375 rtc::Buffer packet(data, len);
376 HandlePacket(rtcp, &packet, packet_time);
377 }
378
OnReadyToSend(TransportChannel * channel)379 void BaseChannel::OnReadyToSend(TransportChannel* channel) {
380 SetReadyToSend(channel, true);
381 }
382
SetReadyToSend(TransportChannel * channel,bool ready)383 void BaseChannel::SetReadyToSend(TransportChannel* channel, bool ready) {
384 ASSERT(channel == transport_channel_ || channel == rtcp_transport_channel_);
385 if (channel == transport_channel_) {
386 rtp_ready_to_send_ = ready;
387 }
388 if (channel == rtcp_transport_channel_) {
389 rtcp_ready_to_send_ = ready;
390 }
391
392 if (!ready) {
393 // Notify the MediaChannel when either rtp or rtcp channel can't send.
394 media_channel_->OnReadyToSend(false);
395 } else if (rtp_ready_to_send_ &&
396 // In the case of rtcp mux |rtcp_transport_channel_| will be null.
397 (rtcp_ready_to_send_ || !rtcp_transport_channel_)) {
398 // Notify the MediaChannel when both rtp and rtcp channel can send.
399 media_channel_->OnReadyToSend(true);
400 }
401 }
402
PacketIsRtcp(const TransportChannel * channel,const char * data,size_t len)403 bool BaseChannel::PacketIsRtcp(const TransportChannel* channel,
404 const char* data, size_t len) {
405 return (channel == rtcp_transport_channel_ ||
406 rtcp_mux_filter_.DemuxRtcp(data, static_cast<int>(len)));
407 }
408
SendPacket(bool rtcp,rtc::Buffer * packet,rtc::DiffServCodePoint dscp)409 bool BaseChannel::SendPacket(bool rtcp, rtc::Buffer* packet,
410 rtc::DiffServCodePoint dscp) {
411 // SendPacket gets called from MediaEngine, typically on an encoder thread.
412 // If the thread is not our worker thread, we will post to our worker
413 // so that the real work happens on our worker. This avoids us having to
414 // synchronize access to all the pieces of the send path, including
415 // SRTP and the inner workings of the transport channels.
416 // The only downside is that we can't return a proper failure code if
417 // needed. Since UDP is unreliable anyway, this should be a non-issue.
418 if (rtc::Thread::Current() != worker_thread_) {
419 // Avoid a copy by transferring the ownership of the packet data.
420 int message_id = (!rtcp) ? MSG_RTPPACKET : MSG_RTCPPACKET;
421 PacketMessageData* data = new PacketMessageData;
422 packet->TransferTo(&data->packet);
423 data->dscp = dscp;
424 worker_thread_->Post(this, message_id, data);
425 return true;
426 }
427
428 // Now that we are on the correct thread, ensure we have a place to send this
429 // packet before doing anything. (We might get RTCP packets that we don't
430 // intend to send.) If we've negotiated RTCP mux, send RTCP over the RTP
431 // transport.
432 TransportChannel* channel = (!rtcp || rtcp_mux_filter_.IsActive()) ?
433 transport_channel_ : rtcp_transport_channel_;
434 if (!channel || !channel->writable()) {
435 return false;
436 }
437
438 // Protect ourselves against crazy data.
439 if (!ValidPacket(rtcp, packet)) {
440 LOG(LS_ERROR) << "Dropping outgoing " << content_name_ << " "
441 << PacketType(rtcp) << " packet: wrong size="
442 << packet->length();
443 return false;
444 }
445
446 // Signal to the media sink before protecting the packet.
447 {
448 rtc::CritScope cs(&signal_send_packet_cs_);
449 SignalSendPacketPreCrypto(packet->data(), packet->length(), rtcp);
450 }
451
452 rtc::PacketOptions options(dscp);
453 // Protect if needed.
454 if (srtp_filter_.IsActive()) {
455 bool res;
456 char* data = packet->data();
457 int len = static_cast<int>(packet->length());
458 if (!rtcp) {
459 // If ENABLE_EXTERNAL_AUTH flag is on then packet authentication is not done
460 // inside libsrtp for a RTP packet. A external HMAC module will be writing
461 // a fake HMAC value. This is ONLY done for a RTP packet.
462 // Socket layer will update rtp sendtime extension header if present in
463 // packet with current time before updating the HMAC.
464 #if !defined(ENABLE_EXTERNAL_AUTH)
465 res = srtp_filter_.ProtectRtp(
466 data, len, static_cast<int>(packet->capacity()), &len);
467 #else
468 options.packet_time_params.rtp_sendtime_extension_id =
469 rtp_abs_sendtime_extn_id_;
470 res = srtp_filter_.ProtectRtp(
471 data, len, static_cast<int>(packet->capacity()), &len,
472 &options.packet_time_params.srtp_packet_index);
473 // If protection succeeds, let's get auth params from srtp.
474 if (res) {
475 uint8* auth_key = NULL;
476 int key_len;
477 res = srtp_filter_.GetRtpAuthParams(
478 &auth_key, &key_len, &options.packet_time_params.srtp_auth_tag_len);
479 if (res) {
480 options.packet_time_params.srtp_auth_key.resize(key_len);
481 options.packet_time_params.srtp_auth_key.assign(auth_key,
482 auth_key + key_len);
483 }
484 }
485 #endif
486 if (!res) {
487 int seq_num = -1;
488 uint32 ssrc = 0;
489 GetRtpSeqNum(data, len, &seq_num);
490 GetRtpSsrc(data, len, &ssrc);
491 LOG(LS_ERROR) << "Failed to protect " << content_name_
492 << " RTP packet: size=" << len
493 << ", seqnum=" << seq_num << ", SSRC=" << ssrc;
494 return false;
495 }
496 } else {
497 res = srtp_filter_.ProtectRtcp(data, len,
498 static_cast<int>(packet->capacity()),
499 &len);
500 if (!res) {
501 int type = -1;
502 GetRtcpType(data, len, &type);
503 LOG(LS_ERROR) << "Failed to protect " << content_name_
504 << " RTCP packet: size=" << len << ", type=" << type;
505 return false;
506 }
507 }
508
509 // Update the length of the packet now that we've added the auth tag.
510 packet->SetLength(len);
511 } else if (secure_required_) {
512 // This is a double check for something that supposedly can't happen.
513 LOG(LS_ERROR) << "Can't send outgoing " << PacketType(rtcp)
514 << " packet when SRTP is inactive and crypto is required";
515
516 ASSERT(false);
517 return false;
518 }
519
520 // Signal to the media sink after protecting the packet.
521 {
522 rtc::CritScope cs(&signal_send_packet_cs_);
523 SignalSendPacketPostCrypto(packet->data(), packet->length(), rtcp);
524 }
525
526 // Bon voyage.
527 int ret = channel->SendPacket(packet->data(), packet->length(), options,
528 (secure() && secure_dtls()) ? PF_SRTP_BYPASS : 0);
529 if (ret != static_cast<int>(packet->length())) {
530 if (channel->GetError() == EWOULDBLOCK) {
531 LOG(LS_WARNING) << "Got EWOULDBLOCK from socket.";
532 SetReadyToSend(channel, false);
533 }
534 return false;
535 }
536 return true;
537 }
538
WantsPacket(bool rtcp,rtc::Buffer * packet)539 bool BaseChannel::WantsPacket(bool rtcp, rtc::Buffer* packet) {
540 // Protect ourselves against crazy data.
541 if (!ValidPacket(rtcp, packet)) {
542 LOG(LS_ERROR) << "Dropping incoming " << content_name_ << " "
543 << PacketType(rtcp) << " packet: wrong size="
544 << packet->length();
545 return false;
546 }
547
548 // Bundle filter handles both rtp and rtcp packets.
549 return bundle_filter_.DemuxPacket(packet->data(), packet->length(), rtcp);
550 }
551
HandlePacket(bool rtcp,rtc::Buffer * packet,const rtc::PacketTime & packet_time)552 void BaseChannel::HandlePacket(bool rtcp, rtc::Buffer* packet,
553 const rtc::PacketTime& packet_time) {
554 if (!WantsPacket(rtcp, packet)) {
555 return;
556 }
557
558 if (!has_received_packet_) {
559 has_received_packet_ = true;
560 signaling_thread()->Post(this, MSG_FIRSTPACKETRECEIVED);
561 }
562
563 // Signal to the media sink before unprotecting the packet.
564 {
565 rtc::CritScope cs(&signal_recv_packet_cs_);
566 SignalRecvPacketPostCrypto(packet->data(), packet->length(), rtcp);
567 }
568
569 // Unprotect the packet, if needed.
570 if (srtp_filter_.IsActive()) {
571 char* data = packet->data();
572 int len = static_cast<int>(packet->length());
573 bool res;
574 if (!rtcp) {
575 res = srtp_filter_.UnprotectRtp(data, len, &len);
576 if (!res) {
577 int seq_num = -1;
578 uint32 ssrc = 0;
579 GetRtpSeqNum(data, len, &seq_num);
580 GetRtpSsrc(data, len, &ssrc);
581 LOG(LS_ERROR) << "Failed to unprotect " << content_name_
582 << " RTP packet: size=" << len
583 << ", seqnum=" << seq_num << ", SSRC=" << ssrc;
584 return;
585 }
586 } else {
587 res = srtp_filter_.UnprotectRtcp(data, len, &len);
588 if (!res) {
589 int type = -1;
590 GetRtcpType(data, len, &type);
591 LOG(LS_ERROR) << "Failed to unprotect " << content_name_
592 << " RTCP packet: size=" << len << ", type=" << type;
593 return;
594 }
595 }
596
597 packet->SetLength(len);
598 } else if (secure_required_) {
599 // Our session description indicates that SRTP is required, but we got a
600 // packet before our SRTP filter is active. This means either that
601 // a) we got SRTP packets before we received the SDES keys, in which case
602 // we can't decrypt it anyway, or
603 // b) we got SRTP packets before DTLS completed on both the RTP and RTCP
604 // channels, so we haven't yet extracted keys, even if DTLS did complete
605 // on the channel that the packets are being sent on. It's really good
606 // practice to wait for both RTP and RTCP to be good to go before sending
607 // media, to prevent weird failure modes, so it's fine for us to just eat
608 // packets here. This is all sidestepped if RTCP mux is used anyway.
609 LOG(LS_WARNING) << "Can't process incoming " << PacketType(rtcp)
610 << " packet when SRTP is inactive and crypto is required";
611 return;
612 }
613
614 // Signal to the media sink after unprotecting the packet.
615 {
616 rtc::CritScope cs(&signal_recv_packet_cs_);
617 SignalRecvPacketPreCrypto(packet->data(), packet->length(), rtcp);
618 }
619
620 // Push it down to the media channel.
621 if (!rtcp) {
622 media_channel_->OnPacketReceived(packet, packet_time);
623 } else {
624 media_channel_->OnRtcpReceived(packet, packet_time);
625 }
626 }
627
OnNewLocalDescription(BaseSession * session,ContentAction action)628 void BaseChannel::OnNewLocalDescription(
629 BaseSession* session, ContentAction action) {
630 const ContentInfo* content_info =
631 GetFirstContent(session->local_description());
632 const MediaContentDescription* content_desc =
633 GetContentDescription(content_info);
634 std::string error_desc;
635 if (content_desc && content_info && !content_info->rejected &&
636 !SetLocalContent(content_desc, action, &error_desc)) {
637 SetSessionError(session_, BaseSession::ERROR_CONTENT, error_desc);
638 LOG(LS_ERROR) << "Failure in SetLocalContent with action " << action;
639 }
640 }
641
OnNewRemoteDescription(BaseSession * session,ContentAction action)642 void BaseChannel::OnNewRemoteDescription(
643 BaseSession* session, ContentAction action) {
644 const ContentInfo* content_info =
645 GetFirstContent(session->remote_description());
646 const MediaContentDescription* content_desc =
647 GetContentDescription(content_info);
648 std::string error_desc;
649 if (content_desc && content_info && !content_info->rejected &&
650 !SetRemoteContent(content_desc, action, &error_desc)) {
651 SetSessionError(session_, BaseSession::ERROR_CONTENT, error_desc);
652 LOG(LS_ERROR) << "Failure in SetRemoteContent with action " << action;
653 }
654 }
655
EnableMedia_w()656 void BaseChannel::EnableMedia_w() {
657 ASSERT(worker_thread_ == rtc::Thread::Current());
658 if (enabled_)
659 return;
660
661 LOG(LS_INFO) << "Channel enabled";
662 enabled_ = true;
663 ChangeState();
664 }
665
DisableMedia_w()666 void BaseChannel::DisableMedia_w() {
667 ASSERT(worker_thread_ == rtc::Thread::Current());
668 if (!enabled_)
669 return;
670
671 LOG(LS_INFO) << "Channel disabled";
672 enabled_ = false;
673 ChangeState();
674 }
675
MuteStream_w(uint32 ssrc,bool mute)676 bool BaseChannel::MuteStream_w(uint32 ssrc, bool mute) {
677 ASSERT(worker_thread_ == rtc::Thread::Current());
678 bool ret = media_channel()->MuteStream(ssrc, mute);
679 if (ret) {
680 if (mute)
681 muted_streams_.insert(ssrc);
682 else
683 muted_streams_.erase(ssrc);
684 }
685 return ret;
686 }
687
IsStreamMuted_w(uint32 ssrc)688 bool BaseChannel::IsStreamMuted_w(uint32 ssrc) {
689 ASSERT(worker_thread_ == rtc::Thread::Current());
690 return muted_streams_.find(ssrc) != muted_streams_.end();
691 }
692
ChannelWritable_w()693 void BaseChannel::ChannelWritable_w() {
694 ASSERT(worker_thread_ == rtc::Thread::Current());
695 if (writable_)
696 return;
697
698 LOG(LS_INFO) << "Channel socket writable ("
699 << transport_channel_->content_name() << ", "
700 << transport_channel_->component() << ")"
701 << (was_ever_writable_ ? "" : " for the first time");
702
703 std::vector<ConnectionInfo> infos;
704 transport_channel_->GetStats(&infos);
705 for (std::vector<ConnectionInfo>::const_iterator it = infos.begin();
706 it != infos.end(); ++it) {
707 if (it->best_connection) {
708 LOG(LS_INFO) << "Using " << it->local_candidate.ToSensitiveString()
709 << "->" << it->remote_candidate.ToSensitiveString();
710 break;
711 }
712 }
713
714 // If we're doing DTLS-SRTP, now is the time.
715 if (!was_ever_writable_ && ShouldSetupDtlsSrtp()) {
716 if (!SetupDtlsSrtp(false)) {
717 const std::string error_desc =
718 "Couldn't set up DTLS-SRTP on RTP channel.";
719 // Sent synchronously.
720 signaling_thread()->Invoke<void>(Bind(
721 &SetSessionError,
722 session_,
723 BaseSession::ERROR_TRANSPORT,
724 error_desc));
725 return;
726 }
727
728 if (rtcp_transport_channel_) {
729 if (!SetupDtlsSrtp(true)) {
730 const std::string error_desc =
731 "Couldn't set up DTLS-SRTP on RTCP channel";
732 // Sent synchronously.
733 signaling_thread()->Invoke<void>(Bind(
734 &SetSessionError,
735 session_,
736 BaseSession::ERROR_TRANSPORT,
737 error_desc));
738 return;
739 }
740 }
741 }
742
743 was_ever_writable_ = true;
744 writable_ = true;
745 ChangeState();
746 }
747
SetDtlsSrtpCiphers(TransportChannel * tc,bool rtcp)748 bool BaseChannel::SetDtlsSrtpCiphers(TransportChannel *tc, bool rtcp) {
749 std::vector<std::string> ciphers;
750 // We always use the default SRTP ciphers for RTCP, but we may use different
751 // ciphers for RTP depending on the media type.
752 if (!rtcp) {
753 GetSrtpCiphers(&ciphers);
754 } else {
755 GetSupportedDefaultCryptoSuites(&ciphers);
756 }
757 return tc->SetSrtpCiphers(ciphers);
758 }
759
ShouldSetupDtlsSrtp() const760 bool BaseChannel::ShouldSetupDtlsSrtp() const {
761 return true;
762 }
763
764 // This function returns true if either DTLS-SRTP is not in use
765 // *or* DTLS-SRTP is successfully set up.
SetupDtlsSrtp(bool rtcp_channel)766 bool BaseChannel::SetupDtlsSrtp(bool rtcp_channel) {
767 bool ret = false;
768
769 TransportChannel *channel = rtcp_channel ?
770 rtcp_transport_channel_ : transport_channel_;
771
772 // No DTLS
773 if (!channel->IsDtlsActive())
774 return true;
775
776 std::string selected_cipher;
777
778 if (!channel->GetSrtpCipher(&selected_cipher)) {
779 LOG(LS_ERROR) << "No DTLS-SRTP selected cipher";
780 return false;
781 }
782
783 LOG(LS_INFO) << "Installing keys from DTLS-SRTP on "
784 << content_name() << " "
785 << PacketType(rtcp_channel);
786
787 // OK, we're now doing DTLS (RFC 5764)
788 std::vector<unsigned char> dtls_buffer(SRTP_MASTER_KEY_KEY_LEN * 2 +
789 SRTP_MASTER_KEY_SALT_LEN * 2);
790
791 // RFC 5705 exporter using the RFC 5764 parameters
792 if (!channel->ExportKeyingMaterial(
793 kDtlsSrtpExporterLabel,
794 NULL, 0, false,
795 &dtls_buffer[0], dtls_buffer.size())) {
796 LOG(LS_WARNING) << "DTLS-SRTP key export failed";
797 ASSERT(false); // This should never happen
798 return false;
799 }
800
801 // Sync up the keys with the DTLS-SRTP interface
802 std::vector<unsigned char> client_write_key(SRTP_MASTER_KEY_KEY_LEN +
803 SRTP_MASTER_KEY_SALT_LEN);
804 std::vector<unsigned char> server_write_key(SRTP_MASTER_KEY_KEY_LEN +
805 SRTP_MASTER_KEY_SALT_LEN);
806 size_t offset = 0;
807 memcpy(&client_write_key[0], &dtls_buffer[offset],
808 SRTP_MASTER_KEY_KEY_LEN);
809 offset += SRTP_MASTER_KEY_KEY_LEN;
810 memcpy(&server_write_key[0], &dtls_buffer[offset],
811 SRTP_MASTER_KEY_KEY_LEN);
812 offset += SRTP_MASTER_KEY_KEY_LEN;
813 memcpy(&client_write_key[SRTP_MASTER_KEY_KEY_LEN],
814 &dtls_buffer[offset], SRTP_MASTER_KEY_SALT_LEN);
815 offset += SRTP_MASTER_KEY_SALT_LEN;
816 memcpy(&server_write_key[SRTP_MASTER_KEY_KEY_LEN],
817 &dtls_buffer[offset], SRTP_MASTER_KEY_SALT_LEN);
818
819 std::vector<unsigned char> *send_key, *recv_key;
820 rtc::SSLRole role;
821 if (!channel->GetSslRole(&role)) {
822 LOG(LS_WARNING) << "GetSslRole failed";
823 return false;
824 }
825
826 if (role == rtc::SSL_SERVER) {
827 send_key = &server_write_key;
828 recv_key = &client_write_key;
829 } else {
830 send_key = &client_write_key;
831 recv_key = &server_write_key;
832 }
833
834 if (rtcp_channel) {
835 ret = srtp_filter_.SetRtcpParams(
836 selected_cipher,
837 &(*send_key)[0],
838 static_cast<int>(send_key->size()),
839 selected_cipher,
840 &(*recv_key)[0],
841 static_cast<int>(recv_key->size()));
842 } else {
843 ret = srtp_filter_.SetRtpParams(
844 selected_cipher,
845 &(*send_key)[0],
846 static_cast<int>(send_key->size()),
847 selected_cipher,
848 &(*recv_key)[0],
849 static_cast<int>(recv_key->size()));
850 }
851
852 if (!ret)
853 LOG(LS_WARNING) << "DTLS-SRTP key installation failed";
854 else
855 dtls_keyed_ = true;
856
857 return ret;
858 }
859
ChannelNotWritable_w()860 void BaseChannel::ChannelNotWritable_w() {
861 ASSERT(worker_thread_ == rtc::Thread::Current());
862 if (!writable_)
863 return;
864
865 LOG(LS_INFO) << "Channel socket not writable ("
866 << transport_channel_->content_name() << ", "
867 << transport_channel_->component() << ")";
868 writable_ = false;
869 ChangeState();
870 }
871
872 // |dtls| will be set to true if DTLS is active for transport channel and
873 // crypto is empty.
CheckSrtpConfig(const std::vector<CryptoParams> & cryptos,bool * dtls,std::string * error_desc)874 bool BaseChannel::CheckSrtpConfig(const std::vector<CryptoParams>& cryptos,
875 bool* dtls,
876 std::string* error_desc) {
877 *dtls = transport_channel_->IsDtlsActive();
878 if (*dtls && !cryptos.empty()) {
879 SafeSetError("Cryptos must be empty when DTLS is active.",
880 error_desc);
881 return false;
882 }
883 return true;
884 }
885
SetRecvRtpHeaderExtensions_w(const MediaContentDescription * content,MediaChannel * media_channel,std::string * error_desc)886 bool BaseChannel::SetRecvRtpHeaderExtensions_w(
887 const MediaContentDescription* content,
888 MediaChannel* media_channel,
889 std::string* error_desc) {
890 if (content->rtp_header_extensions_set()) {
891 if (!media_channel->SetRecvRtpHeaderExtensions(
892 content->rtp_header_extensions())) {
893 std::ostringstream desc;
894 desc << "Failed to set receive rtp header extensions for "
895 << MediaTypeToString(content->type()) << " content.";
896 SafeSetError(desc.str(), error_desc);
897 return false;
898 }
899 }
900 return true;
901 }
902
SetSendRtpHeaderExtensions_w(const MediaContentDescription * content,MediaChannel * media_channel,std::string * error_desc)903 bool BaseChannel::SetSendRtpHeaderExtensions_w(
904 const MediaContentDescription* content,
905 MediaChannel* media_channel,
906 std::string* error_desc) {
907 if (content->rtp_header_extensions_set()) {
908 if (!media_channel->SetSendRtpHeaderExtensions(
909 content->rtp_header_extensions())) {
910 std::ostringstream desc;
911 desc << "Failed to set send rtp header extensions for "
912 << MediaTypeToString(content->type()) << " content.";
913 SafeSetError(desc.str(), error_desc);
914 return false;
915 } else {
916 MaybeCacheRtpAbsSendTimeHeaderExtension(content->rtp_header_extensions());
917 }
918 }
919 return true;
920 }
921
SetSrtp_w(const std::vector<CryptoParams> & cryptos,ContentAction action,ContentSource src,std::string * error_desc)922 bool BaseChannel::SetSrtp_w(const std::vector<CryptoParams>& cryptos,
923 ContentAction action,
924 ContentSource src,
925 std::string* error_desc) {
926 if (action == CA_UPDATE) {
927 // no crypto params.
928 return true;
929 }
930 bool ret = false;
931 bool dtls = false;
932 ret = CheckSrtpConfig(cryptos, &dtls, error_desc);
933 if (!ret) {
934 return false;
935 }
936 switch (action) {
937 case CA_OFFER:
938 // If DTLS is already active on the channel, we could be renegotiating
939 // here. We don't update the srtp filter.
940 if (!dtls) {
941 ret = srtp_filter_.SetOffer(cryptos, src);
942 }
943 break;
944 case CA_PRANSWER:
945 // If we're doing DTLS-SRTP, we don't want to update the filter
946 // with an answer, because we already have SRTP parameters.
947 if (!dtls) {
948 ret = srtp_filter_.SetProvisionalAnswer(cryptos, src);
949 }
950 break;
951 case CA_ANSWER:
952 // If we're doing DTLS-SRTP, we don't want to update the filter
953 // with an answer, because we already have SRTP parameters.
954 if (!dtls) {
955 ret = srtp_filter_.SetAnswer(cryptos, src);
956 }
957 break;
958 default:
959 break;
960 }
961 if (!ret) {
962 SafeSetError("Failed to setup SRTP filter.", error_desc);
963 return false;
964 }
965 return true;
966 }
967
SetRtcpMux_w(bool enable,ContentAction action,ContentSource src,std::string * error_desc)968 bool BaseChannel::SetRtcpMux_w(bool enable, ContentAction action,
969 ContentSource src,
970 std::string* error_desc) {
971 bool ret = false;
972 switch (action) {
973 case CA_OFFER:
974 ret = rtcp_mux_filter_.SetOffer(enable, src);
975 break;
976 case CA_PRANSWER:
977 ret = rtcp_mux_filter_.SetProvisionalAnswer(enable, src);
978 break;
979 case CA_ANSWER:
980 ret = rtcp_mux_filter_.SetAnswer(enable, src);
981 if (ret && rtcp_mux_filter_.IsActive()) {
982 // We activated RTCP mux, close down the RTCP transport.
983 set_rtcp_transport_channel(NULL);
984 }
985 break;
986 case CA_UPDATE:
987 // No RTCP mux info.
988 ret = true;
989 default:
990 break;
991 }
992 if (!ret) {
993 SafeSetError("Failed to setup RTCP mux filter.", error_desc);
994 return false;
995 }
996 // |rtcp_mux_filter_| can be active if |action| is CA_PRANSWER or
997 // CA_ANSWER, but we only want to tear down the RTCP transport channel if we
998 // received a final answer.
999 if (rtcp_mux_filter_.IsActive()) {
1000 // If the RTP transport is already writable, then so are we.
1001 if (transport_channel_->writable()) {
1002 ChannelWritable_w();
1003 }
1004 }
1005
1006 return true;
1007 }
1008
AddRecvStream_w(const StreamParams & sp)1009 bool BaseChannel::AddRecvStream_w(const StreamParams& sp) {
1010 ASSERT(worker_thread() == rtc::Thread::Current());
1011 if (!media_channel()->AddRecvStream(sp))
1012 return false;
1013
1014 return bundle_filter_.AddStream(sp);
1015 }
1016
RemoveRecvStream_w(uint32 ssrc)1017 bool BaseChannel::RemoveRecvStream_w(uint32 ssrc) {
1018 ASSERT(worker_thread() == rtc::Thread::Current());
1019 bundle_filter_.RemoveStream(ssrc);
1020 return media_channel()->RemoveRecvStream(ssrc);
1021 }
1022
UpdateLocalStreams_w(const std::vector<StreamParams> & streams,ContentAction action,std::string * error_desc)1023 bool BaseChannel::UpdateLocalStreams_w(const std::vector<StreamParams>& streams,
1024 ContentAction action,
1025 std::string* error_desc) {
1026 if (!VERIFY(action == CA_OFFER || action == CA_ANSWER ||
1027 action == CA_PRANSWER || action == CA_UPDATE))
1028 return false;
1029
1030 // If this is an update, streams only contain streams that have changed.
1031 if (action == CA_UPDATE) {
1032 for (StreamParamsVec::const_iterator it = streams.begin();
1033 it != streams.end(); ++it) {
1034 StreamParams existing_stream;
1035 bool stream_exist = GetStreamByIds(local_streams_, it->groupid,
1036 it->id, &existing_stream);
1037 if (!stream_exist && it->has_ssrcs()) {
1038 if (media_channel()->AddSendStream(*it)) {
1039 local_streams_.push_back(*it);
1040 LOG(LS_INFO) << "Add send stream ssrc: " << it->first_ssrc();
1041 } else {
1042 std::ostringstream desc;
1043 desc << "Failed to add send stream ssrc: " << it->first_ssrc();
1044 SafeSetError(desc.str(), error_desc);
1045 return false;
1046 }
1047 } else if (stream_exist && !it->has_ssrcs()) {
1048 if (!media_channel()->RemoveSendStream(existing_stream.first_ssrc())) {
1049 std::ostringstream desc;
1050 desc << "Failed to remove send stream with ssrc "
1051 << it->first_ssrc() << ".";
1052 SafeSetError(desc.str(), error_desc);
1053 return false;
1054 }
1055 RemoveStreamBySsrc(&local_streams_, existing_stream.first_ssrc());
1056 } else {
1057 LOG(LS_WARNING) << "Ignore unsupported stream update";
1058 }
1059 }
1060 return true;
1061 }
1062 // Else streams are all the streams we want to send.
1063
1064 // Check for streams that have been removed.
1065 bool ret = true;
1066 for (StreamParamsVec::const_iterator it = local_streams_.begin();
1067 it != local_streams_.end(); ++it) {
1068 if (!GetStreamBySsrc(streams, it->first_ssrc(), NULL)) {
1069 if (!media_channel()->RemoveSendStream(it->first_ssrc())) {
1070 std::ostringstream desc;
1071 desc << "Failed to remove send stream with ssrc "
1072 << it->first_ssrc() << ".";
1073 SafeSetError(desc.str(), error_desc);
1074 ret = false;
1075 }
1076 }
1077 }
1078 // Check for new streams.
1079 for (StreamParamsVec::const_iterator it = streams.begin();
1080 it != streams.end(); ++it) {
1081 if (!GetStreamBySsrc(local_streams_, it->first_ssrc(), NULL)) {
1082 if (media_channel()->AddSendStream(*it)) {
1083 LOG(LS_INFO) << "Add send ssrc: " << it->ssrcs[0];
1084 } else {
1085 std::ostringstream desc;
1086 desc << "Failed to add send stream ssrc: " << it->first_ssrc();
1087 SafeSetError(desc.str(), error_desc);
1088 ret = false;
1089 }
1090 }
1091 }
1092 local_streams_ = streams;
1093 return ret;
1094 }
1095
UpdateRemoteStreams_w(const std::vector<StreamParams> & streams,ContentAction action,std::string * error_desc)1096 bool BaseChannel::UpdateRemoteStreams_w(
1097 const std::vector<StreamParams>& streams,
1098 ContentAction action,
1099 std::string* error_desc) {
1100 if (!VERIFY(action == CA_OFFER || action == CA_ANSWER ||
1101 action == CA_PRANSWER || action == CA_UPDATE))
1102 return false;
1103
1104 // If this is an update, streams only contain streams that have changed.
1105 if (action == CA_UPDATE) {
1106 for (StreamParamsVec::const_iterator it = streams.begin();
1107 it != streams.end(); ++it) {
1108 StreamParams existing_stream;
1109 bool stream_exists = GetStreamByIds(remote_streams_, it->groupid,
1110 it->id, &existing_stream);
1111 if (!stream_exists && it->has_ssrcs()) {
1112 if (AddRecvStream_w(*it)) {
1113 remote_streams_.push_back(*it);
1114 LOG(LS_INFO) << "Add remote stream ssrc: " << it->first_ssrc();
1115 } else {
1116 std::ostringstream desc;
1117 desc << "Failed to add remote stream ssrc: " << it->first_ssrc();
1118 SafeSetError(desc.str(), error_desc);
1119 return false;
1120 }
1121 } else if (stream_exists && !it->has_ssrcs()) {
1122 if (!RemoveRecvStream_w(existing_stream.first_ssrc())) {
1123 std::ostringstream desc;
1124 desc << "Failed to remove remote stream with ssrc "
1125 << it->first_ssrc() << ".";
1126 SafeSetError(desc.str(), error_desc);
1127 return false;
1128 }
1129 RemoveStreamBySsrc(&remote_streams_, existing_stream.first_ssrc());
1130 } else {
1131 LOG(LS_WARNING) << "Ignore unsupported stream update."
1132 << " Stream exists? " << stream_exists
1133 << " existing stream = " << existing_stream.ToString()
1134 << " new stream = " << it->ToString();
1135 }
1136 }
1137 return true;
1138 }
1139 // Else streams are all the streams we want to receive.
1140
1141 // Check for streams that have been removed.
1142 bool ret = true;
1143 for (StreamParamsVec::const_iterator it = remote_streams_.begin();
1144 it != remote_streams_.end(); ++it) {
1145 if (!GetStreamBySsrc(streams, it->first_ssrc(), NULL)) {
1146 if (!RemoveRecvStream_w(it->first_ssrc())) {
1147 std::ostringstream desc;
1148 desc << "Failed to remove remote stream with ssrc "
1149 << it->first_ssrc() << ".";
1150 SafeSetError(desc.str(), error_desc);
1151 ret = false;
1152 }
1153 }
1154 }
1155 // Check for new streams.
1156 for (StreamParamsVec::const_iterator it = streams.begin();
1157 it != streams.end(); ++it) {
1158 if (!GetStreamBySsrc(remote_streams_, it->first_ssrc(), NULL)) {
1159 if (AddRecvStream_w(*it)) {
1160 LOG(LS_INFO) << "Add remote ssrc: " << it->ssrcs[0];
1161 } else {
1162 std::ostringstream desc;
1163 desc << "Failed to add remote stream ssrc: " << it->first_ssrc();
1164 SafeSetError(desc.str(), error_desc);
1165 ret = false;
1166 }
1167 }
1168 }
1169 remote_streams_ = streams;
1170 return ret;
1171 }
1172
SetBaseLocalContent_w(const MediaContentDescription * content,ContentAction action,std::string * error_desc)1173 bool BaseChannel::SetBaseLocalContent_w(const MediaContentDescription* content,
1174 ContentAction action,
1175 std::string* error_desc) {
1176 // Cache secure_required_ for belt and suspenders check on SendPacket
1177 secure_required_ = content->crypto_required() != CT_NONE;
1178 // Set local RTP header extensions.
1179 bool ret = SetRecvRtpHeaderExtensions_w(content, media_channel(), error_desc);
1180 // Set local SRTP parameters (what we will encrypt with).
1181 ret &= SetSrtp_w(content->cryptos(), action, CS_LOCAL, error_desc);
1182 // Set local RTCP mux parameters.
1183 ret &= SetRtcpMux_w(content->rtcp_mux(), action, CS_LOCAL, error_desc);
1184
1185 // Call UpdateLocalStreams_w last to make sure as many settings as possible
1186 // are already set when creating streams.
1187 ret &= UpdateLocalStreams_w(content->streams(), action, error_desc);
1188 set_local_content_direction(content->direction());
1189 return ret;
1190 }
1191
SetBaseRemoteContent_w(const MediaContentDescription * content,ContentAction action,std::string * error_desc)1192 bool BaseChannel::SetBaseRemoteContent_w(const MediaContentDescription* content,
1193 ContentAction action,
1194 std::string* error_desc) {
1195 // Set remote RTP header extensions.
1196 bool ret = SetSendRtpHeaderExtensions_w(content, media_channel(), error_desc);
1197 // Set remote SRTP parameters (what the other side will encrypt with).
1198 ret &= SetSrtp_w(content->cryptos(), action, CS_REMOTE, error_desc);
1199 // Set remote RTCP mux parameters.
1200 ret &= SetRtcpMux_w(content->rtcp_mux(), action, CS_REMOTE, error_desc);
1201 if (!media_channel()->SetMaxSendBandwidth(content->bandwidth())) {
1202 std::ostringstream desc;
1203 desc << "Failed to set max send bandwidth for "
1204 << MediaTypeToString(content->type()) << " content.";
1205 SafeSetError(desc.str(), error_desc);
1206 ret = false;
1207 }
1208
1209 // Call UpdateRemoteStreams_w last to make sure as many settings as possible
1210 // are already set when creating streams.
1211 ret &= UpdateRemoteStreams_w(content->streams(), action, error_desc);
1212 set_remote_content_direction(content->direction());
1213 return ret;
1214 }
1215
MaybeCacheRtpAbsSendTimeHeaderExtension(const std::vector<RtpHeaderExtension> & extensions)1216 void BaseChannel::MaybeCacheRtpAbsSendTimeHeaderExtension(
1217 const std::vector<RtpHeaderExtension>& extensions) {
1218 const RtpHeaderExtension* send_time_extension =
1219 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
1220 rtp_abs_sendtime_extn_id_ =
1221 send_time_extension ? send_time_extension->id : -1;
1222 }
1223
OnMessage(rtc::Message * pmsg)1224 void BaseChannel::OnMessage(rtc::Message *pmsg) {
1225 switch (pmsg->message_id) {
1226 case MSG_RTPPACKET:
1227 case MSG_RTCPPACKET: {
1228 PacketMessageData* data = static_cast<PacketMessageData*>(pmsg->pdata);
1229 SendPacket(pmsg->message_id == MSG_RTCPPACKET, &data->packet, data->dscp);
1230 delete data; // because it is Posted
1231 break;
1232 }
1233 case MSG_FIRSTPACKETRECEIVED: {
1234 SignalFirstPacketReceived(this);
1235 break;
1236 }
1237 }
1238 }
1239
FlushRtcpMessages()1240 void BaseChannel::FlushRtcpMessages() {
1241 // Flush all remaining RTCP messages. This should only be called in
1242 // destructor.
1243 ASSERT(rtc::Thread::Current() == worker_thread_);
1244 rtc::MessageList rtcp_messages;
1245 worker_thread_->Clear(this, MSG_RTCPPACKET, &rtcp_messages);
1246 for (rtc::MessageList::iterator it = rtcp_messages.begin();
1247 it != rtcp_messages.end(); ++it) {
1248 worker_thread_->Send(this, MSG_RTCPPACKET, it->pdata);
1249 }
1250 }
1251
VoiceChannel(rtc::Thread * thread,MediaEngineInterface * media_engine,VoiceMediaChannel * media_channel,BaseSession * session,const std::string & content_name,bool rtcp)1252 VoiceChannel::VoiceChannel(rtc::Thread* thread,
1253 MediaEngineInterface* media_engine,
1254 VoiceMediaChannel* media_channel,
1255 BaseSession* session,
1256 const std::string& content_name,
1257 bool rtcp)
1258 : BaseChannel(thread, media_engine, media_channel, session, content_name,
1259 rtcp),
1260 received_media_(false) {
1261 }
1262
~VoiceChannel()1263 VoiceChannel::~VoiceChannel() {
1264 StopAudioMonitor();
1265 StopMediaMonitor();
1266 // this can't be done in the base class, since it calls a virtual
1267 DisableMedia_w();
1268 Deinit();
1269 }
1270
Init()1271 bool VoiceChannel::Init() {
1272 TransportChannel* rtcp_channel = rtcp() ? session()->CreateChannel(
1273 content_name(), "rtcp", ICE_CANDIDATE_COMPONENT_RTCP) : NULL;
1274 if (!BaseChannel::Init(session()->CreateChannel(
1275 content_name(), "rtp", ICE_CANDIDATE_COMPONENT_RTP),
1276 rtcp_channel)) {
1277 return false;
1278 }
1279 media_channel()->SignalMediaError.connect(
1280 this, &VoiceChannel::OnVoiceChannelError);
1281 srtp_filter()->SignalSrtpError.connect(
1282 this, &VoiceChannel::OnSrtpError);
1283 return true;
1284 }
1285
SetRemoteRenderer(uint32 ssrc,AudioRenderer * renderer)1286 bool VoiceChannel::SetRemoteRenderer(uint32 ssrc, AudioRenderer* renderer) {
1287 return InvokeOnWorker(Bind(&VoiceMediaChannel::SetRemoteRenderer,
1288 media_channel(), ssrc, renderer));
1289 }
1290
SetLocalRenderer(uint32 ssrc,AudioRenderer * renderer)1291 bool VoiceChannel::SetLocalRenderer(uint32 ssrc, AudioRenderer* renderer) {
1292 return InvokeOnWorker(Bind(&VoiceMediaChannel::SetLocalRenderer,
1293 media_channel(), ssrc, renderer));
1294 }
1295
SetRingbackTone(const void * buf,int len)1296 bool VoiceChannel::SetRingbackTone(const void* buf, int len) {
1297 return InvokeOnWorker(Bind(&VoiceChannel::SetRingbackTone_w, this, buf, len));
1298 }
1299
1300 // TODO(juberti): Handle early media the right way. We should get an explicit
1301 // ringing message telling us to start playing local ringback, which we cancel
1302 // if any early media actually arrives. For now, we do the opposite, which is
1303 // to wait 1 second for early media, and start playing local ringback if none
1304 // arrives.
SetEarlyMedia(bool enable)1305 void VoiceChannel::SetEarlyMedia(bool enable) {
1306 if (enable) {
1307 // Start the early media timeout
1308 worker_thread()->PostDelayed(kEarlyMediaTimeout, this,
1309 MSG_EARLYMEDIATIMEOUT);
1310 } else {
1311 // Stop the timeout if currently going.
1312 worker_thread()->Clear(this, MSG_EARLYMEDIATIMEOUT);
1313 }
1314 }
1315
PlayRingbackTone(uint32 ssrc,bool play,bool loop)1316 bool VoiceChannel::PlayRingbackTone(uint32 ssrc, bool play, bool loop) {
1317 return InvokeOnWorker(Bind(&VoiceChannel::PlayRingbackTone_w,
1318 this, ssrc, play, loop));
1319 }
1320
PressDTMF(int digit,bool playout)1321 bool VoiceChannel::PressDTMF(int digit, bool playout) {
1322 int flags = DF_SEND;
1323 if (playout) {
1324 flags |= DF_PLAY;
1325 }
1326 int duration_ms = 160;
1327 return InsertDtmf(0, digit, duration_ms, flags);
1328 }
1329
CanInsertDtmf()1330 bool VoiceChannel::CanInsertDtmf() {
1331 return InvokeOnWorker(Bind(&VoiceMediaChannel::CanInsertDtmf,
1332 media_channel()));
1333 }
1334
InsertDtmf(uint32 ssrc,int event_code,int duration,int flags)1335 bool VoiceChannel::InsertDtmf(uint32 ssrc, int event_code, int duration,
1336 int flags) {
1337 return InvokeOnWorker(Bind(&VoiceChannel::InsertDtmf_w, this,
1338 ssrc, event_code, duration, flags));
1339 }
1340
SetOutputScaling(uint32 ssrc,double left,double right)1341 bool VoiceChannel::SetOutputScaling(uint32 ssrc, double left, double right) {
1342 return InvokeOnWorker(Bind(&VoiceMediaChannel::SetOutputScaling,
1343 media_channel(), ssrc, left, right));
1344 }
1345
GetStats(VoiceMediaInfo * stats)1346 bool VoiceChannel::GetStats(VoiceMediaInfo* stats) {
1347 return InvokeOnWorker(Bind(&VoiceMediaChannel::GetStats,
1348 media_channel(), stats));
1349 }
1350
StartMediaMonitor(int cms)1351 void VoiceChannel::StartMediaMonitor(int cms) {
1352 media_monitor_.reset(new VoiceMediaMonitor(media_channel(), worker_thread(),
1353 rtc::Thread::Current()));
1354 media_monitor_->SignalUpdate.connect(
1355 this, &VoiceChannel::OnMediaMonitorUpdate);
1356 media_monitor_->Start(cms);
1357 }
1358
StopMediaMonitor()1359 void VoiceChannel::StopMediaMonitor() {
1360 if (media_monitor_) {
1361 media_monitor_->Stop();
1362 media_monitor_->SignalUpdate.disconnect(this);
1363 media_monitor_.reset();
1364 }
1365 }
1366
StartAudioMonitor(int cms)1367 void VoiceChannel::StartAudioMonitor(int cms) {
1368 audio_monitor_.reset(new AudioMonitor(this, rtc::Thread::Current()));
1369 audio_monitor_
1370 ->SignalUpdate.connect(this, &VoiceChannel::OnAudioMonitorUpdate);
1371 audio_monitor_->Start(cms);
1372 }
1373
StopAudioMonitor()1374 void VoiceChannel::StopAudioMonitor() {
1375 if (audio_monitor_) {
1376 audio_monitor_->Stop();
1377 audio_monitor_.reset();
1378 }
1379 }
1380
IsAudioMonitorRunning() const1381 bool VoiceChannel::IsAudioMonitorRunning() const {
1382 return (audio_monitor_.get() != NULL);
1383 }
1384
StartTypingMonitor(const TypingMonitorOptions & settings)1385 void VoiceChannel::StartTypingMonitor(const TypingMonitorOptions& settings) {
1386 typing_monitor_.reset(new TypingMonitor(this, worker_thread(), settings));
1387 SignalAutoMuted.repeat(typing_monitor_->SignalMuted);
1388 }
1389
StopTypingMonitor()1390 void VoiceChannel::StopTypingMonitor() {
1391 typing_monitor_.reset();
1392 }
1393
IsTypingMonitorRunning() const1394 bool VoiceChannel::IsTypingMonitorRunning() const {
1395 return typing_monitor_;
1396 }
1397
MuteStream_w(uint32 ssrc,bool mute)1398 bool VoiceChannel::MuteStream_w(uint32 ssrc, bool mute) {
1399 bool ret = BaseChannel::MuteStream_w(ssrc, mute);
1400 if (typing_monitor_ && mute)
1401 typing_monitor_->OnChannelMuted();
1402 return ret;
1403 }
1404
GetInputLevel_w()1405 int VoiceChannel::GetInputLevel_w() {
1406 return media_engine()->GetInputLevel();
1407 }
1408
GetOutputLevel_w()1409 int VoiceChannel::GetOutputLevel_w() {
1410 return media_channel()->GetOutputLevel();
1411 }
1412
GetActiveStreams_w(AudioInfo::StreamList * actives)1413 void VoiceChannel::GetActiveStreams_w(AudioInfo::StreamList* actives) {
1414 media_channel()->GetActiveStreams(actives);
1415 }
1416
OnChannelRead(TransportChannel * channel,const char * data,size_t len,const rtc::PacketTime & packet_time,int flags)1417 void VoiceChannel::OnChannelRead(TransportChannel* channel,
1418 const char* data, size_t len,
1419 const rtc::PacketTime& packet_time,
1420 int flags) {
1421 BaseChannel::OnChannelRead(channel, data, len, packet_time, flags);
1422
1423 // Set a flag when we've received an RTP packet. If we're waiting for early
1424 // media, this will disable the timeout.
1425 if (!received_media_ && !PacketIsRtcp(channel, data, len)) {
1426 received_media_ = true;
1427 }
1428 }
1429
ChangeState()1430 void VoiceChannel::ChangeState() {
1431 // Render incoming data if we're the active call, and we have the local
1432 // content. We receive data on the default channel and multiplexed streams.
1433 bool recv = IsReadyToReceive();
1434 if (!media_channel()->SetPlayout(recv)) {
1435 SendLastMediaError();
1436 }
1437
1438 // Send outgoing data if we're the active call, we have the remote content,
1439 // and we have had some form of connectivity.
1440 bool send = IsReadyToSend();
1441 SendFlags send_flag = send ? SEND_MICROPHONE : SEND_NOTHING;
1442 if (!media_channel()->SetSend(send_flag)) {
1443 LOG(LS_ERROR) << "Failed to SetSend " << send_flag << " on voice channel";
1444 SendLastMediaError();
1445 }
1446
1447 LOG(LS_INFO) << "Changing voice state, recv=" << recv << " send=" << send;
1448 }
1449
GetFirstContent(const SessionDescription * sdesc)1450 const ContentInfo* VoiceChannel::GetFirstContent(
1451 const SessionDescription* sdesc) {
1452 return GetFirstAudioContent(sdesc);
1453 }
1454
SetLocalContent_w(const MediaContentDescription * content,ContentAction action,std::string * error_desc)1455 bool VoiceChannel::SetLocalContent_w(const MediaContentDescription* content,
1456 ContentAction action,
1457 std::string* error_desc) {
1458 ASSERT(worker_thread() == rtc::Thread::Current());
1459 LOG(LS_INFO) << "Setting local voice description";
1460
1461 const AudioContentDescription* audio =
1462 static_cast<const AudioContentDescription*>(content);
1463 ASSERT(audio != NULL);
1464 if (!audio) {
1465 SafeSetError("Can't find audio content in local description.", error_desc);
1466 return false;
1467 }
1468
1469 bool ret = SetBaseLocalContent_w(content, action, error_desc);
1470 // Set local audio codecs (what we want to receive).
1471 // TODO(whyuan): Change action != CA_UPDATE to !audio->partial() when partial
1472 // is set properly.
1473 if (action != CA_UPDATE || audio->has_codecs()) {
1474 if (!media_channel()->SetRecvCodecs(audio->codecs())) {
1475 SafeSetError("Failed to set audio receive codecs.", error_desc);
1476 ret = false;
1477 }
1478 }
1479
1480 // If everything worked, see if we can start receiving.
1481 if (ret) {
1482 std::vector<AudioCodec>::const_iterator it = audio->codecs().begin();
1483 for (; it != audio->codecs().end(); ++it) {
1484 bundle_filter()->AddPayloadType(it->id);
1485 }
1486 ChangeState();
1487 } else {
1488 LOG(LS_WARNING) << "Failed to set local voice description";
1489 }
1490 return ret;
1491 }
1492
SetRemoteContent_w(const MediaContentDescription * content,ContentAction action,std::string * error_desc)1493 bool VoiceChannel::SetRemoteContent_w(const MediaContentDescription* content,
1494 ContentAction action,
1495 std::string* error_desc) {
1496 ASSERT(worker_thread() == rtc::Thread::Current());
1497 LOG(LS_INFO) << "Setting remote voice description";
1498
1499 const AudioContentDescription* audio =
1500 static_cast<const AudioContentDescription*>(content);
1501 ASSERT(audio != NULL);
1502 if (!audio) {
1503 SafeSetError("Can't find audio content in remote description.", error_desc);
1504 return false;
1505 }
1506
1507 bool ret = true;
1508 // Set remote video codecs (what the other side wants to receive).
1509 if (action != CA_UPDATE || audio->has_codecs()) {
1510 if (!media_channel()->SetSendCodecs(audio->codecs())) {
1511 SafeSetError("Failed to set audio send codecs.", error_desc);
1512 ret = false;
1513 }
1514 }
1515
1516 ret &= SetBaseRemoteContent_w(content, action, error_desc);
1517
1518 if (action != CA_UPDATE) {
1519 // Tweak our audio processing settings, if needed.
1520 AudioOptions audio_options;
1521 if (!media_channel()->GetOptions(&audio_options)) {
1522 LOG(LS_WARNING) << "Can not set audio options from on remote content.";
1523 } else {
1524 if (audio->conference_mode()) {
1525 audio_options.conference_mode.Set(true);
1526 }
1527 if (audio->agc_minus_10db()) {
1528 audio_options.adjust_agc_delta.Set(kAgcMinus10db);
1529 }
1530 if (!media_channel()->SetOptions(audio_options)) {
1531 // Log an error on failure, but don't abort the call.
1532 LOG(LS_ERROR) << "Failed to set voice channel options";
1533 }
1534 }
1535 }
1536
1537 // If everything worked, see if we can start sending.
1538 if (ret) {
1539 ChangeState();
1540 } else {
1541 LOG(LS_WARNING) << "Failed to set remote voice description";
1542 }
1543 return ret;
1544 }
1545
SetRingbackTone_w(const void * buf,int len)1546 bool VoiceChannel::SetRingbackTone_w(const void* buf, int len) {
1547 ASSERT(worker_thread() == rtc::Thread::Current());
1548 return media_channel()->SetRingbackTone(static_cast<const char*>(buf), len);
1549 }
1550
PlayRingbackTone_w(uint32 ssrc,bool play,bool loop)1551 bool VoiceChannel::PlayRingbackTone_w(uint32 ssrc, bool play, bool loop) {
1552 ASSERT(worker_thread() == rtc::Thread::Current());
1553 if (play) {
1554 LOG(LS_INFO) << "Playing ringback tone, loop=" << loop;
1555 } else {
1556 LOG(LS_INFO) << "Stopping ringback tone";
1557 }
1558 return media_channel()->PlayRingbackTone(ssrc, play, loop);
1559 }
1560
HandleEarlyMediaTimeout()1561 void VoiceChannel::HandleEarlyMediaTimeout() {
1562 // This occurs on the main thread, not the worker thread.
1563 if (!received_media_) {
1564 LOG(LS_INFO) << "No early media received before timeout";
1565 SignalEarlyMediaTimeout(this);
1566 }
1567 }
1568
InsertDtmf_w(uint32 ssrc,int event,int duration,int flags)1569 bool VoiceChannel::InsertDtmf_w(uint32 ssrc, int event, int duration,
1570 int flags) {
1571 if (!enabled()) {
1572 return false;
1573 }
1574
1575 return media_channel()->InsertDtmf(ssrc, event, duration, flags);
1576 }
1577
SetChannelOptions(const AudioOptions & options)1578 bool VoiceChannel::SetChannelOptions(const AudioOptions& options) {
1579 return InvokeOnWorker(Bind(&VoiceMediaChannel::SetOptions,
1580 media_channel(), options));
1581 }
1582
OnMessage(rtc::Message * pmsg)1583 void VoiceChannel::OnMessage(rtc::Message *pmsg) {
1584 switch (pmsg->message_id) {
1585 case MSG_EARLYMEDIATIMEOUT:
1586 HandleEarlyMediaTimeout();
1587 break;
1588 case MSG_CHANNEL_ERROR: {
1589 VoiceChannelErrorMessageData* data =
1590 static_cast<VoiceChannelErrorMessageData*>(pmsg->pdata);
1591 SignalMediaError(this, data->ssrc, data->error);
1592 delete data;
1593 break;
1594 }
1595 default:
1596 BaseChannel::OnMessage(pmsg);
1597 break;
1598 }
1599 }
1600
OnConnectionMonitorUpdate(SocketMonitor * monitor,const std::vector<ConnectionInfo> & infos)1601 void VoiceChannel::OnConnectionMonitorUpdate(
1602 SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos) {
1603 SignalConnectionMonitor(this, infos);
1604 }
1605
OnMediaMonitorUpdate(VoiceMediaChannel * media_channel,const VoiceMediaInfo & info)1606 void VoiceChannel::OnMediaMonitorUpdate(
1607 VoiceMediaChannel* media_channel, const VoiceMediaInfo& info) {
1608 ASSERT(media_channel == this->media_channel());
1609 SignalMediaMonitor(this, info);
1610 }
1611
OnAudioMonitorUpdate(AudioMonitor * monitor,const AudioInfo & info)1612 void VoiceChannel::OnAudioMonitorUpdate(AudioMonitor* monitor,
1613 const AudioInfo& info) {
1614 SignalAudioMonitor(this, info);
1615 }
1616
OnVoiceChannelError(uint32 ssrc,VoiceMediaChannel::Error err)1617 void VoiceChannel::OnVoiceChannelError(
1618 uint32 ssrc, VoiceMediaChannel::Error err) {
1619 VoiceChannelErrorMessageData* data = new VoiceChannelErrorMessageData(
1620 ssrc, err);
1621 signaling_thread()->Post(this, MSG_CHANNEL_ERROR, data);
1622 }
1623
OnSrtpError(uint32 ssrc,SrtpFilter::Mode mode,SrtpFilter::Error error)1624 void VoiceChannel::OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode,
1625 SrtpFilter::Error error) {
1626 switch (error) {
1627 case SrtpFilter::ERROR_FAIL:
1628 OnVoiceChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
1629 VoiceMediaChannel::ERROR_REC_SRTP_ERROR :
1630 VoiceMediaChannel::ERROR_PLAY_SRTP_ERROR);
1631 break;
1632 case SrtpFilter::ERROR_AUTH:
1633 OnVoiceChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
1634 VoiceMediaChannel::ERROR_REC_SRTP_AUTH_FAILED :
1635 VoiceMediaChannel::ERROR_PLAY_SRTP_AUTH_FAILED);
1636 break;
1637 case SrtpFilter::ERROR_REPLAY:
1638 // Only receving channel should have this error.
1639 ASSERT(mode == SrtpFilter::UNPROTECT);
1640 OnVoiceChannelError(ssrc, VoiceMediaChannel::ERROR_PLAY_SRTP_REPLAY);
1641 break;
1642 default:
1643 break;
1644 }
1645 }
1646
GetSrtpCiphers(std::vector<std::string> * ciphers) const1647 void VoiceChannel::GetSrtpCiphers(std::vector<std::string>* ciphers) const {
1648 GetSupportedAudioCryptoSuites(ciphers);
1649 }
1650
VideoChannel(rtc::Thread * thread,MediaEngineInterface * media_engine,VideoMediaChannel * media_channel,BaseSession * session,const std::string & content_name,bool rtcp,VoiceChannel * voice_channel)1651 VideoChannel::VideoChannel(rtc::Thread* thread,
1652 MediaEngineInterface* media_engine,
1653 VideoMediaChannel* media_channel,
1654 BaseSession* session,
1655 const std::string& content_name,
1656 bool rtcp,
1657 VoiceChannel* voice_channel)
1658 : BaseChannel(thread, media_engine, media_channel, session, content_name,
1659 rtcp),
1660 voice_channel_(voice_channel),
1661 renderer_(NULL),
1662 previous_we_(rtc::WE_CLOSE) {
1663 }
1664
Init()1665 bool VideoChannel::Init() {
1666 TransportChannel* rtcp_channel = rtcp() ? session()->CreateChannel(
1667 content_name(), "video_rtcp", ICE_CANDIDATE_COMPONENT_RTCP) : NULL;
1668 if (!BaseChannel::Init(session()->CreateChannel(
1669 content_name(), "video_rtp", ICE_CANDIDATE_COMPONENT_RTP),
1670 rtcp_channel)) {
1671 return false;
1672 }
1673 media_channel()->SignalMediaError.connect(
1674 this, &VideoChannel::OnVideoChannelError);
1675 srtp_filter()->SignalSrtpError.connect(
1676 this, &VideoChannel::OnSrtpError);
1677 return true;
1678 }
1679
SendLastMediaError()1680 void VoiceChannel::SendLastMediaError() {
1681 uint32 ssrc;
1682 VoiceMediaChannel::Error error;
1683 media_channel()->GetLastMediaError(&ssrc, &error);
1684 SignalMediaError(this, ssrc, error);
1685 }
1686
~VideoChannel()1687 VideoChannel::~VideoChannel() {
1688 std::vector<uint32> screencast_ssrcs;
1689 ScreencastMap::iterator iter;
1690 while (!screencast_capturers_.empty()) {
1691 if (!RemoveScreencast(screencast_capturers_.begin()->first)) {
1692 LOG(LS_ERROR) << "Unable to delete screencast with ssrc "
1693 << screencast_capturers_.begin()->first;
1694 ASSERT(false);
1695 break;
1696 }
1697 }
1698
1699 StopMediaMonitor();
1700 // this can't be done in the base class, since it calls a virtual
1701 DisableMedia_w();
1702
1703 Deinit();
1704 }
1705
SetRenderer(uint32 ssrc,VideoRenderer * renderer)1706 bool VideoChannel::SetRenderer(uint32 ssrc, VideoRenderer* renderer) {
1707 worker_thread()->Invoke<void>(Bind(
1708 &VideoMediaChannel::SetRenderer, media_channel(), ssrc, renderer));
1709 return true;
1710 }
1711
ApplyViewRequest(const ViewRequest & request)1712 bool VideoChannel::ApplyViewRequest(const ViewRequest& request) {
1713 return InvokeOnWorker(Bind(&VideoChannel::ApplyViewRequest_w, this, request));
1714 }
1715
AddScreencast(uint32 ssrc,VideoCapturer * capturer)1716 bool VideoChannel::AddScreencast(uint32 ssrc, VideoCapturer* capturer) {
1717 return worker_thread()->Invoke<bool>(Bind(
1718 &VideoChannel::AddScreencast_w, this, ssrc, capturer));
1719 }
1720
SetCapturer(uint32 ssrc,VideoCapturer * capturer)1721 bool VideoChannel::SetCapturer(uint32 ssrc, VideoCapturer* capturer) {
1722 return InvokeOnWorker(Bind(&VideoMediaChannel::SetCapturer,
1723 media_channel(), ssrc, capturer));
1724 }
1725
RemoveScreencast(uint32 ssrc)1726 bool VideoChannel::RemoveScreencast(uint32 ssrc) {
1727 return InvokeOnWorker(Bind(&VideoChannel::RemoveScreencast_w, this, ssrc));
1728 }
1729
IsScreencasting()1730 bool VideoChannel::IsScreencasting() {
1731 return InvokeOnWorker(Bind(&VideoChannel::IsScreencasting_w, this));
1732 }
1733
GetScreencastFps(uint32 ssrc)1734 int VideoChannel::GetScreencastFps(uint32 ssrc) {
1735 ScreencastDetailsData data(ssrc);
1736 worker_thread()->Invoke<void>(Bind(
1737 &VideoChannel::GetScreencastDetails_w, this, &data));
1738 return data.fps;
1739 }
1740
GetScreencastMaxPixels(uint32 ssrc)1741 int VideoChannel::GetScreencastMaxPixels(uint32 ssrc) {
1742 ScreencastDetailsData data(ssrc);
1743 worker_thread()->Invoke<void>(Bind(
1744 &VideoChannel::GetScreencastDetails_w, this, &data));
1745 return data.screencast_max_pixels;
1746 }
1747
SendIntraFrame()1748 bool VideoChannel::SendIntraFrame() {
1749 worker_thread()->Invoke<void>(Bind(
1750 &VideoMediaChannel::SendIntraFrame, media_channel()));
1751 return true;
1752 }
1753
RequestIntraFrame()1754 bool VideoChannel::RequestIntraFrame() {
1755 worker_thread()->Invoke<void>(Bind(
1756 &VideoMediaChannel::RequestIntraFrame, media_channel()));
1757 return true;
1758 }
1759
ChangeState()1760 void VideoChannel::ChangeState() {
1761 // Render incoming data if we're the active call, and we have the local
1762 // content. We receive data on the default channel and multiplexed streams.
1763 bool recv = IsReadyToReceive();
1764 if (!media_channel()->SetRender(recv)) {
1765 LOG(LS_ERROR) << "Failed to SetRender on video channel";
1766 // TODO(gangji): Report error back to server.
1767 }
1768
1769 // Send outgoing data if we're the active call, we have the remote content,
1770 // and we have had some form of connectivity.
1771 bool send = IsReadyToSend();
1772 if (!media_channel()->SetSend(send)) {
1773 LOG(LS_ERROR) << "Failed to SetSend on video channel";
1774 // TODO(gangji): Report error back to server.
1775 }
1776
1777 LOG(LS_INFO) << "Changing video state, recv=" << recv << " send=" << send;
1778 }
1779
GetStats(const StatsOptions & options,VideoMediaInfo * stats)1780 bool VideoChannel::GetStats(
1781 const StatsOptions& options, VideoMediaInfo* stats) {
1782 return InvokeOnWorker(Bind(&VideoMediaChannel::GetStats,
1783 media_channel(), options, stats));
1784 }
1785
StartMediaMonitor(int cms)1786 void VideoChannel::StartMediaMonitor(int cms) {
1787 media_monitor_.reset(new VideoMediaMonitor(media_channel(), worker_thread(),
1788 rtc::Thread::Current()));
1789 media_monitor_->SignalUpdate.connect(
1790 this, &VideoChannel::OnMediaMonitorUpdate);
1791 media_monitor_->Start(cms);
1792 }
1793
StopMediaMonitor()1794 void VideoChannel::StopMediaMonitor() {
1795 if (media_monitor_) {
1796 media_monitor_->Stop();
1797 media_monitor_.reset();
1798 }
1799 }
1800
GetFirstContent(const SessionDescription * sdesc)1801 const ContentInfo* VideoChannel::GetFirstContent(
1802 const SessionDescription* sdesc) {
1803 return GetFirstVideoContent(sdesc);
1804 }
1805
SetLocalContent_w(const MediaContentDescription * content,ContentAction action,std::string * error_desc)1806 bool VideoChannel::SetLocalContent_w(const MediaContentDescription* content,
1807 ContentAction action,
1808 std::string* error_desc) {
1809 ASSERT(worker_thread() == rtc::Thread::Current());
1810 LOG(LS_INFO) << "Setting local video description";
1811
1812 const VideoContentDescription* video =
1813 static_cast<const VideoContentDescription*>(content);
1814 ASSERT(video != NULL);
1815 if (!video) {
1816 SafeSetError("Can't find video content in local description.", error_desc);
1817 return false;
1818 }
1819
1820 bool ret = SetBaseLocalContent_w(content, action, error_desc);
1821 // Set local video codecs (what we want to receive).
1822 if (action != CA_UPDATE || video->has_codecs()) {
1823 if (!media_channel()->SetRecvCodecs(video->codecs())) {
1824 SafeSetError("Failed to set video receive codecs.", error_desc);
1825 ret = false;
1826 }
1827 }
1828
1829 if (action != CA_UPDATE) {
1830 VideoOptions video_options;
1831 media_channel()->GetOptions(&video_options);
1832 video_options.buffered_mode_latency.Set(video->buffered_mode_latency());
1833
1834 if (!media_channel()->SetOptions(video_options)) {
1835 // Log an error on failure, but don't abort the call.
1836 LOG(LS_ERROR) << "Failed to set video channel options";
1837 }
1838 }
1839
1840 // If everything worked, see if we can start receiving.
1841 if (ret) {
1842 std::vector<VideoCodec>::const_iterator it = video->codecs().begin();
1843 for (; it != video->codecs().end(); ++it) {
1844 bundle_filter()->AddPayloadType(it->id);
1845 }
1846 ChangeState();
1847 } else {
1848 LOG(LS_WARNING) << "Failed to set local video description";
1849 }
1850 return ret;
1851 }
1852
SetRemoteContent_w(const MediaContentDescription * content,ContentAction action,std::string * error_desc)1853 bool VideoChannel::SetRemoteContent_w(const MediaContentDescription* content,
1854 ContentAction action,
1855 std::string* error_desc) {
1856 ASSERT(worker_thread() == rtc::Thread::Current());
1857 LOG(LS_INFO) << "Setting remote video description";
1858
1859 const VideoContentDescription* video =
1860 static_cast<const VideoContentDescription*>(content);
1861 ASSERT(video != NULL);
1862 if (!video) {
1863 SafeSetError("Can't find video content in remote description.", error_desc);
1864 return false;
1865 }
1866
1867 bool ret = true;
1868 // Set remote video codecs (what the other side wants to receive).
1869 if (action != CA_UPDATE || video->has_codecs()) {
1870 if (!media_channel()->SetSendCodecs(video->codecs())) {
1871 SafeSetError("Failed to set video send codecs.", error_desc);
1872 ret = false;
1873 }
1874 }
1875
1876 ret &= SetBaseRemoteContent_w(content, action, error_desc);
1877
1878 if (action != CA_UPDATE) {
1879 // Tweak our video processing settings, if needed.
1880 VideoOptions video_options;
1881 media_channel()->GetOptions(&video_options);
1882 if (video->conference_mode()) {
1883 video_options.conference_mode.Set(true);
1884 }
1885 video_options.buffered_mode_latency.Set(video->buffered_mode_latency());
1886
1887 if (!media_channel()->SetOptions(video_options)) {
1888 // Log an error on failure, but don't abort the call.
1889 LOG(LS_ERROR) << "Failed to set video channel options";
1890 }
1891 }
1892
1893 // If everything worked, see if we can start sending.
1894 if (ret) {
1895 ChangeState();
1896 } else {
1897 LOG(LS_WARNING) << "Failed to set remote video description";
1898 }
1899 return ret;
1900 }
1901
ApplyViewRequest_w(const ViewRequest & request)1902 bool VideoChannel::ApplyViewRequest_w(const ViewRequest& request) {
1903 bool ret = true;
1904 // Set the send format for each of the local streams. If the view request
1905 // does not contain a local stream, set its send format to 0x0, which will
1906 // drop all frames.
1907 for (std::vector<StreamParams>::const_iterator it = local_streams().begin();
1908 it != local_streams().end(); ++it) {
1909 VideoFormat format(0, 0, 0, cricket::FOURCC_I420);
1910 StaticVideoViews::const_iterator view;
1911 for (view = request.static_video_views.begin();
1912 view != request.static_video_views.end(); ++view) {
1913 if (view->selector.Matches(*it)) {
1914 format.width = view->width;
1915 format.height = view->height;
1916 format.interval = cricket::VideoFormat::FpsToInterval(view->framerate);
1917 break;
1918 }
1919 }
1920
1921 ret &= media_channel()->SetSendStreamFormat(it->first_ssrc(), format);
1922 }
1923
1924 // Check if the view request has invalid streams.
1925 for (StaticVideoViews::const_iterator it = request.static_video_views.begin();
1926 it != request.static_video_views.end(); ++it) {
1927 if (!GetStream(local_streams(), it->selector, NULL)) {
1928 LOG(LS_WARNING) << "View request for ("
1929 << it->selector.ssrc << ", '"
1930 << it->selector.groupid << "', '"
1931 << it->selector.streamid << "'"
1932 << ") is not in the local streams.";
1933 }
1934 }
1935
1936 return ret;
1937 }
1938
AddScreencast_w(uint32 ssrc,VideoCapturer * capturer)1939 bool VideoChannel::AddScreencast_w(uint32 ssrc, VideoCapturer* capturer) {
1940 if (screencast_capturers_.find(ssrc) != screencast_capturers_.end()) {
1941 return false;
1942 }
1943 capturer->SignalStateChange.connect(this, &VideoChannel::OnStateChange);
1944 screencast_capturers_[ssrc] = capturer;
1945 return true;
1946 }
1947
RemoveScreencast_w(uint32 ssrc)1948 bool VideoChannel::RemoveScreencast_w(uint32 ssrc) {
1949 ScreencastMap::iterator iter = screencast_capturers_.find(ssrc);
1950 if (iter == screencast_capturers_.end()) {
1951 return false;
1952 }
1953 // Clean up VideoCapturer.
1954 delete iter->second;
1955 screencast_capturers_.erase(iter);
1956 return true;
1957 }
1958
IsScreencasting_w() const1959 bool VideoChannel::IsScreencasting_w() const {
1960 return !screencast_capturers_.empty();
1961 }
1962
GetScreencastDetails_w(ScreencastDetailsData * data) const1963 void VideoChannel::GetScreencastDetails_w(
1964 ScreencastDetailsData* data) const {
1965 ScreencastMap::const_iterator iter = screencast_capturers_.find(data->ssrc);
1966 if (iter == screencast_capturers_.end()) {
1967 return;
1968 }
1969 VideoCapturer* capturer = iter->second;
1970 const VideoFormat* video_format = capturer->GetCaptureFormat();
1971 data->fps = VideoFormat::IntervalToFps(video_format->interval);
1972 data->screencast_max_pixels = capturer->screencast_max_pixels();
1973 }
1974
OnScreencastWindowEvent_s(uint32 ssrc,rtc::WindowEvent we)1975 void VideoChannel::OnScreencastWindowEvent_s(uint32 ssrc,
1976 rtc::WindowEvent we) {
1977 ASSERT(signaling_thread() == rtc::Thread::Current());
1978 SignalScreencastWindowEvent(ssrc, we);
1979 }
1980
SetChannelOptions(const VideoOptions & options)1981 bool VideoChannel::SetChannelOptions(const VideoOptions &options) {
1982 return InvokeOnWorker(Bind(&VideoMediaChannel::SetOptions,
1983 media_channel(), options));
1984 }
1985
OnMessage(rtc::Message * pmsg)1986 void VideoChannel::OnMessage(rtc::Message *pmsg) {
1987 switch (pmsg->message_id) {
1988 case MSG_SCREENCASTWINDOWEVENT: {
1989 const ScreencastEventMessageData* data =
1990 static_cast<ScreencastEventMessageData*>(pmsg->pdata);
1991 OnScreencastWindowEvent_s(data->ssrc, data->event);
1992 delete data;
1993 break;
1994 }
1995 case MSG_CHANNEL_ERROR: {
1996 const VideoChannelErrorMessageData* data =
1997 static_cast<VideoChannelErrorMessageData*>(pmsg->pdata);
1998 SignalMediaError(this, data->ssrc, data->error);
1999 delete data;
2000 break;
2001 }
2002 default:
2003 BaseChannel::OnMessage(pmsg);
2004 break;
2005 }
2006 }
2007
OnConnectionMonitorUpdate(SocketMonitor * monitor,const std::vector<ConnectionInfo> & infos)2008 void VideoChannel::OnConnectionMonitorUpdate(
2009 SocketMonitor *monitor, const std::vector<ConnectionInfo> &infos) {
2010 SignalConnectionMonitor(this, infos);
2011 }
2012
2013 // TODO(pthatcher): Look into removing duplicate code between
2014 // audio, video, and data, perhaps by using templates.
OnMediaMonitorUpdate(VideoMediaChannel * media_channel,const VideoMediaInfo & info)2015 void VideoChannel::OnMediaMonitorUpdate(
2016 VideoMediaChannel* media_channel, const VideoMediaInfo &info) {
2017 ASSERT(media_channel == this->media_channel());
2018 SignalMediaMonitor(this, info);
2019 }
2020
OnScreencastWindowEvent(uint32 ssrc,rtc::WindowEvent event)2021 void VideoChannel::OnScreencastWindowEvent(uint32 ssrc,
2022 rtc::WindowEvent event) {
2023 ScreencastEventMessageData* pdata =
2024 new ScreencastEventMessageData(ssrc, event);
2025 signaling_thread()->Post(this, MSG_SCREENCASTWINDOWEVENT, pdata);
2026 }
2027
OnStateChange(VideoCapturer * capturer,CaptureState ev)2028 void VideoChannel::OnStateChange(VideoCapturer* capturer, CaptureState ev) {
2029 // Map capturer events to window events. In the future we may want to simply
2030 // pass these events up directly.
2031 rtc::WindowEvent we;
2032 if (ev == CS_STOPPED) {
2033 we = rtc::WE_CLOSE;
2034 } else if (ev == CS_PAUSED) {
2035 we = rtc::WE_MINIMIZE;
2036 } else if (ev == CS_RUNNING && previous_we_ == rtc::WE_MINIMIZE) {
2037 we = rtc::WE_RESTORE;
2038 } else {
2039 return;
2040 }
2041 previous_we_ = we;
2042
2043 uint32 ssrc = 0;
2044 if (!GetLocalSsrc(capturer, &ssrc)) {
2045 return;
2046 }
2047
2048 OnScreencastWindowEvent(ssrc, we);
2049 }
2050
GetLocalSsrc(const VideoCapturer * capturer,uint32 * ssrc)2051 bool VideoChannel::GetLocalSsrc(const VideoCapturer* capturer, uint32* ssrc) {
2052 *ssrc = 0;
2053 for (ScreencastMap::iterator iter = screencast_capturers_.begin();
2054 iter != screencast_capturers_.end(); ++iter) {
2055 if (iter->second == capturer) {
2056 *ssrc = iter->first;
2057 return true;
2058 }
2059 }
2060 return false;
2061 }
2062
OnVideoChannelError(uint32 ssrc,VideoMediaChannel::Error error)2063 void VideoChannel::OnVideoChannelError(uint32 ssrc,
2064 VideoMediaChannel::Error error) {
2065 VideoChannelErrorMessageData* data = new VideoChannelErrorMessageData(
2066 ssrc, error);
2067 signaling_thread()->Post(this, MSG_CHANNEL_ERROR, data);
2068 }
2069
OnSrtpError(uint32 ssrc,SrtpFilter::Mode mode,SrtpFilter::Error error)2070 void VideoChannel::OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode,
2071 SrtpFilter::Error error) {
2072 switch (error) {
2073 case SrtpFilter::ERROR_FAIL:
2074 OnVideoChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
2075 VideoMediaChannel::ERROR_REC_SRTP_ERROR :
2076 VideoMediaChannel::ERROR_PLAY_SRTP_ERROR);
2077 break;
2078 case SrtpFilter::ERROR_AUTH:
2079 OnVideoChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
2080 VideoMediaChannel::ERROR_REC_SRTP_AUTH_FAILED :
2081 VideoMediaChannel::ERROR_PLAY_SRTP_AUTH_FAILED);
2082 break;
2083 case SrtpFilter::ERROR_REPLAY:
2084 // Only receving channel should have this error.
2085 ASSERT(mode == SrtpFilter::UNPROTECT);
2086 // TODO(gangji): Turn on the signaling of replay error once we have
2087 // switched to the new mechanism for doing video retransmissions.
2088 // OnVideoChannelError(ssrc, VideoMediaChannel::ERROR_PLAY_SRTP_REPLAY);
2089 break;
2090 default:
2091 break;
2092 }
2093 }
2094
2095
GetSrtpCiphers(std::vector<std::string> * ciphers) const2096 void VideoChannel::GetSrtpCiphers(std::vector<std::string>* ciphers) const {
2097 GetSupportedVideoCryptoSuites(ciphers);
2098 }
2099
DataChannel(rtc::Thread * thread,DataMediaChannel * media_channel,BaseSession * session,const std::string & content_name,bool rtcp)2100 DataChannel::DataChannel(rtc::Thread* thread,
2101 DataMediaChannel* media_channel,
2102 BaseSession* session,
2103 const std::string& content_name,
2104 bool rtcp)
2105 // MediaEngine is NULL
2106 : BaseChannel(thread, NULL, media_channel, session, content_name, rtcp),
2107 data_channel_type_(cricket::DCT_NONE),
2108 ready_to_send_data_(false) {
2109 }
2110
~DataChannel()2111 DataChannel::~DataChannel() {
2112 StopMediaMonitor();
2113 // this can't be done in the base class, since it calls a virtual
2114 DisableMedia_w();
2115
2116 Deinit();
2117 }
2118
Init()2119 bool DataChannel::Init() {
2120 TransportChannel* rtcp_channel = rtcp() ? session()->CreateChannel(
2121 content_name(), "data_rtcp", ICE_CANDIDATE_COMPONENT_RTCP) : NULL;
2122 if (!BaseChannel::Init(session()->CreateChannel(
2123 content_name(), "data_rtp", ICE_CANDIDATE_COMPONENT_RTP),
2124 rtcp_channel)) {
2125 return false;
2126 }
2127 media_channel()->SignalDataReceived.connect(
2128 this, &DataChannel::OnDataReceived);
2129 media_channel()->SignalMediaError.connect(
2130 this, &DataChannel::OnDataChannelError);
2131 media_channel()->SignalReadyToSend.connect(
2132 this, &DataChannel::OnDataChannelReadyToSend);
2133 media_channel()->SignalStreamClosedRemotely.connect(
2134 this, &DataChannel::OnStreamClosedRemotely);
2135 srtp_filter()->SignalSrtpError.connect(
2136 this, &DataChannel::OnSrtpError);
2137 return true;
2138 }
2139
SendData(const SendDataParams & params,const rtc::Buffer & payload,SendDataResult * result)2140 bool DataChannel::SendData(const SendDataParams& params,
2141 const rtc::Buffer& payload,
2142 SendDataResult* result) {
2143 return InvokeOnWorker(Bind(&DataMediaChannel::SendData,
2144 media_channel(), params, payload, result));
2145 }
2146
GetFirstContent(const SessionDescription * sdesc)2147 const ContentInfo* DataChannel::GetFirstContent(
2148 const SessionDescription* sdesc) {
2149 return GetFirstDataContent(sdesc);
2150 }
2151
WantsPacket(bool rtcp,rtc::Buffer * packet)2152 bool DataChannel::WantsPacket(bool rtcp, rtc::Buffer* packet) {
2153 if (data_channel_type_ == DCT_SCTP) {
2154 // TODO(pthatcher): Do this in a more robust way by checking for
2155 // SCTP or DTLS.
2156 return !IsRtpPacket(packet->data(), packet->length());
2157 } else if (data_channel_type_ == DCT_RTP) {
2158 return BaseChannel::WantsPacket(rtcp, packet);
2159 }
2160 return false;
2161 }
2162
SetDataChannelType(DataChannelType new_data_channel_type,std::string * error_desc)2163 bool DataChannel::SetDataChannelType(DataChannelType new_data_channel_type,
2164 std::string* error_desc) {
2165 // It hasn't been set before, so set it now.
2166 if (data_channel_type_ == DCT_NONE) {
2167 data_channel_type_ = new_data_channel_type;
2168 return true;
2169 }
2170
2171 // It's been set before, but doesn't match. That's bad.
2172 if (data_channel_type_ != new_data_channel_type) {
2173 std::ostringstream desc;
2174 desc << "Data channel type mismatch."
2175 << " Expected " << data_channel_type_
2176 << " Got " << new_data_channel_type;
2177 SafeSetError(desc.str(), error_desc);
2178 return false;
2179 }
2180
2181 // It's hasn't changed. Nothing to do.
2182 return true;
2183 }
2184
SetDataChannelTypeFromContent(const DataContentDescription * content,std::string * error_desc)2185 bool DataChannel::SetDataChannelTypeFromContent(
2186 const DataContentDescription* content,
2187 std::string* error_desc) {
2188 bool is_sctp = ((content->protocol() == kMediaProtocolSctp) ||
2189 (content->protocol() == kMediaProtocolDtlsSctp));
2190 DataChannelType data_channel_type = is_sctp ? DCT_SCTP : DCT_RTP;
2191 return SetDataChannelType(data_channel_type, error_desc);
2192 }
2193
SetLocalContent_w(const MediaContentDescription * content,ContentAction action,std::string * error_desc)2194 bool DataChannel::SetLocalContent_w(const MediaContentDescription* content,
2195 ContentAction action,
2196 std::string* error_desc) {
2197 ASSERT(worker_thread() == rtc::Thread::Current());
2198 LOG(LS_INFO) << "Setting local data description";
2199
2200 const DataContentDescription* data =
2201 static_cast<const DataContentDescription*>(content);
2202 ASSERT(data != NULL);
2203 if (!data) {
2204 SafeSetError("Can't find data content in local description.", error_desc);
2205 return false;
2206 }
2207
2208 bool ret = false;
2209 if (!SetDataChannelTypeFromContent(data, error_desc)) {
2210 return false;
2211 }
2212
2213 if (data_channel_type_ == DCT_SCTP) {
2214 // SCTP data channels don't need the rest of the stuff.
2215 ret = UpdateLocalStreams_w(data->streams(), action, error_desc);
2216 if (ret) {
2217 set_local_content_direction(content->direction());
2218 // As in SetRemoteContent_w, make sure we set the local SCTP port
2219 // number as specified in our DataContentDescription.
2220 if (!media_channel()->SetRecvCodecs(data->codecs())) {
2221 SafeSetError("Failed to set data receive codecs.", error_desc);
2222 ret = false;
2223 }
2224 }
2225 } else {
2226 ret = SetBaseLocalContent_w(content, action, error_desc);
2227 if (action != CA_UPDATE || data->has_codecs()) {
2228 if (!media_channel()->SetRecvCodecs(data->codecs())) {
2229 SafeSetError("Failed to set data receive codecs.", error_desc);
2230 ret = false;
2231 }
2232 }
2233 }
2234
2235 // If everything worked, see if we can start receiving.
2236 if (ret) {
2237 std::vector<DataCodec>::const_iterator it = data->codecs().begin();
2238 for (; it != data->codecs().end(); ++it) {
2239 bundle_filter()->AddPayloadType(it->id);
2240 }
2241 ChangeState();
2242 } else {
2243 LOG(LS_WARNING) << "Failed to set local data description";
2244 }
2245 return ret;
2246 }
2247
SetRemoteContent_w(const MediaContentDescription * content,ContentAction action,std::string * error_desc)2248 bool DataChannel::SetRemoteContent_w(const MediaContentDescription* content,
2249 ContentAction action,
2250 std::string* error_desc) {
2251 ASSERT(worker_thread() == rtc::Thread::Current());
2252
2253 const DataContentDescription* data =
2254 static_cast<const DataContentDescription*>(content);
2255 ASSERT(data != NULL);
2256 if (!data) {
2257 SafeSetError("Can't find data content in remote description.", error_desc);
2258 return false;
2259 }
2260
2261 bool ret = true;
2262 if (!SetDataChannelTypeFromContent(data, error_desc)) {
2263 return false;
2264 }
2265
2266 if (data_channel_type_ == DCT_SCTP) {
2267 LOG(LS_INFO) << "Setting SCTP remote data description";
2268 // SCTP data channels don't need the rest of the stuff.
2269 ret = UpdateRemoteStreams_w(content->streams(), action, error_desc);
2270 if (ret) {
2271 set_remote_content_direction(content->direction());
2272 // We send the SCTP port number (not to be confused with the underlying
2273 // UDP port number) as a codec parameter. Make sure it gets there.
2274 if (!media_channel()->SetSendCodecs(data->codecs())) {
2275 SafeSetError("Failed to set data send codecs.", error_desc);
2276 ret = false;
2277 }
2278 }
2279 } else {
2280 // If the remote data doesn't have codecs and isn't an update, it
2281 // must be empty, so ignore it.
2282 if (action != CA_UPDATE && !data->has_codecs()) {
2283 return true;
2284 }
2285 LOG(LS_INFO) << "Setting remote data description";
2286
2287 // Set remote video codecs (what the other side wants to receive).
2288 if (action != CA_UPDATE || data->has_codecs()) {
2289 if (!media_channel()->SetSendCodecs(data->codecs())) {
2290 SafeSetError("Failed to set data send codecs.", error_desc);
2291 ret = false;
2292 }
2293 }
2294
2295 if (ret) {
2296 ret &= SetBaseRemoteContent_w(content, action, error_desc);
2297 }
2298
2299 if (action != CA_UPDATE) {
2300 int bandwidth_bps = data->bandwidth();
2301 if (!media_channel()->SetMaxSendBandwidth(bandwidth_bps)) {
2302 std::ostringstream desc;
2303 desc << "Failed to set max send bandwidth for data content.";
2304 SafeSetError(desc.str(), error_desc);
2305 ret = false;
2306 }
2307 }
2308 }
2309
2310 // If everything worked, see if we can start sending.
2311 if (ret) {
2312 ChangeState();
2313 } else {
2314 LOG(LS_WARNING) << "Failed to set remote data description";
2315 }
2316 return ret;
2317 }
2318
ChangeState()2319 void DataChannel::ChangeState() {
2320 // Render incoming data if we're the active call, and we have the local
2321 // content. We receive data on the default channel and multiplexed streams.
2322 bool recv = IsReadyToReceive();
2323 if (!media_channel()->SetReceive(recv)) {
2324 LOG(LS_ERROR) << "Failed to SetReceive on data channel";
2325 }
2326
2327 // Send outgoing data if we're the active call, we have the remote content,
2328 // and we have had some form of connectivity.
2329 bool send = IsReadyToSend();
2330 if (!media_channel()->SetSend(send)) {
2331 LOG(LS_ERROR) << "Failed to SetSend on data channel";
2332 }
2333
2334 // Trigger SignalReadyToSendData asynchronously.
2335 OnDataChannelReadyToSend(send);
2336
2337 LOG(LS_INFO) << "Changing data state, recv=" << recv << " send=" << send;
2338 }
2339
OnMessage(rtc::Message * pmsg)2340 void DataChannel::OnMessage(rtc::Message *pmsg) {
2341 switch (pmsg->message_id) {
2342 case MSG_READYTOSENDDATA: {
2343 DataChannelReadyToSendMessageData* data =
2344 static_cast<DataChannelReadyToSendMessageData*>(pmsg->pdata);
2345 ready_to_send_data_ = data->data();
2346 SignalReadyToSendData(ready_to_send_data_);
2347 delete data;
2348 break;
2349 }
2350 case MSG_DATARECEIVED: {
2351 DataReceivedMessageData* data =
2352 static_cast<DataReceivedMessageData*>(pmsg->pdata);
2353 SignalDataReceived(this, data->params, data->payload);
2354 delete data;
2355 break;
2356 }
2357 case MSG_CHANNEL_ERROR: {
2358 const DataChannelErrorMessageData* data =
2359 static_cast<DataChannelErrorMessageData*>(pmsg->pdata);
2360 SignalMediaError(this, data->ssrc, data->error);
2361 delete data;
2362 break;
2363 }
2364 case MSG_STREAMCLOSEDREMOTELY: {
2365 rtc::TypedMessageData<uint32>* data =
2366 static_cast<rtc::TypedMessageData<uint32>*>(pmsg->pdata);
2367 SignalStreamClosedRemotely(data->data());
2368 delete data;
2369 break;
2370 }
2371 default:
2372 BaseChannel::OnMessage(pmsg);
2373 break;
2374 }
2375 }
2376
OnConnectionMonitorUpdate(SocketMonitor * monitor,const std::vector<ConnectionInfo> & infos)2377 void DataChannel::OnConnectionMonitorUpdate(
2378 SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos) {
2379 SignalConnectionMonitor(this, infos);
2380 }
2381
StartMediaMonitor(int cms)2382 void DataChannel::StartMediaMonitor(int cms) {
2383 media_monitor_.reset(new DataMediaMonitor(media_channel(), worker_thread(),
2384 rtc::Thread::Current()));
2385 media_monitor_->SignalUpdate.connect(
2386 this, &DataChannel::OnMediaMonitorUpdate);
2387 media_monitor_->Start(cms);
2388 }
2389
StopMediaMonitor()2390 void DataChannel::StopMediaMonitor() {
2391 if (media_monitor_) {
2392 media_monitor_->Stop();
2393 media_monitor_->SignalUpdate.disconnect(this);
2394 media_monitor_.reset();
2395 }
2396 }
2397
OnMediaMonitorUpdate(DataMediaChannel * media_channel,const DataMediaInfo & info)2398 void DataChannel::OnMediaMonitorUpdate(
2399 DataMediaChannel* media_channel, const DataMediaInfo& info) {
2400 ASSERT(media_channel == this->media_channel());
2401 SignalMediaMonitor(this, info);
2402 }
2403
OnDataReceived(const ReceiveDataParams & params,const char * data,size_t len)2404 void DataChannel::OnDataReceived(
2405 const ReceiveDataParams& params, const char* data, size_t len) {
2406 DataReceivedMessageData* msg = new DataReceivedMessageData(
2407 params, data, len);
2408 signaling_thread()->Post(this, MSG_DATARECEIVED, msg);
2409 }
2410
OnDataChannelError(uint32 ssrc,DataMediaChannel::Error err)2411 void DataChannel::OnDataChannelError(
2412 uint32 ssrc, DataMediaChannel::Error err) {
2413 DataChannelErrorMessageData* data = new DataChannelErrorMessageData(
2414 ssrc, err);
2415 signaling_thread()->Post(this, MSG_CHANNEL_ERROR, data);
2416 }
2417
OnDataChannelReadyToSend(bool writable)2418 void DataChannel::OnDataChannelReadyToSend(bool writable) {
2419 // This is usded for congestion control to indicate that the stream is ready
2420 // to send by the MediaChannel, as opposed to OnReadyToSend, which indicates
2421 // that the transport channel is ready.
2422 signaling_thread()->Post(this, MSG_READYTOSENDDATA,
2423 new DataChannelReadyToSendMessageData(writable));
2424 }
2425
OnSrtpError(uint32 ssrc,SrtpFilter::Mode mode,SrtpFilter::Error error)2426 void DataChannel::OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode,
2427 SrtpFilter::Error error) {
2428 switch (error) {
2429 case SrtpFilter::ERROR_FAIL:
2430 OnDataChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
2431 DataMediaChannel::ERROR_SEND_SRTP_ERROR :
2432 DataMediaChannel::ERROR_RECV_SRTP_ERROR);
2433 break;
2434 case SrtpFilter::ERROR_AUTH:
2435 OnDataChannelError(ssrc, (mode == SrtpFilter::PROTECT) ?
2436 DataMediaChannel::ERROR_SEND_SRTP_AUTH_FAILED :
2437 DataMediaChannel::ERROR_RECV_SRTP_AUTH_FAILED);
2438 break;
2439 case SrtpFilter::ERROR_REPLAY:
2440 // Only receving channel should have this error.
2441 ASSERT(mode == SrtpFilter::UNPROTECT);
2442 OnDataChannelError(ssrc, DataMediaChannel::ERROR_RECV_SRTP_REPLAY);
2443 break;
2444 default:
2445 break;
2446 }
2447 }
2448
GetSrtpCiphers(std::vector<std::string> * ciphers) const2449 void DataChannel::GetSrtpCiphers(std::vector<std::string>* ciphers) const {
2450 GetSupportedDataCryptoSuites(ciphers);
2451 }
2452
ShouldSetupDtlsSrtp() const2453 bool DataChannel::ShouldSetupDtlsSrtp() const {
2454 return (data_channel_type_ == DCT_RTP);
2455 }
2456
OnStreamClosedRemotely(uint32 sid)2457 void DataChannel::OnStreamClosedRemotely(uint32 sid) {
2458 rtc::TypedMessageData<uint32>* message =
2459 new rtc::TypedMessageData<uint32>(sid);
2460 signaling_thread()->Post(this, MSG_STREAMCLOSEDREMOTELY, message);
2461 }
2462
2463 } // namespace cricket
2464