6 #define PACKET_BUFFER_SIZE 1000
7 #define TIMEOUT_SEC 1.000
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)
20 gettimeofday(&last_sent_packet, NULL);
23 void Reorderer::send_packet(uint16_t proto, const string& data, int seq)
26 gettimeofday(&now, NULL);
29 if (packet_buffer.size() >= PACKET_BUFFER_SIZE) {
30 printf("Gave up waiting for packets [%d,%d> (buffer full)\n",
31 last_seq + 1, packet_buffer.top().seq);
33 last_seq = packet_buffer.top().seq - 1;
34 } else if (!packet_buffer.empty() &&
35 tdiff(packet_buffer.top().ts, now) > TIMEOUT_SEC) {
36 printf("Gave up waiting for packets [%d,%d> (timeout)\n",
37 last_seq + 1, packet_buffer.top().seq);
39 last_seq = packet_buffer.top().seq - 1;
40 // TODO: Rerun immediately after we've cleared out,
41 // in case there are more timeouts.
44 // In case of restarts.
45 if (packet_buffer.empty() &&
47 tdiff(last_sent_packet, now) > 5.0) {
48 printf("No good data for five seconds, resetting sequence to %d\n", seq);
57 packet_buffer.push(packet);
59 while (!packet_buffer.empty() &&
60 (last_seq == -1 || packet_buffer.top().seq <= last_seq + 1)) {
61 int front_seq = packet_buffer.top().seq;
62 if (front_seq < last_seq + 1) {
63 printf("Duplicate packet or way out-of-order: seq=%d front_seq=%d\n",
64 front_seq, last_seq + 1);
68 //if (packet_buffer.size() > 1) {
69 // printf("seq=%d (REORDER %d)\n", front_seq, int(packet_buffer.size()));
71 // printf("seq=%d\n", front_seq);
73 const string &data = packet_buffer.top().data;
74 check_ts_discontinuity(packet_buffer.top().proto, data, silence);
75 sender->send_packet(proto, data, seq);
78 last_sent_packet = now;
79 if (!silence && !packet_buffer.empty()) {
80 printf("Reordering with packet buffer size %d: seq=%d new_front_seq=%d\n", int(packet_buffer.size()), front_seq, packet_buffer.top().seq);
86 void Reorderer::check_ts_discontinuity(uint16_t proto, const string &data, bool silence)
88 if (data.size() == 1344) {
89 for (int i = 0; i < 7; ++i) {
90 const char *pkt = &data[i * 188 + 28];
91 int pid = (ntohl(*(uint32_t *)(pkt)) & 0x1fff00) >> 8;
96 int has_payload = pkt[3] & 0x10;
97 int cc = pkt[3] & 0xf;
99 int last_cc = ccs[pid];
100 if (!silence && cc != ((last_cc + 1) & 0xf)) {
101 printf("Pid %d discontinuity (expected %d, got %d)\n", pid, (last_cc + 1) & 0xf, cc);