Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / webrtc / test / rtp_file_reader.cc
1 /*
2  *  Copyright (c) 2014 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 "webrtc/test/rtp_file_reader.h"
12
13 #include <stdio.h>
14
15 #include <map>
16 #include <string>
17 #include <vector>
18
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"
22
23 namespace webrtc {
24 namespace test {
25
26 static const size_t kFirstLineLength = 40;
27 static uint16_t kPacketHeaderSize = 8;
28
29 #if 1
30 # define DEBUG_LOG(text)
31 # define DEBUG_LOG1(text, arg)
32 #else
33 # define DEBUG_LOG(text) (printf(text "\n"))
34 # define DEBUG_LOG1(text, arg) (printf(text "\n", arg))
35 #endif
36
37 #define TRY(expr)                                      \
38   do {                                                 \
39     if (!(expr)) {                                     \
40       DEBUG_LOG1("FAIL at " __FILE__ ":%d", __LINE__); \
41       return false;                                    \
42     }                                                  \
43   } while (0)
44
45 class RtpFileReaderImpl : public RtpFileReader {
46  public:
47   virtual bool Init(const std::string& filename) = 0;
48 };
49
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 {
53  public:
54   RtpDumpReader() : file_(NULL) {}
55   virtual ~RtpDumpReader() {
56     if (file_ != NULL) {
57       fclose(file_);
58       file_ = NULL;
59     }
60   }
61
62   bool Init(const std::string& filename) {
63     file_ = fopen(filename.c_str(), "rb");
64     if (file_ == NULL) {
65       printf("ERROR: Can't open file: %s\n", filename.c_str());
66       return false;
67     }
68
69     char firstline[kFirstLineLength + 1] = {0};
70     if (fgets(firstline, kFirstLineLength, file_) == NULL) {
71       DEBUG_LOG("ERROR: Can't read from file\n");
72       return false;
73     }
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");
77         return false;
78       }
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");
82         return false;
83       }
84     } else {
85       DEBUG_LOG("ERROR: wrong file format of input file\n");
86       return false;
87     }
88
89     uint32_t start_sec;
90     uint32_t start_usec;
91     uint32_t source;
92     uint16_t port;
93     uint16_t padding;
94     TRY(Read(&start_sec));
95     TRY(Read(&start_usec));
96     TRY(Read(&source));
97     TRY(Read(&port));
98     TRY(Read(&padding));
99
100     return true;
101   }
102
103   virtual bool NextPacket(Packet* packet) OVERRIDE {
104     uint8_t* rtp_data = packet->data;
105     packet->length = Packet::kMaxPacketBufferSize;
106
107     uint16_t len;
108     uint16_t plen;
109     uint32_t offset;
110     TRY(Read(&len));
111     TRY(Read(&plen));
112     TRY(Read(&offset));
113
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 "
118               << packet->length
119               << " bytes allocated. Consider increasing the buffer "
120                  "size";
121     }
122     if (fread(rtp_data, 1, len, file_) != len) {
123       return false;
124     }
125
126     packet->length = len;
127     packet->original_length = plen;
128     packet->time_ms = offset;
129     return true;
130   }
131
132  private:
133   bool Read(uint32_t* out) {
134     *out = 0;
135     for (size_t i = 0; i < 4; ++i) {
136       *out <<= 8;
137       uint8_t tmp;
138       if (fread(&tmp, 1, sizeof(uint8_t), file_) != sizeof(uint8_t))
139         return false;
140       *out |= tmp;
141     }
142     return true;
143   }
144
145   bool Read(uint16_t* out) {
146     *out = 0;
147     for (size_t i = 0; i < 2; ++i) {
148       *out <<= 8;
149       uint8_t tmp;
150       if (fread(&tmp, 1, sizeof(uint8_t), file_) != sizeof(uint8_t))
151         return false;
152       *out |= tmp;
153     }
154     return true;
155   }
156
157   FILE* file_;
158
159   DISALLOW_COPY_AND_ASSIGN(RtpDumpReader);
160 };
161
162 enum {
163   kResultFail = -1,
164   kResultSuccess = 0,
165   kResultSkip = 1,
166
167   kPcapVersionMajor = 2,
168   kPcapVersionMinor = 4,
169   kLinktypeNull = 0,
170   kLinktypeEthernet = 1,
171   kBsdNullLoopback1 = 0x00000002,
172   kBsdNullLoopback2 = 0x02000000,
173   kEthernetIIHeaderMacSkip = 12,
174   kEthertypeIp = 0x0800,
175   kIpVersion4 = 4,
176   kMinIpHeaderLength = 20,
177   kFragmentOffsetClear = 0x0000,
178   kFragmentOffsetDoNotFragment = 0x4000,
179   kProtocolTcp = 0x06,
180   kProtocolUdp = 0x11,
181   kUdpHeaderLength = 8,
182   kMaxReadBufferSize = 4096
183 };
184
185 const uint32_t kPcapBOMSwapOrder = 0xd4c3b2a1UL;
186 const uint32_t kPcapBOMNoSwapOrder = 0xa1b2c3d4UL;
187
188 #define TRY_PCAP(expr)                                 \
189   do {                                                 \
190     int r = (expr);                                    \
191     if (r == kResultFail) {                            \
192       DEBUG_LOG1("FAIL at " __FILE__ ":%d", __LINE__); \
193       return kResultFail;                              \
194     } else if (r == kResultSkip) {                     \
195       return kResultSkip;                              \
196     }                                                  \
197   } while (0)
198
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 {
202  public:
203   PcapReader()
204     : file_(NULL),
205       swap_pcap_byte_order_(false),
206 #ifdef WEBRTC_ARCH_BIG_ENDIAN
207       swap_network_byte_order_(false),
208 #else
209       swap_network_byte_order_(true),
210 #endif
211       read_buffer_(),
212       packets_by_ssrc_(),
213       packets_(),
214       next_packet_it_() {
215   }
216
217   virtual ~PcapReader() {
218     if (file_ != NULL) {
219       fclose(file_);
220       file_ = NULL;
221     }
222   }
223
224   bool Init(const std::string& filename) OVERRIDE {
225     return Initialize(filename) == kResultSuccess;
226   }
227
228   int Initialize(const std::string& filename) {
229     file_ = fopen(filename.c_str(), "rb");
230     if (file_ == NULL) {
231       printf("ERROR: Can't open file: %s\n", filename.c_str());
232       return kResultFail;
233     }
234
235     if (ReadGlobalHeader() < 0) {
236       return kResultFail;
237     }
238
239     int total_packet_count = 0;
240     uint32_t stream_start_ms = 0;
241     int32_t next_packet_pos = ftell(file_);
242     for (;;) {
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) {
247         break;
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;
253       }
254     }
255
256     if (feof(file_) == 0) {
257       printf("Failed reading file!\n");
258       return kResultFail;
259     }
260
261     printf("Total packets in file: %d\n", total_packet_count);
262     printf("Total RTP/RTCP packets: %d\n", static_cast<int>(packets_.size()));
263
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);
271     }
272
273     // TODO(solenberg): Better validation of identified SSRC streams.
274     //
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.:
280     //
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.
288
289     next_packet_it_ = packets_.begin();
290     return kResultSuccess;
291   }
292
293   virtual bool NextPacket(Packet* packet) OVERRIDE {
294     uint32_t length = Packet::kMaxPacketBufferSize;
295     if (NextPcap(packet->data, &length, &packet->time_ms) != kResultSuccess)
296       return false;
297     packet->length = static_cast<size_t>(length);
298     packet->original_length = packet->length;
299     return true;
300   }
301
302   virtual int NextPcap(uint8_t* data, uint32_t* length, uint32_t* time_ms) {
303     assert(data);
304     assert(length);
305     assert(time_ms);
306
307     if (next_packet_it_ == packets_.end()) {
308       return -1;
309     }
310     if (*length < next_packet_it_->payload_length) {
311       return -1;
312     }
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;
317     next_packet_it_++;
318
319     return 0;
320   }
321
322  private:
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;
327     uint32_t source_ip;
328     uint32_t dest_ip;
329     uint16_t source_port;
330     uint16_t dest_port;
331     RTPHeader rtp_header;
332     int32_t pos_in_file;      // Byte offset of payload from start of file.
333     uint32_t payload_length;
334   };
335
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;
339
340   int ReadGlobalHeader() {
341     uint32_t magic;
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;
347     } else {
348       return kResultFail;
349     }
350
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) {
357       return kResultFail;
358     }
359
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));
368
369     // Accept only LINKTYPE_NULL and LINKTYPE_ETHERNET.
370     // See: http://www.tcpdump.org/linktypes.html
371     if (network != kLinktypeNull && network != kLinktypeEthernet) {
372       return kResultFail;
373     }
374
375     return kResultSuccess;
376   }
377
378   int ReadPacket(int32_t* next_packet_pos, uint32_t stream_start_ms,
379                  uint32_t number) {
380     assert(next_packet_pos);
381
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));
390
391     *next_packet_pos = ftell(file_) + incl_len;
392
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_);
398
399     if (marker.payload_length > sizeof(read_buffer_)) {
400       printf("Packet too large!\n");
401       return kResultFail;
402     }
403     TRY_PCAP(Read(read_buffer_, marker.payload_length));
404
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);
409     } else {
410       if (!rtp_parser.Parse(marker.rtp_header, NULL)) {
411         DEBUG_LOG("Not recognized as RTP/RTCP");
412         return kResultSkip;
413       }
414
415       uint32_t ssrc = marker.rtp_header.ssrc;
416       packets_by_ssrc_[ssrc].push_back(marker.packet_number);
417       packets_.push_back(marker);
418     }
419
420     return kResultSuccess;
421   }
422
423   int ReadPacketHeader(RtpPacketMarker* marker) {
424     int32_t file_pos = ftell(file_);
425
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.
430     uint32_t protocol;
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) {
436         return result;
437       }
438     }
439
440     TRY_PCAP(fseek(file_, file_pos, SEEK_SET));
441
442     // Check for Ethernet II, IP frame header.
443     uint16_t type;
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) {
450         return result;
451       }
452     }
453
454     return kResultSkip;
455   }
456
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 +
460         500) / 1000;
461     uint64_t t1_ms = static_cast<uint64_t>(start_ms);
462     if (t2_ms < t1_ms) {
463       return 0;
464     } else {
465       return t2_ms - t1_ms;
466     }
467   }
468
469   int ReadXxpIpHeader(RtpPacketMarker* marker) {
470     assert(marker);
471
472     uint16_t version;
473     uint16_t length;
474     uint16_t id;
475     uint16_t fragment;
476     uint16_t protocol;
477     uint16_t checksum;
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));
486
487     if (((version >> 12) & 0x000f) != kIpVersion4) {
488       DEBUG_LOG("IP header is not IPv4");
489       return kResultSkip;
490     }
491
492     if (fragment != kFragmentOffsetClear &&
493         fragment != kFragmentOffsetDoNotFragment) {
494       DEBUG_LOG("IP fragments cannot be handled");
495       return kResultSkip;
496     }
497
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));
502
503     protocol = protocol & 0x00ff;
504     if (protocol == kProtocolTcp) {
505       DEBUG_LOG("TCP packets are not handled");
506       return kResultSkip;
507     } else if (protocol == kProtocolUdp) {
508       uint16_t length;
509       uint16_t checksum;
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;
515     } else {
516       DEBUG_LOG("Unknown transport (expected UDP or TCP)");
517       return kResultSkip;
518     }
519
520     return kResultSuccess;
521   }
522
523   int Read(uint32_t* out, bool expect_network_order) {
524     uint32_t tmp = 0;
525     if (fread(&tmp, 1, sizeof(uint32_t), file_) != sizeof(uint32_t)) {
526       return kResultFail;
527     }
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);
532     }
533     *out = tmp;
534     return kResultSuccess;
535   }
536
537   int Read(uint16_t* out, bool expect_network_order) {
538     uint16_t tmp = 0;
539     if (fread(&tmp, 1, sizeof(uint16_t), file_) != sizeof(uint16_t)) {
540       return kResultFail;
541     }
542     if ((!expect_network_order && swap_pcap_byte_order_) ||
543         (expect_network_order && swap_network_byte_order_)) {
544       tmp = ((tmp >> 8) & 0x00ff) | (tmp << 8);
545     }
546     *out = tmp;
547     return kResultSuccess;
548   }
549
550   int Read(uint8_t* out, uint32_t count) {
551     if (fread(out, 1, count, file_) != count) {
552       return kResultFail;
553     }
554     return kResultSuccess;
555   }
556
557   int Read(int32_t* out, bool expect_network_order) {
558     int32_t tmp = 0;
559     if (fread(&tmp, 1, sizeof(uint32_t), file_) != sizeof(uint32_t)) {
560       return kResultFail;
561     }
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);
566     }
567     *out = tmp;
568     return kResultSuccess;
569   }
570
571   int Skip(uint32_t length) {
572     if (fseek(file_, length, SEEK_CUR) != 0) {
573       return kResultFail;
574     }
575     return kResultSuccess;
576   }
577
578   FILE* file_;
579   bool swap_pcap_byte_order_;
580   const bool swap_network_byte_order_;
581   uint8_t read_buffer_[kMaxReadBufferSize];
582
583   SsrcMap packets_by_ssrc_;
584   std::vector<RtpPacketMarker> packets_;
585   PacketIterator next_packet_it_;
586
587   DISALLOW_COPY_AND_ASSIGN(PcapReader);
588 };
589
590 RtpFileReader* RtpFileReader::Create(FileFormat format,
591                                      const std::string& filename) {
592   RtpFileReaderImpl* reader = NULL;
593   switch (format) {
594     case kPcap:
595       reader = new PcapReader();
596       break;
597     case kRtpDump:
598       reader = new RtpDumpReader();
599       break;
600   }
601   if (!reader->Init(filename)) {
602     delete reader;
603     return NULL;
604   }
605   return reader;
606 }
607
608 }  // namespace test
609 }  // namespace webrtc