2 * Copyright (c) 2013 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/modules/video_coding/main/test/pcap_file_reader.h"
17 #include <arpa/inet.h>
26 #include "webrtc/modules/rtp_rtcp/source/rtp_utility.h"
27 #include "webrtc/modules/video_coding/main/test/rtp_player.h"
28 #include "webrtc/system_wrappers/interface/scoped_ptr.h"
38 kPcapVersionMajor = 2,
39 kPcapVersionMinor = 4,
41 kLinktypeEthernet = 1,
42 kBsdNullLoopback1 = 0x00000002,
43 kBsdNullLoopback2 = 0x02000000,
44 kEthernetIIHeaderMacSkip = 12,
45 kEthertypeIp = 0x0800,
47 kMinIpHeaderLength = 20,
48 kFragmentOffsetClear = 0x0000,
49 kFragmentOffsetDoNotFragment = 0x4000,
53 kMaxReadBufferSize = 4096
56 const uint32_t kPcapBOMSwapOrder = 0xd4c3b2a1UL;
57 const uint32_t kPcapBOMNoSwapOrder = 0xa1b2c3d4UL;
60 # define DEBUG_LOG(text)
61 # define DEBUG_LOG1(text, arg)
63 # define DEBUG_LOG(text) (printf(text "\n"))
64 # define DEBUG_LOG1(text, arg) (printf(text "\n", arg))
70 if (r == kResultFail) { \
71 DEBUG_LOG1("FAIL at " __FILE__ ":%d", __LINE__); \
73 } else if (r == kResultSkip) { \
78 // Read RTP packets from file in tcpdump/libpcap format, as documented at:
79 // http://wiki.wireshark.org/Development/LibpcapFileFormat
80 class PcapFileReaderImpl : public RtpPacketSourceInterface {
84 swap_pcap_byte_order_(false),
85 swap_network_byte_order_(false),
90 int16_t test = 0x7f00;
91 if (test != htons(test)) {
92 swap_network_byte_order_ = true;
96 virtual ~PcapFileReaderImpl() {
103 int Initialize(const std::string& filename) {
104 file_ = fopen(filename.c_str(), "rb");
106 printf("ERROR: Can't open file: %s\n", filename.c_str());
110 if (ReadGlobalHeader() < 0) {
114 int total_packet_count = 0;
115 uint32_t stream_start_ms = 0;
116 int32_t next_packet_pos = ftell(file_);
118 TRY(fseek(file_, next_packet_pos, SEEK_SET));
119 int result = ReadPacket(&next_packet_pos, stream_start_ms,
120 ++total_packet_count);
121 if (result == kResultFail) {
123 } else if (result == kResultSuccess && packets_.size() == 1) {
124 assert(stream_start_ms == 0);
125 PacketIterator it = packets_.begin();
126 stream_start_ms = it->time_offset_ms;
127 it->time_offset_ms = 0;
131 if (feof(file_) == 0) {
132 printf("Failed reading file!\n");
136 printf("Total packets in file: %d\n", total_packet_count);
137 printf("Total RTP/RTCP packets: %d\n", static_cast<int>(packets_.size()));
139 for (SsrcMapIterator mit = packets_by_ssrc_.begin();
140 mit != packets_by_ssrc_.end(); ++mit) {
141 uint32_t ssrc = mit->first;
142 const std::vector<uint32_t>& packet_numbers = mit->second;
143 uint8_t pt = packets_[packet_numbers[0]].rtp_header.payloadType;
144 printf("SSRC: %08x, %d packets, pt=%d\n", ssrc,
145 static_cast<int>(packet_numbers.size()), pt);
148 // TODO(solenberg): Better validation of identified SSRC streams.
150 // Since we're dealing with raw network data here, we will wrongly identify
151 // some packets as RTP. When these packets are consumed by RtpPlayer, they
152 // are unlikely to cause issues as they will ultimately be filtered out by
153 // the RtpRtcp module. However, we should really do better filtering here,
154 // which we can accomplish in a number of ways, e.g.:
156 // - Verify that the time stamps and sequence numbers for RTP packets are
157 // both increasing/decreasing. If they move in different directions, the
158 // SSRC is likely bogus and can be dropped. (Normally they should be inc-
159 // reasing but we must allow packet reordering).
160 // - If RTP sequence number is not changing, drop the stream.
161 // - Can also use srcip:port->dstip:port pairs, assuming few SSRC collisions
162 // for up/down streams.
164 next_packet_it_ = packets_.begin();
165 return kResultSuccess;
168 virtual int NextPacket(uint8_t* data, uint32_t* length, uint32_t* time_ms) {
173 if (next_packet_it_ == packets_.end()) {
176 if (*length < next_packet_it_->payload_length) {
179 TRY(fseek(file_, next_packet_it_->pos_in_file, SEEK_SET));
180 TRY(Read(data, next_packet_it_->payload_length));
181 *length = next_packet_it_->payload_length;
182 *time_ms = next_packet_it_->time_offset_ms;
189 // A marker of an RTP packet within the file.
190 struct RtpPacketMarker {
191 uint32_t packet_number; // One-based index (like in WireShark)
192 uint32_t time_offset_ms;
195 uint16_t source_port;
197 RTPHeader rtp_header;
198 int32_t pos_in_file; // Byte offset of payload from start of file.
199 uint32_t payload_length;
202 typedef std::vector<RtpPacketMarker>::iterator PacketIterator;
203 typedef std::map<uint32_t, std::vector<uint32_t> > SsrcMap;
204 typedef std::map<uint32_t, std::vector<uint32_t> >::iterator SsrcMapIterator;
206 int ReadGlobalHeader() {
208 TRY(Read(&magic, false));
209 if (magic == kPcapBOMSwapOrder) {
210 swap_pcap_byte_order_ = true;
211 } else if (magic == kPcapBOMNoSwapOrder) {
212 swap_pcap_byte_order_ = false;
217 uint16_t version_major;
218 uint16_t version_minor;
219 TRY(Read(&version_major, false));
220 TRY(Read(&version_minor, false));
221 if (version_major != kPcapVersionMajor ||
222 version_minor != kPcapVersionMinor) {
226 int32_t this_zone; // GMT to local correction.
227 uint32_t sigfigs; // Accuracy of timestamps.
228 uint32_t snaplen; // Max length of captured packets, in octets.
229 uint32_t network; // Data link type.
230 TRY(Read(&this_zone, false));
231 TRY(Read(&sigfigs, false));
232 TRY(Read(&snaplen, false));
233 TRY(Read(&network, false));
235 // Accept only LINKTYPE_NULL and LINKTYPE_ETHERNET.
236 // See: http://www.tcpdump.org/linktypes.html
237 if (network != kLinktypeNull && network != kLinktypeEthernet) {
241 return kResultSuccess;
244 int ReadPacket(int32_t* next_packet_pos, uint32_t stream_start_ms,
246 assert(next_packet_pos);
248 uint32_t ts_sec; // Timestamp seconds.
249 uint32_t ts_usec; // Timestamp microseconds.
250 uint32_t incl_len; // Number of octets of packet saved in file.
251 uint32_t orig_len; // Actual length of packet.
252 TRY(Read(&ts_sec, false));
253 TRY(Read(&ts_usec, false));
254 TRY(Read(&incl_len, false));
255 TRY(Read(&orig_len, false));
257 *next_packet_pos = ftell(file_) + incl_len;
259 RtpPacketMarker marker = {0};
260 marker.packet_number = number;
261 marker.time_offset_ms = CalcTimeDelta(ts_sec, ts_usec, stream_start_ms);
262 TRY(ReadPacketHeader(&marker));
263 marker.pos_in_file = ftell(file_);
265 if (marker.payload_length > sizeof(read_buffer_)) {
266 printf("Packet too large!\n");
269 TRY(Read(read_buffer_, marker.payload_length));
271 ModuleRTPUtility::RTPHeaderParser rtp_parser(read_buffer_,
272 marker.payload_length);
273 if (rtp_parser.RTCP()) {
274 rtp_parser.ParseRtcp(&marker.rtp_header);
275 packets_.push_back(marker);
277 if (!rtp_parser.Parse(marker.rtp_header, NULL)) {
278 DEBUG_LOG("Not recognized as RTP/RTCP");
282 uint32_t ssrc = marker.rtp_header.ssrc;
283 packets_by_ssrc_[ssrc].push_back(marker.packet_number);
284 packets_.push_back(marker);
287 return kResultSuccess;
290 int ReadPacketHeader(RtpPacketMarker* marker) {
291 int32_t file_pos = ftell(file_);
293 // Check for BSD null/loopback frame header. The header is just 4 bytes in
294 // native byte order, so we check for both versions as we don't care about
295 // the header as such and will likely fail reading the IP header if this is
296 // something else than null/loopback.
298 TRY(Read(&protocol, true));
299 if (protocol == kBsdNullLoopback1 || protocol == kBsdNullLoopback2) {
300 int result = ReadXxpIpHeader(marker);
301 DEBUG_LOG("Recognized loopback frame");
302 if (result != kResultSkip) {
307 TRY(fseek(file_, file_pos, SEEK_SET));
309 // Check for Ethernet II, IP frame header.
311 TRY(Skip(kEthernetIIHeaderMacSkip)); // Source+destination MAC.
312 TRY(Read(&type, true));
313 if (type == kEthertypeIp) {
314 int result = ReadXxpIpHeader(marker);
315 DEBUG_LOG("Recognized ethernet 2 frame");
316 if (result != kResultSkip) {
324 uint32_t CalcTimeDelta(uint32_t ts_sec, uint32_t ts_usec, uint32_t start_ms) {
325 // Round to nearest ms.
326 uint64_t t2_ms = ((static_cast<uint64_t>(ts_sec) * 1000000) + ts_usec +
328 uint64_t t1_ms = static_cast<uint64_t>(start_ms);
332 return t2_ms - t1_ms;
336 int ReadXxpIpHeader(RtpPacketMarker* marker) {
345 TRY(Read(&version, true));
346 TRY(Read(&length, true));
347 TRY(Read(&id, true));
348 TRY(Read(&fragment, true));
349 TRY(Read(&protocol, true));
350 TRY(Read(&checksum, true));
351 TRY(Read(&marker->source_ip, true));
352 TRY(Read(&marker->dest_ip, true));
354 if (((version >> 12) & 0x000f) != kIpVersion4) {
355 DEBUG_LOG("IP header is not IPv4");
359 if (fragment != kFragmentOffsetClear &&
360 fragment != kFragmentOffsetDoNotFragment) {
361 DEBUG_LOG("IP fragments cannot be handled");
365 // Skip remaining fields of IP header.
366 uint16_t header_length = (version & 0x0f00) >> (8 - 2);
367 assert(header_length >= kMinIpHeaderLength);
368 TRY(Skip(header_length - kMinIpHeaderLength));
370 protocol = protocol & 0x00ff;
371 if (protocol == kProtocolTcp) {
372 DEBUG_LOG("TCP packets are not handled");
374 } else if (protocol == kProtocolUdp) {
377 TRY(Read(&marker->source_port, true));
378 TRY(Read(&marker->dest_port, true));
379 TRY(Read(&length, true));
380 TRY(Read(&checksum, true));
381 marker->payload_length = length - kUdpHeaderLength;
383 DEBUG_LOG("Unknown transport (expected UDP or TCP)");
387 return kResultSuccess;
390 int Read(uint32_t* out, bool expect_network_order) {
392 if (fread(&tmp, 1, sizeof(uint32_t), file_) != sizeof(uint32_t)) {
395 if ((!expect_network_order && swap_pcap_byte_order_) ||
396 (expect_network_order && swap_network_byte_order_)) {
397 tmp = ((tmp >> 24) & 0x000000ff) | (tmp << 24) |
398 ((tmp >> 8) & 0x0000ff00) | ((tmp << 8) & 0x00ff0000);
401 return kResultSuccess;
404 int Read(uint16_t* out, bool expect_network_order) {
406 if (fread(&tmp, 1, sizeof(uint16_t), file_) != sizeof(uint16_t)) {
409 if ((!expect_network_order && swap_pcap_byte_order_) ||
410 (expect_network_order && swap_network_byte_order_)) {
411 tmp = ((tmp >> 8) & 0x00ff) | (tmp << 8);
414 return kResultSuccess;
417 int Read(uint8_t* out, uint32_t count) {
418 if (fread(out, 1, count, file_) != count) {
421 return kResultSuccess;
424 int Read(int32_t* out, bool expect_network_order) {
426 if (fread(&tmp, 1, sizeof(uint32_t), file_) != sizeof(uint32_t)) {
429 if ((!expect_network_order && swap_pcap_byte_order_) ||
430 (expect_network_order && swap_network_byte_order_)) {
431 tmp = ((tmp >> 24) & 0x000000ff) | (tmp << 24) |
432 ((tmp >> 8) & 0x0000ff00) | ((tmp << 8) & 0x00ff0000);
435 return kResultSuccess;
438 int Skip(uint32_t length) {
439 if (fseek(file_, length, SEEK_CUR) != 0) {
442 return kResultSuccess;
446 bool swap_pcap_byte_order_;
447 bool swap_network_byte_order_;
448 uint8_t read_buffer_[kMaxReadBufferSize];
450 SsrcMap packets_by_ssrc_;
451 std::vector<RtpPacketMarker> packets_;
452 PacketIterator next_packet_it_;
454 DISALLOW_COPY_AND_ASSIGN(PcapFileReaderImpl);
457 RtpPacketSourceInterface* CreatePcapFileReader(const std::string& filename) {
458 scoped_ptr<PcapFileReaderImpl> impl(new PcapFileReaderImpl());
459 if (impl->Initialize(filename) != 0) {
462 return impl.release();
464 } // namespace rtpplayer
465 } // namespace webrtc