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