2 * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
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.
11 #include "webrtc/test/rtp_file_reader.h"
19 #include "webrtc/base/checks.h"
20 #include "webrtc/modules/rtp_rtcp/source/rtp_utility.h"
21 #include "webrtc/system_wrappers/interface/scoped_ptr.h"
26 static const size_t kFirstLineLength = 40;
27 static uint16_t kPacketHeaderSize = 8;
30 # define DEBUG_LOG(text)
31 # define DEBUG_LOG1(text, arg)
33 # define DEBUG_LOG(text) (printf(text "\n"))
34 # define DEBUG_LOG1(text, arg) (printf(text "\n", arg))
40 DEBUG_LOG1("FAIL at " __FILE__ ":%d", __LINE__); \
45 class RtpFileReaderImpl : public RtpFileReader {
47 virtual bool Init(const std::string& filename) = 0;
50 // Read RTP packets from file in rtpdump format, as documented at:
51 // http://www.cs.columbia.edu/irt/software/rtptools/
52 class RtpDumpReader : public RtpFileReaderImpl {
54 RtpDumpReader() : file_(NULL) {}
55 virtual ~RtpDumpReader() {
62 bool Init(const std::string& filename) {
63 file_ = fopen(filename.c_str(), "rb");
65 printf("ERROR: Can't open file: %s\n", filename.c_str());
69 char firstline[kFirstLineLength + 1] = {0};
70 if (fgets(firstline, kFirstLineLength, file_) == NULL) {
71 DEBUG_LOG("ERROR: Can't read from file\n");
74 if (strncmp(firstline, "#!rtpplay", 9) == 0) {
75 if (strncmp(firstline, "#!rtpplay1.0", 12) != 0) {
76 DEBUG_LOG("ERROR: wrong rtpplay version, must be 1.0\n");
79 } else if (strncmp(firstline, "#!RTPencode", 11) == 0) {
80 if (strncmp(firstline, "#!RTPencode1.0", 14) != 0) {
81 DEBUG_LOG("ERROR: wrong RTPencode version, must be 1.0\n");
85 DEBUG_LOG("ERROR: wrong file format of input file\n");
94 TRY(Read(&start_sec));
95 TRY(Read(&start_usec));
103 virtual bool NextPacket(Packet* packet) OVERRIDE {
104 uint8_t* rtp_data = packet->data;
105 packet->length = Packet::kMaxPacketBufferSize;
114 // Use 'len' here because a 'plen' of 0 specifies rtcp.
115 len -= kPacketHeaderSize;
116 if (packet->length < len) {
117 FATAL() << "Packet is too large to fit: " << len << " bytes vs "
119 << " bytes allocated. Consider increasing the buffer "
122 if (fread(rtp_data, 1, len, file_) != len) {
126 packet->length = len;
127 packet->original_length = plen;
128 packet->time_ms = offset;
133 bool Read(uint32_t* out) {
135 for (size_t i = 0; i < 4; ++i) {
138 if (fread(&tmp, 1, sizeof(uint8_t), file_) != sizeof(uint8_t))
145 bool Read(uint16_t* out) {
147 for (size_t i = 0; i < 2; ++i) {
150 if (fread(&tmp, 1, sizeof(uint8_t), file_) != sizeof(uint8_t))
159 DISALLOW_COPY_AND_ASSIGN(RtpDumpReader);
167 kPcapVersionMajor = 2,
168 kPcapVersionMinor = 4,
170 kLinktypeEthernet = 1,
171 kBsdNullLoopback1 = 0x00000002,
172 kBsdNullLoopback2 = 0x02000000,
173 kEthernetIIHeaderMacSkip = 12,
174 kEthertypeIp = 0x0800,
176 kMinIpHeaderLength = 20,
177 kFragmentOffsetClear = 0x0000,
178 kFragmentOffsetDoNotFragment = 0x4000,
181 kUdpHeaderLength = 8,
182 kMaxReadBufferSize = 4096
185 const uint32_t kPcapBOMSwapOrder = 0xd4c3b2a1UL;
186 const uint32_t kPcapBOMNoSwapOrder = 0xa1b2c3d4UL;
188 #define TRY_PCAP(expr) \
191 if (r == kResultFail) { \
192 DEBUG_LOG1("FAIL at " __FILE__ ":%d", __LINE__); \
193 return kResultFail; \
194 } else if (r == kResultSkip) { \
195 return kResultSkip; \
199 // Read RTP packets from file in tcpdump/libpcap format, as documented at:
200 // http://wiki.wireshark.org/Development/LibpcapFileFormat
201 class PcapReader : public RtpFileReaderImpl {
205 swap_pcap_byte_order_(false),
206 #ifdef WEBRTC_ARCH_BIG_ENDIAN
207 swap_network_byte_order_(false),
209 swap_network_byte_order_(true),
217 virtual ~PcapReader() {
224 bool Init(const std::string& filename) OVERRIDE {
225 return Initialize(filename) == kResultSuccess;
228 int Initialize(const std::string& filename) {
229 file_ = fopen(filename.c_str(), "rb");
231 printf("ERROR: Can't open file: %s\n", filename.c_str());
235 if (ReadGlobalHeader() < 0) {
239 int total_packet_count = 0;
240 uint32_t stream_start_ms = 0;
241 int32_t next_packet_pos = ftell(file_);
243 TRY_PCAP(fseek(file_, next_packet_pos, SEEK_SET));
244 int result = ReadPacket(&next_packet_pos, stream_start_ms,
245 ++total_packet_count);
246 if (result == kResultFail) {
248 } else if (result == kResultSuccess && packets_.size() == 1) {
249 assert(stream_start_ms == 0);
250 PacketIterator it = packets_.begin();
251 stream_start_ms = it->time_offset_ms;
252 it->time_offset_ms = 0;
256 if (feof(file_) == 0) {
257 printf("Failed reading file!\n");
261 printf("Total packets in file: %d\n", total_packet_count);
262 printf("Total RTP/RTCP packets: %d\n", static_cast<int>(packets_.size()));
264 for (SsrcMapIterator mit = packets_by_ssrc_.begin();
265 mit != packets_by_ssrc_.end(); ++mit) {
266 uint32_t ssrc = mit->first;
267 const std::vector<uint32_t>& packet_numbers = mit->second;
268 uint8_t pt = packets_[packet_numbers[0]].rtp_header.payloadType;
269 printf("SSRC: %08x, %d packets, pt=%d\n", ssrc,
270 static_cast<int>(packet_numbers.size()), pt);
273 // TODO(solenberg): Better validation of identified SSRC streams.
275 // Since we're dealing with raw network data here, we will wrongly identify
276 // some packets as RTP. When these packets are consumed by RtpPlayer, they
277 // are unlikely to cause issues as they will ultimately be filtered out by
278 // the RtpRtcp module. However, we should really do better filtering here,
279 // which we can accomplish in a number of ways, e.g.:
281 // - Verify that the time stamps and sequence numbers for RTP packets are
282 // both increasing/decreasing. If they move in different directions, the
283 // SSRC is likely bogus and can be dropped. (Normally they should be inc-
284 // reasing but we must allow packet reordering).
285 // - If RTP sequence number is not changing, drop the stream.
286 // - Can also use srcip:port->dstip:port pairs, assuming few SSRC collisions
287 // for up/down streams.
289 next_packet_it_ = packets_.begin();
290 return kResultSuccess;
293 virtual bool NextPacket(Packet* packet) OVERRIDE {
294 uint32_t length = Packet::kMaxPacketBufferSize;
295 if (NextPcap(packet->data, &length, &packet->time_ms) != kResultSuccess)
297 packet->length = static_cast<size_t>(length);
298 packet->original_length = packet->length;
302 virtual int NextPcap(uint8_t* data, uint32_t* length, uint32_t* time_ms) {
307 if (next_packet_it_ == packets_.end()) {
310 if (*length < next_packet_it_->payload_length) {
313 TRY_PCAP(fseek(file_, next_packet_it_->pos_in_file, SEEK_SET));
314 TRY_PCAP(Read(data, next_packet_it_->payload_length));
315 *length = next_packet_it_->payload_length;
316 *time_ms = next_packet_it_->time_offset_ms;
323 // A marker of an RTP packet within the file.
324 struct RtpPacketMarker {
325 uint32_t packet_number; // One-based index (like in WireShark)
326 uint32_t time_offset_ms;
329 uint16_t source_port;
331 RTPHeader rtp_header;
332 int32_t pos_in_file; // Byte offset of payload from start of file.
333 uint32_t payload_length;
336 typedef std::vector<RtpPacketMarker>::iterator PacketIterator;
337 typedef std::map<uint32_t, std::vector<uint32_t> > SsrcMap;
338 typedef std::map<uint32_t, std::vector<uint32_t> >::iterator SsrcMapIterator;
340 int ReadGlobalHeader() {
342 TRY_PCAP(Read(&magic, false));
343 if (magic == kPcapBOMSwapOrder) {
344 swap_pcap_byte_order_ = true;
345 } else if (magic == kPcapBOMNoSwapOrder) {
346 swap_pcap_byte_order_ = false;
351 uint16_t version_major;
352 uint16_t version_minor;
353 TRY_PCAP(Read(&version_major, false));
354 TRY_PCAP(Read(&version_minor, false));
355 if (version_major != kPcapVersionMajor ||
356 version_minor != kPcapVersionMinor) {
360 int32_t this_zone; // GMT to local correction.
361 uint32_t sigfigs; // Accuracy of timestamps.
362 uint32_t snaplen; // Max length of captured packets, in octets.
363 uint32_t network; // Data link type.
364 TRY_PCAP(Read(&this_zone, false));
365 TRY_PCAP(Read(&sigfigs, false));
366 TRY_PCAP(Read(&snaplen, false));
367 TRY_PCAP(Read(&network, false));
369 // Accept only LINKTYPE_NULL and LINKTYPE_ETHERNET.
370 // See: http://www.tcpdump.org/linktypes.html
371 if (network != kLinktypeNull && network != kLinktypeEthernet) {
375 return kResultSuccess;
378 int ReadPacket(int32_t* next_packet_pos, uint32_t stream_start_ms,
380 assert(next_packet_pos);
382 uint32_t ts_sec; // Timestamp seconds.
383 uint32_t ts_usec; // Timestamp microseconds.
384 uint32_t incl_len; // Number of octets of packet saved in file.
385 uint32_t orig_len; // Actual length of packet.
386 TRY_PCAP(Read(&ts_sec, false));
387 TRY_PCAP(Read(&ts_usec, false));
388 TRY_PCAP(Read(&incl_len, false));
389 TRY_PCAP(Read(&orig_len, false));
391 *next_packet_pos = ftell(file_) + incl_len;
393 RtpPacketMarker marker = {0};
394 marker.packet_number = number;
395 marker.time_offset_ms = CalcTimeDelta(ts_sec, ts_usec, stream_start_ms);
396 TRY_PCAP(ReadPacketHeader(&marker));
397 marker.pos_in_file = ftell(file_);
399 if (marker.payload_length > sizeof(read_buffer_)) {
400 printf("Packet too large!\n");
403 TRY_PCAP(Read(read_buffer_, marker.payload_length));
405 RtpUtility::RtpHeaderParser rtp_parser(read_buffer_, marker.payload_length);
406 if (rtp_parser.RTCP()) {
407 rtp_parser.ParseRtcp(&marker.rtp_header);
408 packets_.push_back(marker);
410 if (!rtp_parser.Parse(marker.rtp_header, NULL)) {
411 DEBUG_LOG("Not recognized as RTP/RTCP");
415 uint32_t ssrc = marker.rtp_header.ssrc;
416 packets_by_ssrc_[ssrc].push_back(marker.packet_number);
417 packets_.push_back(marker);
420 return kResultSuccess;
423 int ReadPacketHeader(RtpPacketMarker* marker) {
424 int32_t file_pos = ftell(file_);
426 // Check for BSD null/loopback frame header. The header is just 4 bytes in
427 // native byte order, so we check for both versions as we don't care about
428 // the header as such and will likely fail reading the IP header if this is
429 // something else than null/loopback.
431 TRY_PCAP(Read(&protocol, true));
432 if (protocol == kBsdNullLoopback1 || protocol == kBsdNullLoopback2) {
433 int result = ReadXxpIpHeader(marker);
434 DEBUG_LOG("Recognized loopback frame");
435 if (result != kResultSkip) {
440 TRY_PCAP(fseek(file_, file_pos, SEEK_SET));
442 // Check for Ethernet II, IP frame header.
444 TRY_PCAP(Skip(kEthernetIIHeaderMacSkip)); // Source+destination MAC.
445 TRY_PCAP(Read(&type, true));
446 if (type == kEthertypeIp) {
447 int result = ReadXxpIpHeader(marker);
448 DEBUG_LOG("Recognized ethernet 2 frame");
449 if (result != kResultSkip) {
457 uint32_t CalcTimeDelta(uint32_t ts_sec, uint32_t ts_usec, uint32_t start_ms) {
458 // Round to nearest ms.
459 uint64_t t2_ms = ((static_cast<uint64_t>(ts_sec) * 1000000) + ts_usec +
461 uint64_t t1_ms = static_cast<uint64_t>(start_ms);
465 return t2_ms - t1_ms;
469 int ReadXxpIpHeader(RtpPacketMarker* marker) {
478 TRY_PCAP(Read(&version, true));
479 TRY_PCAP(Read(&length, true));
480 TRY_PCAP(Read(&id, true));
481 TRY_PCAP(Read(&fragment, true));
482 TRY_PCAP(Read(&protocol, true));
483 TRY_PCAP(Read(&checksum, true));
484 TRY_PCAP(Read(&marker->source_ip, true));
485 TRY_PCAP(Read(&marker->dest_ip, true));
487 if (((version >> 12) & 0x000f) != kIpVersion4) {
488 DEBUG_LOG("IP header is not IPv4");
492 if (fragment != kFragmentOffsetClear &&
493 fragment != kFragmentOffsetDoNotFragment) {
494 DEBUG_LOG("IP fragments cannot be handled");
498 // Skip remaining fields of IP header.
499 uint16_t header_length = (version & 0x0f00) >> (8 - 2);
500 assert(header_length >= kMinIpHeaderLength);
501 TRY_PCAP(Skip(header_length - kMinIpHeaderLength));
503 protocol = protocol & 0x00ff;
504 if (protocol == kProtocolTcp) {
505 DEBUG_LOG("TCP packets are not handled");
507 } else if (protocol == kProtocolUdp) {
510 TRY_PCAP(Read(&marker->source_port, true));
511 TRY_PCAP(Read(&marker->dest_port, true));
512 TRY_PCAP(Read(&length, true));
513 TRY_PCAP(Read(&checksum, true));
514 marker->payload_length = length - kUdpHeaderLength;
516 DEBUG_LOG("Unknown transport (expected UDP or TCP)");
520 return kResultSuccess;
523 int Read(uint32_t* out, bool expect_network_order) {
525 if (fread(&tmp, 1, sizeof(uint32_t), file_) != sizeof(uint32_t)) {
528 if ((!expect_network_order && swap_pcap_byte_order_) ||
529 (expect_network_order && swap_network_byte_order_)) {
530 tmp = ((tmp >> 24) & 0x000000ff) | (tmp << 24) |
531 ((tmp >> 8) & 0x0000ff00) | ((tmp << 8) & 0x00ff0000);
534 return kResultSuccess;
537 int Read(uint16_t* out, bool expect_network_order) {
539 if (fread(&tmp, 1, sizeof(uint16_t), file_) != sizeof(uint16_t)) {
542 if ((!expect_network_order && swap_pcap_byte_order_) ||
543 (expect_network_order && swap_network_byte_order_)) {
544 tmp = ((tmp >> 8) & 0x00ff) | (tmp << 8);
547 return kResultSuccess;
550 int Read(uint8_t* out, uint32_t count) {
551 if (fread(out, 1, count, file_) != count) {
554 return kResultSuccess;
557 int Read(int32_t* out, bool expect_network_order) {
559 if (fread(&tmp, 1, sizeof(uint32_t), file_) != sizeof(uint32_t)) {
562 if ((!expect_network_order && swap_pcap_byte_order_) ||
563 (expect_network_order && swap_network_byte_order_)) {
564 tmp = ((tmp >> 24) & 0x000000ff) | (tmp << 24) |
565 ((tmp >> 8) & 0x0000ff00) | ((tmp << 8) & 0x00ff0000);
568 return kResultSuccess;
571 int Skip(uint32_t length) {
572 if (fseek(file_, length, SEEK_CUR) != 0) {
575 return kResultSuccess;
579 bool swap_pcap_byte_order_;
580 const bool swap_network_byte_order_;
581 uint8_t read_buffer_[kMaxReadBufferSize];
583 SsrcMap packets_by_ssrc_;
584 std::vector<RtpPacketMarker> packets_;
585 PacketIterator next_packet_it_;
587 DISALLOW_COPY_AND_ASSIGN(PcapReader);
590 RtpFileReader* RtpFileReader::Create(FileFormat format,
591 const std::string& filename) {
592 RtpFileReaderImpl* reader = NULL;
595 reader = new PcapReader();
598 reader = new RtpDumpReader();
601 if (!reader->Init(filename)) {
609 } // namespace webrtc