mgcp: Calculate the packet loss as of Appendix A of RFC 3550

Calculate the expected packages and packet loss as of RFC 3550.
The values should be clamped but our packet loss counter is 32
bits and not 24 and we should clamp at other values but I am
waiting for some issues first before dealing with that.
diff --git a/openbsc/src/libmgcp/mgcp_network.c b/openbsc/src/libmgcp/mgcp_network.c
index 233418b..fe72b7b 100644
--- a/openbsc/src/libmgcp/mgcp_network.c
+++ b/openbsc/src/libmgcp/mgcp_network.c
@@ -2,8 +2,8 @@
 /* The protocol implementation */
 
 /*
- * (C) 2009-2011 by Holger Hans Peter Freyther <zecke@selfish.org>
- * (C) 2009-2011 by On-Waves
+ * (C) 2009-2012 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * (C) 2009-2012 by On-Waves
  * All Rights Reserved
  *
  * This program is free software; you can redistribute it and/or modify
@@ -607,3 +607,31 @@
 
 	return 0;
 }
+
+
+void mgcp_state_calc_loss(struct mgcp_rtp_state *state,
+			struct mgcp_rtp_end *end, uint32_t *expected,
+			int *loss)
+{
+	*expected = state->cycles + state->max_seq;
+	*expected = *expected - state->base_seq + 1;
+
+	if (!state->initialized) {
+		*expected = 0;
+		*loss = 0;
+		return;
+	}
+
+	/*
+	 * Make sure the sign is correct and use the biggest
+	 * positive/negative number that fits.
+	 */
+	*loss = *expected - end->packets;
+	if (*expected < end->packets) {
+		if (*loss > 0)
+			*loss = INT_MIN;
+	} else {
+		if (*loss < 0)
+			*loss = INT_MAX;
+	}
+}
diff --git a/openbsc/src/libmgcp/mgcp_protocol.c b/openbsc/src/libmgcp/mgcp_protocol.c
index d57ad00..0d8e9ea 100644
--- a/openbsc/src/libmgcp/mgcp_protocol.c
+++ b/openbsc/src/libmgcp/mgcp_protocol.c
@@ -1121,8 +1121,14 @@
 
 void mgcp_format_stats(struct mgcp_endpoint *endp, char *msg, size_t size)
 {
-	snprintf(msg, size, "\r\nP: PS=%u, OS=%u, PR=%u, OR=%u",
+	uint32_t expected;
+	int ploss;
+	mgcp_state_calc_loss(&endp->net_state, &endp->net_end,
+				&expected, &ploss);
+
+	snprintf(msg, size, "\r\nP: PS=%u, OS=%u, PR=%u, OR=%u, PL=%d",
 			endp->bts_end.packets, endp->bts_end.octets,
-			endp->net_end.packets, endp->net_end.octets);
+			endp->net_end.packets, endp->net_end.octets,
+			ploss);
 	msg[size - 1] = '\0';
 }