Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(138)

Side by Side Diff: talk/session/media/channel.cc

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

Powered by Google App Engine
This is Rietveld 408576698