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

Side by Side Diff: webrtc/api/datachannel.cc

Issue 2514883002: Create //webrtc/api:libjingle_peerconnection_api + refactorings. (Closed)
Patch Set: Big move! Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * Copyright 2012 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 "webrtc/api/datachannel.h"
12
13 #include <memory>
14 #include <string>
15
16 #include "webrtc/api/sctputils.h"
17 #include "webrtc/base/logging.h"
18 #include "webrtc/base/refcount.h"
19 #include "webrtc/media/sctp/sctpdataengine.h"
20
21 namespace webrtc {
22
23 static size_t kMaxQueuedReceivedDataBytes = 16 * 1024 * 1024;
24 static size_t kMaxQueuedSendDataBytes = 16 * 1024 * 1024;
25
26 enum {
27 MSG_CHANNELREADY,
28 };
29
30 bool SctpSidAllocator::AllocateSid(rtc::SSLRole role, int* sid) {
31 int potential_sid = (role == rtc::SSL_CLIENT) ? 0 : 1;
32 while (!IsSidAvailable(potential_sid)) {
33 potential_sid += 2;
34 if (potential_sid > static_cast<int>(cricket::kMaxSctpSid)) {
35 return false;
36 }
37 }
38
39 *sid = potential_sid;
40 used_sids_.insert(potential_sid);
41 return true;
42 }
43
44 bool SctpSidAllocator::ReserveSid(int sid) {
45 if (!IsSidAvailable(sid)) {
46 return false;
47 }
48 used_sids_.insert(sid);
49 return true;
50 }
51
52 void SctpSidAllocator::ReleaseSid(int sid) {
53 auto it = used_sids_.find(sid);
54 if (it != used_sids_.end()) {
55 used_sids_.erase(it);
56 }
57 }
58
59 bool SctpSidAllocator::IsSidAvailable(int sid) const {
60 if (sid < static_cast<int>(cricket::kMinSctpSid) ||
61 sid > static_cast<int>(cricket::kMaxSctpSid)) {
62 return false;
63 }
64 return used_sids_.find(sid) == used_sids_.end();
65 }
66
67 DataChannel::PacketQueue::PacketQueue() : byte_count_(0) {}
68
69 DataChannel::PacketQueue::~PacketQueue() {
70 Clear();
71 }
72
73 bool DataChannel::PacketQueue::Empty() const {
74 return packets_.empty();
75 }
76
77 DataBuffer* DataChannel::PacketQueue::Front() {
78 return packets_.front();
79 }
80
81 void DataChannel::PacketQueue::Pop() {
82 if (packets_.empty()) {
83 return;
84 }
85
86 byte_count_ -= packets_.front()->size();
87 packets_.pop_front();
88 }
89
90 void DataChannel::PacketQueue::Push(DataBuffer* packet) {
91 byte_count_ += packet->size();
92 packets_.push_back(packet);
93 }
94
95 void DataChannel::PacketQueue::Clear() {
96 while (!packets_.empty()) {
97 delete packets_.front();
98 packets_.pop_front();
99 }
100 byte_count_ = 0;
101 }
102
103 void DataChannel::PacketQueue::Swap(PacketQueue* other) {
104 size_t other_byte_count = other->byte_count_;
105 other->byte_count_ = byte_count_;
106 byte_count_ = other_byte_count;
107
108 other->packets_.swap(packets_);
109 }
110
111 rtc::scoped_refptr<DataChannel> DataChannel::Create(
112 DataChannelProviderInterface* provider,
113 cricket::DataChannelType dct,
114 const std::string& label,
115 const InternalDataChannelInit& config) {
116 rtc::scoped_refptr<DataChannel> channel(
117 new rtc::RefCountedObject<DataChannel>(provider, dct, label));
118 if (!channel->Init(config)) {
119 return NULL;
120 }
121 return channel;
122 }
123
124 DataChannel::DataChannel(
125 DataChannelProviderInterface* provider,
126 cricket::DataChannelType dct,
127 const std::string& label)
128 : label_(label),
129 observer_(nullptr),
130 state_(kConnecting),
131 messages_sent_(0),
132 bytes_sent_(0),
133 messages_received_(0),
134 bytes_received_(0),
135 data_channel_type_(dct),
136 provider_(provider),
137 handshake_state_(kHandshakeInit),
138 connected_to_provider_(false),
139 send_ssrc_set_(false),
140 receive_ssrc_set_(false),
141 writable_(false),
142 send_ssrc_(0),
143 receive_ssrc_(0) {
144 }
145
146 bool DataChannel::Init(const InternalDataChannelInit& config) {
147 if (data_channel_type_ == cricket::DCT_RTP) {
148 if (config.reliable ||
149 config.id != -1 ||
150 config.maxRetransmits != -1 ||
151 config.maxRetransmitTime != -1) {
152 LOG(LS_ERROR) << "Failed to initialize the RTP data channel due to "
153 << "invalid DataChannelInit.";
154 return false;
155 }
156 handshake_state_ = kHandshakeReady;
157 } else if (data_channel_type_ == cricket::DCT_SCTP) {
158 if (config.id < -1 ||
159 config.maxRetransmits < -1 ||
160 config.maxRetransmitTime < -1) {
161 LOG(LS_ERROR) << "Failed to initialize the SCTP data channel due to "
162 << "invalid DataChannelInit.";
163 return false;
164 }
165 if (config.maxRetransmits != -1 && config.maxRetransmitTime != -1) {
166 LOG(LS_ERROR) <<
167 "maxRetransmits and maxRetransmitTime should not be both set.";
168 return false;
169 }
170 config_ = config;
171
172 switch (config_.open_handshake_role) {
173 case webrtc::InternalDataChannelInit::kNone: // pre-negotiated
174 handshake_state_ = kHandshakeReady;
175 break;
176 case webrtc::InternalDataChannelInit::kOpener:
177 handshake_state_ = kHandshakeShouldSendOpen;
178 break;
179 case webrtc::InternalDataChannelInit::kAcker:
180 handshake_state_ = kHandshakeShouldSendAck;
181 break;
182 };
183
184 // Try to connect to the transport in case the transport channel already
185 // exists.
186 OnTransportChannelCreated();
187
188 // Checks if the transport is ready to send because the initial channel
189 // ready signal may have been sent before the DataChannel creation.
190 // This has to be done async because the upper layer objects (e.g.
191 // Chrome glue and WebKit) are not wired up properly until after this
192 // function returns.
193 if (provider_->ReadyToSendData()) {
194 rtc::Thread::Current()->Post(RTC_FROM_HERE, this, MSG_CHANNELREADY, NULL);
195 }
196 }
197
198 return true;
199 }
200
201 DataChannel::~DataChannel() {}
202
203 void DataChannel::RegisterObserver(DataChannelObserver* observer) {
204 observer_ = observer;
205 DeliverQueuedReceivedData();
206 }
207
208 void DataChannel::UnregisterObserver() {
209 observer_ = NULL;
210 }
211
212 bool DataChannel::reliable() const {
213 if (data_channel_type_ == cricket::DCT_RTP) {
214 return false;
215 } else {
216 return config_.maxRetransmits == -1 &&
217 config_.maxRetransmitTime == -1;
218 }
219 }
220
221 uint64_t DataChannel::buffered_amount() const {
222 return queued_send_data_.byte_count();
223 }
224
225 void DataChannel::Close() {
226 if (state_ == kClosed)
227 return;
228 send_ssrc_ = 0;
229 send_ssrc_set_ = false;
230 SetState(kClosing);
231 UpdateState();
232 }
233
234 bool DataChannel::Send(const DataBuffer& buffer) {
235 if (state_ != kOpen) {
236 return false;
237 }
238
239 // TODO(jiayl): the spec is unclear about if the remote side should get the
240 // onmessage event. We need to figure out the expected behavior and change the
241 // code accordingly.
242 if (buffer.size() == 0) {
243 return true;
244 }
245
246 // If the queue is non-empty, we're waiting for SignalReadyToSend,
247 // so just add to the end of the queue and keep waiting.
248 if (!queued_send_data_.Empty()) {
249 // Only SCTP DataChannel queues the outgoing data when the transport is
250 // blocked.
251 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
252 if (!QueueSendDataMessage(buffer)) {
253 Close();
254 }
255 return true;
256 }
257
258 bool success = SendDataMessage(buffer, true);
259 if (data_channel_type_ == cricket::DCT_RTP) {
260 return success;
261 }
262
263 // Always return true for SCTP DataChannel per the spec.
264 return true;
265 }
266
267 void DataChannel::SetReceiveSsrc(uint32_t receive_ssrc) {
268 ASSERT(data_channel_type_ == cricket::DCT_RTP);
269
270 if (receive_ssrc_set_) {
271 return;
272 }
273 receive_ssrc_ = receive_ssrc;
274 receive_ssrc_set_ = true;
275 UpdateState();
276 }
277
278 // The remote peer request that this channel shall be closed.
279 void DataChannel::RemotePeerRequestClose() {
280 DoClose();
281 }
282
283 void DataChannel::SetSctpSid(int sid) {
284 ASSERT(config_.id < 0 && sid >= 0 && data_channel_type_ == cricket::DCT_SCTP);
285 if (config_.id == sid) {
286 return;
287 }
288
289 config_.id = sid;
290 provider_->AddSctpDataStream(sid);
291 }
292
293 void DataChannel::OnTransportChannelCreated() {
294 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
295 if (!connected_to_provider_) {
296 connected_to_provider_ = provider_->ConnectDataChannel(this);
297 }
298 // The sid may have been unassigned when provider_->ConnectDataChannel was
299 // done. So always add the streams even if connected_to_provider_ is true.
300 if (config_.id >= 0) {
301 provider_->AddSctpDataStream(config_.id);
302 }
303 }
304
305 void DataChannel::OnTransportChannelDestroyed() {
306 // This method needs to synchronously close the data channel, which means any
307 // queued data needs to be discarded.
308 queued_send_data_.Clear();
309 queued_control_data_.Clear();
310 DoClose();
311 }
312
313 void DataChannel::SetSendSsrc(uint32_t send_ssrc) {
314 ASSERT(data_channel_type_ == cricket::DCT_RTP);
315 if (send_ssrc_set_) {
316 return;
317 }
318 send_ssrc_ = send_ssrc;
319 send_ssrc_set_ = true;
320 UpdateState();
321 }
322
323 void DataChannel::OnMessage(rtc::Message* msg) {
324 switch (msg->message_id) {
325 case MSG_CHANNELREADY:
326 OnChannelReady(true);
327 break;
328 }
329 }
330
331 void DataChannel::OnDataReceived(cricket::DataChannel* channel,
332 const cricket::ReceiveDataParams& params,
333 const rtc::CopyOnWriteBuffer& payload) {
334 uint32_t expected_ssrc =
335 (data_channel_type_ == cricket::DCT_RTP) ? receive_ssrc_ : config_.id;
336 if (params.ssrc != expected_ssrc) {
337 return;
338 }
339
340 if (params.type == cricket::DMT_CONTROL) {
341 ASSERT(data_channel_type_ == cricket::DCT_SCTP);
342 if (handshake_state_ != kHandshakeWaitingForAck) {
343 // Ignore it if we are not expecting an ACK message.
344 LOG(LS_WARNING) << "DataChannel received unexpected CONTROL message, "
345 << "sid = " << params.ssrc;
346 return;
347 }
348 if (ParseDataChannelOpenAckMessage(payload)) {
349 // We can send unordered as soon as we receive the ACK message.
350 handshake_state_ = kHandshakeReady;
351 LOG(LS_INFO) << "DataChannel received OPEN_ACK message, sid = "
352 << params.ssrc;
353 } else {
354 LOG(LS_WARNING) << "DataChannel failed to parse OPEN_ACK message, sid = "
355 << params.ssrc;
356 }
357 return;
358 }
359
360 ASSERT(params.type == cricket::DMT_BINARY ||
361 params.type == cricket::DMT_TEXT);
362
363 LOG(LS_VERBOSE) << "DataChannel received DATA message, sid = " << params.ssrc;
364 // We can send unordered as soon as we receive any DATA message since the
365 // remote side must have received the OPEN (and old clients do not send
366 // OPEN_ACK).
367 if (handshake_state_ == kHandshakeWaitingForAck) {
368 handshake_state_ = kHandshakeReady;
369 }
370
371 bool binary = (params.type == cricket::DMT_BINARY);
372 std::unique_ptr<DataBuffer> buffer(new DataBuffer(payload, binary));
373 if (state_ == kOpen && observer_) {
374 ++messages_received_;
375 bytes_received_ += buffer->size();
376 observer_->OnMessage(*buffer.get());
377 } else {
378 if (queued_received_data_.byte_count() + payload.size() >
379 kMaxQueuedReceivedDataBytes) {
380 LOG(LS_ERROR) << "Queued received data exceeds the max buffer size.";
381
382 queued_received_data_.Clear();
383 if (data_channel_type_ != cricket::DCT_RTP) {
384 Close();
385 }
386
387 return;
388 }
389 queued_received_data_.Push(buffer.release());
390 }
391 }
392
393 void DataChannel::OnStreamClosedRemotely(uint32_t sid) {
394 if (data_channel_type_ == cricket::DCT_SCTP &&
395 sid == static_cast<uint32_t>(config_.id)) {
396 Close();
397 }
398 }
399
400 void DataChannel::OnChannelReady(bool writable) {
401 writable_ = writable;
402 if (!writable) {
403 return;
404 }
405
406 SendQueuedControlMessages();
407 SendQueuedDataMessages();
408 UpdateState();
409 }
410
411 void DataChannel::DoClose() {
412 if (state_ == kClosed)
413 return;
414
415 receive_ssrc_set_ = false;
416 send_ssrc_set_ = false;
417 SetState(kClosing);
418 UpdateState();
419 }
420
421 void DataChannel::UpdateState() {
422 // UpdateState determines what to do from a few state variables. Include
423 // all conditions required for each state transition here for
424 // clarity. OnChannelReady(true) will send any queued data and then invoke
425 // UpdateState().
426 switch (state_) {
427 case kConnecting: {
428 if (send_ssrc_set_ == receive_ssrc_set_) {
429 if (data_channel_type_ == cricket::DCT_RTP && !connected_to_provider_) {
430 connected_to_provider_ = provider_->ConnectDataChannel(this);
431 }
432 if (connected_to_provider_) {
433 if (handshake_state_ == kHandshakeShouldSendOpen) {
434 rtc::CopyOnWriteBuffer payload;
435 WriteDataChannelOpenMessage(label_, config_, &payload);
436 SendControlMessage(payload);
437 } else if (handshake_state_ == kHandshakeShouldSendAck) {
438 rtc::CopyOnWriteBuffer payload;
439 WriteDataChannelOpenAckMessage(&payload);
440 SendControlMessage(payload);
441 }
442 if (writable_ &&
443 (handshake_state_ == kHandshakeReady ||
444 handshake_state_ == kHandshakeWaitingForAck)) {
445 SetState(kOpen);
446 // If we have received buffers before the channel got writable.
447 // Deliver them now.
448 DeliverQueuedReceivedData();
449 }
450 }
451 }
452 break;
453 }
454 case kOpen: {
455 break;
456 }
457 case kClosing: {
458 if (queued_send_data_.Empty() && queued_control_data_.Empty()) {
459 if (connected_to_provider_) {
460 DisconnectFromProvider();
461 }
462
463 if (!connected_to_provider_ && !send_ssrc_set_ && !receive_ssrc_set_) {
464 SetState(kClosed);
465 }
466 }
467 break;
468 }
469 case kClosed:
470 break;
471 }
472 }
473
474 void DataChannel::SetState(DataState state) {
475 if (state_ == state) {
476 return;
477 }
478
479 state_ = state;
480 if (observer_) {
481 observer_->OnStateChange();
482 }
483 if (state_ == kOpen) {
484 SignalOpened(this);
485 } else if (state_ == kClosed) {
486 SignalClosed(this);
487 }
488 }
489
490 void DataChannel::DisconnectFromProvider() {
491 if (!connected_to_provider_)
492 return;
493
494 provider_->DisconnectDataChannel(this);
495 connected_to_provider_ = false;
496
497 if (data_channel_type_ == cricket::DCT_SCTP && config_.id >= 0) {
498 provider_->RemoveSctpDataStream(config_.id);
499 }
500 }
501
502 void DataChannel::DeliverQueuedReceivedData() {
503 if (!observer_) {
504 return;
505 }
506
507 while (!queued_received_data_.Empty()) {
508 std::unique_ptr<DataBuffer> buffer(queued_received_data_.Front());
509 ++messages_received_;
510 bytes_received_ += buffer->size();
511 observer_->OnMessage(*buffer);
512 queued_received_data_.Pop();
513 }
514 }
515
516 void DataChannel::SendQueuedDataMessages() {
517 if (queued_send_data_.Empty()) {
518 return;
519 }
520
521 ASSERT(state_ == kOpen || state_ == kClosing);
522
523 uint64_t start_buffered_amount = buffered_amount();
524 while (!queued_send_data_.Empty()) {
525 DataBuffer* buffer = queued_send_data_.Front();
526 if (!SendDataMessage(*buffer, false)) {
527 // Leave the message in the queue if sending is aborted.
528 break;
529 }
530 queued_send_data_.Pop();
531 delete buffer;
532 }
533
534 if (observer_ && buffered_amount() < start_buffered_amount) {
535 observer_->OnBufferedAmountChange(start_buffered_amount);
536 }
537 }
538
539 bool DataChannel::SendDataMessage(const DataBuffer& buffer,
540 bool queue_if_blocked) {
541 cricket::SendDataParams send_params;
542
543 if (data_channel_type_ == cricket::DCT_SCTP) {
544 send_params.ordered = config_.ordered;
545 // Send as ordered if it is still going through OPEN/ACK signaling.
546 if (handshake_state_ != kHandshakeReady && !config_.ordered) {
547 send_params.ordered = true;
548 LOG(LS_VERBOSE) << "Sending data as ordered for unordered DataChannel "
549 << "because the OPEN_ACK message has not been received.";
550 }
551
552 send_params.max_rtx_count = config_.maxRetransmits;
553 send_params.max_rtx_ms = config_.maxRetransmitTime;
554 send_params.ssrc = config_.id;
555 } else {
556 send_params.ssrc = send_ssrc_;
557 }
558 send_params.type = buffer.binary ? cricket::DMT_BINARY : cricket::DMT_TEXT;
559
560 cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
561 bool success = provider_->SendData(send_params, buffer.data, &send_result);
562
563 if (success) {
564 ++messages_sent_;
565 bytes_sent_ += buffer.size();
566 return true;
567 }
568
569 if (data_channel_type_ != cricket::DCT_SCTP) {
570 return false;
571 }
572
573 if (send_result == cricket::SDR_BLOCK) {
574 if (!queue_if_blocked || QueueSendDataMessage(buffer)) {
575 return false;
576 }
577 }
578 // Close the channel if the error is not SDR_BLOCK, or if queuing the
579 // message failed.
580 LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send data, "
581 << "send_result = " << send_result;
582 Close();
583
584 return false;
585 }
586
587 bool DataChannel::QueueSendDataMessage(const DataBuffer& buffer) {
588 size_t start_buffered_amount = buffered_amount();
589 if (start_buffered_amount >= kMaxQueuedSendDataBytes) {
590 LOG(LS_ERROR) << "Can't buffer any more data for the data channel.";
591 return false;
592 }
593 queued_send_data_.Push(new DataBuffer(buffer));
594
595 // The buffer can have length zero, in which case there is no change.
596 if (observer_ && buffered_amount() > start_buffered_amount) {
597 observer_->OnBufferedAmountChange(start_buffered_amount);
598 }
599 return true;
600 }
601
602 void DataChannel::SendQueuedControlMessages() {
603 PacketQueue control_packets;
604 control_packets.Swap(&queued_control_data_);
605
606 while (!control_packets.Empty()) {
607 std::unique_ptr<DataBuffer> buf(control_packets.Front());
608 SendControlMessage(buf->data);
609 control_packets.Pop();
610 }
611 }
612
613 void DataChannel::QueueControlMessage(const rtc::CopyOnWriteBuffer& buffer) {
614 queued_control_data_.Push(new DataBuffer(buffer, true));
615 }
616
617 bool DataChannel::SendControlMessage(const rtc::CopyOnWriteBuffer& buffer) {
618 bool is_open_message = handshake_state_ == kHandshakeShouldSendOpen;
619
620 ASSERT(data_channel_type_ == cricket::DCT_SCTP &&
621 writable_ &&
622 config_.id >= 0 &&
623 (!is_open_message || !config_.negotiated));
624
625 cricket::SendDataParams send_params;
626 send_params.ssrc = config_.id;
627 // Send data as ordered before we receive any message from the remote peer to
628 // make sure the remote peer will not receive any data before it receives the
629 // OPEN message.
630 send_params.ordered = config_.ordered || is_open_message;
631 send_params.type = cricket::DMT_CONTROL;
632
633 cricket::SendDataResult send_result = cricket::SDR_SUCCESS;
634 bool retval = provider_->SendData(send_params, buffer, &send_result);
635 if (retval) {
636 LOG(LS_INFO) << "Sent CONTROL message on channel " << config_.id;
637
638 if (handshake_state_ == kHandshakeShouldSendAck) {
639 handshake_state_ = kHandshakeReady;
640 } else if (handshake_state_ == kHandshakeShouldSendOpen) {
641 handshake_state_ = kHandshakeWaitingForAck;
642 }
643 } else if (send_result == cricket::SDR_BLOCK) {
644 QueueControlMessage(buffer);
645 } else {
646 LOG(LS_ERROR) << "Closing the DataChannel due to a failure to send"
647 << " the CONTROL message, send_result = " << send_result;
648 Close();
649 }
650 return retval;
651 }
652
653 } // namespace webrtc
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698