6 #define PACKET_BUFFER_SIZE 100
7 #define TIMEOUT_SEC 0.100
11 double tdiff(const timeval& a, const timeval& b)
13 return b.tv_sec - a.tv_sec +
14 1e-6 * (b.tv_usec - a.tv_usec);
17 Reorderer::Reorderer(Sender* sender)
18 : sender(sender), last_seq(-1)
22 void Reorderer::send_packet(uint16_t proto, const string& data, int seq)
25 gettimeofday(&now, NULL);
28 if (packet_buffer.size() >= PACKET_BUFFER_SIZE) {
29 printf("Gave up waiting for packets [%d,%d> (buffer full)\n",
30 last_seq + 1, packet_buffer.top().seq);
32 last_seq = packet_buffer.top().seq - 1;
33 } else if (!packet_buffer.empty() &&
34 tdiff(packet_buffer.top().ts, now) > TIMEOUT_SEC) {
35 printf("Gave up waiting for packets [%d,%d> (timeout)\n",
36 last_seq + 1, packet_buffer.top().seq);
38 last_seq = packet_buffer.top().seq - 1;
39 // TODO: Rerun immediately after we've cleared out,
40 // in case there are more timeouts.
48 packet_buffer.push(packet);
50 while (!packet_buffer.empty() &&
51 (last_seq == -1 || packet_buffer.top().seq <= last_seq + 1)) {
52 int front_seq = packet_buffer.top().seq;
53 if (front_seq < last_seq + 1) {
54 printf("Duplicate packet or way out-of-order: seq=%d front_seq=%d\n",
55 front_seq, last_seq + 1);
59 //if (packet_buffer.size() > 1) {
60 // printf("seq=%d (REORDER %d)\n", front_seq, int(packet_buffer.size()));
62 // printf("seq=%d\n", front_seq);
64 const string &data = packet_buffer.top().data;
65 check_ts_discontinuity(packet_buffer.top().proto, data, silence);
66 sender->send_packet(proto, data, seq);
69 if (!silence && !packet_buffer.empty()) {
70 printf("Reordering with packet buffer size %d: seq=%d new_front_seq=%d\n", int(packet_buffer.size()), front_seq, packet_buffer.top().seq);
76 void Reorderer::check_ts_discontinuity(uint16_t proto, const string &data, bool silence)
78 if (data.size() == 1344) {
79 for (int i = 0; i < 7; ++i) {
80 const char *pkt = &data[i * 188 + 28];
81 int pid = (ntohl(*(uint32_t *)(pkt)) & 0x1fff00) >> 8;
86 int has_payload = pkt[3] & 0x10;
87 int cc = pkt[3] & 0xf;
89 int last_cc = ccs[pid];
90 if (!silence && cc != ((last_cc + 1) & 0xf)) {
91 printf("Pid %d discontinuity (expected %d, got %d)\n", pid, (last_cc + 1) & 0xf, cc);