7 #define PACKET_BUFFER_SIZE 1000
8 #define TIMEOUT_SEC 1.000
12 Reorderer::Reorderer(Sender* sender)
13 : sender(sender), last_seq(-1)
15 gettimeofday(&last_sent_packet, NULL);
18 void Reorderer::send_packet(uint16_t proto, const string& data, int seq)
21 gettimeofday(&now, NULL);
24 if (packet_buffer.size() >= PACKET_BUFFER_SIZE) {
25 printf("Gave up waiting for packets [%d,%d> (buffer full)\n",
26 last_seq + 1, packet_buffer.top().seq);
28 last_seq = packet_buffer.top().seq - 1;
29 } else if (!packet_buffer.empty() &&
30 tdiff(packet_buffer.top().ts, now) > TIMEOUT_SEC) {
31 printf("Gave up waiting for packets [%d,%d> (timeout)\n",
32 last_seq + 1, packet_buffer.top().seq);
34 last_seq = packet_buffer.top().seq - 1;
35 // TODO: Rerun immediately after we've cleared out,
36 // in case there are more timeouts.
39 // In case of restarts.
40 if (packet_buffer.empty() &&
42 tdiff(last_sent_packet, now) > 5.0) {
43 printf("No good data for five seconds, resetting sequence to %d\n", seq);
52 packet_buffer.push(packet);
54 while (!packet_buffer.empty() &&
55 (last_seq == -1 || packet_buffer.top().seq <= last_seq + 1)) {
56 int front_seq = packet_buffer.top().seq;
57 if (front_seq < last_seq + 1) {
58 printf("Duplicate packet or way out-of-order: seq=%d front_seq=%d\n",
59 front_seq, last_seq + 1);
63 //if (packet_buffer.size() > 1) {
64 // printf("seq=%d (REORDER %d)\n", front_seq, int(packet_buffer.size()));
66 // printf("seq=%d\n", front_seq);
68 const string &data = packet_buffer.top().data;
69 check_ts_discontinuity(packet_buffer.top().proto, data, silence);
70 sender->send_packet(proto, data, seq);
73 last_sent_packet = now;
74 if (!silence && !packet_buffer.empty()) {
75 printf("Reordering with packet buffer size %d: seq=%d new_front_seq=%d\n", int(packet_buffer.size()), front_seq, packet_buffer.top().seq);
81 void Reorderer::check_ts_discontinuity(uint16_t proto, const string &data, bool silence)
83 if (data.size() == 1344) {
84 for (int i = 0; i < 7; ++i) {
85 const char *pkt = &data[i * 188 + 28];
86 int pid = (ntohl(*(uint32_t *)(pkt)) & 0x1fff00) >> 8;
91 int has_payload = pkt[3] & 0x10;
92 int cc = pkt[3] & 0xf;
94 int last_cc = ccs[pid];
95 if (!silence && cc != ((last_cc + 1) & 0xf)) {
96 printf("Pid %d discontinuity (expected %d, got %d)\n", pid, (last_cc + 1) & 0xf, cc);