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