1 /*
2  *  Copyright (c) 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 "media/base/rtpdataengine.h"
12 
13 #include <map>
14 
15 #include "media/base/codec.h"
16 #include "media/base/mediaconstants.h"
17 #include "media/base/rtputils.h"
18 #include "media/base/streamparams.h"
19 #include "rtc_base/copyonwritebuffer.h"
20 #include "rtc_base/helpers.h"
21 #include "rtc_base/logging.h"
22 #include "rtc_base/ratelimiter.h"
23 #include "rtc_base/sanitizer.h"
24 #include "rtc_base/stringutils.h"
25 
26 namespace cricket {
27 
28 // We want to avoid IP fragmentation.
29 static const size_t kDataMaxRtpPacketLen = 1200U;
30 // We reserve space after the RTP header for future wiggle room.
31 static const unsigned char kReservedSpace[] = {
32   0x00, 0x00, 0x00, 0x00
33 };
34 
35 // Amount of overhead SRTP may take.  We need to leave room in the
36 // buffer for it, otherwise SRTP will fail later.  If SRTP ever uses
37 // more than this, we need to increase this number.
38 static const size_t kMaxSrtpHmacOverhead = 16;
39 
RtpDataEngine()40 RtpDataEngine::RtpDataEngine() {
41   data_codecs_.push_back(
42       DataCodec(kGoogleRtpDataCodecPlType, kGoogleRtpDataCodecName));
43 }
44 
CreateChannel(const MediaConfig & config)45 DataMediaChannel* RtpDataEngine::CreateChannel(
46     const MediaConfig& config) {
47   return new RtpDataMediaChannel(config);
48 }
49 
FindCodecByName(const std::vector<DataCodec> & codecs,const std::string & name)50 static const DataCodec* FindCodecByName(const std::vector<DataCodec>& codecs,
51                                         const std::string& name) {
52   for (const DataCodec& codec : codecs) {
53     if (_stricmp(name.c_str(), codec.name.c_str()) == 0)
54       return &codec;
55   }
56   return nullptr;
57 }
58 
RtpDataMediaChannel(const MediaConfig & config)59 RtpDataMediaChannel::RtpDataMediaChannel(const MediaConfig& config)
60     : DataMediaChannel(config) {
61   Construct();
62 }
63 
Construct()64 void RtpDataMediaChannel::Construct() {
65   sending_ = false;
66   receiving_ = false;
67   send_limiter_.reset(new rtc::RateLimiter(kDataMaxBandwidth / 8, 1.0));
68 }
69 
70 
~RtpDataMediaChannel()71 RtpDataMediaChannel::~RtpDataMediaChannel() {
72   std::map<uint32_t, RtpClock*>::const_iterator iter;
73   for (iter = rtp_clock_by_send_ssrc_.begin();
74        iter != rtp_clock_by_send_ssrc_.end();
75        ++iter) {
76     delete iter->second;
77   }
78 }
79 
80 void RTC_NO_SANITIZE("float-cast-overflow")  // bugs.webrtc.org/8204
Tick(double now,int * seq_num,uint32_t * timestamp)81 RtpClock::Tick(double now, int* seq_num, uint32_t* timestamp) {
82   *seq_num = ++last_seq_num_;
83   *timestamp = timestamp_offset_ + static_cast<uint32_t>(now * clockrate_);
84   // UBSan: 5.92374e+10 is outside the range of representable values of type
85   // 'unsigned int'
86 }
87 
FindUnknownCodec(const std::vector<DataCodec> & codecs)88 const DataCodec* FindUnknownCodec(const std::vector<DataCodec>& codecs) {
89   DataCodec data_codec(kGoogleRtpDataCodecPlType, kGoogleRtpDataCodecName);
90   std::vector<DataCodec>::const_iterator iter;
91   for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
92     if (!iter->Matches(data_codec)) {
93       return &(*iter);
94     }
95   }
96   return NULL;
97 }
98 
FindKnownCodec(const std::vector<DataCodec> & codecs)99 const DataCodec* FindKnownCodec(const std::vector<DataCodec>& codecs) {
100   DataCodec data_codec(kGoogleRtpDataCodecPlType, kGoogleRtpDataCodecName);
101   std::vector<DataCodec>::const_iterator iter;
102   for (iter = codecs.begin(); iter != codecs.end(); ++iter) {
103     if (iter->Matches(data_codec)) {
104       return &(*iter);
105     }
106   }
107   return NULL;
108 }
109 
SetRecvCodecs(const std::vector<DataCodec> & codecs)110 bool RtpDataMediaChannel::SetRecvCodecs(const std::vector<DataCodec>& codecs) {
111   const DataCodec* unknown_codec = FindUnknownCodec(codecs);
112   if (unknown_codec) {
113     RTC_LOG(LS_WARNING) << "Failed to SetRecvCodecs because of unknown codec: "
114                         << unknown_codec->ToString();
115     return false;
116   }
117 
118   recv_codecs_ = codecs;
119   return true;
120 }
121 
SetSendCodecs(const std::vector<DataCodec> & codecs)122 bool RtpDataMediaChannel::SetSendCodecs(const std::vector<DataCodec>& codecs) {
123   const DataCodec* known_codec = FindKnownCodec(codecs);
124   if (!known_codec) {
125     RTC_LOG(LS_WARNING)
126         << "Failed to SetSendCodecs because there is no known codec.";
127     return false;
128   }
129 
130   send_codecs_ = codecs;
131   return true;
132 }
133 
SetSendParameters(const DataSendParameters & params)134 bool RtpDataMediaChannel::SetSendParameters(const DataSendParameters& params) {
135   return (SetSendCodecs(params.codecs) &&
136           SetMaxSendBandwidth(params.max_bandwidth_bps));
137 }
138 
SetRecvParameters(const DataRecvParameters & params)139 bool RtpDataMediaChannel::SetRecvParameters(const DataRecvParameters& params) {
140   return SetRecvCodecs(params.codecs);
141 }
142 
AddSendStream(const StreamParams & stream)143 bool RtpDataMediaChannel::AddSendStream(const StreamParams& stream) {
144   if (!stream.has_ssrcs()) {
145     return false;
146   }
147 
148   if (GetStreamBySsrc(send_streams_, stream.first_ssrc())) {
149     RTC_LOG(LS_WARNING) << "Not adding data send stream '" << stream.id
150                         << "' with ssrc=" << stream.first_ssrc()
151                         << " because stream already exists.";
152     return false;
153   }
154 
155   send_streams_.push_back(stream);
156   // TODO(pthatcher): This should be per-stream, not per-ssrc.
157   // And we should probably allow more than one per stream.
158   rtp_clock_by_send_ssrc_[stream.first_ssrc()] = new RtpClock(
159       kDataCodecClockrate,
160       rtc::CreateRandomNonZeroId(), rtc::CreateRandomNonZeroId());
161 
162   RTC_LOG(LS_INFO) << "Added data send stream '" << stream.id
163                    << "' with ssrc=" << stream.first_ssrc();
164   return true;
165 }
166 
RemoveSendStream(uint32_t ssrc)167 bool RtpDataMediaChannel::RemoveSendStream(uint32_t ssrc) {
168   if (!GetStreamBySsrc(send_streams_, ssrc)) {
169     return false;
170   }
171 
172   RemoveStreamBySsrc(&send_streams_, ssrc);
173   delete rtp_clock_by_send_ssrc_[ssrc];
174   rtp_clock_by_send_ssrc_.erase(ssrc);
175   return true;
176 }
177 
AddRecvStream(const StreamParams & stream)178 bool RtpDataMediaChannel::AddRecvStream(const StreamParams& stream) {
179   if (!stream.has_ssrcs()) {
180     return false;
181   }
182 
183   if (GetStreamBySsrc(recv_streams_, stream.first_ssrc())) {
184     RTC_LOG(LS_WARNING) << "Not adding data recv stream '" << stream.id
185                         << "' with ssrc=" << stream.first_ssrc()
186                         << " because stream already exists.";
187     return false;
188   }
189 
190   recv_streams_.push_back(stream);
191   RTC_LOG(LS_INFO) << "Added data recv stream '" << stream.id
192                    << "' with ssrc=" << stream.first_ssrc();
193   return true;
194 }
195 
RemoveRecvStream(uint32_t ssrc)196 bool RtpDataMediaChannel::RemoveRecvStream(uint32_t ssrc) {
197   RemoveStreamBySsrc(&recv_streams_, ssrc);
198   return true;
199 }
200 
OnPacketReceived(rtc::CopyOnWriteBuffer * packet,const rtc::PacketTime & packet_time)201 void RtpDataMediaChannel::OnPacketReceived(
202     rtc::CopyOnWriteBuffer* packet, const rtc::PacketTime& packet_time) {
203   RtpHeader header;
204   if (!GetRtpHeader(packet->cdata(), packet->size(), &header)) {
205     // Don't want to log for every corrupt packet.
206     // RTC_LOG(LS_WARNING) << "Could not read rtp header from packet of length "
207     //                 << packet->length() << ".";
208     return;
209   }
210 
211   size_t header_length;
212   if (!GetRtpHeaderLen(packet->cdata(), packet->size(), &header_length)) {
213     // Don't want to log for every corrupt packet.
214     // RTC_LOG(LS_WARNING) << "Could not read rtp header"
215     //                 << length from packet of length "
216     //                 << packet->length() << ".";
217     return;
218   }
219   const char* data =
220       packet->cdata<char>() + header_length + sizeof(kReservedSpace);
221   size_t data_len = packet->size() - header_length - sizeof(kReservedSpace);
222 
223   if (!receiving_) {
224     RTC_LOG(LS_WARNING) << "Not receiving packet " << header.ssrc << ":"
225                         << header.seq_num << " before SetReceive(true) called.";
226     return;
227   }
228 
229   if (!FindCodecById(recv_codecs_, header.payload_type)) {
230     // For bundling, this will be logged for every message.
231     // So disable this logging.
232     // RTC_LOG(LS_WARNING) << "Not receiving packet "
233     //                << header.ssrc << ":" << header.seq_num
234     //                << " (" << data_len << ")"
235     //                << " because unknown payload id: " << header.payload_type;
236     return;
237   }
238 
239   if (!GetStreamBySsrc(recv_streams_, header.ssrc)) {
240     RTC_LOG(LS_WARNING) << "Received packet for unknown ssrc: " << header.ssrc;
241     return;
242   }
243 
244   // Uncomment this for easy debugging.
245   // const auto* found_stream = GetStreamBySsrc(recv_streams_, header.ssrc);
246   // RTC_LOG(LS_INFO) << "Received packet"
247   //              << " groupid=" << found_stream.groupid
248   //              << ", ssrc=" << header.ssrc
249   //              << ", seqnum=" << header.seq_num
250   //              << ", timestamp=" << header.timestamp
251   //              << ", len=" << data_len;
252 
253   ReceiveDataParams params;
254   params.ssrc = header.ssrc;
255   params.seq_num = header.seq_num;
256   params.timestamp = header.timestamp;
257   SignalDataReceived(params, data, data_len);
258 }
259 
SetMaxSendBandwidth(int bps)260 bool RtpDataMediaChannel::SetMaxSendBandwidth(int bps) {
261   if (bps <= 0) {
262     bps = kDataMaxBandwidth;
263   }
264   send_limiter_.reset(new rtc::RateLimiter(bps / 8, 1.0));
265   RTC_LOG(LS_INFO) << "RtpDataMediaChannel::SetSendBandwidth to " << bps
266                    << "bps.";
267   return true;
268 }
269 
SendData(const SendDataParams & params,const rtc::CopyOnWriteBuffer & payload,SendDataResult * result)270 bool RtpDataMediaChannel::SendData(
271     const SendDataParams& params,
272     const rtc::CopyOnWriteBuffer& payload,
273     SendDataResult* result) {
274   if (result) {
275     // If we return true, we'll set this to SDR_SUCCESS.
276     *result = SDR_ERROR;
277   }
278   if (!sending_) {
279     RTC_LOG(LS_WARNING) << "Not sending packet with ssrc=" << params.ssrc
280                         << " len=" << payload.size()
281                         << " before SetSend(true).";
282     return false;
283   }
284 
285   if (params.type != cricket::DMT_TEXT) {
286     RTC_LOG(LS_WARNING)
287         << "Not sending data because binary type is unsupported.";
288     return false;
289   }
290 
291   const StreamParams* found_stream =
292       GetStreamBySsrc(send_streams_, params.ssrc);
293   if (!found_stream) {
294     RTC_LOG(LS_WARNING) << "Not sending data because ssrc is unknown: "
295                         << params.ssrc;
296     return false;
297   }
298 
299   const DataCodec* found_codec =
300       FindCodecByName(send_codecs_, kGoogleRtpDataCodecName);
301   if (!found_codec) {
302     RTC_LOG(LS_WARNING) << "Not sending data because codec is unknown: "
303                         << kGoogleRtpDataCodecName;
304     return false;
305   }
306 
307   size_t packet_len = (kMinRtpPacketLen + sizeof(kReservedSpace) +
308                        payload.size() + kMaxSrtpHmacOverhead);
309   if (packet_len > kDataMaxRtpPacketLen) {
310     return false;
311   }
312 
313   double now =
314       rtc::TimeMicros() / static_cast<double>(rtc::kNumMicrosecsPerSec);
315 
316   if (!send_limiter_->CanUse(packet_len, now)) {
317     RTC_LOG(LS_VERBOSE) << "Dropped data packet of len=" << packet_len
318                         << "; already sent " << send_limiter_->used_in_period()
319                         << "/" << send_limiter_->max_per_period();
320     return false;
321   }
322 
323   RtpHeader header;
324   header.payload_type = found_codec->id;
325   header.ssrc = params.ssrc;
326   rtp_clock_by_send_ssrc_[header.ssrc]->Tick(
327       now, &header.seq_num, &header.timestamp);
328 
329   rtc::CopyOnWriteBuffer packet(kMinRtpPacketLen, packet_len);
330   if (!SetRtpHeader(packet.data(), packet.size(), header)) {
331     return false;
332   }
333   packet.AppendData(kReservedSpace);
334   packet.AppendData(payload);
335 
336   RTC_LOG(LS_VERBOSE) << "Sent RTP data packet: "
337                       << " stream=" << found_stream->id
338                       << " ssrc=" << header.ssrc
339                       << ", seqnum=" << header.seq_num
340                       << ", timestamp=" << header.timestamp
341                       << ", len=" << payload.size();
342 
343   MediaChannel::SendPacket(&packet, rtc::PacketOptions());
344   send_limiter_->Use(packet_len, now);
345   if (result) {
346     *result = SDR_SUCCESS;
347   }
348   return true;
349 }
350 
PreferredDscp() const351 rtc::DiffServCodePoint RtpDataMediaChannel::PreferredDscp() const {
352   return rtc::DSCP_AF41;
353 }
354 
355 }  // namespace cricket
356