1f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org/*
2f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * libjingle
3f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * Copyright 2010 Google Inc.
4f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *
5f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * Redistribution and use in source and binary forms, with or without
6f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * modification, are permitted provided that the following conditions are met:
7f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *
8f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *  1. Redistributions of source code must retain the above copyright notice,
9f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *     this list of conditions and the following disclaimer.
10f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *  2. Redistributions in binary form must reproduce the above copyright notice,
11f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *     this list of conditions and the following disclaimer in the documentation
12f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *     and/or other materials provided with the distribution.
13f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *  3. The name of the author may not be used to endorse or promote products
14f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *     derived from this software without specific prior written permission.
15f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org *
16f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org */
27f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
28f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "talk/media/base/rtpdump.h"
29f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
30f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <ctype.h>
31f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
32f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <string>
33f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
34f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "talk/media/base/rtputils.h"
35f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "webrtc/base/byteorder.h"
36f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "webrtc/base/logging.h"
37f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "webrtc/base/timeutils.h"
38f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
39f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgnamespace {
40f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic const int kRtpSsrcOffset = 8;
41f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgconst int  kWarnSlowWritesDelayMs = 50;
42f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}  // namespace
43f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
44f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgnamespace cricket {
45f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
46f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgconst char RtpDumpFileHeader::kFirstLine[] = "#!rtpplay1.0 0.0.0.0/0\n";
47f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
48f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgRtpDumpFileHeader::RtpDumpFileHeader(uint32 start_ms, uint32 s, uint16 p)
49f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org    : start_sec(start_ms / 1000),
50f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org      start_usec(start_ms % 1000 * 1000),
51f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org      source(s),
52f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org      port(p),
53f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org      padding(0) {
54f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
55f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
56f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgvoid RtpDumpFileHeader::WriteToByteBuffer(rtc::ByteBuffer* buf) {
57f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  buf->WriteUInt32(start_sec);
58f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  buf->WriteUInt32(start_usec);
59f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  buf->WriteUInt32(source);
60f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  buf->WriteUInt16(port);
61f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org  buf->WriteUInt16(padding);
62f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org}
63f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
64f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.orgstatic const uint32 kDefaultTimeIncrease = 30;
65f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
66bool RtpDumpPacket::IsValidRtpPacket() const {
67  return original_data_len >= data.size() &&
68      data.size() >= kMinRtpPacketLen;
69}
70
71bool RtpDumpPacket::IsValidRtcpPacket() const {
72  return original_data_len == 0 &&
73      data.size() >= kMinRtcpPacketLen;
74}
75
76bool RtpDumpPacket::GetRtpPayloadType(int* pt) const {
77  return IsValidRtpPacket() &&
78      cricket::GetRtpPayloadType(&data[0], data.size(), pt);
79}
80
81bool RtpDumpPacket::GetRtpSeqNum(int* seq_num) const {
82  return IsValidRtpPacket() &&
83      cricket::GetRtpSeqNum(&data[0], data.size(), seq_num);
84}
85
86bool RtpDumpPacket::GetRtpTimestamp(uint32* ts) const {
87  return IsValidRtpPacket() &&
88      cricket::GetRtpTimestamp(&data[0], data.size(), ts);
89}
90
91bool RtpDumpPacket::GetRtpSsrc(uint32* ssrc) const {
92  return IsValidRtpPacket() &&
93      cricket::GetRtpSsrc(&data[0], data.size(), ssrc);
94}
95
96bool RtpDumpPacket::GetRtpHeaderLen(size_t* len) const {
97  return IsValidRtpPacket() &&
98      cricket::GetRtpHeaderLen(&data[0], data.size(), len);
99}
100
101bool RtpDumpPacket::GetRtcpType(int* type) const {
102  return IsValidRtcpPacket() &&
103      cricket::GetRtcpType(&data[0], data.size(), type);
104}
105
106///////////////////////////////////////////////////////////////////////////
107// Implementation of RtpDumpReader.
108///////////////////////////////////////////////////////////////////////////
109
110void RtpDumpReader::SetSsrc(uint32 ssrc) {
111  ssrc_override_ = ssrc;
112}
113
114rtc::StreamResult RtpDumpReader::ReadPacket(RtpDumpPacket* packet) {
115  if (!packet) return rtc::SR_ERROR;
116
117  rtc::StreamResult res = rtc::SR_SUCCESS;
118  // Read the file header if it has not been read yet.
119  if (!file_header_read_) {
120    res = ReadFileHeader();
121    if (res != rtc::SR_SUCCESS) {
122      return res;
123    }
124    file_header_read_ = true;
125  }
126
127  // Read the RTP dump packet header.
128  char header[RtpDumpPacket::kHeaderLength];
129  res = stream_->ReadAll(header, sizeof(header), NULL, NULL);
130  if (res != rtc::SR_SUCCESS) {
131    return res;
132  }
133  rtc::ByteBuffer buf(header, sizeof(header));
134  uint16 dump_packet_len;
135  uint16 data_len;
136  // Read the full length of the rtpdump packet, including the rtpdump header.
137  buf.ReadUInt16(&dump_packet_len);
138  packet->data.resize(dump_packet_len - sizeof(header));
139  // Read the size of the original packet, which may be larger than the size in
140  // the rtpdump file, in the event that only part of the packet (perhaps just
141  // the header) was recorded. Note that this field is set to zero for RTCP
142  // packets, which have their own internal length field.
143  buf.ReadUInt16(&data_len);
144  packet->original_data_len = data_len;
145  // Read the elapsed time for this packet (different than RTP timestamp).
146  buf.ReadUInt32(&packet->elapsed_time);
147
148  // Read the actual RTP or RTCP packet.
149  res = stream_->ReadAll(&packet->data[0], packet->data.size(), NULL, NULL);
150
151  // If the packet is RTP and we have specified a ssrc, replace the RTP ssrc
152  // with the specified ssrc.
153  if (res == rtc::SR_SUCCESS &&
154      packet->IsValidRtpPacket() &&
155      ssrc_override_ != 0) {
156    rtc::SetBE32(&packet->data[kRtpSsrcOffset], ssrc_override_);
157  }
158
159  return res;
160}
161
162rtc::StreamResult RtpDumpReader::ReadFileHeader() {
163  // Read the first line.
164  std::string first_line;
165  rtc::StreamResult res = stream_->ReadLine(&first_line);
166  if (res != rtc::SR_SUCCESS) {
167    return res;
168  }
169  if (!CheckFirstLine(first_line)) {
170    return rtc::SR_ERROR;
171  }
172
173  // Read the 16 byte file header.
174  char header[RtpDumpFileHeader::kHeaderLength];
175  res = stream_->ReadAll(header, sizeof(header), NULL, NULL);
176  if (res == rtc::SR_SUCCESS) {
177    rtc::ByteBuffer buf(header, sizeof(header));
178    uint32 start_sec;
179    uint32 start_usec;
180    buf.ReadUInt32(&start_sec);
181    buf.ReadUInt32(&start_usec);
182    start_time_ms_ = start_sec * 1000 + start_usec / 1000;
183    // Increase the length by 1 since first_line does not contain the ending \n.
184    first_line_and_file_header_len_ = first_line.size() + 1 + sizeof(header);
185  }
186  return res;
187}
188
189bool RtpDumpReader::CheckFirstLine(const std::string& first_line) {
190  // The first line is like "#!rtpplay1.0 address/port"
191  bool matched = (0 == first_line.find("#!rtpplay1.0 "));
192
193  // The address could be IP or hostname. We do not check it here. Instead, we
194  // check the port at the end.
195  size_t pos = first_line.find('/');
196  matched &= (pos != std::string::npos && pos < first_line.size() - 1);
197  for (++pos; pos < first_line.size() && matched; ++pos) {
198    matched &= (0 != isdigit(first_line[pos]));
199  }
200
201  return matched;
202}
203
204///////////////////////////////////////////////////////////////////////////
205// Implementation of RtpDumpLoopReader.
206///////////////////////////////////////////////////////////////////////////
207RtpDumpLoopReader::RtpDumpLoopReader(rtc::StreamInterface* stream)
208    : RtpDumpReader(stream),
209      loop_count_(0),
210      elapsed_time_increases_(0),
211      rtp_seq_num_increase_(0),
212      rtp_timestamp_increase_(0),
213      packet_count_(0),
214      frame_count_(0),
215      first_elapsed_time_(0),
216      first_rtp_seq_num_(0),
217      first_rtp_timestamp_(0),
218      prev_elapsed_time_(0),
219      prev_rtp_seq_num_(0),
220      prev_rtp_timestamp_(0) {
221}
222
223rtc::StreamResult RtpDumpLoopReader::ReadPacket(RtpDumpPacket* packet) {
224  if (!packet) return rtc::SR_ERROR;
225
226  rtc::StreamResult res = RtpDumpReader::ReadPacket(packet);
227  if (rtc::SR_SUCCESS == res) {
228    if (0 == loop_count_) {
229      // During the first loop, we update the statistics of the input stream.
230      UpdateStreamStatistics(*packet);
231    }
232  } else if (rtc::SR_EOS == res) {
233    if (0 == loop_count_) {
234      // At the end of the first loop, calculate elapsed_time_increases_,
235      // rtp_seq_num_increase_, and rtp_timestamp_increase_, which will be
236      // used during the second and later loops.
237      CalculateIncreases();
238    }
239
240    // Rewind the input stream to the first dump packet and read again.
241    ++loop_count_;
242    if (RewindToFirstDumpPacket()) {
243      res = RtpDumpReader::ReadPacket(packet);
244    }
245  }
246
247  if (rtc::SR_SUCCESS == res && loop_count_ > 0) {
248    // During the second and later loops, we update the elapsed time of the dump
249    // packet. If the dumped packet is a RTP packet, we also update its RTP
250    // sequence number and timestamp.
251    UpdateDumpPacket(packet);
252  }
253
254  return res;
255}
256
257void RtpDumpLoopReader::UpdateStreamStatistics(const RtpDumpPacket& packet) {
258  // Get the RTP sequence number and timestamp of the dump packet.
259  int rtp_seq_num = 0;
260  packet.GetRtpSeqNum(&rtp_seq_num);
261  uint32 rtp_timestamp = 0;
262  packet.GetRtpTimestamp(&rtp_timestamp);
263
264  // Set the timestamps and sequence number for the first dump packet.
265  if (0 == packet_count_++) {
266    first_elapsed_time_ = packet.elapsed_time;
267    first_rtp_seq_num_ = rtp_seq_num;
268    first_rtp_timestamp_ = rtp_timestamp;
269    // The first packet belongs to a new payload frame.
270    ++frame_count_;
271  } else if (rtp_timestamp != prev_rtp_timestamp_) {
272    // The current and previous packets belong to different payload frames.
273    ++frame_count_;
274  }
275
276  prev_elapsed_time_ = packet.elapsed_time;
277  prev_rtp_timestamp_ = rtp_timestamp;
278  prev_rtp_seq_num_ = rtp_seq_num;
279}
280
281void RtpDumpLoopReader::CalculateIncreases() {
282  // At this time, prev_elapsed_time_, prev_rtp_seq_num_, and
283  // prev_rtp_timestamp_ are values of the last dump packet in the input stream.
284  rtp_seq_num_increase_ = prev_rtp_seq_num_ - first_rtp_seq_num_ + 1;
285  // If we have only one packet or frame, we use the default timestamp
286  // increase. Otherwise, we use the difference between the first and the last
287  // packets or frames.
288  elapsed_time_increases_ = packet_count_ <= 1 ? kDefaultTimeIncrease :
289      (prev_elapsed_time_ - first_elapsed_time_) * packet_count_ /
290      (packet_count_ - 1);
291  rtp_timestamp_increase_ = frame_count_ <= 1 ? kDefaultTimeIncrease :
292      (prev_rtp_timestamp_ - first_rtp_timestamp_) * frame_count_ /
293      (frame_count_ - 1);
294}
295
296void RtpDumpLoopReader::UpdateDumpPacket(RtpDumpPacket* packet) {
297  // Increase the elapsed time of the dump packet.
298  packet->elapsed_time += loop_count_ * elapsed_time_increases_;
299
300  if (packet->IsValidRtpPacket()) {
301    // Get the old RTP sequence number and timestamp.
302    int sequence = 0;
303    packet->GetRtpSeqNum(&sequence);
304    uint32 timestamp = 0;
305    packet->GetRtpTimestamp(&timestamp);
306    // Increase the RTP sequence number and timestamp.
307    sequence += loop_count_ * rtp_seq_num_increase_;
308    timestamp += loop_count_ * rtp_timestamp_increase_;
309    // Write the updated sequence number and timestamp back to the RTP packet.
310    rtc::ByteBuffer buffer;
311    buffer.WriteUInt16(sequence);
312    buffer.WriteUInt32(timestamp);
313    memcpy(&packet->data[2], buffer.Data(), buffer.Length());
314  }
315}
316
317///////////////////////////////////////////////////////////////////////////
318// Implementation of RtpDumpWriter.
319///////////////////////////////////////////////////////////////////////////
320
321RtpDumpWriter::RtpDumpWriter(rtc::StreamInterface* stream)
322    : stream_(stream),
323      packet_filter_(PF_ALL),
324      file_header_written_(false),
325      start_time_ms_(rtc::Time()),
326      warn_slow_writes_delay_(kWarnSlowWritesDelayMs) {
327}
328
329void RtpDumpWriter::set_packet_filter(int filter) {
330  packet_filter_ = filter;
331  LOG(LS_INFO) << "RtpDumpWriter set_packet_filter to " << packet_filter_;
332}
333
334uint32 RtpDumpWriter::GetElapsedTime() const {
335  return rtc::TimeSince(start_time_ms_);
336}
337
338rtc::StreamResult RtpDumpWriter::WriteFileHeader() {
339  rtc::StreamResult res = WriteToStream(
340      RtpDumpFileHeader::kFirstLine,
341      strlen(RtpDumpFileHeader::kFirstLine));
342  if (res != rtc::SR_SUCCESS) {
343    return res;
344  }
345
346  rtc::ByteBuffer buf;
347  RtpDumpFileHeader file_header(rtc::Time(), 0, 0);
348  file_header.WriteToByteBuffer(&buf);
349  return WriteToStream(buf.Data(), buf.Length());
350}
351
352rtc::StreamResult RtpDumpWriter::WritePacket(
353    const void* data, size_t data_len, uint32 elapsed, bool rtcp) {
354  if (!stream_ || !data || 0 == data_len) return rtc::SR_ERROR;
355
356  rtc::StreamResult res = rtc::SR_SUCCESS;
357  // Write the file header if it has not been written yet.
358  if (!file_header_written_) {
359    res = WriteFileHeader();
360    if (res != rtc::SR_SUCCESS) {
361      return res;
362    }
363    file_header_written_ = true;
364  }
365
366  // Figure out what to write.
367  size_t write_len = FilterPacket(data, data_len, rtcp);
368  if (write_len == 0) {
369    return rtc::SR_SUCCESS;
370  }
371
372  // Write the dump packet header.
373  rtc::ByteBuffer buf;
374  buf.WriteUInt16(static_cast<uint16>(
375                      RtpDumpPacket::kHeaderLength + write_len));
376  buf.WriteUInt16(static_cast<uint16>(rtcp ? 0 : data_len));
377  buf.WriteUInt32(elapsed);
378  res = WriteToStream(buf.Data(), buf.Length());
379  if (res != rtc::SR_SUCCESS) {
380    return res;
381  }
382
383  // Write the header or full packet as indicated by write_len.
384  return WriteToStream(data, write_len);
385}
386
387size_t RtpDumpWriter::FilterPacket(const void* data, size_t data_len,
388                                   bool rtcp) {
389  size_t filtered_len = 0;
390  if (!rtcp) {
391    if ((packet_filter_ & PF_RTPPACKET) == PF_RTPPACKET) {
392      // RTP header + payload
393      filtered_len = data_len;
394    } else if ((packet_filter_ & PF_RTPHEADER) == PF_RTPHEADER) {
395      // RTP header only
396      size_t header_len;
397      if (GetRtpHeaderLen(data, data_len, &header_len)) {
398        filtered_len = header_len;
399      }
400    }
401  } else {
402    if ((packet_filter_ & PF_RTCPPACKET) == PF_RTCPPACKET) {
403      // RTCP header + payload
404      filtered_len = data_len;
405    }
406  }
407
408  return filtered_len;
409}
410
411rtc::StreamResult RtpDumpWriter::WriteToStream(
412    const void* data, size_t data_len) {
413  uint32 before = rtc::Time();
414  rtc::StreamResult result =
415      stream_->WriteAll(data, data_len, NULL, NULL);
416  uint32 delay = rtc::TimeSince(before);
417  if (delay >= warn_slow_writes_delay_) {
418    LOG(LS_WARNING) << "Slow RtpDump: took " << delay << "ms to write "
419                    << data_len << " bytes.";
420  }
421  return result;
422}
423
424}  // namespace cricket
425