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