Added Realtime Text (RFC 4103) without having tied it to the phone software yet
authorRick van Rein <vanrein@hwdev.(none)>
Tue, 15 Nov 2011 14:05:59 +0000 (14:05 +0000)
committerRick van Rein <vanrein@hwdev.(none)>
Tue, 15 Nov 2011 14:05:59 +0000 (14:05 +0000)
31 files changed:
src/codec/README [new file with mode: 0644]
src/codec/rtt/Makefile.desktop [new file with mode: 0644]
src/codec/rtt/README [new file with mode: 0644]
src/codec/rtt/TODO [new file with mode: 0644]
src/codec/rtt/desktop.c [new file with mode: 0644]
src/codec/rtt/recvkeys.c [new file with mode: 0644]
src/codec/rtt/sendkeys.c [new file with mode: 0644]
src/codec/rtt/sendkeys_orig.c [new file with mode: 0644]
src/codec/spandsp/AUTHORS [new file with mode: 0644]
src/codec/spandsp/COPYING [new file with mode: 0644]
src/codec/spandsp/README [new file with mode: 0644]
src/codec/spandsp/README.0cpm-Firmerware [new file with mode: 0644]
src/codec/spandsp/src/floating_fudge.h [new file with mode: 0644]
src/codec/spandsp/src/g711.c [new file with mode: 0644]
src/codec/spandsp/src/g722.c [new file with mode: 0644]
src/codec/spandsp/src/g726.c [new file with mode: 0644]
src/codec/spandsp/src/spandsp/bit_operations.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/bitstream.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/dc_restore.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/fast_convert.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/g711.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/g722.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/g726.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/private/README [new file with mode: 0644]
src/codec/spandsp/src/spandsp/private/bitstream.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/private/g711.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/private/g722.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/private/g726.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/saturated.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/telephony.h [new file with mode: 0644]
src/codec/spandsp/src/spandsp/vector_int.h [new file with mode: 0644]

diff --git a/src/codec/README b/src/codec/README
new file mode 100644 (file)
index 0000000..5902e1f
--- /dev/null
@@ -0,0 +1,26 @@
+Codec selection for 0cpm Firmerware
+===================================
+
+The codecs in this tree have been defined with a number of goals in mind:
+
+* No patent-encumbered codecs: patents constipate progress
+* Support for encryption through ZRTP
+* Support for various applications in common use:
+
+  - G.711 for direct exchanges with ISDN
+  - G.726 for direct exchanges with DECT
+  - G.722 for direct exchanges with wideband VoIP and CAT-iq
+  - Speex for its wide range and excellent quality/bitrate ratio
+
+* Enhancement of facilities:
+
+  - RTT helps with speech and hearing impairments; and can speedup IVRs for the rest of us
+  - Ogg/RTP can play radio stations from multicast sources
+  - L16 can play PCM and replace computer sound devices
+
+
+Codecs that are large are made optional:
+
+* Ogg decoding (Internet radio support) could be done by the multicasting node
+* Speex encoder/decoder which consumes about 100 kB of code size
+
diff --git a/src/codec/rtt/Makefile.desktop b/src/codec/rtt/Makefile.desktop
new file mode 100644 (file)
index 0000000..7e0c25c
--- /dev/null
@@ -0,0 +1,23 @@
+TARGET=rtt_desktop_test
+OBJS=recvkeys.o sendkeys.o desktop.o
+
+# CFLAGS=-m32
+CFLAGS=-m64
+
+# CFLAGS+=-ggdb3
+
+all: tags $(TARGET)
+
+clean:
+       rm -f $(TARGET) *.o *.obj
+
+anew: clean all
+
+.c.o:
+       gcc $(CFLAGS) -I/usr/include -I../../../include -c -o $@ $<
+
+$(TARGET): $(OBJS)
+       gcc $(CFLAGS) -o $@ $(OBJS)
+
+tags:
+       ctags *.c
diff --git a/src/codec/rtt/README b/src/codec/rtt/README
new file mode 100644 (file)
index 0000000..97fea7b
--- /dev/null
@@ -0,0 +1,75 @@
+Realtime Text support
+=====================
+
+This is an implementation of RFC 4103, "RTP Payload for Text Conversation".  Note
+that 2 errata exist to this specification.  The 0cpm Firmerware implements both
+the text/t.140 and the text/red MIME-types.  It is currently limited to ASCII
+transmissions plus a few special control characters.
+
+Realtime Text or RTT is an RTP profile that exchanges text as soon as it is typed.
+Aside from being a great asset for people with speach or hearing impairments, it is
+also a good way to automatically attend to users.  Think of menus shown on your
+display, instead of slowly read out by an IVR.  Or both.  You'll steer your way
+through annnoying menus at a much faster pace!
+
+This implementation was made specifically for the 0cpm Firmerware.  It exhibits a
+call rtt_send_keys () that buffers a few keystrokes for a limited amount of
+time, and ships them off at the specified intervals.  The other way around, a call
+to rtt_recv_keys () is made to display one or more new keystrokes.  The
+error detection/correction incorporated into RTT is implemented in this module,
+so the application can assume a fairly reliable keypress exchange interface.
+
+To the user, RTT will show itself as an application named "text".  It will popup
+as soon as RTT is sent to the phone, in response to it being offered as part of
+the SDP negotiation.  If the remote side supports reception of RTT, then this
+application will also be enabled to the user, who may then pull it up manually.
+The end user will hardly notice that RTT is being used; to him, it will simply
+be useful to have a texting facility in parallel to speech, and a bit special
+that the interaction is live.  The automated popup when RTT is received by the
+phone calls for the user's attention at just the right moments.
+
+
+Try it on a desktop
+-------------------
+
+The RTT functions described here can be tested separately on a desktop system.
+This simplifies development and may also be a starting point for cool games,
+adventures and general inetd wrapping schemes for communication with an
+automated attended of various kinds.  In doing so, please remember that the
+software resides under GPLv3, like the rest of the 0cpm Firmerware.
+
+To build it, use the specially supplied Makefile and the wrapper functions in
+desktop.c -- but please note that this was made for testing purposes, and not
+for portability.  Your best chances are on Linux.
+
+To build, run::
+
+       make -f Makefile.desktop
+
+To test, run a command like this on each side::
+
+       ./rtt_desktop_test /dev/tty3 2001:db8:123::45 1212 2001:db8:99::6 1313
+
+The parameters are:
+
+* ``/dev/tty3`` is the terminal to which output should be sent.  The terminal
+  on which this is run will become the input terminal.  Using different
+  terminals for input and output avoids cluttered output.
+
+* ``2001:db8:123::45`` and ``1212`` are the local address and port to bind to.
+
+* ``2001:db8:99::6`` and ``1313`` are the remote address and port to connect to.
+
+If you wanted to use IPv4 you would prefix the address with ``::`` and get
+away with it -- but you might have trouble routing through NAT.  The tester
+opens a hole in customary local firewalls, including NAT, but the translation
+of the address may make it impossible to bootstrap the connection.  It is time
+that we came to the realisation that peer-to-peer communication, of which this
+clearly is an example, requires the use of IPv6 to do it well.  If you need
+a quick IPv6 tunnel, you can use the 6bed4 mechanism, described on
+http://devel.0cpm.org/6bed4/
+
+
+Have fun!
+
+Rick van Rein
diff --git a/src/codec/rtt/TODO b/src/codec/rtt/TODO
new file mode 100644 (file)
index 0000000..86975e2
--- /dev/null
@@ -0,0 +1 @@
+X bs-key zendt als DEL
diff --git a/src/codec/rtt/desktop.c b/src/codec/rtt/desktop.c
new file mode 100644 (file)
index 0000000..c38acac
--- /dev/null
@@ -0,0 +1,360 @@
+/* Realtime Text sending, according to RFC 4103 (plus its 2 errata).
+ *
+ * This file is part of 0cpm Firmerware, but will not be included
+ * in the firmware itself.  It is here for testing on a desktop
+ * system.  See the README in this directory for details.
+ *
+ * 0cpm Firmerware is Copyright (c)2011 Rick van Rein, OpenFortress.
+ *
+ * 0cpm Firmerware is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 3.
+ *
+ * 0cpm Firmerware is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with 0cpm Firmerware.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+
+#include <config.h>
+
+#include <0cpm/cpu.h>
+#include <0cpm/irq.h>
+#include <0cpm/timer.h>
+
+// #include <0cpm/netdb.h>
+// #include <0cpm/netinet.h>
+typedef uint8_t  nint8_t;
+typedef uint16_t nint16_t;
+typedef uint32_t nint32_t;
+#include <0cpm/netfun.h>
+
+#undef htons
+#undef htonl
+#undef ntohs
+#undef ntohl
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <termios.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <sys/timeb.h>
+
+
+extern uint8_t rtt_paytp_red;
+extern uint8_t rtt_paytp_t140;
+
+
+packet_t wbuf;
+
+
+bool have_timer = false;
+struct timeval timer;
+irqtimer_t *rtos_timer;
+irq_handler_t timer_hdl;
+
+int sox;
+
+
+struct termios stdin_oldstate;
+
+
+/* Return the time in the timer base value */
+timing_t bottom_time (void) {
+       struct timeb tp;
+       ftime (&tp);
+       return ((timing_t) tp.time) * TIME_MSEC (1000) + tp.millitm * TIME_MSEC (1);
+}
+
+
+/* Prefix and fill UDP/IPv6 headers -- Linux socket does that for us */
+uint8_t *netsend_udp6 (uint8_t *pout, intptr_t *mem) {
+       mem [MEM_UDP6_HEAD] = (intptr_t) pout;
+       return pout;
+}
+
+/* Send buffer after calculating checksums -- which Linux will handle for us */
+void netcore_send_buffer (intptr_t *mem, uint8_t *wbuf) {
+       size_t udp6len = mem [MEM_ALL_DONE] - mem [MEM_UDP6_HEAD];
+       if (send (sox, wbuf, udp6len, 0) == -1) {
+               perror ("Failed sending keystrokes");
+       }
+}
+
+
+/* RTT received key presses -- process them by printing on the output tty */
+void rtt_recv_keys (uint8_t *text, uint16_t len) {
+       ssize_t shown = write (1, text, len);
+       if (shown != (ssize_t) len) {
+               fprintf (stderr, "\nWarning: Only %d out of %d characters shown\n", (int) shown, (int) len);
+       }
+}
+
+
+void irqtimer_start (irqtimer_t *tmr, timing_t dt, irq_handler_t hdl, priority_t prio) {
+       /*
+        * Explicitly use the fact that Linux reduces the timer value
+        * when it returns from select(), so another call would just
+        * continue with the timer, a somewhat inaccurate but
+        * test-worthy but realtime timer mechanism.
+        */
+       rtos_timer = tmr;
+       have_timer = true;
+       timer_hdl = hdl;
+       timer.tv_sec = 0;
+       timer.tv_usec = dt * TIME_MSEC (1000);          /* 1000 is strange but effective */
+}
+
+void irqtimer_restart (irqtimer_t *tmr, timing_t dt) {
+       /*
+        * Although it would be best to add this offset to the time of
+        * the previous timer expiry, simply restarting when done will be
+        * sufficiently accurate for testing purposes.
+        */
+       irqtimer_start (tmr, dt, timer_hdl, 0);
+}
+
+void irqtimer_stop (irqtimer_t *tmr) {
+       /*
+        * Not having a timer actually means that the timer is used at
+        * a 57-second interval, and an empty UDP message is sent out,
+        * under the assumption that this interval will suffice to keep
+        * local firewalls open for return traffic.  As a result, a
+        * session should not expire as long as both ends are running
+        * this program.
+        *
+        * Explicitly use the fact that Linux reduces the timer value
+        * when it returns from select(), so another call would just
+        * continue with the timer, a somewhat inaccurate but
+        * test-worthy but realtime timer mechanism.
+        */
+       have_timer = false;
+       timer.tv_sec = 57;
+       timer.tv_usec = 0;
+}
+
+
+/* Open local firewalls for RTT, or keep them open */
+void open_local_firewalls () {
+       if (send (sox, "", 0, 0) == -1) {
+               perror ("Failed opening firewall hole");
+       }
+       irqtimer_stop (NULL);
+}
+
+
+/* Return stdin tty to normal use; done at exit */
+void stdin_reset(void) { /* set it to normal! */
+       tcsetattr(0, TCSAFLUSH, &stdin_oldstate);
+}
+
+/* Code based on online demonstration code */
+void stdin_raw(void) {       /* RAW! mode */
+       struct termios  stdin_newstate;
+
+       if (tcgetattr(0, &stdin_oldstate) < 0) { /* get the original state */
+               fprintf (stderr, "Failed to retrieve original terminal setup\n");
+               exit (1);
+       }
+       atexit (stdin_reset);
+
+       stdin_newstate = stdin_oldstate;
+
+       stdin_newstate.c_lflag &= ~( ICANON | IEXTEN | ISIG);
+                    /* canonical mode off, extended input
+                       processing off, signal chars off;
+                      do not suppress local echo */
+
+       stdin_newstate.c_iflag &= ~(BRKINT | ISTRIP | IXON);
+                    /* no SIGINT on BREAK, input parity
+                       check off, don't strip the 8th bit on input,
+                       ouput flow control off;
+                      retain CR-toNL off */
+
+       stdin_newstate.c_lflag |= ISIG;
+                   /* recognise and process specials like ^C */
+
+       stdin_newstate.c_cflag &= ~(CSIZE | PARENB);
+                    /* clear size bits, parity checking off */
+
+       stdin_newstate.c_cflag |= CS8;
+                    /* set 8 bits/char */
+
+       // stdin_newstate.c_oflag &= ~(OPOST);
+                    /* output processing off */
+
+       // stdin_newstate.c_oflag |= ONLCR;
+                   /* map newline to CR-LF on output  */
+
+       stdin_newstate.c_cc[VMIN] = 1;  /* 1 byte at a time */
+       stdin_newstate.c_cc[VTIME] = 0; /* no timer on input */
+       stdin_newstate.c_cc[VERASE] = 127; /* use backspace to delete characters */
+
+       if (tcsetattr(0, TCSAFLUSH, &stdin_newstate) < 0) {
+               perror ("Failed to reconfigure input in raw mode\n");
+               exit (1);
+       }
+}
+
+
+int main (int argc, char *argv []) {
+       int fdo;
+       int port;
+       uint8_t input [20];
+       size_t inlen = 0;
+       uint16_t inofs = 0;
+       struct sockaddr_in6 local, remot;
+       //
+       // Test arguments
+       if (argc != 6) {
+               fprintf (stderr, "Usage: %s /dev/ttyN myAddr myPort remoteAddr remotePort\n"
+                               "   Where /dev/ttyN is an output terminal, and addresses are IPv6.\n"
+                               "   This is not a fancy interface, but rather demonstrates the protocol.\n",
+                       argv [0]);
+               exit (1);
+       }
+       //
+       // Test stdin to be interactive
+       if (!isatty (0)) {
+               fprintf (stderr, "Please run the command with a terminal for input\n");
+               exit (1);
+       }
+       //
+       // Create sockaddr_in6 for local/remot
+       bzero (&local, sizeof (local));
+       bzero (&remot, sizeof (remot));
+       local.sin6_family = AF_INET6;
+       remot.sin6_family = AF_INET6;
+       if (inet_pton (AF_INET6, argv [2], &local.sin6_addr) != 1) {
+               fprintf (stderr, "Failed to parse local IPv6 address\n");
+               exit (1);
+       }
+       if (inet_pton (AF_INET6, argv [4], &remot.sin6_addr) != 1) {
+               fprintf (stderr, "Failed to parse remote IPv6 address\n");
+               exit (1);
+       }
+       port = atoi (argv [3]);
+       if ((port <= 0) || (port > 65535)) {
+               fprintf (stderr, "Invalid local port\n");
+               exit (1);
+       }
+       local.sin6_port = htons (port);
+       port = atoi (argv [5]);
+       if ((port <= 0) || (port > 65535)) {
+               fprintf (stderr, "Invalid remote port\n");
+               exit (1);
+       }
+       remot.sin6_port = htons (port);
+       //
+       // Create a socket for UDP with the given endpoints
+       sox = socket (AF_INET6, SOCK_DGRAM, 0);
+       if (sox == -1) {
+               perror ("Failed to create local UDP socket");
+               exit (1);
+       }
+       if (bind (sox, (struct sockaddr *) &local, sizeof (local)) == -1) {
+               perror ("Failed to bind to local address/port");
+               exit (1);
+       }
+       if (connect (sox, (struct sockaddr *) &remot, sizeof (remot)) == -1) {
+               perror ("Failed to setup remote address/port");
+               exit (1);
+       }
+       //
+       // An empty UDP message will open any local firewalls for return traffic
+       open_local_firewalls ();
+       //
+       // Replace stdout with provided terminal handle
+       fdo = open (argv [1], O_RDWR);
+       if (fdo == -1) {
+               fprintf (stderr, "Failed to write output to %s\n", argv [1]);
+               exit (1);
+       }
+       close (1);
+       if (dup2 (fdo, 1) == -1) {
+               perror ("Failed to redirect output");
+               exit (1);
+       }
+       close (fdo);
+       //
+       // Change input to raw mode (and have it returned to normal upon exit)
+       stdin_raw ();
+       //
+       // Main loop -- wait for input from stdin or the UDP port, and relay it
+       while (true) {
+               fd_set ears;
+               int seln;
+               FD_ZERO (&ears);
+               if (inlen == 0) {
+                       FD_SET (0, &ears);      // Only when nothing left to send
+               }
+               FD_SET (sox,   &ears);          // No limits on incoming cps
+               seln = select (sox+1, &ears, NULL, NULL, &timer);
+               if (seln == -1) {
+                       perror ("Failed to select input source");
+                       exit (1);
+               }
+               if (seln == 0) {
+                       if (have_timer) {
+                               (*timer_hdl) (&rtos_timer->tmr_irq);
+                               if (inlen > 0) {
+                                       /* Try again on pending data */
+                                       FD_SET (0, &ears);
+                               }
+                       } else {
+                               open_local_firewalls ();
+                       }
+               }
+               if (FD_ISSET (0, &ears)) {
+                       /* If no input awaits sending, pickup new data */
+                       if (inlen == 0) {
+                               inlen = read (0, input, sizeof (input));
+                               inofs = 0;
+                               if (inlen == -1) {
+                                       perror ("Error reading from stdin");
+                                       exit (1);
+                               }
+                       }
+                       /* If input is available, send as much of it as possible */
+                       if (inlen > 0) {
+                               uint16_t fwlen = rtt_send_keys (input + inofs, (uint16_t) inlen);
+                               inlen -= fwlen;
+                               inofs += fwlen;
+                       }
+               }
+               if (FD_ISSET (sox, &ears)) {
+                       uint8_t rtpbuf [2048];
+                       size_t rtplen = recv (sox, rtpbuf, sizeof (rtpbuf), 0);
+                       if (rtplen == -1) {
+                               perror ("Failed to receive realtime text");
+                               //TODO:WAIT4PEER// exit (1);
+                       }
+                       if (rtplen < 12) {
+                               continue;
+                       }
+                       if ((rtpbuf [1] & 0x7f) == rtt_paytp_red)  {
+                               rtp_paytype_text_red (rtpbuf, rtplen);
+                       } else if ((rtpbuf [1] & 0x7f) == rtt_paytp_t140) {
+                               rtp_paytype_text_t140 (rtpbuf, rtplen);
+                       } else {
+                               //TODO:TOO_TOLERANT?// fprintf (stderr, "Received RTP with unknown payload type %d\n", rtpbuf [1] & 0x7f);
+                               //TODO:TOO_TOLERANT?// exit (1);
+                       }
+               }
+       }
+}
+
diff --git a/src/codec/rtt/recvkeys.c b/src/codec/rtt/recvkeys.c
new file mode 100644 (file)
index 0000000..2de2ce4
--- /dev/null
@@ -0,0 +1,161 @@
+/* Realtime Text sending, according to RFC 4103 (plus its 2 errata).
+ *
+ * RTT or Realtime Text was designed to support people with speech or
+ * hearing impairments to communicate interactively with text.  The
+ * realtime delivery of keystrokes is also useful to plain users,
+ * for instance in interactive menu's served by an automated attendent.
+ * For this reason, it is built into the 0cpm Firmerware by default.
+ * An extra reason is that impaired people can now reach more other
+ * people over plain telephony.
+ *
+ * To the end-user, RTT will merely show as an application named
+ * "text" that happens to be interactive.  It can also be encrypted
+ * through ZRTP, another advantage for this style of messaging.
+ *
+ * RTT is announced with MIME-types text/t140 and text/red in an SDP
+ * profile.  If it is offered, the 0cpm Firmerware will enable an
+ * application for local text entry, as well as display of text.  The
+ * remote side is offered text/t140 and text/red in all SDP offers,
+ * and any subsequent sends to this service will cause text to popup.
+ *
+ * This file is part of 0cpm Firmerware.
+ *
+ * 0cpm Firmerware is Copyright (c)2011 Rick van Rein, OpenFortress.
+ *
+ * 0cpm Firmerware is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 3.
+ *
+ * 0cpm Firmerware is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with 0cpm Firmerware.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+
+#include <config.h>
+
+#include <0cpm/cpu.h>
+#include <0cpm/irq.h>
+#include <0cpm/timer.h>
+
+typedef unsigned char uint8_t;
+
+#include <0cpm/netdb.h>
+#include <0cpm/netinet.h>
+#include <0cpm/netfun.h>
+
+
+/* The missing character code 0xfffd, encoded in UTF-8 */
+uint8_t rtt_missing_text [] = { 0xef, 0xbf, 0xbd };
+
+/* The newline character 0x2028, encoded in UTF-8 */
+uint8_t rtt_linesep [] = { 0xe2, 0x80, 0xa8 };
+
+
+static uint16_t rtt_seqnr;
+
+
+static void rtt_skipheader (uint8_t **msg, uint16_t *len, uint16_t *newseqptr, uint16_t *gencountptr) {
+       uint8_t hdrlen = 12;
+       uint8_t gencount;
+       if ((*msg) [0] & 0x20) {        /* "P" for padding? */
+               *len -= (*msg) [*len - 1];
+       }
+       hdrlen += ((*msg) [0] & 0x0f) << 2;
+       if ((*msg) [0] & 0x10) {        /* "X" for extension header? */
+               hdrlen += netget16 (* (nint16_t *) &(*msg) [hdrlen]);
+
+       }
+       *newseqptr = netget16 (* (nint16_t *) &(*msg) [2]);
+       if ((*msg) [1] & 0x80) {        /* "M" marks (re)start of a sequence */
+               rtt_seqnr = *newseqptr - 1;
+       }
+       *msg += hdrlen;
+       *len -= hdrlen;
+       if (gencountptr) {
+               uint8_t *msgptr = *msg;
+               gencount = 1;
+               while (*msgptr & 0x80) {
+                       msgptr += 4;
+                       gencount++;
+               }
+               *gencountptr = gencount;
+       }
+}
+
+
+void rtp_paytype_text_t140 (uint8_t *msg, uint16_t len) {
+       uint16_t newseq;
+       void rtt_recv_keys (uint8_t *text, uint16_t len);
+       rtt_skipheader (&msg, &len, &newseq, NULL);
+       switch ((int16_t) (newseq - rtt_seqnr)) {
+       case -2:
+       case -1:
+       case 0:
+               /* Replicated packet, known seqnr */
+               return;
+       default:
+               /* Packets out of sync, report missing text */
+               rtt_recv_keys (rtt_missing_text, sizeof (rtt_missing_text));
+               // ...continue into handling the one extension...
+       case 1:
+               /* Packets properly ordered */
+               rtt_recv_keys (msg, len);
+               rtt_seqnr = newseq;
+       }
+}
+
+
+void rtp_paytype_text_red (uint8_t *msg, uint16_t len) {
+       uint16_t newseq;
+       uint16_t gencount, skipcount, skipbytes;
+       void rtt_recv_keys (uint8_t *text, uint16_t len);
+       rtt_skipheader (&msg, &len, &newseq, &gencount);
+       //
+       // Skip the redundant parts that were processed before
+       if (gencount < (newseq - rtt_seqnr)) {
+               /* Packets are missing -- report and use what is supplied */
+               rtt_recv_keys (rtt_missing_text, sizeof (rtt_missing_text));
+               skipcount = 0;
+       } else {
+               /* No missing packets -- skip 0 or more redundant generations */
+               skipcount = gencount - (newseq - rtt_seqnr);
+       }
+       rtt_seqnr = newseq;
+       skipbytes = 0;
+       while (skipcount-- > 0) {
+               uint16_t blklen = ((msg [2] & 0x03) << 8) | msg [3];
+               skipbytes += blklen;
+               len -= 4;
+               if ((msg [0] & 0x80) == 0x00) {
+                       break;  // This must have been the last one
+               }
+               msg += 4;
+       }
+       while ((msg [0] & 0x80) == 0x80) {
+               /* Continue to skip headers, but produce their bytes later on */
+               len -= 4;
+               msg += 4;
+       }
+       msg++;  /* Skip the primary element header */
+       len--;
+       msg += skipbytes;       /* Skip the duplicated bytes (from skipcount) */
+       len -= skipbytes;
+       //
+       // Copy the redundant parts that are new
+       if (((int16_t) len) > 0) {
+               rtt_recv_keys (msg, len);
+       }
+}
+
+
diff --git a/src/codec/rtt/sendkeys.c b/src/codec/rtt/sendkeys.c
new file mode 100644 (file)
index 0000000..86b7a94
--- /dev/null
@@ -0,0 +1,258 @@
+/* Realtime Text sending, according to RFC 4103 (plus its 2 errata).
+ *
+ * RTT or Realtime Text was designed to support people with speech or
+ * hearing impairments to communicate interactively with text.  The
+ * realtime delivery of keystrokes is also useful to plain users,
+ * for instance in interactive menu's served by an automated attendent.
+ * For this reason, it is built into the 0cpm Firmerware by default.
+ * An extra reason is that impaired people can now reach more other
+ * people over plain telephony.
+ *
+ * To the end-user, RTT will merely show as an application named
+ * "text" that happens to be interactive.  It can also be encrypted
+ * through ZRTP, another advantage for this style of messaging.
+ *
+ * RTT is announced with MIME-types text/t140 and text/red in an SDP
+ * profile.  If it is offered, the 0cpm Firmerware will enable an
+ * application for local text entry, as well as display of text.  The
+ * remote side is offered text/t140 and text/red in all SDP offers,
+ * and any subsequent sends to this service will cause text to popup.
+ *
+ * This file is part of 0cpm Firmerware.
+ *
+ * 0cpm Firmerware is Copyright (c)2011 Rick van Rein, OpenFortress.
+ *
+ * 0cpm Firmerware is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 3.
+ *
+ * 0cpm Firmerware is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with 0cpm Firmerware.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+
+#include <config.h>
+
+#include <0cpm/cpu.h>
+#include <0cpm/irq.h>
+#include <0cpm/timer.h>
+
+#include <0cpm/netdb.h>
+#include <0cpm/netinet.h>
+#include <0cpm/netfun.h>
+
+
+
+/* The number of historic versions kept for resending */
+#ifndef RTT_GENERATIONS
+#   define RTT_GENERATIONS 3
+#endif
+
+/* The maximum number of key bytes to buffer */
+#ifndef RTT_HISTBUFSZ
+#   define RTT_HISTBUFSZ 128
+#endif
+
+#if RTT_HISTBUFSZ > 1023 * RTT_GENERATIONS
+#   error "Realtime Text cannot handle textblock generations of 1024 or more bytes"
+#endif
+
+/* The current historic generations of history being written */
+static uint8_t rtt_generation = 1;
+
+/* The historic buffer itself */
+static uint8_t rtt_buffer [RTT_HISTBUFSZ];
+
+/* The number of bytes per history version */
+static uint16_t rtt_offsets [RTT_GENERATIONS + 1];
+
+/* The timing of the individual submissions */
+static timing_t rtt_timings [RTT_GENERATIONS + 1];
+
+/* After radio silence, including at the start, send right away */
+static bool rtt_silence = true;
+
+/* Redundancy flag and payload types for redundant and t.140 text */
+bool rtt_redundancy = true;
+uint8_t rtt_paytp_red = 100;
+uint8_t rtt_paytp_t140 = 98;
+
+/* Sequence number for RTP packet counting */
+static uint16_t rtt_seqnr = 0x9a81;    //TODO// Random starting point
+
+/* Timer interrupt for the regular sending interval */
+static irqtimer_t rtt_timer;
+
+
+/* The strut 0xfeff in UTF-8.  ITU calls this "zero width no-break space" */
+uint8_t rtt_strut [] = { 0xef, 0xbb, 0xbf };
+
+
+/* TODO: rtt_init() should fill an rttctx_t for this "codec" */
+
+
+/* Copy from a cyclical buffer to a linear one */
+//TODO// This is generic functionality, move it to a central place
+void memcpy_cyc2lin (uint8_t *dst, uint8_t *src, uint16_t src_ofs, uint16_t src_sz, uint16_t cplen) {
+       uint16_t pass1maxlen = src_sz - src_ofs;
+       if (cplen > pass1maxlen) {
+               memcpy (dst, src + src_ofs, pass1maxlen);
+               dst   += pass1maxlen;
+               cplen -= pass1maxlen;
+               src_ofs = 0;
+       }
+       memcpy (dst, src + src_ofs, cplen);
+}
+
+
+/* Copy from linear buffer to a cyclical one */
+//TODO// This is generic functionality, move it to a central place
+void memcpy_lin2cyc (uint8_t *dst, uint16_t dst_ofs, uint16_t dst_sz, uint8_t *src, uint16_t cplen) {
+       uint16_t pass1maxlen = dst_sz - dst_ofs;
+       if (cplen > pass1maxlen) {
+               memcpy (dst + dst_ofs, src, pass1maxlen);
+               src   += pass1maxlen;
+               cplen -= pass1maxlen;
+               dst_ofs = 0;
+       }
+       memcpy (dst + dst_ofs, src, cplen);
+}
+
+
+
+/* Send the current buffer contents immediately.  This involves
+ * stopping any timer that may have been running.  Unless there
+ * have been three resends with the exact same information, the
+ * timer is restarted to expire in 300 ms from now.
+ *
+ * TODO: Setup cps*0.3 as the size limit for chars to add.
+ */
+void rtt_send_buffer (irq_t *irq) {
+       extern packet_t wbuf;
+       uint8_t *pout = wbuf.data;
+       irqtimer_t *tmr = (irqtimer_t *) irq;
+       intptr_t mem [MEM_NETVAR_COUNT];        //TODO// Consider global or per-connection static mem[]
+       uint8_t idx, idx2;
+       uint16_t cplen;
+       //
+       // If this is the 3rd time of sending nothing, stop the interval timer
+       if ((rtt_generation == RTT_GENERATIONS) && (rtt_offsets [0] == rtt_offsets [RTT_GENERATIONS])) {
+               irqtimer_stop (tmr);
+               rtt_silence = true;
+               return;
+       }
+       //
+       // Construct a buffer with the RTP packet
+       rtt_timings [rtt_generation] = bottom_time () * 1000 / TIME_MSEC (1000);
+       bzero (mem, sizeof (mem));
+       //TODO// Setup mem[] with actual output pointers
+       pout = netsend_udp6 (pout, mem);
+       //TODO// RTP-pktgen is generic functionality, move it to a more central place
+       pout [0] = 0x80;                // V=2, P=0, X=0, CC=0
+       pout [1] = (rtt_redundancy? rtt_paytp_red: rtt_paytp_t140) | (rtt_silence? 0x80: 0x00);
+       netset16 (*(nint16_t *) &pout [2], rtt_seqnr);
+       netset32 (*(nint32_t *) &pout [4], rtt_timings [rtt_generation]);
+       netset32 (*(nint32_t *) &pout [8], 0);          // SSRC -- TODO, 0 OK?
+       rtt_seqnr++;
+       pout += 12;
+       if (rtt_redundancy) {
+               idx2 = 1;
+               idx = idx2;
+               while (idx2 != rtt_generation) {
+                       uint32_t tdiff;
+                       tdiff = rtt_timings [rtt_generation] - rtt_timings [idx2];
+                       if (tdiff <= 16383) {
+                               uint16_t bytelen = (RTT_HISTBUFSZ + rtt_offsets [idx2] - rtt_offsets [idx2-1]) % RTT_HISTBUFSZ;
+                               *pout++ = 0x80 | rtt_paytp_t140;        /* Flag: more to come */
+                               netset16 (*(nint16_t *) pout, (tdiff << 2) | (bytelen >> 8));
+                               pout += 2;
+                               *pout++ = bytelen & 0xff;
+                       } else {
+                               // too old => skip here => also when sending text
+                               idx = idx2 + 1;
+                       }
+                       idx2++;
+               }
+               *pout++ = 0x00 | rtt_paytp_t140;                        /* Flag: last */
+       } else {
+               idx = rtt_generation;
+       }
+       //
+       // Copy bytes from cyclic buffer at rtt_offsets [idx-1]..rtt_offsets [rtt_generation]
+       cplen = (RTT_HISTBUFSZ + rtt_offsets [rtt_generation] - rtt_offsets [idx-1]) % RTT_HISTBUFSZ;
+       memcpy_cyc2lin (pout, rtt_buffer, rtt_offsets [idx-1], RTT_HISTBUFSZ, cplen);
+       pout += cplen;
+       //
+       // Actually send the buffer
+       mem [MEM_ALL_DONE] = (intptr_t) pout;
+       netcore_send_buffer (mem, wbuf.data);
+       //
+       // Move on to the next historic version (optional with t.140)
+       if (rtt_generation < RTT_GENERATIONS) {
+               rtt_generation++;
+               rtt_offsets [rtt_generation] = rtt_offsets [rtt_generation - 1];
+       } else {
+               uint8_t i = 0;
+               while (i++ < RTT_GENERATIONS) {
+                       rtt_offsets [i - 1] = rtt_offsets [i];
+                       rtt_timings [i - 1] = rtt_timings [i];
+               }
+       }
+       if (rtt_silence) {
+               irqtimer_start (tmr, TIME_MSEC(300), rtt_send_buffer, CPU_PRIO_MEDIUM);
+               rtt_silence = false;
+       } else {
+               irqtimer_restart (tmr, TIME_MSEC(300));
+       }
+}
+
+
+/* Send a number of bytes, to indicate one or more keys being pressed.
+ * The return value indicates how much of the offered characters were sent.
+ * If not everything could be sent, it is recommended to wait before
+ * trying to send the rest.  Buffers and sending limits may have gotten
+ * in the way of a long text submission.
+ */
+uint16_t rtt_send_keys (uint8_t *keys, uint16_t len) {
+       uint16_t plen;
+       uint16_t genofs;
+       uint16_t genlen;
+       //
+       // Determine the number of bytes to send in this block
+       // TODO: Maximum can be determined per session, and inlcude cps*0.3
+       genofs = rtt_offsets [rtt_generation];
+       plen = ((RTT_HISTBUFSZ + rtt_offsets [0] - 1) - genofs) % RTT_HISTBUFSZ;
+       if (len < plen) {
+               plen = len;
+       }
+       if (plen >= RTT_HISTBUFSZ / RTT_GENERATIONS) {
+               plen = RTT_HISTBUFSZ / RTT_GENERATIONS;
+       }
+       //TODO// Reduce plen to cover a fixed number of chars
+       //
+       // Store values in the history
+       memcpy_lin2cyc (rtt_buffer, genofs, RTT_HISTBUFSZ, keys, plen);
+       genofs += plen;
+       genofs %= RTT_HISTBUFSZ;
+       rtt_offsets [rtt_generation] = genofs;
+       //
+       // Consider sending the current buffer when currently silent
+       if (rtt_silence) {
+               rtt_send_buffer (&rtt_timer.tmr_irq);   /* Send now, and repeat from now on */
+       }
+       //
+       // Return the number of copied key bytes
+       return plen;
+}
+
diff --git a/src/codec/rtt/sendkeys_orig.c b/src/codec/rtt/sendkeys_orig.c
new file mode 100644 (file)
index 0000000..96ab813
--- /dev/null
@@ -0,0 +1,238 @@
+/* Realtime Text sending, according to RFC 4103 (plus its 2 errata).
+ *
+ * RTT or Realtime Text was designed to support people with speech or
+ * hearing impairments to communicate interactively with text.  The
+ * realtime delivery of keystrokes is also useful to plain users,
+ * for instance in interactive menu's served by an automated attendent.
+ * For this reason, it is built into the 0cpm Firmerware by default.
+ * An extra reason is that impaired people can now reach more other
+ * people over plain telephony.
+ *
+ * To the end-user, RTT will merely show as an application named
+ * "text" that happens to be interactive.  It can also be encrypted
+ * through ZRTP, another advantage for this style of messaging.
+ *
+ * RTT is announced with MIME-types text/t140 and text/red in an SDP
+ * profile.  If it is offered, the 0cpm Firmerware will enable an
+ * application for local text entry, as well as display of text.  The
+ * remote side is offered text/t140 and text/red in all SDP offers,
+ * and any subsequent sends to this service will cause text to popup.
+ *
+ * This file is part of 0cpm Firmerware.
+ *
+ * 0cpm Firmerware is Copyright (c)2011 Rick van Rein, OpenFortress.
+ *
+ * 0cpm Firmerware is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License as
+ * published by the Free Software Foundation, version 3.
+ *
+ * 0cpm Firmerware is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with 0cpm Firmerware.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+
+#include <config.h>
+
+#include <0cpm/cpu.h>
+#include <0cpm/irq.h>
+#include <0cpm/timer.h>
+
+#include <0cpm/netdb.h>
+#include <0cpm/netinet.h>
+#include <0cpm/netfun.h>
+
+
+
+/* The number of historic versions kept for resending */
+#ifndef RTT_HISTLEN
+#   define RTT_HISTLEN 3
+#endif
+
+/* The maximum number of key bytes permitted in each block */
+#ifndef RTT_MAXBYTES
+#   define RTT_MAXBYTES 16
+#endif
+
+#if RTT_MAXBYTES >= 1024
+#   error "Realtime Text cannot handle blocks of 1024 or more bytes"
+#endif
+
+/* The number of historic versions available */
+static uint8_t rtt_histlen = 0;
+
+/* The current history entry being write */
+static uint8_t rtt_histcurr = 0;
+
+/* The number of bytes per history version */
+static uint16_t rtt_histbytes [RTT_HISTLEN];
+
+/* The timing of the individual submissions */
+static timing_t rtt_timing [RTT_HISTLEN];
+
+/* The history itself */
+static uint8_t rtt_history [RTT_HISTLEN] [RTT_MAXBYTES];
+
+/* After radio silence, including at the start, send right away */
+static bool rtt_silence = true;
+
+/* Count the number of repeated sends of the exact same information */
+static uint8_t rtt_repeats = 0;
+static uint8_t rtt_repeated = 0xff;
+
+/* Redundancy flag and payload types for redundant and t.140 text */
+bool rtt_redundancy = true;
+uint8_t rtt_paytp_red = 100;
+uint8_t rtt_paytp_t140 = 98;
+
+/* Sequence number for RTP packet counting */
+static uint16_t rtt_seqnr = 0x9a81;    //TODO// Random starting point
+
+/* Timer interrupt for the regular sending interval */
+static irqtimer_t rtt_timer;
+
+
+/* TODO: rtt_init() should fill an rttctx_t for this "codec" */
+
+
+/* Send the current buffer contents immediately.  This involves
+ * stopping any timer that may have been running.  Unless there
+ * have been three resends with the exact same information, the
+ * timer is restarted to expire in 300 ms from now.
+ */
+void rtt_send_buffer (irq_t *irq) {
+       extern packet_t wbuf;
+       uint8_t *pout = wbuf.data;
+       irqtimer_t *tmr = (irqtimer_t *) irq;
+       intptr_t mem [MEM_NETVAR_COUNT];        //TODO// Consider purpose-specific global mem[]
+       uint8_t idx, idx2;
+       //
+       // Stop any current timer activity
+       //TODO// Better to use restart further down, and always fire this after timer exp
+       if (! rtt_silence) {
+               irqtimer_stop (tmr);
+       }
+       //
+       // Construct a buffer with the RTP packet
+       rtt_timing [rtt_histcurr] = bottom_time () * 1000 / TIME_MSEC (1000);
+       bzero (mem, sizeof (mem));
+       //TODO// Setup mem[] with actual output pointers
+       pout = netsend_udp6 (pout, mem);
+       pout [0] = 0x80;                // V=2, P=0, X=0, CC=0
+       pout [1] = (rtt_redundancy? rtt_paytp_red: rtt_paytp_t140) | (rtt_silence? 0x80: 0x00);
+       netset16 (*(nint16_t *) &pout [2], rtt_seqnr++);
+       netset32 (*(nint32_t *) &pout [4], rtt_timing [rtt_histcurr]);
+       netset32 (*(nint32_t *) &pout [8], 0);          // SSRC -- TODO, 0 OK?
+       pout += 12;
+       if (rtt_redundancy) {
+               idx2 = RTT_HISTLEN + rtt_histcurr - (rtt_histlen - 1);
+               if (idx2 >= RTT_HISTLEN) {
+                       idx2 -= RTT_HISTLEN;
+               }
+               idx = idx2;
+               while (idx2 != rtt_histcurr) {
+                       uint32_t tdiff;
+                       tdiff = rtt_timing [rtt_histcurr] - rtt_timing [idx2];
+                       if (tdiff <= 16383) {
+                               uint16_t bytelen = rtt_histbytes [idx2];
+                               *pout++ = 0x80 | rtt_paytp_t140;        /* Flag: more to come */
+                               netset16 (*(nint16_t *) pout, (tdiff << 2) | (bytelen >> 8));
+                               pout += 2;
+                               *pout++ = bytelen & 0xff;
+                       } else {
+                               // too old => skip here => also below
+                               idx = idx2 + 1;
+                               if (idx >= RTT_HISTLEN) {
+                                       idx = 0;
+                               }
+                       }
+                       idx2++;
+                       if (idx2 >= RTT_HISTLEN) {
+                               idx2 = 0;
+                       }
+               }
+               *pout++ = 0x00 | rtt_paytp_t140;                        /* Flag: last */
+       } else {
+               idx = rtt_histcurr;
+       }
+       do {
+               memcpy (pout, rtt_history [idx], rtt_histbytes [idx]);
+               pout += rtt_histbytes [idx];
+               idx2 = idx;
+               idx++;
+               if (idx >= RTT_HISTLEN) {
+                       idx = 0;
+               }
+       } while (idx2 != rtt_histcurr);
+       //
+       // Actually send the buffer
+       mem [MEM_ALL_DONE] = (intptr_t) pout;
+       netcore_send_buffer (mem, wbuf.data);
+       //
+       // Move on to the next historic version
+       rtt_histcurr++;
+       if (rtt_histcurr >= RTT_HISTLEN) {
+               rtt_histcurr = 0;
+       }
+       rtt_histbytes [rtt_histcurr] = 0;
+       if (rtt_histlen < RTT_HISTLEN) {
+               rtt_histlen++;
+       }
+       //
+       // If not repeating endlessly, trigger this action again in 300 ms
+       if (rtt_repeated != rtt_histcurr) {
+               rtt_repeated = rtt_histcurr;
+               rtt_repeats = 0;
+       }
+       //TODO// Better to wait for last timer expiry, but not send then
+       rtt_silence = (rtt_repeats++ >= RTT_HISTLEN-1);
+       if (! rtt_silence) {
+               irqtimer_start (tmr, TIME_MSEC(300), rtt_send_buffer, CPU_PRIO_MEDIUM);
+       }
+}
+
+
+/* Send a number of bytes, to indicate one or more keys being pressed.
+ * The return value indicates how much of the offered characters were sent.
+ * If not everything could be sent, it is recommended to wait before
+ * trying to send the rest.  Buffers and sending limits may have gotten
+ * in the way of a long text submission.
+ */
+uint16_t rtt_send_keys (uint8_t *keys, uint16_t len) {
+       uint16_t plen;
+       //
+       // Determine the number of bytes to send in this block
+       plen = RTT_MAXBYTES - rtt_histbytes [rtt_histcurr];
+       if (len < plen) {
+               plen = len;
+       }
+       //TODO// Reduce plen to cover a fixed number of chars
+       //
+       // Store values in the history
+       memcpy (rtt_history [rtt_histcurr] + rtt_histbytes [rtt_histcurr], keys, plen);
+       rtt_histbytes [rtt_histcurr] += plen;
+       //
+       // Consider sending the current buffer:
+       //   1. When out of buffer space
+       //   2. Otherwise, when currently silent
+       //   3. Otherwise, after a regular interval delay.
+       if ((len > plen) || (rtt_histbytes [rtt_histcurr] == RTT_MAXBYTES)) {
+               rtt_send_buffer (&rtt_timer.tmr_irq);   /* Send now, next block may follow soon */
+       } else if (rtt_silence) {
+               rtt_send_buffer (&rtt_timer.tmr_irq);   /* Send now, and repeat from now on */
+       } else {
+               ;       /* Await timer expiration */
+       }
+       return plen;
+}
+
diff --git a/src/codec/spandsp/AUTHORS b/src/codec/spandsp/AUTHORS
new file mode 100644 (file)
index 0000000..0fbb495
--- /dev/null
@@ -0,0 +1 @@
+Steve Underwood <steveu@coppice.org>
diff --git a/src/codec/spandsp/COPYING b/src/codec/spandsp/COPYING
new file mode 100644 (file)
index 0000000..65263af
--- /dev/null
@@ -0,0 +1,853 @@
+The spandsp library is licenced under LGPL 2.1. The test suite, and some of
+the supporting code, are licenced under GPL 2. The full text of both licences
+may be found below.
+
+
+
+                 GNU LESSER GENERAL PUBLIC LICENSE
+                      Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+     51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+                 GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                           NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
+
+
+
+
+                   GNU GENERAL PUBLIC LICENSE
+                      Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+\f
+                   GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+\f
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+\f
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+\f
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                           NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+\f
+           How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year  name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/src/codec/spandsp/README b/src/codec/spandsp/README
new file mode 100644 (file)
index 0000000..093960b
--- /dev/null
@@ -0,0 +1,35 @@
+spandsp 0.0.5 - A DSP library for telephony
+-------------------------------------------
+
+SpanDSP is a library of DSP functions for telephony, in the 8000 sample per
+second world of E1s, T1s, and higher order PCM channels. It contains low level
+functions, such as basic filters. It also contains higher level functions, such
+as cadenced supervisory tone detection, and a complete software FAX machine.
+The software has been designed to avoid intellectual property issues, using
+mature techniques where all relevant patents have expired. See the file
+DueDiligence for important information about these intellectual property issues.
+
+The library is licenced under the LGPL 2.1 licence. The test suite, and some support
+programs are licenced under the GPL 2 licence. The full text of these licences can
+be found in the file COPYING.
+
+Dependencies
+------------
+
+spandsp depends on various other packages for various tasks. Most of these
+dependencies relate to building the test suite.
+
+libtiff (and libtiff-devel on most Linux distributions) is required to
+build the spandsp library.
+
+libaudiofile (and libaudiofile-devel) is required to build the test suite
+fftw (and fftw-devel) is required to build the test suite. Version 2 or 3 of
+FFTW may be used. Spandsp adapts to the differences between them.
+
+fltk (and fltk-devel), Fl_Cartesian and Fl_Audio_Meter are required to build
+the test suite with GUI interfaces for some of the tests. The tests will build
+without these packages, but the GUI features will not be available.
+Fl_Cartesian and Fl_Audio_Meter can be downloaded from
+http://www.soft-switch.org/downloads.
+
+Steve Underwood <steveu@coppice.org>
diff --git a/src/codec/spandsp/README.0cpm-Firmerware b/src/codec/spandsp/README.0cpm-Firmerware
new file mode 100644 (file)
index 0000000..f124a29
--- /dev/null
@@ -0,0 +1,43 @@
+spandsp codec description
+=========================
+
+This directory holds files from the spandsp library, a software-encded version of codecs and
+other voice/modem protocols.  Many thanks to Steve Underwood and his Speech Team at CMU; all
+that works about these codecs is undoubtly their work and all that fails is probably badly
+integrated into the 0cpm Firmerware.
+
+Specifically worth mentioning is the team's effort to collect a useful set of protocols that
+are unencumbered by patents or other methods to constipate progress.  This is exactly the
+sort of thing needed in the 0cpm Firmerware, if not for the fact that the firmware must
+remain open, then at least for the reason that most phone manufacturers seem to make the
+same choice.  If you want to retract your software from daily use, be sure to patent it!
+
+
+License compatibility
+---------------------
+
+The spandsp software is released under LGPL v2.1 which is compatible with the GPL v3 used
+for the 0cpm Firmerware, according to this table:
+
+http://www.gnu.org/licenses/gpl-faq.html#AllCompatibility
+
+In line with this table, the complete 0cpm Firmerware is shipped under GPL v3.
+
+
+Changes to files
+----------------
+
+We've edited several files to make them fit better with the embedded architecture of the
+0cpm Firmerware.  This means no support (or need) for dynamic allocation of structures
+and, where possible, target-specific implementations of heavy-duty mathematics.
+
+
+Original file versions
+----------------------
+
+Documentation          spandsp-0.0.6pre18
+g711.c / g711.h                spandsp-0.0.6pre18
+g722.c / g722.h                spandsp-0.0.6pre18
+g726.c / g726.h                spandsp-0.0.6pre18
+
+
diff --git a/src/codec/spandsp/src/floating_fudge.h b/src/codec/spandsp/src/floating_fudge.h
new file mode 100644 (file)
index 0000000..2ef0423
--- /dev/null
@@ -0,0 +1,137 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * floating_fudge.h - A bunch of shims, to use double maths
+ *                    functions on platforms which lack the
+ *                    float versions with an 'f' at the end,
+ *                    and to deal with the vaguaries of lrint().
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2008 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#if !defined(_FLOATING_FUDGE_H_)
+#define _FLOATING_FUDGE_H_
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+#if !defined(HAVE_SINF)
+static __inline__ float sinf(float x)
+{
+       return (float) sin((double) x);
+}
+#endif
+
+#if !defined(HAVE_COSF)
+static __inline__ float cosf(float x)
+{
+       return (float) cos((double) x);
+}
+#endif
+
+#if !defined(HAVE_TANF)
+static __inline__ float tanf(float x)
+{
+       return (float) tan((double) x);
+}
+#endif
+
+#if !defined(HAVE_ASINF)
+static __inline__ float asinf(float x)
+{
+       return (float) asin((double) x);
+}
+#endif
+
+#if !defined(HAVE_ACOSF)
+static __inline__ float acosf(float x)
+{
+       return (float) acos((double) x);
+}
+#endif
+
+#if !defined(HAVE_ATANF)
+static __inline__ float atanf(float x)
+{
+       return (float) atan((double) x);
+}
+
+#endif
+
+#if !defined(HAVE_ATAN2F)
+static __inline__ float atan2f(float y, float x)
+{
+       return (float) atan2((double) y, (double) x);
+}
+
+#endif
+
+#if !defined(HAVE_CEILF)
+static __inline__ float ceilf(float x)
+{
+       return (float) ceil((double) x);
+}
+#endif
+
+#if !defined(HAVE_FLOORF)
+static __inline__ float floorf(float x)
+{
+       return (float) floor((double) x);
+}
+
+#endif
+
+#if !defined(HAVE_POWF)
+static __inline__ float powf(float x, float y)
+{
+    return (float) pow((double) x, (double) y);
+}
+#endif
+
+#if !defined(HAVE_EXPF)
+static __inline__ float expf(float x)
+{
+    return (float) expf((double) x);
+}
+#endif
+
+#if !defined(HAVE_LOGF)
+static __inline__ float logf(float x)
+{
+       return (float) logf((double) x);
+}
+#endif
+
+#if !defined(HAVE_LOG10F)
+static __inline__ float log10f(float x)
+{
+    return (float) log10((double) x);
+}
+#endif
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/g711.c b/src/codec/spandsp/src/g711.c
new file mode 100644 (file)
index 0000000..8077334
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * g711.c - A-law and u-law transcoding routines
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2006 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/*! \file */
+
+#if defined(HAVE_CONFIG_H)
+#include "config.h"
+#endif
+
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "spandsp/telephony.h"
+#include "spandsp/bit_operations.h"
+#include "spandsp/g711.h"
+#include "spandsp/private/g711.h"
+
+/* Copied from the CCITT G.711 specification */
+static const uint8_t ulaw_to_alaw_table[256] =
+{
+     42,  43,  40,  41,  46,  47,  44,  45,  34,  35,  32,  33,  38,  39,  36,  37,
+     58,  59,  56,  57,  62,  63,  60,  61,  50,  51,  48,  49,  54,  55,  52,  53,
+     10,  11,   8,   9,  14,  15,  12,  13,   2,   3,   0,   1,   6,   7,   4,  26,
+     27,  24,  25,  30,  31,  28,  29,  18,  19,  16,  17,  22,  23,  20,  21, 106,
+    104, 105, 110, 111, 108, 109,  98,  99,  96,  97, 102, 103, 100, 101, 122, 120,
+    126, 127, 124, 125, 114, 115, 112, 113, 118, 119, 116, 117,  75,  73,  79,  77,
+     66,  67,  64,  65,  70,  71,  68,  69,  90,  91,  88,  89,  94,  95,  92,  93,
+     82,  82,  83,  83,  80,  80,  81,  81,  86,  86,  87,  87,  84,  84,  85,  85,
+    170, 171, 168, 169, 174, 175, 172, 173, 162, 163, 160, 161, 166, 167, 164, 165,
+    186, 187, 184, 185, 190, 191, 188, 189, 178, 179, 176, 177, 182, 183, 180, 181,
+    138, 139, 136, 137, 142, 143, 140, 141, 130, 131, 128, 129, 134, 135, 132, 154,
+    155, 152, 153, 158, 159, 156, 157, 146, 147, 144, 145, 150, 151, 148, 149, 234,
+    232, 233, 238, 239, 236, 237, 226, 227, 224, 225, 230, 231, 228, 229, 250, 248,
+    254, 255, 252, 253, 242, 243, 240, 241, 246, 247, 244, 245, 203, 201, 207, 205,
+    194, 195, 192, 193, 198, 199, 196, 197, 218, 219, 216, 217, 222, 223, 220, 221,
+    210, 210, 211, 211, 208, 208, 209, 209, 214, 214, 215, 215, 212, 212, 213, 213
+};
+
+/* These transcoding tables are copied from the CCITT G.711 specification. To achieve
+   optimal results, do not change them. */
+
+static const uint8_t alaw_to_ulaw_table[256] =
+{
+     42,  43,  40,  41,  46,  47,  44,  45,  34,  35,  32,  33,  38,  39,  36,  37,
+     57,  58,  55,  56,  61,  62,  59,  60,  49,  50,  47,  48,  53,  54,  51,  52,
+     10,  11,   8,   9,  14,  15,  12,  13,   2,   3,   0,   1,   6,   7,   4,   5,
+     26,  27,  24,  25,  30,  31,  28,  29,  18,  19,  16,  17,  22,  23,  20,  21,
+     98,  99,  96,  97, 102, 103, 100, 101,  93,  93,  92,  92,  95,  95,  94,  94,
+    116, 118, 112, 114, 124, 126, 120, 122, 106, 107, 104, 105, 110, 111, 108, 109,
+     72,  73,  70,  71,  76,  77,  74,  75,  64,  65,  63,  63,  68,  69,  66,  67,
+     86,  87,  84,  85,  90,  91,  88,  89,  79,  79,  78,  78,  82,  83,  80,  81,
+    170, 171, 168, 169, 174, 175, 172, 173, 162, 163, 160, 161, 166, 167, 164, 165,
+    185, 186, 183, 184, 189, 190, 187, 188, 177, 178, 175, 176, 181, 182, 179, 180,
+    138, 139, 136, 137, 142, 143, 140, 141, 130, 131, 128, 129, 134, 135, 132, 133,
+    154, 155, 152, 153, 158, 159, 156, 157, 146, 147, 144, 145, 150, 151, 148, 149,
+    226, 227, 224, 225, 230, 231, 228, 229, 221, 221, 220, 220, 223, 223, 222, 222,
+    244, 246, 240, 242, 252, 254, 248, 250, 234, 235, 232, 233, 238, 239, 236, 237,
+    200, 201, 198, 199, 204, 205, 202, 203, 192, 193, 191, 191, 196, 197, 194, 195,
+    214, 215, 212, 213, 218, 219, 216, 217, 207, 207, 206, 206, 210, 211, 208, 209
+};
+
+SPAN_DECLARE(uint8_t) alaw_to_ulaw(uint8_t alaw)
+{
+    return alaw_to_ulaw_table[alaw];
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(uint8_t) ulaw_to_alaw(uint8_t ulaw)
+{
+    return ulaw_to_alaw_table[ulaw];
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g711_decode(g711_state_t *s,
+                              int16_t amp[],
+                              const uint8_t g711_data[],
+                              int g711_bytes)
+{
+    int i;
+
+    if (s->mode == G711_ALAW)
+    {
+        for (i = 0;  i < g711_bytes;  i++)
+            amp[i] = alaw_to_linear(g711_data[i]);
+        /*endfor*/
+    }
+    else
+    {
+        for (i = 0;  i < g711_bytes;  i++)
+            amp[i] = ulaw_to_linear(g711_data[i]);
+        /*endfor*/
+    }
+    /*endif*/
+    return g711_bytes;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g711_encode(g711_state_t *s,
+                              uint8_t g711_data[],
+                              const int16_t amp[],
+                              int len)
+{
+    int i;
+
+    if (s->mode == G711_ALAW)
+    {
+        for (i = 0;  i < len;  i++)
+            g711_data[i] = linear_to_alaw(amp[i]);
+        /*endfor*/
+    }
+    else
+    {
+        for (i = 0;  i < len;  i++)
+            g711_data[i] = linear_to_ulaw(amp[i]);
+        /*endfor*/
+    }
+    /*endif*/
+    return len;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g711_transcode(g711_state_t *s,
+                                 uint8_t g711_out[],
+                                 const uint8_t g711_in[],
+                                 int g711_bytes)
+{
+    int i;
+
+    if (s->mode == G711_ALAW)
+    {
+        for (i = 0;  i < g711_bytes;  i++)
+            g711_out[i] = alaw_to_ulaw_table[g711_in[i]];
+        /*endfor*/
+    }
+    else
+    {
+        for (i = 0;  i < g711_bytes;  i++)
+            g711_out[i] = ulaw_to_alaw_table[g711_in[i]];
+        /*endfor*/
+    }
+    /*endif*/
+    return g711_bytes;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(g711_state_t *) g711_init(g711_state_t *s, int mode)
+{
+#ifndef SPANDSP_PRIOR_ALLOCATION
+    if (s == NULL)
+    {
+        if ((s = (g711_state_t *) malloc(sizeof(*s))) == NULL)
+            return  NULL;
+    }
+#endif
+    s->mode = mode;
+    return s;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g711_release(g711_state_t *s)
+{
+    return 0;
+}
+/*- End of function --------------------------------------------------------*/
+
+#ifndef SPANDSP_PRIOR_ALLOCATION
+SPAN_DECLARE(int) g711_free(g711_state_t *s)
+{
+    free(s);
+    return 0;
+}
+#endif
+/*- End of function --------------------------------------------------------*/
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/g722.c b/src/codec/spandsp/src/g722.c
new file mode 100644 (file)
index 0000000..796895b
--- /dev/null
@@ -0,0 +1,637 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * g722.c - The ITU G.722 codec.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2005 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ * Based in part on a single channel G.722 codec which is:
+ *
+ * Copyright (c) CMU 1993
+ * Computer Science, Speech Group
+ * Chengxiang Lu and Alex Hauptmann
+ */
+
+/*! \file */
+
+#if defined(HAVE_CONFIG_H)
+#include "config.h"
+#endif
+
+#include <inttypes.h>
+#include <memory.h>
+#include <stdlib.h>
+#if defined(HAVE_TGMATH_H)
+#include <tgmath.h>
+#endif
+#if defined(HAVE_MATH_H)
+#include <math.h>
+#endif
+#include "floating_fudge.h"
+
+#include "spandsp/telephony.h"
+#include "spandsp/fast_convert.h"
+#include "spandsp/saturated.h"
+#include "spandsp/vector_int.h"
+#include "spandsp/g722.h"
+
+#include "spandsp/private/g722.h"
+
+static const int16_t qmf_coeffs_fwd[12] =
+{
+      3,  -11,   12,   32, -210,  951, 3876, -805,  362, -156,   53,  -11,
+};
+
+static const int16_t qmf_coeffs_rev[12] =
+{
+    -11,   53, -156,  362, -805, 3876,  951, -210,   32,   12,  -11,    3
+};
+
+static const int16_t qm2[4] =
+{
+    -7408,  -1616,   7408,   1616
+};
+
+static const int16_t qm4[16] =
+{
+         0, -20456, -12896,  -8968,
+     -6288,  -4240,  -2584,  -1200,
+     20456,  12896,   8968,   6288,
+      4240,   2584,   1200,      0
+};
+
+static const int16_t qm5[32] =
+{
+      -280,   -280, -23352, -17560,
+    -14120, -11664,  -9752,  -8184,
+     -6864,  -5712,  -4696,  -3784,
+     -2960,  -2208,  -1520,   -880,
+     23352,  17560,  14120,  11664,
+      9752,   8184,   6864,   5712,
+      4696,   3784,   2960,   2208,
+      1520,    880,    280,   -280
+};
+
+static const int16_t qm6[64] =
+{
+      -136,   -136,   -136,   -136,
+    -24808, -21904, -19008, -16704,
+    -14984, -13512, -12280, -11192,
+    -10232,  -9360,  -8576,  -7856,
+     -7192,  -6576,  -6000,  -5456,
+     -4944,  -4464,  -4008,  -3576,
+     -3168,  -2776,  -2400,  -2032,
+     -1688,  -1360,  -1040,   -728,
+     24808,  21904,  19008,  16704,
+     14984,  13512,  12280,  11192,
+     10232,   9360,   8576,   7856,
+      7192,   6576,   6000,   5456,
+      4944,   4464,   4008,   3576,
+      3168,   2776,   2400,   2032,
+      1688,   1360,   1040,    728,
+       432,    136,   -432,   -136
+};
+
+static const int16_t q6[32] =
+{
+         0,     35,     72,    110,
+       150,    190,    233,    276,
+       323,    370,    422,    473,
+       530,    587,    650,    714,
+       786,    858,    940,   1023,
+      1121,   1219,   1339,   1458,
+      1612,   1765,   1980,   2195,
+      2557,   2919,      0,      0
+};
+
+static const int16_t ilb[32] =
+{
+      2048,   2093,   2139,   2186,
+      2233,   2282,   2332,   2383,
+      2435,   2489,   2543,   2599,
+      2656,   2714,   2774,   2834,
+      2896,   2960,   3025,   3091,
+      3158,   3228,   3298,   3371,
+      3444,   3520,   3597,   3676,
+      3756,   3838,   3922,   4008
+};
+
+static const int16_t iln[32] =
+{
+     0, 63, 62, 31, 30, 29, 28, 27,
+    26, 25, 24, 23, 22, 21, 20, 19,
+    18, 17, 16, 15, 14, 13, 12, 11,
+    10,  9,  8,  7,  6,  5,  4,  0
+};
+
+static const int16_t ilp[32] =
+{
+     0, 61, 60, 59, 58, 57, 56, 55,
+    54, 53, 52, 51, 50, 49, 48, 47,
+    46, 45, 44, 43, 42, 41, 40, 39,
+    38, 37, 36, 35, 34, 33, 32,  0
+};
+
+static const int16_t ihn[3] =
+{
+    0,  1,  0
+};
+
+static const int16_t ihp[3] =
+{
+    0,  3,  2
+};
+
+static const int16_t wl[8] =
+{
+    -60, -30, 58, 172, 334, 538, 1198, 3042
+};
+
+static const int16_t rl42[16] =
+{
+    0,  7,  6,  5,  4,  3,  2,  1,
+    7,  6,  5,  4,  3,  2,  1,  0
+};
+
+static const int16_t wh[3] =
+{
+    0, -214, 798
+};
+
+static const int16_t rh2[4] =
+{
+    2,  1,  2,  1
+};
+
+static void block4(g722_band_t *s, int16_t dx)
+{
+    int16_t wd1;
+    int16_t wd2;
+    int16_t wd3;
+    int16_t sp;
+    int16_t r;
+    int16_t p;
+    int16_t ap[2];
+    int32_t wd32;
+    int32_t sz;
+    int i;
+
+    /* RECONS */
+    r = saturated_add16(s->s, dx);
+    /* PARREC */
+    p = saturated_add16(s->sz, dx);
+
+    /* UPPOL2 */
+    wd1 = saturate((int32_t) s->a[0] << 2);
+    wd32 = ((p ^ s->p[0]) & 0x8000)  ?  wd1  :  -wd1;
+    if (wd32 > 32767)
+        wd32 = 32767;
+    wd3 = (int16_t) ((((p ^ s->p[1]) & 0x8000)  ?  -128  :  128)
+                     + (wd32 >> 7)
+                     + (((int32_t) s->a[1]*(int32_t) 32512) >> 15));
+    if (abs(wd3) > 12288)
+        wd3 = (wd3 < 0)  ?  -12288  :  12288;
+    ap[1] = wd3;
+
+    /* UPPOL1 */
+    wd1 = ((p ^ s->p[0]) & 0x8000)  ?  -192  :  192;
+    wd2 = (int16_t) (((int32_t) s->a[0]*(int32_t) 32640) >> 15);
+    ap[0] = saturated_add16(wd1, wd2);
+
+    wd3 = saturated_sub16(15360, ap[1]);
+    if (abs(ap[0]) > wd3)
+        ap[0] = (ap[0] < 0)  ?  -wd3  :  wd3;
+
+    /* FILTEP */
+    wd1 = saturated_add16(r, r);
+    wd1 = (int16_t) (((int32_t) ap[0]*(int32_t) wd1) >> 15);
+    wd2 = saturated_add16(s->r, s->r);
+    wd2 = (int16_t) (((int32_t) ap[1]*(int32_t) wd2) >> 15);
+    sp = saturated_add16(wd1, wd2);
+    s->r = r;
+    s->a[1] = ap[1];
+    s->a[0] = ap[0];
+    s->p[1] = s->p[0];
+    s->p[0] = p;
+
+    /* UPZERO */
+    /* DELAYA */
+    /* FILTEZ */
+    wd1 = (dx == 0)  ?  0  :  128;
+    s->d[0] = dx;
+    sz = 0;
+    for (i = 5;  i >= 0;  i--)
+    {
+        wd2 = ((s->d[i + 1] ^ dx) & 0x8000)  ?  -wd1  :  wd1;
+        wd3 = (int16_t) (((int32_t) s->b[i]*(int32_t) 32640) >> 15);
+        s->b[i] = saturated_add16(wd2, wd3);
+        wd3 = saturated_add16(s->d[i], s->d[i]);
+        sz += ((int32_t) s->b[i]*(int32_t) wd3) >> 15;
+        s->d[i + 1] = s->d[i];
+    }
+    s->sz = saturate(sz);
+
+    /* PREDIC */
+    s->s = saturated_add16(sp, s->sz);
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(g722_decode_state_t *) g722_decode_init(g722_decode_state_t *s, int rate, int options)
+{
+#ifndef SPANDSP_PRIOR_ALLOCATION
+    if (s == NULL)
+    {
+        if ((s = (g722_decode_state_t *) malloc(sizeof(*s))) == NULL)
+            return NULL;
+    }
+#endif
+    memset(s, 0, sizeof(*s));
+    if (rate == 48000)
+        s->bits_per_sample = 6;
+    else if (rate == 56000)
+        s->bits_per_sample = 7;
+    else
+        s->bits_per_sample = 8;
+    if ((options & G722_SAMPLE_RATE_8000))
+        s->eight_k = TRUE;
+    if ((options & G722_PACKED)  &&  s->bits_per_sample != 8)
+        s->packed = TRUE;
+    else
+        s->packed = FALSE;
+    s->band[0].det = 32;
+    s->band[1].det = 8;
+    return s;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g722_decode_release(g722_decode_state_t *s)
+{
+    return 0;
+}
+/*- End of function --------------------------------------------------------*/
+
+#ifndef SPANDSP_PRIOR_ALLOCATION
+SPAN_DECLARE(int) g722_decode_free(g722_decode_state_t *s)
+{
+    free(s);
+    return 0;
+}
+#endif
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g722_decode(g722_decode_state_t *s, int16_t amp[], const uint8_t g722_data[], int len)
+{
+    int rlow;
+    int ihigh;
+    int16_t dlow;
+    int16_t dhigh;
+    int rhigh;
+    int wd1;
+    int wd2;
+    int wd3;
+    int code;
+    int outlen;
+    int j;
+
+    outlen = 0;
+    rhigh = 0;
+    for (j = 0;  j < len;  )
+    {
+        if (s->packed)
+        {
+            /* Unpack the code bits */
+            if (s->in_bits < s->bits_per_sample)
+            {
+                s->in_buffer |= (g722_data[j++] << s->in_bits);
+                s->in_bits += 8;
+            }
+            code = s->in_buffer & ((1 << s->bits_per_sample) - 1);
+            s->in_buffer >>= s->bits_per_sample;
+            s->in_bits -= s->bits_per_sample;
+        }
+        else
+        {
+            code = g722_data[j++];
+        }
+
+        switch (s->bits_per_sample)
+        {
+        default:
+        case 8:
+            wd1 = code & 0x3F;
+            ihigh = (code >> 6) & 0x03;
+            wd2 = qm6[wd1];
+            wd1 >>= 2;
+            break;
+        case 7:
+            wd1 = code & 0x1F;
+            ihigh = (code >> 5) & 0x03;
+            wd2 = qm5[wd1];
+            wd1 >>= 1;
+            break;
+        case 6:
+            wd1 = code & 0x0F;
+            ihigh = (code >> 4) & 0x03;
+            wd2 = qm4[wd1];
+            break;
+        }
+        /* Block 5L, LOW BAND INVQBL */
+        wd2 = ((int32_t) s->band[0].det*(int32_t) wd2) >> 15;
+        /* Block 5L, RECONS */
+        /* Block 6L, LIMIT */
+        rlow = saturate15(s->band[0].s + wd2);
+
+        /* Block 2L, INVQAL */
+        wd2 = qm4[wd1];
+        dlow = (int16_t) (((int32_t) s->band[0].det*(int32_t) wd2) >> 15);
+
+        /* Block 3L, LOGSCL */
+        wd2 = rl42[wd1];
+        wd1 = ((int32_t) s->band[0].nb*(int32_t) 127) >> 7;
+        wd1 += wl[wd2];
+        if (wd1 < 0)
+            wd1 = 0;
+        else if (wd1 > 18432)
+            wd1 = 18432;
+        s->band[0].nb = (int16_t) wd1;
+            
+        /* Block 3L, SCALEL */
+        wd1 = (s->band[0].nb >> 6) & 31;
+        wd2 = 8 - (s->band[0].nb >> 11);
+        wd3 = (wd2 < 0)  ?  (ilb[wd1] << -wd2)  :  (ilb[wd1] >> wd2);
+        s->band[0].det = (int16_t) (wd3 << 2);
+
+        block4(&s->band[0], dlow);
+        
+        if (!s->eight_k)
+        {
+            /* Block 2H, INVQAH */
+            wd2 = qm2[ihigh];
+            dhigh = (int16_t) (((int32_t) s->band[1].det*(int32_t) wd2) >> 15);
+            /* Block 5H, RECONS */
+            /* Block 6H, LIMIT */
+            rhigh = saturate15(dhigh + s->band[1].s);
+
+            /* Block 2H, INVQAH */
+            wd2 = rh2[ihigh];
+            wd1 = ((int32_t) s->band[1].nb*(int32_t) 127) >> 7;
+            wd1 += wh[wd2];
+            if (wd1 < 0)
+                wd1 = 0;
+            else if (wd1 > 22528)
+                wd1 = 22528;
+            s->band[1].nb = (int16_t) wd1;
+            
+            /* Block 3H, SCALEH */
+            wd1 = (s->band[1].nb >> 6) & 31;
+            wd2 = 10 - (s->band[1].nb >> 11);
+            wd3 = (wd2 < 0)  ?  (ilb[wd1] << -wd2)  :  (ilb[wd1] >> wd2);
+            s->band[1].det = (int16_t) (wd3 << 2);
+
+            block4(&s->band[1], dhigh);
+        }
+
+        if (s->itu_test_mode)
+        {
+            amp[outlen++] = (int16_t) (rlow << 1);
+            amp[outlen++] = (int16_t) (rhigh << 1);
+        }
+        else
+        {
+            if (s->eight_k)
+            {
+                /* We shift by 1 to allow for the 15 bit input to the G.722 algorithm. */
+                amp[outlen++] = (int16_t) (rlow << 1);
+            }
+            else
+            {
+                /* Apply the QMF to build the final signal */
+                s->x[s->ptr] = (int16_t) (rlow + rhigh);
+                s->y[s->ptr] = (int16_t) (rlow - rhigh);
+                if (++s->ptr >= 12)
+                    s->ptr = 0;
+                /* We shift by 12 to allow for the QMF filters (DC gain = 4096), less 1
+                   to allow for the 15 bit input to the G.722 algorithm. */
+                amp[outlen++] = (int16_t) (vec_circular_dot_prodi16(s->y, qmf_coeffs_rev, 12, s->ptr) >> 11);
+                amp[outlen++] = (int16_t) (vec_circular_dot_prodi16(s->x, qmf_coeffs_fwd, 12, s->ptr) >> 11);
+            }
+        }
+    }
+    return outlen;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(g722_encode_state_t *) g722_encode_init(g722_encode_state_t *s, int rate, int options)
+{
+#ifndef SPANDSP_PRIOR_ALLOCATION
+    if (s == NULL)
+    {
+        if ((s = (g722_encode_state_t *) malloc(sizeof(*s))) == NULL)
+            return NULL;
+    }
+#endif
+    memset(s, 0, sizeof(*s));
+    if (rate == 48000)
+        s->bits_per_sample = 6;
+    else if (rate == 56000)
+        s->bits_per_sample = 7;
+    else
+        s->bits_per_sample = 8;
+    if ((options & G722_SAMPLE_RATE_8000))
+        s->eight_k = TRUE;
+    if ((options & G722_PACKED)  &&  s->bits_per_sample != 8)
+        s->packed = TRUE;
+    else
+        s->packed = FALSE;
+    s->band[0].det = 32;
+    s->band[1].det = 8;
+    return s;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g722_encode_release(g722_encode_state_t *s)
+{
+    return 0;
+}
+/*- End of function --------------------------------------------------------*/
+
+#ifndef SPANDSP_PRIOR_ALLOCATION
+SPAN_DECLARE(int) g722_encode_free(g722_encode_state_t *s)
+{
+    free(s);
+    return 0;
+}
+#endif
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g722_encode(g722_encode_state_t *s, uint8_t g722_data[], const int16_t amp[], int len)
+{
+    int16_t dlow;
+    int16_t dhigh;
+    int el;
+    int wd;
+    int wd1;
+    int ril;
+    int wd2;
+    int il4;
+    int ih2;
+    int wd3;
+    int eh;
+    int g722_bytes;
+    int ihigh;
+    int ilow;
+    int code;
+    /* Low and high band PCM from the QMF */
+    int16_t xlow;
+    int16_t xhigh;
+    int32_t sumeven;
+    int32_t sumodd;
+    int mih;
+    int i;
+    int j;
+
+    g722_bytes = 0;
+    xhigh = 0;
+    for (j = 0;  j < len;  )
+    {
+        if (s->itu_test_mode)
+        {
+            xlow =
+            xhigh = amp[j++] >> 1;
+        }
+        else
+        {
+            if (s->eight_k)
+            {
+                /* We shift by 1 to allow for the 15 bit input to the G.722 algorithm. */
+                xlow = amp[j++] >> 1;
+            }
+            else
+            {
+                /* Apply the transmit QMF */
+                s->x[s->ptr] = amp[j++];
+                s->y[s->ptr] = amp[j++];
+                if (++s->ptr >= 12)
+                    s->ptr = 0;
+                sumodd = vec_circular_dot_prodi16(s->x, qmf_coeffs_fwd, 12, s->ptr);
+                sumeven = vec_circular_dot_prodi16(s->y, qmf_coeffs_rev, 12, s->ptr);
+                /* We shift by 12 to allow for the QMF filters (DC gain = 4096), plus 1
+                   to allow for us summing two filters, plus 1 to allow for the 15 bit
+                   input to the G.722 algorithm. */
+                xlow = (int16_t) ((sumeven + sumodd) >> 14);
+                xhigh = (int16_t) ((sumeven - sumodd) >> 14);
+            }
+        }
+        /* Block 1L, SUBTRA */
+        el = saturated_sub16(xlow, s->band[0].s);
+
+        /* Block 1L, QUANTL */
+        wd = (el >= 0)  ?  el  :  ~el;
+
+        for (i = 1;  i < 30;  i++)
+        {
+            wd1 = ((int32_t) q6[i]*(int32_t) s->band[0].det) >> 12;
+            if (wd < wd1)
+                break;
+        }
+        ilow = (el < 0)  ?  iln[i]  :  ilp[i];
+
+        /* Block 2L, INVQAL */
+        ril = ilow >> 2;
+        wd2 = qm4[ril];
+        dlow = (int16_t) (((int32_t) s->band[0].det*(int32_t) wd2) >> 15);
+
+        /* Block 3L, LOGSCL */
+        il4 = rl42[ril];
+        wd = ((int32_t) s->band[0].nb*(int32_t) 127) >> 7;
+        s->band[0].nb = (int16_t) (wd + wl[il4]);
+        if (s->band[0].nb < 0)
+            s->band[0].nb = 0;
+        else if (s->band[0].nb > 18432)
+            s->band[0].nb = 18432;
+
+        /* Block 3L, SCALEL */
+        wd1 = (s->band[0].nb >> 6) & 31;
+        wd2 = 8 - (s->band[0].nb >> 11);
+        wd3 = (wd2 < 0)  ?  (ilb[wd1] << -wd2)  :  (ilb[wd1] >> wd2);
+        s->band[0].det = (int16_t) (wd3 << 2);
+
+        block4(&s->band[0], dlow);
+        
+        if (s->eight_k)
+        {
+            /* Just leave the high bits as zero */
+            code = (0xC0 | ilow) >> (8 - s->bits_per_sample);
+        }
+        else
+        {
+            /* Block 1H, SUBTRA */
+            eh = saturated_sub16(xhigh, s->band[1].s);
+
+            /* Block 1H, QUANTH */
+            wd = (eh >= 0)  ?  eh  :  ~eh;
+            wd1 = (564*s->band[1].det) >> 12;
+            mih = (wd >= wd1)  ?  2  :  1;
+            ihigh = (eh < 0)  ?  ihn[mih]  :  ihp[mih];
+
+            /* Block 2H, INVQAH */
+            wd2 = qm2[ihigh];
+            dhigh = (int16_t) (((int32_t) s->band[1].det*(int32_t) wd2) >> 15);
+
+            /* Block 3H, LOGSCH */
+            ih2 = rh2[ihigh];
+            wd = ((int32_t) s->band[1].nb*(int32_t) 127) >> 7;
+            s->band[1].nb = (int16_t) (wd + wh[ih2]);
+            if (s->band[1].nb < 0)
+                s->band[1].nb = 0;
+            else if (s->band[1].nb > 22528)
+                s->band[1].nb = 22528;
+
+            /* Block 3H, SCALEH */
+            wd1 = (s->band[1].nb >> 6) & 31;
+            wd2 = 10 - (s->band[1].nb >> 11);
+            wd3 = (wd2 < 0)  ?  (ilb[wd1] << -wd2)  :  (ilb[wd1] >> wd2);
+            s->band[1].det = (int16_t) (wd3 << 2);
+
+            block4(&s->band[1], dhigh);
+            code = ((ihigh << 6) | ilow) >> (8 - s->bits_per_sample);
+        }
+
+        if (s->packed)
+        {
+            /* Pack the code bits */
+            s->out_buffer |= (code << s->out_bits);
+            s->out_bits += s->bits_per_sample;
+            if (s->out_bits >= 8)
+            {
+                g722_data[g722_bytes++] = (uint8_t) (s->out_buffer & 0xFF);
+                s->out_bits -= 8;
+                s->out_buffer >>= 8;
+            }
+        }
+        else
+        {
+            g722_data[g722_bytes++] = (uint8_t) code;
+        }
+    }
+    return g722_bytes;
+}
+/*- End of function --------------------------------------------------------*/
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/g726.c b/src/codec/spandsp/src/g726.c
new file mode 100644 (file)
index 0000000..166a529
--- /dev/null
@@ -0,0 +1,1190 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * g726.c - The ITU G.726 codec.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2006 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ * Based on G.721/G.723 code which is:
+ *
+ * This source code is a product of Sun Microsystems, Inc. and is provided
+ * for unrestricted use.  Users may copy or modify this source code without
+ * charge.
+ *
+ * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING
+ * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
+ *
+ * Sun source code is provided with no support and without any obligation on
+ * the part of Sun Microsystems, Inc. to assist in its use, correction,
+ * modification or enhancement.
+ *
+ * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
+ * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE
+ * OR ANY PART THEREOF.
+ *
+ * In no event will Sun Microsystems, Inc. be liable for any lost revenue
+ * or profits or other special, indirect and consequential damages, even if
+ * Sun has been advised of the possibility of such damages.
+ *
+ * Sun Microsystems, Inc.
+ * 2550 Garcia Avenue
+ * Mountain View, California  94043
+ */
+
+/*! \file */
+
+#if defined(HAVE_CONFIG_H)
+#include "config.h"
+#endif
+
+#include <inttypes.h>
+#include <memory.h>
+#include <stdlib.h>
+#if defined(HAVE_TGMATH_H)
+#include <tgmath.h>
+#endif
+#if defined(HAVE_MATH_H)
+#include <math.h>
+#endif
+#include "floating_fudge.h"
+
+#include "spandsp/telephony.h"
+#include "spandsp/dc_restore.h"
+#include "spandsp/bitstream.h"
+#include "spandsp/bit_operations.h"
+#include "spandsp/g711.h"
+#include "spandsp/g726.h"
+
+#include "spandsp/private/bitstream.h"
+#include "spandsp/private/g726.h"
+
+/*
+ * Maps G.726_16 code word to reconstructed scale factor normalized log
+ * magnitude values.
+ */
+static const int g726_16_dqlntab[4] =
+{
+    116, 365, 365, 116
+};
+
+/* Maps G.726_16 code word to log of scale factor multiplier. */
+static const int g726_16_witab[4] =
+{
+    -704, 14048, 14048, -704
+};
+
+/*
+ * Maps G.726_16 code words to a set of values whose long and short
+ * term averages are computed and then compared to give an indication
+ * how stationary (steady state) the signal is.
+ */
+static const int g726_16_fitab[4] =
+{
+    0x000, 0xE00, 0xE00, 0x000
+};
+
+static const int qtab_726_16[1] =
+{
+    261
+};
+
+/*
+ * Maps G.726_24 code word to reconstructed scale factor normalized log
+ * magnitude values.
+ */
+static const int g726_24_dqlntab[8] =
+{
+    -2048, 135, 273, 373, 373, 273, 135, -2048
+};
+
+/* Maps G.726_24 code word to log of scale factor multiplier. */
+static const int g726_24_witab[8] =
+{
+    -128, 960, 4384, 18624, 18624, 4384, 960, -128
+};
+
+/*
+ * Maps G.726_24 code words to a set of values whose long and short
+ * term averages are computed and then compared to give an indication
+ * how stationary (steady state) the signal is.
+ */
+static const int g726_24_fitab[8] =
+{
+    0x000, 0x200, 0x400, 0xE00, 0xE00, 0x400, 0x200, 0x000
+};
+
+static const int qtab_726_24[3] =
+{
+    8, 218, 331
+};
+
+/*
+ * Maps G.726_32 code word to reconstructed scale factor normalized log
+ * magnitude values.
+ */
+static const int g726_32_dqlntab[16] =
+{
+    -2048,   4, 135, 213, 273, 323, 373,   425,
+      425, 373, 323, 273, 213, 135,   4, -2048
+};
+
+/* Maps G.726_32 code word to log of scale factor multiplier. */
+static const int g726_32_witab[16] =
+{
+     -384,   576,  1312,  2048,  3584,  6336, 11360, 35904,
+    35904, 11360,  6336,  3584,  2048,  1312,   576,  -384
+};
+
+/*
+ * Maps G.726_32 code words to a set of values whose long and short
+ * term averages are computed and then compared to give an indication
+ * how stationary (steady state) the signal is.
+ */
+static const int g726_32_fitab[16] =
+{
+    0x000, 0x000, 0x000, 0x200, 0x200, 0x200, 0x600, 0xE00,
+    0xE00, 0x600, 0x200, 0x200, 0x200, 0x000, 0x000, 0x000
+};
+
+static const int qtab_726_32[7] =
+{
+    -124, 80, 178, 246, 300, 349, 400
+};
+
+/*
+ * Maps G.726_40 code word to ructeconstructed scale factor normalized log
+ * magnitude values.
+ */
+static const int g726_40_dqlntab[32] =
+{
+    -2048, -66, 28, 104, 169, 224, 274, 318,
+      358, 395, 429, 459, 488, 514, 539, 566,
+      566, 539, 514, 488, 459, 429, 395, 358,
+      318, 274, 224, 169, 104, 28, -66, -2048
+};
+
+/* Maps G.726_40 code word to log of scale factor multiplier. */
+static const int g726_40_witab[32] =
+{
+      448,   448,   768,  1248,  1280,  1312,  1856,  3200,
+     4512,  5728,  7008,  8960, 11456, 14080, 16928, 22272,
+    22272, 16928, 14080, 11456,  8960,  7008,  5728,  4512,
+     3200,  1856,  1312,  1280,  1248,   768,   448,   448
+};
+
+/*
+ * Maps G.726_40 code words to a set of values whose long and short
+ * term averages are computed and then compared to give an indication
+ * how stationary (steady state) the signal is.
+ */
+static const int g726_40_fitab[32] =
+{
+    0x000, 0x000, 0x000, 0x000, 0x000, 0x200, 0x200, 0x200,
+    0x200, 0x200, 0x400, 0x600, 0x800, 0xA00, 0xC00, 0xC00,
+    0xC00, 0xC00, 0xA00, 0x800, 0x600, 0x400, 0x200, 0x200,
+    0x200, 0x200, 0x200, 0x000, 0x000, 0x000, 0x000, 0x000
+};
+
+static const int qtab_726_40[15] =
+{
+    -122, -16,  68, 139, 198, 250, 298, 339,
+     378, 413, 445, 475, 502, 528, 553
+};
+
+/*
+ * returns the integer product of the 14-bit integer "an" and
+ * "floating point" representation (4-bit exponent, 6-bit mantessa) "srn".
+ */
+static int16_t fmult(int16_t an, int16_t srn)
+{
+    int16_t anmag;
+    int16_t anexp;
+    int16_t anmant;
+    int16_t wanexp;
+    int16_t wanmant;
+    int16_t retval;
+
+    anmag = (an > 0)  ?  an  :  ((-an) & 0x1FFF);
+    anexp = (int16_t) (top_bit(anmag) - 5);
+    anmant = (anmag == 0)  ?  32  :  (anexp >= 0)  ?  (anmag >> anexp)  :  (anmag << -anexp);
+    wanexp = anexp + ((srn >> 6) & 0xF) - 13;
+
+    wanmant = (anmant*(srn & 0x3F) + 0x30) >> 4;
+    retval = (wanexp >= 0)  ?  ((wanmant << wanexp) & 0x7FFF)  :  (wanmant >> -wanexp);
+
+    return (((an ^ srn) < 0)  ?  -retval  :  retval);
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Compute the estimated signal from the 6-zero predictor.
+ */
+static __inline__ int16_t predictor_zero(g726_state_t *s)
+{
+    int i;
+    int sezi;
+
+    sezi = fmult(s->b[0] >> 2, s->dq[0]);
+    /* ACCUM */
+    for (i = 1;  i < 6;  i++)
+        sezi += fmult(s->b[i] >> 2, s->dq[i]);
+    return (int16_t) sezi;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Computes the estimated signal from the 2-pole predictor.
+ */
+static __inline__ int16_t predictor_pole(g726_state_t *s)
+{
+    return (fmult(s->a[1] >> 2, s->sr[1]) + fmult(s->a[0] >> 2, s->sr[0]));
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Computes the quantization step size of the adaptive quantizer.
+ */
+static int step_size(g726_state_t *s)
+{
+    int y;
+    int dif;
+    int al;
+
+    if (s->ap >= 256)
+        return s->yu;
+    y = s->yl >> 6;
+    dif = s->yu - y;
+    al = s->ap >> 2;
+    if (dif > 0)
+        y += (dif*al) >> 6;
+    else if (dif < 0)
+        y += (dif*al + 0x3F) >> 6;
+    return y;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Given a raw sample, 'd', of the difference signal and a
+ * quantization step size scale factor, 'y', this routine returns the
+ * ADPCM codeword to which that sample gets quantized.  The step
+ * size scale factor division operation is done in the log base 2 domain
+ * as a subtraction.
+ */
+static int16_t quantize(int d,                  /* Raw difference signal sample */
+                        int y,                  /* Step size multiplier */
+                        const int table[],     /* quantization table */
+                        int quantizer_states)   /* table size of int16_t integers */
+{
+    int16_t dqm;    /* Magnitude of 'd' */
+    int16_t exp;    /* Integer part of base 2 log of 'd' */
+    int16_t mant;   /* Fractional part of base 2 log */
+    int16_t dl;     /* Log of magnitude of 'd' */
+    int16_t dln;    /* Step size scale factor normalized log */
+    int i;
+    int size;
+
+    /*
+     * LOG
+     *
+     * Compute base 2 log of 'd', and store in 'dl'.
+     */
+    dqm = (int16_t) abs(d);
+    exp = (int16_t) (top_bit(dqm >> 1) + 1);
+    /* Fractional portion. */
+    mant = ((dqm << 7) >> exp) & 0x7F;
+    dl = (exp << 7) + mant;
+
+    /*
+     * SUBTB
+     *
+     * "Divide" by step size multiplier.
+     */
+    dln = dl - (int16_t) (y >> 2);
+
+    /*
+     * QUAN
+     *
+     * Search for codword i for 'dln'.
+     */
+    size = (quantizer_states - 1) >> 1;
+    for (i = 0;  i < size;  i++)
+    {
+        if (dln < table[i])
+            break;
+    }
+    if (d < 0)
+    {
+        /* Take 1's complement of i */
+        return (int16_t) ((size << 1) + 1 - i);
+    }
+    if (i == 0  &&  (quantizer_states & 1))
+    {
+        /* Zero is only valid if there are an even number of states, so
+           take the 1's complement if the code is zero. */
+        return (int16_t) quantizer_states;
+    }
+    return (int16_t) i;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Returns reconstructed difference signal 'dq' obtained from
+ * codeword 'i' and quantization step size scale factor 'y'.
+ * Multiplication is performed in log base 2 domain as addition.
+ */
+static int16_t reconstruct(int sign,    /* 0 for non-negative value */
+                           int dqln,    /* G.72x codeword */
+                           int y)       /* Step size multiplier */
+{
+    int16_t dql;    /* Log of 'dq' magnitude */
+    int16_t dex;    /* Integer part of log */
+    int16_t dqt;
+    int16_t dq;     /* Reconstructed difference signal sample */
+
+    dql = (int16_t) (dqln + (y >> 2));  /* ADDA */
+
+    if (dql < 0)
+        return ((sign)  ?  -0x8000  :  0);
+    /* ANTILOG */
+    dex = (dql >> 7) & 15;
+    dqt = 128 + (dql & 127);
+    dq = (dqt << 7) >> (14 - dex);
+    return ((sign)  ?  (dq - 0x8000)  :  dq);
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * updates the state variables for each output code
+ */
+static void update(g726_state_t *s,
+                   int y,       /* quantizer step size */
+                   int wi,      /* scale factor multiplier */
+                   int fi,      /* for long/short term energies */
+                   int dq,      /* quantized prediction difference */
+                   int sr,      /* reconstructed signal */
+                   int dqsez)   /* difference from 2-pole predictor */
+{
+    int16_t mag;
+    int16_t exp;
+    int16_t a2p;        /* LIMC */
+    int16_t a1ul;       /* UPA1 */
+    int16_t pks1;       /* UPA2 */
+    int16_t fa1;
+    int16_t ylint;
+    int16_t dqthr;
+    int16_t ylfrac;
+    int16_t thr;
+    int16_t pk0;
+    int i;
+    int tr;
+
+    a2p = 0;
+    /* Needed in updating predictor poles */
+    pk0 = (dqsez < 0)  ?  1  :  0;
+
+    /* prediction difference magnitude */
+    mag = (int16_t) (dq & 0x7FFF);
+    /* TRANS */
+    ylint = (int16_t) (s->yl >> 15);            /* exponent part of yl */
+    ylfrac = (int16_t) ((s->yl >> 10) & 0x1F);  /* fractional part of yl */
+    /* Limit threshold to 31 << 10 */
+    thr = (ylint > 9)  ?  (31 << 10)  :  ((32 + ylfrac) << ylint);
+    dqthr = (thr + (thr >> 1)) >> 1;            /* dqthr = 0.75 * thr */
+    if (!s->td)                                 /* signal supposed voice */
+        tr = FALSE;
+    else if (mag <= dqthr)                      /* supposed data, but small mag */
+        tr = FALSE;                             /* treated as voice */
+    else                                        /* signal is data (modem) */
+        tr = TRUE;
+
+    /*
+     * Quantizer scale factor adaptation.
+     */
+
+    /* FUNCTW & FILTD & DELAY */
+    /* update non-steady state step size multiplier */
+    s->yu = (int16_t) (y + ((wi - y) >> 5));
+
+    /* LIMB */
+    if (s->yu < 544)
+        s->yu = 544;
+    else if (s->yu > 5120)
+        s->yu = 5120;
+
+    /* FILTE & DELAY */
+    /* update steady state step size multiplier */
+    s->yl += s->yu + ((-s->yl) >> 6);
+
+    /*
+     * Adaptive predictor coefficients.
+     */
+    if (tr)
+    {
+        /* Reset the a's and b's for a modem signal */
+        s->a[0] = 0;
+        s->a[1] = 0;
+        s->b[0] = 0;
+        s->b[1] = 0;
+        s->b[2] = 0;
+        s->b[3] = 0;
+        s->b[4] = 0;
+        s->b[5] = 0;
+    }
+    else
+    {
+        /* Update the a's and b's */
+        /* UPA2 */
+        pks1 = pk0 ^ s->pk[0];
+
+        /* Update predictor pole a[1] */
+        a2p = s->a[1] - (s->a[1] >> 7);
+        if (dqsez != 0)
+        {
+            fa1 = (pks1)  ?  s->a[0]  :  -s->a[0];
+            /* a2p = function of fa1 */
+            if (fa1 < -8191)
+                a2p -= 0x100;
+            else if (fa1 > 8191)
+                a2p += 0xFF;
+            else
+                a2p += fa1 >> 5;
+
+            if (pk0 ^ s->pk[1])
+            {
+                /* LIMC */
+                if (a2p <= -12160)
+                    a2p = -12288;
+                else if (a2p >= 12416)
+                    a2p = 12288;
+                else
+                    a2p -= 0x80;
+            }
+            else if (a2p <= -12416)
+                a2p = -12288;
+            else if (a2p >= 12160)
+                a2p = 12288;
+            else
+                a2p += 0x80;
+        }
+
+        /* TRIGB & DELAY */
+        s->a[1] = a2p;
+
+        /* UPA1 */
+        /* Update predictor pole a[0] */
+        s->a[0] -= s->a[0] >> 8;
+        if (dqsez != 0)
+        {
+            if (pks1 == 0)
+                s->a[0] += 192;
+            else
+                s->a[0] -= 192;
+        }
+        /* LIMD */
+        a1ul = 15360 - a2p;
+        if (s->a[0] < -a1ul)
+            s->a[0] = -a1ul;
+        else if (s->a[0] > a1ul)
+            s->a[0] = a1ul;
+
+        /* UPB : update predictor zeros b[6] */
+        for (i = 0;  i < 6;  i++)
+        {
+            /* Distinguish 40Kbps mode from the others */
+            s->b[i] -= s->b[i] >> ((s->bits_per_sample == 5)  ?  9  :  8);
+            if (dq & 0x7FFF)
+            {
+                /* XOR */
+                if ((dq ^ s->dq[i]) >= 0)
+                    s->b[i] += 128;
+                else
+                    s->b[i] -= 128;
+            }
+        }
+    }
+
+    for (i = 5;  i > 0;  i--)
+        s->dq[i] = s->dq[i - 1];
+    /* FLOAT A : convert dq[0] to 4-bit exp, 6-bit mantissa f.p. */
+    if (mag == 0)
+    {
+        s->dq[0] = (dq >= 0)  ?  0x20  :  0xFC20;
+    }
+    else
+    {
+        exp = (int16_t) (top_bit(mag) + 1);
+        s->dq[0] = (dq >= 0)
+                 ?  ((exp << 6) + ((mag << 6) >> exp))
+                 :  ((exp << 6) + ((mag << 6) >> exp) - 0x400);
+    }
+
+    s->sr[1] = s->sr[0];
+    /* FLOAT B : convert sr to 4-bit exp., 6-bit mantissa f.p. */
+    if (sr == 0)
+    {
+        s->sr[0] = 0x20;
+    }
+    else if (sr > 0)
+    {
+        exp = (int16_t) (top_bit(sr) + 1);
+        s->sr[0] = (int16_t) ((exp << 6) + ((sr << 6) >> exp));
+    }
+    else if (sr > -32768)
+    {
+        mag = (int16_t) -sr;
+        exp = (int16_t) (top_bit(mag) + 1);
+        s->sr[0] =  (exp << 6) + ((mag << 6) >> exp) - 0x400;
+    }
+    else
+    {
+        s->sr[0] = (uint16_t) 0xFC20;
+    }
+
+    /* DELAY A */
+    s->pk[1] = s->pk[0];
+    s->pk[0] = pk0;
+
+    /* TONE */
+    if (tr)                 /* this sample has been treated as data */
+        s->td = FALSE;      /* next one will be treated as voice */
+    else if (a2p < -11776)  /* small sample-to-sample correlation */
+        s->td = TRUE;       /* signal may be data */
+    else                    /* signal is voice */
+        s->td = FALSE;
+
+    /* Adaptation speed control. */
+    /* FILTA */
+    s->dms += ((int16_t) fi - s->dms) >> 5;
+    /* FILTB */
+    s->dml += (((int16_t) (fi << 2) - s->dml) >> 7);
+
+    if (tr)
+        s->ap = 256;
+    else if (y < 1536)                      /* SUBTC */
+        s->ap += (0x200 - s->ap) >> 4;
+    else if (s->td)
+        s->ap += (0x200 - s->ap) >> 4;
+    else if (abs((s->dms << 2) - s->dml) >= (s->dml >> 3))
+        s->ap += (0x200 - s->ap) >> 4;
+    else
+        s->ap += (-s->ap) >> 4;
+}
+/*- End of function --------------------------------------------------------*/
+
+static int16_t tandem_adjust_alaw(int16_t sr,   /* decoder output linear PCM sample */
+                                  int se,       /* predictor estimate sample */
+                                  int y,        /* quantizer step size */
+                                  int i,        /* decoder input code */
+                                  int sign,
+                                  const int qtab[],
+                                  int quantizer_states)
+{
+    uint8_t sp; /* A-law compressed 8-bit code */
+    int16_t dx; /* prediction error */
+    int id;     /* quantized prediction error */
+    int sd;     /* adjusted A-law decoded sample value */
+
+    if (sr <= -32768)
+        sr = -1;
+    sp = linear_to_alaw((sr >> 1) << 3);
+    /* 16-bit prediction error */
+    dx = (int16_t) ((alaw_to_linear(sp) >> 2) - se);
+    id = quantize(dx, y, qtab, quantizer_states);
+    if (id == i)
+    {
+        /* No adjustment of sp required */
+        return (int16_t) sp;
+    }
+    /* sp adjustment needed */
+    /* ADPCM codes : 8, 9, ... F, 0, 1, ... , 6, 7 */
+    /* 2's complement to biased unsigned */
+    if ((id ^ sign) > (i ^ sign))
+    {
+        /* sp adjusted to next lower value */
+        if (sp & 0x80)
+            sd = (sp == 0xD5)  ?  0x55  :  (((sp ^ 0x55) - 1) ^ 0x55);
+        else
+            sd = (sp == 0x2A)  ?  0x2A  :  (((sp ^ 0x55) + 1) ^ 0x55);
+    }
+    else
+    {
+        /* sp adjusted to next higher value */
+        if (sp & 0x80)
+            sd = (sp == 0xAA)  ?  0xAA  :  (((sp ^ 0x55) + 1) ^ 0x55);
+        else
+            sd = (sp == 0x55)  ?  0xD5  :  (((sp ^ 0x55) - 1) ^ 0x55);
+    }
+    return (int16_t) sd;
+}
+/*- End of function --------------------------------------------------------*/
+
+static int16_t tandem_adjust_ulaw(int16_t sr,   /* decoder output linear PCM sample */
+                                  int se,       /* predictor estimate sample */
+                                  int y,        /* quantizer step size */
+                                  int i,        /* decoder input code */
+                                  int sign,
+                                  const int qtab[],
+                                  int quantizer_states)
+{
+    uint8_t sp; /* u-law compressed 8-bit code */
+    int16_t dx; /* prediction error */
+    int id;     /* quantized prediction error */
+    int sd;     /* adjusted u-law decoded sample value */
+
+    if (sr <= -32768)
+        sr = 0;
+    sp = linear_to_ulaw(sr << 2);
+    /* 16-bit prediction error */
+    dx = (int16_t) ((ulaw_to_linear(sp) >> 2) - se);
+    id = quantize(dx, y, qtab, quantizer_states);
+    if (id == i)
+    {
+        /* No adjustment of sp required. */
+        return (int16_t) sp;
+    }
+    /* ADPCM codes : 8, 9, ... F, 0, 1, ... , 6, 7 */
+    /* 2's complement to biased unsigned */
+    if ((id ^ sign) > (i ^ sign))
+    {
+        /* sp adjusted to next lower value */
+        if (sp & 0x80)
+            sd = (sp == 0xFF)  ?  0x7E  :  (sp + 1);
+        else
+            sd = (sp == 0x00)  ?  0x00  :  (sp - 1);
+    }
+    else
+    {
+        /* sp adjusted to next higher value */
+        if (sp & 0x80)
+            sd = (sp == 0x80)  ?  0x80  :  (sp - 1);
+        else
+            sd = (sp == 0x7F)  ?  0xFE  :  (sp + 1);
+    }
+    return (int16_t) sd;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Encodes a linear PCM, A-law or u-law input sample and returns its 3-bit code.
+ */
+static uint8_t g726_16_encoder(g726_state_t *s, int16_t amp)
+{
+    int y;
+    int16_t sei;
+    int16_t sezi;
+    int16_t se;
+    int16_t d;
+    int16_t sr;
+    int16_t dqsez;
+    int16_t dq;
+    int16_t i;
+    
+    sezi = predictor_zero(s);
+    sei = sezi + predictor_pole(s);
+    se = sei >> 1;
+    d = amp - se;
+
+    /* Quantize prediction difference */
+    y = step_size(s);
+    i = quantize(d, y, qtab_726_16, 4);
+    dq = reconstruct(i & 2, g726_16_dqlntab[i], y);
+
+    /* Reconstruct the signal */
+    sr = (dq < 0)  ?  (se - (dq & 0x3FFF))  :  (se + dq);
+
+    /* Pole prediction difference */
+    dqsez = sr + (sezi >> 1) - se;
+    
+    update(s, y, g726_16_witab[i], g726_16_fitab[i], dq, sr, dqsez);
+    return (uint8_t) i;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Decodes a 2-bit CCITT G.726_16 ADPCM code and returns
+ * the resulting 16-bit linear PCM, A-law or u-law sample value.
+ */
+static int16_t g726_16_decoder(g726_state_t *s, uint8_t code)
+{
+    int16_t sezi;
+    int16_t sei;
+    int16_t se;
+    int16_t sr;
+    int16_t dq;
+    int16_t dqsez;
+    int y;
+
+    /* Mask to get proper bits */
+    code &= 0x03;
+    sezi = predictor_zero(s);
+    sei = sezi + predictor_pole(s);
+
+    y = step_size(s);
+    dq = reconstruct(code & 2, g726_16_dqlntab[code], y);
+
+    /* Reconstruct the signal */
+    se = sei >> 1;
+    sr = (dq < 0)  ?  (se - (dq & 0x3FFF))  :  (se + dq);
+
+    /* Pole prediction difference */
+    dqsez = sr + (sezi >> 1) - se;
+
+    update(s, y, g726_16_witab[code], g726_16_fitab[code], dq, sr, dqsez);
+
+    switch (s->ext_coding)
+    {
+    case G726_ENCODING_ALAW:
+        return tandem_adjust_alaw(sr, se, y, code, 2, qtab_726_16, 4);
+    case G726_ENCODING_ULAW:
+        return tandem_adjust_ulaw(sr, se, y, code, 2, qtab_726_16, 4);
+    }
+    return (sr << 2);
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Encodes a linear PCM, A-law or u-law input sample and returns its 3-bit code.
+ */
+static uint8_t g726_24_encoder(g726_state_t *s, int16_t amp)
+{
+    int16_t sei;
+    int16_t sezi;
+    int16_t se;
+    int16_t d;
+    int16_t sr;
+    int16_t dqsez;
+    int16_t dq;
+    int16_t i;
+    int y;
+    
+    sezi = predictor_zero(s);
+    sei = sezi + predictor_pole(s);
+    se = sei >> 1;
+    d = amp - se;
+
+    /* Quantize prediction difference */
+    y = step_size(s);
+    i = quantize(d, y, qtab_726_24, 7);
+    dq = reconstruct(i & 4, g726_24_dqlntab[i], y);
+
+    /* Reconstruct the signal */
+    sr = (dq < 0)  ?  (se - (dq & 0x3FFF))  :  (se + dq);
+
+    /* Pole prediction difference */
+    dqsez = sr + (sezi >> 1) - se;
+    
+    update(s, y, g726_24_witab[i], g726_24_fitab[i], dq, sr, dqsez);
+    return (uint8_t) i;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Decodes a 3-bit CCITT G.726_24 ADPCM code and returns
+ * the resulting 16-bit linear PCM, A-law or u-law sample value.
+ */
+static int16_t g726_24_decoder(g726_state_t *s, uint8_t code)
+{
+    int16_t sezi;
+    int16_t sei;
+    int16_t se;
+    int16_t sr;
+    int16_t dq;
+    int16_t dqsez;
+    int y;
+
+    /* Mask to get proper bits */
+    code &= 0x07;
+    sezi = predictor_zero(s);
+    sei = sezi + predictor_pole(s);
+
+    y = step_size(s);
+    dq = reconstruct(code & 4, g726_24_dqlntab[code], y);
+
+    /* Reconstruct the signal */
+    se = sei >> 1;
+    sr = (dq < 0)  ?  (se - (dq & 0x3FFF))  :  (se + dq);
+
+    /* Pole prediction difference */
+    dqsez = sr + (sezi >> 1) - se;
+
+    update(s, y, g726_24_witab[code], g726_24_fitab[code], dq, sr, dqsez);
+
+    switch (s->ext_coding)
+    {
+    case G726_ENCODING_ALAW:
+        return tandem_adjust_alaw(sr, se, y, code, 4, qtab_726_24, 7);
+    case G726_ENCODING_ULAW:
+        return tandem_adjust_ulaw(sr, se, y, code, 4, qtab_726_24, 7);
+    }
+    return (sr << 2);
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Encodes a linear input sample and returns its 4-bit code.
+ */
+static uint8_t g726_32_encoder(g726_state_t *s, int16_t amp)
+{
+    int16_t sei;
+    int16_t sezi;
+    int16_t se;
+    int16_t d;
+    int16_t sr;
+    int16_t dqsez;
+    int16_t dq;
+    int16_t i;
+    int y;
+    
+    sezi = predictor_zero(s);
+    sei = sezi + predictor_pole(s);
+    se = sei >> 1;
+    d = amp - se;
+
+    /* Quantize the prediction difference */
+    y = step_size(s);
+    i = quantize(d, y, qtab_726_32, 15);
+    dq = reconstruct(i & 8, g726_32_dqlntab[i], y);
+
+    /* Reconstruct the signal */
+    sr = (dq < 0)  ?  (se - (dq & 0x3FFF))  :  (se + dq);
+
+    /* Pole prediction difference */
+    dqsez = sr + (sezi >> 1) - se;
+
+    update(s, y, g726_32_witab[i], g726_32_fitab[i], dq, sr, dqsez);
+    return (uint8_t) i;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Decodes a 4-bit CCITT G.726_32 ADPCM code and returns
+ * the resulting 16-bit linear PCM, A-law or u-law sample value.
+ */
+static int16_t g726_32_decoder(g726_state_t *s, uint8_t code)
+{
+    int16_t sezi;
+    int16_t sei;
+    int16_t se;
+    int16_t sr;
+    int16_t dq;
+    int16_t dqsez;
+    int y;
+
+    /* Mask to get proper bits */
+    code &= 0x0F;
+    sezi = predictor_zero(s);
+    sei = sezi + predictor_pole(s);
+
+    y = step_size(s);
+    dq = reconstruct(code & 8, g726_32_dqlntab[code], y);
+
+    /* Reconstruct the signal */
+    se = sei >> 1;
+    sr = (dq < 0)  ?  (se - (dq & 0x3FFF))  :  (se + dq);
+
+    /* Pole prediction difference */
+    dqsez = sr + (sezi >> 1) - se;
+
+    update(s, y, g726_32_witab[code], g726_32_fitab[code], dq, sr, dqsez);
+
+    switch (s->ext_coding)
+    {
+    case G726_ENCODING_ALAW:
+        return tandem_adjust_alaw(sr, se, y, code, 8, qtab_726_32, 15);
+    case G726_ENCODING_ULAW:
+        return tandem_adjust_ulaw(sr, se, y, code, 8, qtab_726_32, 15);
+    }
+    return (sr << 2);
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Encodes a 16-bit linear PCM, A-law or u-law input sample and retuens
+ * the resulting 5-bit CCITT G.726 40Kbps code.
+ */
+static uint8_t g726_40_encoder(g726_state_t *s, int16_t amp)
+{
+    int16_t sei;
+    int16_t sezi;
+    int16_t se;
+    int16_t d;
+    int16_t sr;
+    int16_t dqsez;
+    int16_t dq;
+    int16_t i;
+    int y;
+    
+    sezi = predictor_zero(s);
+    sei = sezi + predictor_pole(s);
+    se = sei >> 1;
+    d = amp - se;
+
+    /* Quantize prediction difference */
+    y = step_size(s);
+    i = quantize(d, y, qtab_726_40, 31);
+    dq = reconstruct(i & 0x10, g726_40_dqlntab[i], y);
+
+    /* Reconstruct the signal */
+    sr = (dq < 0)  ?  (se - (dq & 0x7FFF))  :  (se + dq);
+
+    /* Pole prediction difference */
+    dqsez = sr + (sezi >> 1) - se;
+
+    update(s, y, g726_40_witab[i], g726_40_fitab[i], dq, sr, dqsez);
+    return (uint8_t) i;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * Decodes a 5-bit CCITT G.726 40Kbps code and returns
+ * the resulting 16-bit linear PCM, A-law or u-law sample value.
+ */
+static int16_t g726_40_decoder(g726_state_t *s, uint8_t code)
+{
+    int16_t sezi;
+    int16_t sei;
+    int16_t se;
+    int16_t sr;
+    int16_t dq;
+    int16_t dqsez;
+    int y;
+
+    /* Mask to get proper bits */
+    code &= 0x1F;
+    sezi = predictor_zero(s);
+    sei = sezi + predictor_pole(s);
+        
+    y = step_size(s);
+    dq = reconstruct(code & 0x10, g726_40_dqlntab[code], y);
+
+    /* Reconstruct the signal */
+    se = sei >> 1;
+    sr = (dq < 0)  ?  (se - (dq & 0x7FFF))  :  (se + dq);
+
+    /* Pole prediction difference */
+    dqsez = sr + (sezi >> 1) - se;
+
+    update(s, y, g726_40_witab[code], g726_40_fitab[code], dq, sr, dqsez);
+
+    switch (s->ext_coding)
+    {
+    case G726_ENCODING_ALAW:
+        return tandem_adjust_alaw(sr, se, y, code, 0x10, qtab_726_40, 31);
+    case G726_ENCODING_ULAW:
+        return tandem_adjust_ulaw(sr, se, y, code, 0x10, qtab_726_40, 31);
+    }
+    return (sr << 2);
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(g726_state_t *) g726_init(g726_state_t *s, int bit_rate, int ext_coding, int packing)
+{
+    int i;
+
+    if (bit_rate != 16000  &&  bit_rate != 24000  &&  bit_rate != 32000  &&  bit_rate != 40000)
+        return NULL;
+#ifndef SPANDSP_PRIOR_ALLOCATION
+    if (s == NULL)
+    {
+        if ((s = (g726_state_t *) malloc(sizeof(*s))) == NULL)
+            return  NULL;
+    }
+#endif
+    s->yl = 34816;
+    s->yu = 544;
+    s->dms = 0;
+    s->dml = 0;
+    s->ap = 0;
+    s->rate = bit_rate;
+    s->ext_coding = ext_coding;
+    s->packing = packing;
+    for (i = 0; i < 2; i++)
+    {
+        s->a[i] = 0;
+        s->pk[i] = 0;
+        s->sr[i] = 32;
+    }
+    for (i = 0; i < 6; i++)
+    {
+        s->b[i] = 0;
+        s->dq[i] = 32;
+    }
+    s->td = FALSE;
+    switch (bit_rate)
+    {
+    case 16000:
+        s->enc_func = g726_16_encoder;
+        s->dec_func = g726_16_decoder;
+        s->bits_per_sample = 2;
+        break;
+    case 24000:
+        s->enc_func = g726_24_encoder;
+        s->dec_func = g726_24_decoder;
+        s->bits_per_sample = 3;
+        break;
+    case 32000:
+    default:
+        s->enc_func = g726_32_encoder;
+        s->dec_func = g726_32_decoder;
+        s->bits_per_sample = 4;
+        break;
+    case 40000:
+        s->enc_func = g726_40_encoder;
+        s->dec_func = g726_40_decoder;
+        s->bits_per_sample = 5;
+        break;
+    }
+    bitstream_init(&s->bs, (s->packing != G726_PACKING_LEFT));
+    return s;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g726_release(g726_state_t *s)
+{
+    return 0;
+}
+/*- End of function --------------------------------------------------------*/
+
+#ifndef SPANDSP_PRIOR_ALLOCATION
+SPAN_DECLARE(int) g726_free(g726_state_t *s)
+{
+    free(s);
+    return 0;
+}
+#endif
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g726_decode(g726_state_t *s,
+                              int16_t amp[],
+                              const uint8_t g726_data[],
+                              int g726_bytes)
+{
+    int i;
+    int samples;
+    uint8_t code;
+    int sl;
+
+    for (samples = i = 0;  ;  )
+    {
+        if (s->packing != G726_PACKING_NONE)
+        {
+            /* Unpack the code bits */
+            if (s->packing != G726_PACKING_LEFT)
+            {
+                if (s->bs.residue < s->bits_per_sample)
+                {
+                    if (i >= g726_bytes)
+                        break;
+                    s->bs.bitstream |= (g726_data[i++] << s->bs.residue);
+                    s->bs.residue += 8;
+                }
+                code = (uint8_t) (s->bs.bitstream & ((1 << s->bits_per_sample) - 1));
+                s->bs.bitstream >>= s->bits_per_sample;
+            }
+            else
+            {
+                if (s->bs.residue < s->bits_per_sample)
+                {
+                    if (i >= g726_bytes)
+                        break;
+                    s->bs.bitstream = (s->bs.bitstream << 8) | g726_data[i++];
+                    s->bs.residue += 8;
+                }
+                code = (uint8_t) ((s->bs.bitstream >> (s->bs.residue - s->bits_per_sample)) & ((1 << s->bits_per_sample) - 1));
+            }
+            s->bs.residue -= s->bits_per_sample;
+        }
+        else
+        {
+            if (i >= g726_bytes)
+                break;
+            code = g726_data[i++];
+        }
+        sl = s->dec_func(s, code);
+        if (s->ext_coding != G726_ENCODING_LINEAR)
+            ((uint8_t *) amp)[samples++] = (uint8_t) sl;
+        else
+            amp[samples++] = (int16_t) sl;
+    }
+    return samples;
+}
+/*- End of function --------------------------------------------------------*/
+
+SPAN_DECLARE(int) g726_encode(g726_state_t *s,
+                              uint8_t g726_data[],
+                              const int16_t amp[],
+                              int len)
+{
+    int i;
+    int g726_bytes;
+    int16_t sl;
+    uint8_t code;
+
+    for (g726_bytes = i = 0;  i < len;  i++)
+    {
+        /* Linearize the input sample to 14-bit PCM */
+        switch (s->ext_coding)
+        {
+        case G726_ENCODING_ALAW:
+            sl = alaw_to_linear(((const uint8_t *) amp)[i]) >> 2;
+            break;
+        case G726_ENCODING_ULAW:
+            sl = ulaw_to_linear(((const uint8_t *) amp)[i]) >> 2;
+            break;
+        default:
+            sl = amp[i] >> 2;
+            break;
+        }
+        code = s->enc_func(s, sl);
+        if (s->packing != G726_PACKING_NONE)
+        {
+            /* Pack the code bits */
+            if (s->packing != G726_PACKING_LEFT)
+            {
+                s->bs.bitstream |= (code << s->bs.residue);
+                s->bs.residue += s->bits_per_sample;
+                if (s->bs.residue >= 8)
+                {
+                    g726_data[g726_bytes++] = (uint8_t) (s->bs.bitstream & 0xFF);
+                    s->bs.bitstream >>= 8;
+                    s->bs.residue -= 8;
+                }
+            }
+            else
+            {
+                s->bs.bitstream = (s->bs.bitstream << s->bits_per_sample) | code;
+                s->bs.residue += s->bits_per_sample;
+                if (s->bs.residue >= 8)
+                {
+                    g726_data[g726_bytes++] = (uint8_t) ((s->bs.bitstream >> (s->bs.residue - 8)) & 0xFF);
+                    s->bs.residue -= 8;
+                }
+            }
+        }
+        else
+        {
+            g726_data[g726_bytes++] = (uint8_t) code;
+        }
+    }
+    return g726_bytes;
+}
+/*- End of function --------------------------------------------------------*/
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/bit_operations.h b/src/codec/spandsp/src/spandsp/bit_operations.h
new file mode 100644 (file)
index 0000000..df308d9
--- /dev/null
@@ -0,0 +1,312 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * bit_operations.h - Various bit level operations, such as bit reversal
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2006 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/*! \file */
+
+#if !defined(_SPANDSP_BIT_OPERATIONS_H_)
+#define _SPANDSP_BIT_OPERATIONS_H_
+
+#if defined(__i386__)  ||  defined(__x86_64__)
+#if !defined(__SUNPRO_C)  ||  (__SUNPRO_C >= 0x0590)
+#define SPANDSP_USE_86_ASM
+#endif
+#endif
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+/*! \brief Find the bit position of the highest set bit in a word
+    \param bits The word to be searched
+    \return The bit number of the highest set bit, or -1 if the word is zero. */
+static __inline__ int top_bit(unsigned int bits)
+{
+#if defined(SPANDSP_USE_86_ASM)
+    int res;
+
+    __asm__ (" xorl %[res],%[res];\n"
+             " decl %[res];\n"
+             " bsrl %[bits],%[res]\n"
+             : [res] "=&r" (res)
+             : [bits] "rm" (bits));
+    return res;
+#elif defined(__ppc__)  ||   defined(__powerpc__)
+    int res;
+
+    __asm__ ("cntlzw %[res],%[bits];\n"
+             : [res] "=&r" (res)
+             : [bits] "r" (bits));
+    return 31 - res;
+#elif defined(_M_IX86)
+    /* Visual Studio i386 */
+    __asm
+    {
+        xor eax, eax
+        dec eax
+        bsr eax, bits
+    }
+#elif defined(_M_X64)
+    /* Visual Studio x86_64 */
+    /* TODO: Need the appropriate x86_64 code */
+    int res;
+
+    if (bits == 0)
+        return -1;
+    res = 0;
+    if (bits & 0xFFFF0000)
+    {
+        bits &= 0xFFFF0000;
+        res += 16;
+    }
+    if (bits & 0xFF00FF00)
+    {
+        bits &= 0xFF00FF00;
+        res += 8;
+    }
+    if (bits & 0xF0F0F0F0)
+    {
+        bits &= 0xF0F0F0F0;
+        res += 4;
+    }
+    if (bits & 0xCCCCCCCC)
+    {
+        bits &= 0xCCCCCCCC;
+        res += 2;
+    }
+    if (bits & 0xAAAAAAAA)
+    {
+        bits &= 0xAAAAAAAA;
+        res += 1;
+    }
+    return res;
+#else
+    int res;
+
+    if (bits == 0)
+        return -1;
+    res = 0;
+    if (bits & 0xFFFF0000)
+    {
+        bits &= 0xFFFF0000;
+        res += 16;
+    }
+    if (bits & 0xFF00FF00)
+    {
+        bits &= 0xFF00FF00;
+        res += 8;
+    }
+    if (bits & 0xF0F0F0F0)
+    {
+        bits &= 0xF0F0F0F0;
+        res += 4;
+    }
+    if (bits & 0xCCCCCCCC)
+    {
+        bits &= 0xCCCCCCCC;
+        res += 2;
+    }
+    if (bits & 0xAAAAAAAA)
+    {
+        bits &= 0xAAAAAAAA;
+        res += 1;
+    }
+    return res;
+#endif
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Find the bit position of the lowest set bit in a word
+    \param bits The word to be searched
+    \return The bit number of the lowest set bit, or -1 if the word is zero. */
+static __inline__ int bottom_bit(unsigned int bits)
+{
+    int res;
+    
+#if defined(SPANDSP_USE_86_ASM)
+    __asm__ (" xorl %[res],%[res];\n"
+             " decl %[res];\n"
+             " bsfl %[bits],%[res]\n"
+             : [res] "=&r" (res)
+             : [bits] "rm" (bits));
+    return res;
+#else
+    if (bits == 0)
+        return -1;
+    res = 31;
+    if (bits & 0x0000FFFF)
+    {
+        bits &= 0x0000FFFF;
+        res -= 16;
+    }
+    if (bits & 0x00FF00FF)
+    {
+        bits &= 0x00FF00FF;
+        res -= 8;
+    }
+    if (bits & 0x0F0F0F0F)
+    {
+        bits &= 0x0F0F0F0F;
+        res -= 4;
+    }
+    if (bits & 0x33333333)
+    {
+        bits &= 0x33333333;
+        res -= 2;
+    }
+    if (bits & 0x55555555)
+    {
+        bits &= 0x55555555;
+        res -= 1;
+    }
+    return res;
+#endif
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Bit reverse a byte.
+    \param data The byte to be reversed.
+    \return The bit reversed version of data. */
+static __inline__ uint8_t bit_reverse8(uint8_t x)
+{
+#if defined(__i386__)  ||  defined(__x86_64__)  ||  defined(__ppc__)  ||  defined(__powerpc__)
+    /* If multiply is fast */
+    return ((x*0x0802U & 0x22110U) | (x*0x8020U & 0x88440U))*0x10101U >> 16;
+#else
+    /* If multiply is slow, but we have a barrel shifter */
+    x = (x >> 4) | (x << 4);
+    x = ((x & 0xCC) >> 2) | ((x & 0x33) << 2);
+    return ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
+#endif
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Bit reverse a 16 bit word.
+    \param data The word to be reversed.
+    \return The bit reversed version of data. */
+SPAN_DECLARE(uint16_t) bit_reverse16(uint16_t data);
+
+/*! \brief Bit reverse a 32 bit word.
+    \param data The word to be reversed.
+    \return The bit reversed version of data. */
+SPAN_DECLARE(uint32_t) bit_reverse32(uint32_t data);
+
+/*! \brief Bit reverse each of the four bytes in a 32 bit word.
+    \param data The word to be reversed.
+    \return The bit reversed version of data. */
+SPAN_DECLARE(uint32_t) bit_reverse_4bytes(uint32_t data);
+
+#if defined(__x86_64__)
+/*! \brief Bit reverse each of the eight bytes in a 64 bit word.
+    \param data The word to be reversed.
+    \return The bit reversed version of data. */
+SPAN_DECLARE(uint64_t) bit_reverse_8bytes(uint64_t data);
+#endif
+
+/*! \brief Bit reverse each bytes in a buffer.
+    \param to The buffer to place the reversed data in.
+    \param from The buffer containing the data to be reversed.
+    \param len The length of the data in the buffer. */
+SPAN_DECLARE(void) bit_reverse(uint8_t to[], const uint8_t from[], int len);
+
+/*! \brief Find the number of set bits in a 32 bit word.
+    \param x The word to be searched.
+    \return The number of set bits. */
+SPAN_DECLARE(int) one_bits32(uint32_t x);
+
+/*! \brief Create a mask as wide as the number in a 32 bit word.
+    \param x The word to be searched.
+    \return The mask. */
+SPAN_DECLARE(uint32_t) make_mask32(uint32_t x);
+
+/*! \brief Create a mask as wide as the number in a 16 bit word.
+    \param x The word to be searched.
+    \return The mask. */
+SPAN_DECLARE(uint16_t) make_mask16(uint16_t x);
+
+/*! \brief Find the least significant one in a word, and return a word
+           with just that bit set.
+    \param x The word to be searched.
+    \return The word with the single set bit. */
+static __inline__ uint32_t least_significant_one32(uint32_t x)
+{
+    return (x & (-(int32_t) x));
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Find the most significant one in a word, and return a word
+           with just that bit set.
+    \param x The word to be searched.
+    \return The word with the single set bit. */
+static __inline__ uint32_t most_significant_one32(uint32_t x)
+{
+#if defined(__i386__)  ||  defined(__x86_64__)  ||  defined(__ppc__)  ||  defined(__powerpc__)
+    return 1 << top_bit(x);
+#else
+    x = make_mask32(x);
+    return (x ^ (x >> 1));
+#endif
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Find the parity of a byte.
+    \param x The byte to be checked.
+    \return 1 for odd, or 0 for even. */
+static __inline__ int parity8(uint8_t x)
+{
+    x = (x ^ (x >> 4)) & 0x0F;
+    return (0x6996 >> x) & 1;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Find the parity of a 16 bit word.
+    \param x The word to be checked.
+    \return 1 for odd, or 0 for even. */
+static __inline__ int parity16(uint16_t x)
+{
+    x ^= (x >> 8);
+    x = (x ^ (x >> 4)) & 0x0F;
+    return (0x6996 >> x) & 1;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Find the parity of a 32 bit word.
+    \param x The word to be checked.
+    \return 1 for odd, or 0 for even. */
+static __inline__ int parity32(uint32_t x)
+{
+    x ^= (x >> 16);
+    x ^= (x >> 8);
+    x = (x ^ (x >> 4)) & 0x0F;
+    return (0x6996 >> x) & 1;
+}
+/*- End of function --------------------------------------------------------*/
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/bitstream.h b/src/codec/spandsp/src/spandsp/bitstream.h
new file mode 100644 (file)
index 0000000..b55e4af
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * bitstream.h - Bitstream composition and decomposition routines.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2006 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/*! \file */
+
+#if !defined(_SPANDSP_BITSTREAM_H_)
+#define _SPANDSP_BITSTREAM_H_
+
+/*! \page bitstream_page Bitstream composition and decomposition
+\section bitstream_page_sec_1 What does it do?
+
+\section bitstream_page_sec_2 How does it work?
+*/
+
+/*! Bitstream handler state */
+typedef struct bitstream_state_s bitstream_state_t;
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+/*! \brief Put a chunk of bits into the output buffer.
+    \param s A pointer to the bitstream context.
+    \param c A pointer to the bitstream output buffer.
+    \param value The value to be pushed into the output buffer.
+    \param bits The number of bits of value to be pushed. 1 to 25 bits is valid. */
+SPAN_DECLARE(void) bitstream_put(bitstream_state_t *s, uint8_t **c, uint32_t value, int bits);
+
+/*! \brief Get a chunk of bits from the input buffer.
+    \param s A pointer to the bitstream context.
+    \param c A pointer to the bitstream input buffer.
+    \param bits The number of bits of value to be grabbed. 1 to 25 bits is valid.
+    \return The value retrieved from the input buffer. */
+SPAN_DECLARE(uint32_t) bitstream_get(bitstream_state_t *s, const uint8_t **c, int bits);
+
+/*! \brief Emit any residual bits to the output buffer, without actually flushing them.
+           This is useful for getting the buffer fully up to date, ready for things
+           like CRC calculations, while allowing bitstream_put() to be used to continue
+           the message later.
+    \param s A pointer to the bitstream context.
+    \param c A pointer to the bitstream output buffer. */
+SPAN_DECLARE(void) bitstream_emit(bitstream_state_t *s, uint8_t **c);
+
+/*! \brief Flush any residual bits to the output buffer.
+    \param s A pointer to the bitstream context.
+    \param c A pointer to the bitstream output buffer. */
+SPAN_DECLARE(void) bitstream_flush(bitstream_state_t *s, uint8_t **c);
+
+/*! \brief Initialise a bitstream context.
+    \param s A pointer to the bitstream context.
+    \param lsb_first TRUE if the bit stream is LSB first, else its MSB first.
+    \return A pointer to the bitstream context. */
+SPAN_DECLARE(bitstream_state_t *) bitstream_init(bitstream_state_t *s, int direction);
+
+SPAN_DECLARE(int) bitstream_release(bitstream_state_t *s);
+
+SPAN_DECLARE(int) bitstream_free(bitstream_state_t *s);
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/dc_restore.h b/src/codec/spandsp/src/spandsp/dc_restore.h
new file mode 100644 (file)
index 0000000..94ff6c7
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * dc_restore.h - General telephony routines to restore the zero D.C.
+ *                level to audio which has a D.C. bias.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2001 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/*! \file */
+
+#if !defined(_SPANDSP_DC_RESTORE_H_)
+#define _SPANDSP_DC_RESTORE_H_
+
+/*! \page dc_restore_page Removing DC bias from a signal
+
+\section dc_restore_page_sec_1 What does it do?
+
+Telecoms signals often contain considerable DC, but DC upsets a lot of signal
+processing functions. Placing a zero DC restorer at the front of the processing
+chain can often simplify the downstream processing. 
+
+\section dc_restore_page_sec_2 How does it work?
+
+The DC restorer uses a leaky integrator to provide a long-ish term estimate of
+the DC bias in the signal. A 32 bit estimate is used for the 16 bit audio, so
+the noise introduced by the estimation can be keep in the lower bits, and the 16
+bit DC value, which is subtracted from the signal, is fairly clean. The
+following code fragment shows the algorithm used. dc_bias is a 32 bit integer,
+while the sample and the resulting clean_sample are 16 bit integers. 
+
+    dc_bias += ((((int32_t) sample << 15) - dc_bias) >> 14);
+    clean_sample = sample - (dc_bias >> 15); 
+*/
+
+/*!
+    Zero DC restoration descriptor. This defines the working state for a single
+    instance of DC content filter.
+*/
+typedef struct
+{
+    int32_t state;
+} dc_restore_state_t;
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+static __inline__ void dc_restore_init(dc_restore_state_t *dc)
+{
+    dc->state = 0;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t dc_restore(dc_restore_state_t *dc, int16_t sample)
+{
+    dc->state += ((((int32_t) sample << 15) - dc->state) >> 14);
+    return (int16_t) (sample - (dc->state >> 15));
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t dc_restore_estimate(dc_restore_state_t *dc)
+{
+    return (int16_t) (dc->state >> 15);
+}
+/*- End of function --------------------------------------------------------*/
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/fast_convert.h b/src/codec/spandsp/src/spandsp/fast_convert.h
new file mode 100644 (file)
index 0000000..10679ea
--- /dev/null
@@ -0,0 +1,436 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * fast_convert.h - Quick ways to convert floating point numbers to integers
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2009 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#if !defined(_SPANDSP_FAST_CONVERT_H_)
+#define _SPANDSP_FAST_CONVERT_H_
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+/* The following code, to handle issues with lrint() and lrintf() on various
+ * platforms, is adapted from similar code in libsndfile, which is:
+ *
+ * Copyright (C) 2001-2004 Erik de Castro Lopo <erikd@mega-nerd.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published by
+ * the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ */
+
+/*
+ *    On Intel Pentium processors (especially PIII and probably P4), converting
+ *    from float to int is very slow. To meet the C specs, the code produced by
+ *    most C compilers targeting Pentium needs to change the FPU rounding mode
+ *    before the float to int conversion is performed.
+ *
+ *    Changing the FPU rounding mode causes the FPU pipeline to be flushed. It
+ *    is this flushing of the pipeline which is so slow.
+ *
+ *    Fortunately the ISO C99 specification defines the functions lrint, lrintf,
+ *    llrint and llrintf which fix this problem as a side effect.
+ *
+ *    On Unix-like systems, the configure process should have detected the
+ *    presence of these functions. If they weren't found we have to replace them
+ *    here with a standard C cast.
+ */
+
+/*
+ *    The C99 prototypes for these functions are as follows:
+ *
+ *        int rintf(float x);
+ *        int rint(double x);
+ *        long int lrintf(float x);
+ *        long int lrint(double x);
+ *        long long int llrintf(float x);
+ *        long long int llrint(double x);
+ *
+ *    The presence of the required functions are detected during the configure
+ *    process and the values HAVE_LRINT and HAVE_LRINTF are set accordingly in
+ *    the config file.
+ */
+
+#if defined(__CYGWIN__)
+#if !defined(__cplusplus)  &&  (__GNUC__ < 4)
+    /*
+     *    CYGWIN versions prior to 1.7.1 have lrint and lrintf functions, but
+     *    they are slow and buggy:
+     *        http://sourceware.org/ml/cygwin/2005-06/msg00153.html
+     *        http://sourceware.org/ml/cygwin/2005-09/msg00047.html
+     *    These replacement functions (pulled from the Public Domain MinGW
+     *    math.h header) replace the native versions.
+     */
+    static __inline__ long int lrint(double x)
+    {
+        long int retval;
+
+        __asm__ __volatile__
+        (
+            "fistpl %0"
+            : "=m" (retval)
+            : "t" (x)
+            : "st"
+        );
+
+        return retval;
+    }
+
+    static __inline__ long int lrintf(float x)
+    {
+        long int retval;
+
+        __asm__ __volatile__
+        (
+            "fistpl %0"
+            : "=m" (retval)
+            : "t" (x)
+            : "st"
+        );
+        return retval;
+    }
+#endif
+
+    /* The fastest way to convert is the equivalent of lrint() */
+    static __inline__ long int lfastrint(double x)
+    {
+        long int retval;
+
+        __asm__ __volatile__
+        (
+            "fistpl %0"
+            : "=m" (retval)
+            : "t" (x)
+            : "st"
+        );
+
+        return retval;
+    }
+
+    static __inline__ long int lfastrintf(float x)
+    {
+        long int retval;
+
+        __asm__ __volatile__
+        (
+            "fistpl %0"
+            : "=m" (retval)
+            : "t" (x)
+            : "st"
+        );
+        return retval;
+    }
+#elif defined(__GNUC__)  ||  (__SUNPRO_C >= 0x0590)
+
+#if defined(__i386__)
+    /* These routines are guaranteed fast on an i386 machine. Using the built in
+       lrint() and lrintf() should be similar, but they may not always be enabled.
+       Sometimes, especially with "-O0", you might get slow calls to routines. */
+    static __inline__ long int lfastrint(double x)
+    {
+        long int retval;
+
+        __asm__ __volatile__
+        (
+            "fistpl %0"
+            : "=m" (retval)
+            : "t" (x)
+            : "st"
+        );
+
+        return retval;
+    }
+
+    static __inline__ long int lfastrintf(float x)
+    {
+        long int retval;
+
+        __asm__ __volatile__
+        (
+            "fistpl %0"
+            : "=m" (retval)
+            : "t" (x)
+            : "st"
+        );
+        return retval;
+    }
+#elif defined(__x86_64__)
+    /* On an x86_64 machine, the fastest thing seems to be a pure assignment from a
+       double or float to an int. It looks like the design on the x86_64 took account
+       of the default behaviour specified for C. */
+    static __inline__ long int lfastrint(double x)
+    {
+        return (long int) (x);
+    }
+
+    static __inline__ long int lfastrintf(float x)
+    {
+        return (long int) (x);
+    }
+#elif defined(__ppc__)  ||   defined(__powerpc__)
+    static __inline__ long int lfastrint(register double x)
+    {
+        int res[2];
+
+        __asm__ __volatile__
+        (
+            "fctiw %1, %1\n\t"
+            "stfd %1, %0"
+            : "=m" (res)    /* Output */
+            : "f" (x)       /* Input */
+            : "memory"
+        );
+
+        return res[1];
+    }
+
+    static __inline__ long int lfastrintf(register float x)
+    {
+        int res[2];
+
+        __asm__ __volatile__
+        (
+            "fctiw %1, %1\n\t"
+            "stfd %1, %0"
+            : "=m" (res)    /* Output */
+            : "f" (x)       /* Input */
+            : "memory"
+        );
+
+        return res[1];
+    }
+#else
+    /* Fallback routines, for unrecognised platforms */
+    static __inline__ long int lfastrint(double x)
+    {
+        return (long int) x;
+    }
+
+    static __inline__ long int lfastrintf(float x)
+    {
+        return (long int) x;
+    }
+#endif
+
+#elif defined(_M_IX86)
+    /* Visual Studio i386 */
+    /*
+     *    Win32 doesn't seem to have the lrint() and lrintf() functions.
+     *    Therefore implement inline versions of these functions here.
+     */
+
+    __inline long int lrint(double x)
+    {
+        long int i;
+
+        _asm
+        {
+            fld x
+            fistp i
+        };
+        return i;
+    }
+
+    __inline long int lrintf(float x)
+    {
+        long int i;
+
+        _asm
+        {
+            fld x
+            fistp i
+        };
+        return i;
+    }
+
+    __inline float rintf(float flt)
+    {
+       _asm
+       {       fld flt
+               frndint
+       }
+    }
+
+    __inline double rint(double dbl)
+    {
+        _asm 
+       {
+            fld dbl
+            frndint
+        }
+    }
+
+    __inline long int lfastrint(double x)
+    {
+        long int i;
+
+        _asm
+        {
+            fld x
+            fistp i
+        };
+        return i;
+    }
+
+    __inline long int lfastrintf(float x)
+    {
+        long int i;
+
+        _asm
+        {
+            fld x
+            fistp i
+        };
+        return i;
+    }
+#elif defined(_M_X64)
+    /* Visual Studio x86_64 */
+    /* x86_64 machines will do best with a simple assignment. */
+#include <intrin.h>
+
+    __inline long int lrint(double x)
+    {
+               return (long int)_mm_cvtsd_si64x( _mm_loadu_pd ((const double*)&x) );
+    }
+
+    __inline long int lrintf(float x)
+    {
+               return _mm_cvt_ss2si( _mm_load_ss((const float*)&x) );
+    }
+
+    __inline long int lfastrint(double x)
+    {
+        return (long int) (x);
+    }
+
+    __inline long int lfastrintf(float x)
+    {
+        return (long int) (x);
+    }
+#elif defined(__MWERKS__)  &&  defined(macintosh)
+    /* This MacOS 9 solution was provided by Stephane Letz */
+
+    long int __inline__ lfastrint(register double x)
+    {
+        long int res[2];
+
+        asm
+        {
+            fctiw x, x
+            stfd x, res
+        }
+        return res[1];
+    }
+
+    long int __inline__ lfastrintf(register float x)
+    {
+        long int res[2];
+
+        asm
+        {
+            fctiw x, x
+            stfd x, res
+        }
+        return res[1];
+    }
+#elif defined(__MACH__)  &&  defined(__APPLE__)  &&  (defined(__ppc__)  ||  defined(__powerpc__))
+    /* For Apple Mac OS/X - do recent versions still need this? */
+
+    static __inline__ long int lfastrint(register double x)
+    {
+        int res[2];
+
+        __asm__ __volatile__
+        (
+            "fctiw %1, %1\n\t"
+            "stfd %1, %0"
+            : "=m" (res)    /* Output */
+            : "f" (x)       /* Input */
+            : "memory"
+        );
+
+        return res[1];
+    }
+
+    static __inline__ long int lfastrintf(register float x)
+    {
+        int res[2];
+
+        __asm__ __volatile__
+        (
+            "fctiw %1, %1\n\t"
+            "stfd %1, %0"
+            : "=m" (res)    /* Output */
+            : "f" (x)       /* Input */
+            : "memory"
+        );
+
+        return res[1];
+    }
+#else
+    /* There is nothing else to do, but use a simple casting operation, instead of a real
+       rint() type function. Since we are only trying to use rint() to speed up conversions,
+       the accuracy issues related to changing the rounding scheme are of little concern
+       to us. */
+
+    #if !defined(__sgi)  &&  !defined(__sunos)  &&  !defined(__solaris)  &&  !defined(__sun)
+        #warning "No usable lrint() and lrintf() functions available."
+        #warning "Replacing these functions with a simple C cast."
+    #endif
+
+    static __inline__ long int lrint(double x)
+    {
+        return (long int) (x);
+    }
+
+    static __inline__ long int lrintf(float x)
+    {
+        return (long int) (x);
+    }
+
+    static __inline__ long int lfastrint(double x)
+    {
+        return (long int) (x);
+    }
+
+    static __inline__ long int lfastrintf(float x)
+    {
+        return (long int) (x);
+    }
+#endif
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/g711.h b/src/codec/spandsp/src/spandsp/g711.h
new file mode 100644 (file)
index 0000000..a2e0948
--- /dev/null
@@ -0,0 +1,325 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * g711.h - In line A-law and u-law conversion routines
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2001 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/*! \file */
+
+/*! \page g711_page A-law and mu-law handling
+Lookup tables for A-law and u-law look attractive, until you consider the impact
+on the CPU cache. If it causes a substantial area of your processor cache to get
+hit too often, cache sloshing will severely slow things down. The main reason
+these routines are slow in C, is the lack of direct access to the CPU's "find
+the first 1" instruction. A little in-line assembler fixes that, and the
+conversion routines can be faster than lookup tables, in most real world usage.
+A "find the first 1" instruction is available on most modern CPUs, and is a
+much underused feature. 
+
+If an assembly language method of bit searching is not available, these routines
+revert to a method that can be a little slow, so the cache thrashing might not
+seem so bad :(
+
+Feel free to submit patches to add fast "find the first 1" support for your own
+favourite processor.
+
+Look up tables are used for transcoding between A-law and u-law, since it is
+difficult to achieve the precise transcoding procedure laid down in the G.711
+specification by other means.
+*/
+
+#if !defined(_SPANDSP_G711_H_)
+#define _SPANDSP_G711_H_
+
+/* The usual values to use on idle channels, to emulate silence */
+/*! Idle value for A-law channels */
+#define G711_ALAW_IDLE_OCTET        0x5D
+/*! Idle value for u-law channels */
+#define G711_ULAW_IDLE_OCTET        0xFF
+
+enum
+{
+    G711_ALAW = 0,
+    G711_ULAW
+};
+
+/*!
+    G.711 state
+ */
+typedef struct g711_state_s g711_state_t;
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+/* N.B. It is tempting to use look-up tables for A-law and u-law conversion.
+ *      However, you should consider the cache footprint.
+ *
+ *      A 64K byte table for linear to x-law and a 512 byte table for x-law to
+ *      linear sound like peanuts these days, and shouldn't an array lookup be
+ *      real fast? No! When the cache sloshes as badly as this one will, a tight
+ *      calculation may be better. The messiest part is normally finding the
+ *      segment, but a little inline assembly can fix that on an i386, x86_64 and
+ *      many other modern processors.
+ */
+/*
+ * Mu-law is basically as follows:
+ *
+ *      Biased Linear Input Code        Compressed Code
+ *      ------------------------        ---------------
+ *      00000001wxyza                   000wxyz
+ *      0000001wxyzab                   001wxyz
+ *      000001wxyzabc                   010wxyz
+ *      00001wxyzabcd                   011wxyz
+ *      0001wxyzabcde                   100wxyz
+ *      001wxyzabcdef                   101wxyz
+ *      01wxyzabcdefg                   110wxyz
+ *      1wxyzabcdefgh                   111wxyz
+ *
+ * Each biased linear code has a leading 1 which identifies the segment
+ * number. The value of the segment number is equal to 7 minus the number
+ * of leading 0's. The quantization interval is directly available as the
+ * four bits wxyz.  * The trailing bits (a - h) are ignored.
+ *
+ * Ordinarily the complement of the resulting code word is used for
+ * transmission, and so the code word is complemented before it is returned.
+ *
+ * For further information see John C. Bellamy's Digital Telephony, 1982,
+ * John Wiley & Sons, pps 98-111 and 472-476.
+ */
+
+/* Enable the trap as per the MIL-STD */
+//#define G711_ULAW_ZEROTRAP
+/*! Bias for u-law encoding from linear. */
+#define G711_ULAW_BIAS      0x84
+
+/*! \brief Encode a linear sample to u-law
+    \param linear The sample to encode.
+    \return The u-law value.
+*/
+static __inline__ uint8_t linear_to_ulaw(int linear)
+{
+    uint8_t u_val;
+    int mask;
+    int seg;
+
+    /* Get the sign and the magnitude of the value. */
+    if (linear >= 0)
+    {
+        linear = G711_ULAW_BIAS + linear;
+        mask = 0xFF;
+    }
+    else
+    {
+        linear = G711_ULAW_BIAS - linear;
+        mask = 0x7F;
+    }
+
+    seg = top_bit(linear | 0xFF) - 7;
+
+    /*
+     * Combine the sign, segment, quantization bits,
+     * and complement the code word.
+     */
+    if (seg >= 8)
+        u_val = (uint8_t) (0x7F ^ mask);
+    else
+        u_val = (uint8_t) (((seg << 4) | ((linear >> (seg + 3)) & 0xF)) ^ mask);
+#if defined(G711_ULAW_ZEROTRAP)
+    /* Optional ITU trap */
+    if (u_val == 0)
+        u_val = 0x02;
+#endif
+    return  u_val;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Decode an u-law sample to a linear value.
+    \param ulaw The u-law sample to decode.
+    \return The linear value.
+*/
+static __inline__ int16_t ulaw_to_linear(uint8_t ulaw)
+{
+    int t;
+    
+    /* Complement to obtain normal u-law value. */
+    ulaw = ~ulaw;
+    /*
+     * Extract and bias the quantization bits. Then
+     * shift up by the segment number and subtract out the bias.
+     */
+    t = (((ulaw & 0x0F) << 3) + G711_ULAW_BIAS) << (((int) ulaw & 0x70) >> 4);
+    return  (int16_t) ((ulaw & 0x80)  ?  (G711_ULAW_BIAS - t)  :  (t - G711_ULAW_BIAS));
+}
+/*- End of function --------------------------------------------------------*/
+
+/*
+ * A-law is basically as follows:
+ *
+ *      Linear Input Code        Compressed Code
+ *      -----------------        ---------------
+ *      0000000wxyza             000wxyz
+ *      0000001wxyza             001wxyz
+ *      000001wxyzab             010wxyz
+ *      00001wxyzabc             011wxyz
+ *      0001wxyzabcd             100wxyz
+ *      001wxyzabcde             101wxyz
+ *      01wxyzabcdef             110wxyz
+ *      1wxyzabcdefg             111wxyz
+ *
+ * For further information see John C. Bellamy's Digital Telephony, 1982,
+ * John Wiley & Sons, pps 98-111 and 472-476.
+ */
+
+/*! The A-law alternate mark inversion mask */
+#define G711_ALAW_AMI_MASK      0x55
+
+/*! \brief Encode a linear sample to A-law
+    \param linear The sample to encode.
+    \return The A-law value.
+*/
+static __inline__ uint8_t linear_to_alaw(int linear)
+{
+    int mask;
+    int seg;
+    
+    if (linear >= 0)
+    {
+        /* Sign (bit 7) bit = 1 */
+        mask = G711_ALAW_AMI_MASK | 0x80;
+    }
+    else
+    {
+        /* Sign (bit 7) bit = 0 */
+        mask = G711_ALAW_AMI_MASK;
+        linear = -linear - 1;
+    }
+
+    /* Convert the scaled magnitude to segment number. */
+    seg = top_bit(linear | 0xFF) - 7;
+    if (seg >= 8)
+    {
+        if (linear >= 0)
+        {
+            /* Out of range. Return maximum value. */
+            return (uint8_t) (0x7F ^ mask);
+        }
+        /* We must be just a tiny step below zero */
+        return (uint8_t) (0x00 ^ mask);
+    }
+    /* Combine the sign, segment, and quantization bits. */
+    return (uint8_t) (((seg << 4) | ((linear >> ((seg)  ?  (seg + 3)  :  4)) & 0x0F)) ^ mask);
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Decode an A-law sample to a linear value.
+    \param alaw The A-law sample to decode.
+    \return The linear value.
+*/
+static __inline__ int16_t alaw_to_linear(uint8_t alaw)
+{
+    int i;
+    int seg;
+
+    alaw ^= G711_ALAW_AMI_MASK;
+    i = ((alaw & 0x0F) << 4);
+    seg = (((int) alaw & 0x70) >> 4);
+    if (seg)
+        i = (i + 0x108) << (seg - 1);
+    else
+        i += 8;
+    return (int16_t) ((alaw & 0x80)  ?  i  :  -i);
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Transcode from A-law to u-law, using the procedure defined in G.711.
+    \param alaw The A-law sample to transcode.
+    \return The best matching u-law value.
+*/
+SPAN_DECLARE(uint8_t) alaw_to_ulaw(uint8_t alaw);
+
+/*! \brief Transcode from u-law to A-law, using the procedure defined in G.711.
+    \param ulaw The u-law sample to transcode.
+    \return The best matching A-law value.
+*/
+SPAN_DECLARE(uint8_t) ulaw_to_alaw(uint8_t ulaw);
+
+/*! \brief Decode from u-law or A-law to linear.
+    \param s The G.711 context.
+    \param amp The linear audio buffer.
+    \param g711_data The G.711 data.
+    \param g711_bytes The number of G.711 samples to decode.
+    \return The number of samples of linear audio produced.
+*/
+SPAN_DECLARE(int) g711_decode(g711_state_t *s,
+                              int16_t amp[],
+                              const uint8_t g711_data[],
+                              int g711_bytes);
+
+/*! \brief Encode from linear to u-law or A-law.
+    \param s The G.711 context.
+    \param g711_data The G.711 data.
+    \param amp The linear audio buffer.
+    \param len The number of samples to encode.
+    \return The number of G.711 samples produced.
+*/
+SPAN_DECLARE(int) g711_encode(g711_state_t *s,
+                              uint8_t g711_data[],
+                              const int16_t amp[],
+                              int len);
+
+/*! \brief Transcode between u-law and A-law.
+    \param s The G.711 context.
+    \param g711_out The resulting G.711 data.
+    \param g711_in The original G.711 data.
+    \param g711_bytes The number of G.711 samples to transcode.
+    \return The number of G.711 samples produced.
+*/
+SPAN_DECLARE(int) g711_transcode(g711_state_t *s,
+                                 uint8_t g711_out[],
+                                 const uint8_t g711_in[],
+                                 int g711_bytes);
+
+/*! Initialise a G.711 encode or decode context.
+    \param s The G.711 context.
+    \param mode The G.711 mode.
+    \return A pointer to the G.711 context, or NULL for error. */
+SPAN_DECLARE(g711_state_t *) g711_init(g711_state_t *s, int mode);
+
+/*! Release a G.711 encode or decode context.
+    \param s The G.711 context.
+    \return 0 for OK. */
+SPAN_DECLARE(int) g711_release(g711_state_t *s);
+
+/*! Free a G.711 encode or decode context.
+    \param s The G.711 context.
+    \return 0 for OK. */
+SPAN_DECLARE(int) g711_free(g711_state_t *s);
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/g722.h b/src/codec/spandsp/src/spandsp/g722.h
new file mode 100644 (file)
index 0000000..1716e0a
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * g722.h - The ITU G.722 codec.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2005 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ * Based on a single channel G.722 codec which is:
+ *
+ *****    Copyright (c) CMU    1993      *****
+ * Computer Science, Speech Group
+ * Chengxiang Lu and Alex Hauptmann
+ */
+
+
+/*! \file */
+
+#if !defined(_SPANDSP_G722_H_)
+#define _SPANDSP_G722_H_
+
+/*! \page g722_page G.722 encoding and decoding
+\section g722_page_sec_1 What does it do?
+The G.722 module is a bit exact implementation of the ITU G.722 specification for all three
+specified bit rates - 64000bps, 56000bps and 48000bps. It passes the ITU tests.
+
+To allow fast and flexible interworking with narrow band telephony, the encoder and decoder
+support an option for the linear audio to be an 8k samples/second stream. In this mode the
+codec is considerably faster, and still fully compatible with wideband terminals using G.722.
+
+\section g722_page_sec_2 How does it work?
+???.
+*/
+
+enum
+{
+    G722_SAMPLE_RATE_8000 = 0x0001,
+    G722_PACKED = 0x0002
+};
+
+/*!
+    G.722 encode state
+ */
+typedef struct g722_encode_state_s g722_encode_state_t;
+
+/*!
+    G.722 decode state
+ */
+typedef struct g722_decode_state_s g722_decode_state_t;
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+/*! Initialise an G.722 encode context.
+    \param s The G.722 encode context.
+    \param rate The required bit rate for the G.722 data.
+           The valid rates are 64000, 56000 and 48000.
+    \param options
+    \return A pointer to the G.722 encode context, or NULL for error. */
+SPAN_DECLARE(g722_encode_state_t *) g722_encode_init(g722_encode_state_t *s, int rate, int options);
+
+/*! Release a G.722 encode context.
+    \param s The G.722 encode context.
+    \return 0 for OK. */
+SPAN_DECLARE(int) g722_encode_release(g722_encode_state_t *s);
+
+/*! Free a G.722 encode context.
+    \param s The G.722 encode context.
+    \return 0 for OK. */
+SPAN_DECLARE(int) g722_encode_free(g722_encode_state_t *s);
+
+/*! Encode a buffer of linear PCM data to G.722
+    \param s The G.722 context.
+    \param g722_data The G.722 data produced.
+    \param amp The audio sample buffer.
+    \param len The number of samples in the buffer.
+    \return The number of bytes of G.722 data produced. */
+SPAN_DECLARE(int) g722_encode(g722_encode_state_t *s, uint8_t g722_data[], const int16_t amp[], int len);
+
+/*! Initialise an G.722 decode context.
+    \param s The G.722 decode context.
+    \param rate The bit rate of the G.722 data.
+           The valid rates are 64000, 56000 and 48000.
+    \param options
+    \return A pointer to the G.722 decode context, or NULL for error. */
+SPAN_DECLARE(g722_decode_state_t *) g722_decode_init(g722_decode_state_t *s, int rate, int options);
+
+/*! Release a G.722 decode context.
+    \param s The G.722 decode context.
+    \return 0 for OK. */
+SPAN_DECLARE(int) g722_decode_release(g722_decode_state_t *s);
+
+/*! Free a G.722 decode context.
+    \param s The G.722 decode context.
+    \return 0 for OK. */
+SPAN_DECLARE(int) g722_decode_free(g722_decode_state_t *s);
+
+/*! Decode a buffer of G.722 data to linear PCM.
+    \param s The G.722 context.
+    \param amp The audio sample buffer.
+    \param g722_data
+    \param len
+    \return The number of samples returned. */
+SPAN_DECLARE(int) g722_decode(g722_decode_state_t *s, int16_t amp[], const uint8_t g722_data[], int len);
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
diff --git a/src/codec/spandsp/src/spandsp/g726.h b/src/codec/spandsp/src/spandsp/g726.h
new file mode 100644 (file)
index 0000000..f7c6fd6
--- /dev/null
@@ -0,0 +1,120 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * g726.h - ITU G.726 codec.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2006 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/*! \file */
+
+#if !defined(_SPANDSP_G726_H_)
+#define _SPANDSP_G726_H_
+
+/*! \page g726_page G.726 encoding and decoding
+\section g726_page_sec_1 What does it do?
+
+The G.726 module is a bit exact implementation of the full ITU G.726 specification.
+It supports:
+    - 16 kbps, 24kbps, 32kbps, and 40kbps operation.
+    - Tandem adjustment, for interworking with A-law and u-law.
+    - Annex A support, for use in environments not using A-law or u-law.
+
+It passes the ITU tests.
+
+\section g726_page_sec_2 How does it work?
+???.
+*/
+
+enum
+{
+    G726_ENCODING_LINEAR = 0,   /* Interworking with 16 bit signed linear */
+    G726_ENCODING_ULAW,         /* Interworking with u-law */
+    G726_ENCODING_ALAW          /* Interworking with A-law */
+};
+
+enum
+{
+    G726_PACKING_NONE = 0,
+    G726_PACKING_LEFT = 1,
+    G726_PACKING_RIGHT = 2
+};
+
+/*!
+    G.726 state
+ */
+typedef struct g726_state_s g726_state_t;
+
+typedef int16_t (*g726_decoder_func_t)(g726_state_t *s, uint8_t code);
+
+typedef uint8_t (*g726_encoder_func_t)(g726_state_t *s, int16_t amp);
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+/*! Initialise a G.726 encode or decode context.
+    \param s The G.726 context.
+    \param bit_rate The required bit rate for the ADPCM data.
+           The valid rates are 16000, 24000, 32000 and 40000.
+    \param ext_coding The coding used outside G.726.
+    \param packing One of the G.726_PACKING_xxx options.
+    \return A pointer to the G.726 context, or NULL for error. */
+SPAN_DECLARE(g726_state_t *) g726_init(g726_state_t *s, int bit_rate, int ext_coding, int packing);
+
+/*! Release a G.726 encode or decode context.
+    \param s The G.726 context.
+    \return 0 for OK. */
+SPAN_DECLARE(int) g726_release(g726_state_t *s);
+
+/*! Free a G.726 encode or decode context.
+    \param s The G.726 context.
+    \return 0 for OK. */
+SPAN_DECLARE(int) g726_free(g726_state_t *s);
+
+/*! Decode a buffer of G.726 ADPCM data to linear PCM, a-law or u-law.
+    \param s The G.726 context.
+    \param amp The audio sample buffer.
+    \param g726_data
+    \param g726_bytes
+    \return The number of samples returned. */
+SPAN_DECLARE(int) g726_decode(g726_state_t *s,
+                              int16_t amp[],
+                              const uint8_t g726_data[],
+                              int g726_bytes);
+
+/*! Encode a buffer of linear PCM data to G.726 ADPCM.
+    \param s The G.726 context.
+    \param g726_data The G.726 data produced.
+    \param amp The audio sample buffer.
+    \param len The number of samples in the buffer.
+    \return The number of bytes of G.726 data produced. */
+SPAN_DECLARE(int) g726_encode(g726_state_t *s,
+                              uint8_t g726_data[],
+                              const int16_t amp[],
+                              int len);
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/private/README b/src/codec/spandsp/src/spandsp/private/README
new file mode 100644 (file)
index 0000000..41a6b03
--- /dev/null
@@ -0,0 +1,3 @@
+The header files in this directory should only be used by code tightly integrating itself with the\r
+spandsp library to maximise performance. To maximise compatibility with futures revisions of spandsp,\r
+most users should avoid using these headers, or probing into the spandsp data structures in other ways.
\ No newline at end of file
diff --git a/src/codec/spandsp/src/spandsp/private/bitstream.h b/src/codec/spandsp/src/spandsp/private/bitstream.h
new file mode 100644 (file)
index 0000000..aec8d5e
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * private/bitstream.h - Bitstream composition and decomposition routines.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2006 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#if !defined(_SPANDSP_PRIVATE_BITSTREAM_H_)
+#define _SPANDSP_PRIVATE_BITSTREAM_H_
+
+/*! Bitstream handler state */
+struct bitstream_state_s
+{
+    /*! The bit stream. */
+    uint32_t bitstream;
+    /*! The residual bits in bitstream. */
+    int residue;
+    /*! TRUE if the stream is LSB first, else MSB first */
+    int lsb_first;
+};
+
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/private/g711.h b/src/codec/spandsp/src/spandsp/private/g711.h
new file mode 100644 (file)
index 0000000..5ebc171
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * private/g711.h - In line A-law and u-law conversion routines
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2001 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#if !defined(_SPANDSP_PRIVATE_G711_H_)
+#define _SPANDSP_PRIVATE_G711_H_
+
+/*!
+    G.711 state
+ */
+struct g711_state_s
+{
+    /*! One of the G.711_xxx options */
+    int mode;
+};
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/private/g722.h b/src/codec/spandsp/src/spandsp/private/g722.h
new file mode 100644 (file)
index 0000000..5cb2e0b
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * private/g722.h - The ITU G.722 codec.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2005 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ * Based on a single channel G.722 codec which is:
+ *
+ *****    Copyright (c) CMU    1993      *****
+ * Computer Science, Speech Group
+ * Chengxiang Lu and Alex Hauptmann
+ */
+
+
+/*! \file */
+
+#if !defined(_SPANDSP_PRIVATE_G722_H_)
+#define _SPANDSP_PRIVATE_G722_H_
+
+/*! The per band parameters for both encoding and decoding G.722 */
+typedef struct
+{
+    int16_t nb;
+    int16_t det;
+    int16_t s;
+    int16_t sz;
+    int16_t r;
+    int16_t p[2];
+    int16_t a[2];
+    int16_t b[6];
+    int16_t d[7];
+} g722_band_t;
+
+/*!
+    G.722 encode state
+ */
+struct g722_encode_state_s
+{
+    /*! TRUE if the operating in the special ITU test mode, with the band split filters
+             disabled. */
+    int itu_test_mode;
+    /*! TRUE if the G.722 data is packed */
+    int packed;
+    /*! TRUE if encode from 8k samples/second */
+    int eight_k;
+    /*! 6 for 48000kbps, 7 for 56000kbps, or 8 for 64000kbps. */
+    int bits_per_sample;
+
+    /*! Signal history for the QMF */
+    int16_t x[12];
+    int16_t y[12];
+    int ptr;
+
+    g722_band_t band[2];
+
+    uint32_t in_buffer;
+    int in_bits;
+    uint32_t out_buffer;
+    int out_bits;
+};
+
+/*!
+    G.722 decode state
+ */
+struct g722_decode_state_s
+{
+    /*! TRUE if the operating in the special ITU test mode, with the band split filters
+             disabled. */
+    int itu_test_mode;
+    /*! TRUE if the G.722 data is packed */
+    int packed;
+    /*! TRUE if decode to 8k samples/second */
+    int eight_k;
+    /*! 6 for 48000kbps, 7 for 56000kbps, or 8 for 64000kbps. */
+    int bits_per_sample;
+
+    /*! Signal history for the QMF */
+    int16_t x[12];
+    int16_t y[12];
+    int ptr;
+
+    g722_band_t band[2];
+    
+    uint32_t in_buffer;
+    int in_bits;
+    uint32_t out_buffer;
+    int out_bits;
+};
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/private/g726.h b/src/codec/spandsp/src/spandsp/private/g726.h
new file mode 100644 (file)
index 0000000..9d69d00
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * private/g726.h - ITU G.726 codec.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2006 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#if !defined(_SPANDSP_PRIVATE_G726_H_)
+#define _SPANDSP_PRIVATE_G726_H_
+
+/*!
+ * The following is the definition of the state structure
+ * used by the G.726 encoder and decoder to preserve their internal
+ * state between successive calls.  The meanings of the majority
+ * of the state structure fields are explained in detail in the
+ * ITU Recommendation G.726.  The field names are essentially indentical
+ * to variable names in the bit level description of the coding algorithm
+ * included in this recommendation.
+ */
+struct g726_state_s
+{
+    /*! The bit rate */
+    int rate;
+    /*! The external coding, for tandem operation */
+    int ext_coding;
+    /*! The number of bits per sample */
+    int bits_per_sample;
+    /*! One of the G.726_PACKING_xxx options */
+    int packing;
+
+    /*! Locked or steady state step size multiplier. */
+    int32_t yl;
+    /*! Unlocked or non-steady state step size multiplier. */
+    int16_t yu;
+    /*! int16_t term energy estimate. */
+    int16_t dms;
+    /*! Long term energy estimate. */
+    int16_t dml;
+    /*! Linear weighting coefficient of 'yl' and 'yu'. */
+    int16_t ap;
+    
+    /*! Coefficients of pole portion of prediction filter. */
+    int16_t a[2];
+    /*! Coefficients of zero portion of prediction filter. */
+    int16_t b[6];
+    /*! Signs of previous two samples of a partially reconstructed signal. */
+    int16_t pk[2];
+    /*! Previous 6 samples of the quantized difference signal represented in
+        an internal floating point format. */
+    int16_t dq[6];
+    /*! Previous 2 samples of the quantized difference signal represented in an
+        internal floating point format. */
+    int16_t sr[2];
+    /*! Delayed tone detect */
+    int td;
+    
+    /*! \brief The bit stream processing context. */
+    bitstream_state_t bs;
+
+    /*! \brief The current encoder function. */
+    g726_encoder_func_t enc_func;
+    /*! \brief The current decoder function. */
+    g726_decoder_func_t dec_func;
+};
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/saturated.h b/src/codec/spandsp/src/spandsp/saturated.h
new file mode 100644 (file)
index 0000000..958167b
--- /dev/null
@@ -0,0 +1,335 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * saturated.h - General saturated arithmetic routines.
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2001, 2008 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+/*! \file */
+
+#if !defined(_SPANDSP_SATURATED_H_)
+#define _SPANDSP_SATURATED_H_
+
+/*! \page saturated_page Saturated arithmetic
+
+\section saturated_page_sec_1 What does it do?
+
+
+\section saturated_page_sec_2 How does it work?
+
+*/
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+/* This is the same as saturate16(), but is here for historic reasons */
+static __inline__ int16_t saturate(int32_t amp)
+{
+    int16_t amp16;
+
+    /* Hopefully this is optimised for the common case - not clipping */
+    amp16 = (int16_t) amp;
+    if (amp == amp16)
+        return amp16;
+    if (amp > INT16_MAX)
+        return INT16_MAX;
+    return INT16_MIN;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t saturate16(int32_t amp)
+{
+    int16_t amp16;
+
+    /* Hopefully this is optimised for the common case - not clipping */
+    amp16 = (int16_t) amp;
+    if (amp == amp16)
+        return amp16;
+    if (amp > INT16_MAX)
+        return INT16_MAX;
+    return INT16_MIN;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! Saturate to 15 bits, rather than the usual 16 bits. This is often a useful function. */
+static __inline__ int16_t saturate15(int32_t amp)
+{
+    if (amp > 16383)
+        return 16383;
+    if (amp < -16384)
+        return -16384;
+    return (int16_t) amp;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ uint16_t saturateu16(int32_t amp)
+{
+    uint16_t amp16;
+
+    /* Hopefully this is optimised for the common case - not clipping */
+    amp16 = (uint16_t) amp;
+    if (amp == amp16)
+        return amp16;
+    if (amp > UINT16_MAX)
+        return UINT16_MAX;
+    return 0;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ uint8_t saturateu8(int32_t amp)
+{
+    uint8_t amp8;
+
+    /* Hopefully this is optimised for the common case - not clipping */
+    amp8 = (uint8_t) amp;
+    if (amp == amp8)
+        return amp8;
+    if (amp > UINT8_MAX)
+        return UINT8_MAX;
+    return 0;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t fsaturatef(float famp)
+{
+    if (famp > (float) INT16_MAX)
+        return INT16_MAX;
+    if (famp < (float) INT16_MIN)
+        return INT16_MIN;
+    return (int16_t) lrintf(famp);
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t fsaturate(double damp)
+{
+    if (damp > (double) INT16_MAX)
+        return INT16_MAX;
+    if (damp < (double) INT16_MIN)
+        return INT16_MIN;
+    return (int16_t) lrint(damp);
+}
+/*- End of function --------------------------------------------------------*/
+
+/* Saturate to a 16 bit integer, using the fastest float to int conversion */
+static __inline__ int16_t ffastsaturatef(float famp)
+{
+    if (famp > (float) INT16_MAX)
+        return INT16_MAX;
+    if (famp < (float) INT16_MIN)
+        return INT16_MIN;
+    return (int16_t) lfastrintf(famp);
+}
+/*- End of function --------------------------------------------------------*/
+
+/* Saturate to a 16 bit integer, using the fastest double to int conversion */
+static __inline__ int16_t ffastsaturate(double damp)
+{
+    if (damp > (double) INT16_MAX)
+        return INT16_MAX;
+    if (damp < (double) INT16_MIN)
+        return INT16_MIN;
+    return (int16_t) lfastrint(damp);
+}
+/*- End of function --------------------------------------------------------*/
+
+/* Saturate to a 16 bit integer, using the closest float to int conversion */
+static __inline__ float ffsaturatef(float famp)
+{
+    if (famp > (float) INT16_MAX)
+        return (float) INT16_MAX;
+    if (famp < (float) INT16_MIN)
+        return (float) INT16_MIN;
+    return famp;
+}
+/*- End of function --------------------------------------------------------*/
+
+/* Saturate to a 16 bit integer, using the closest double to int conversion */
+static __inline__ double ffsaturate(double famp)
+{
+    if (famp > (double) INT16_MAX)
+        return (double) INT16_MAX;
+    if (famp < (double) INT16_MIN)
+        return (double) INT16_MIN;
+    return famp;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t saturated_add16(int16_t a, int16_t b)
+{
+#if defined(__GNUC__)  &&  (defined(__i386__)  ||  defined(__x86_64__))
+    __asm__ __volatile__(
+        " addw %2,%0;\n"
+        " jno 0f;\n"
+        " movw $0x7fff,%0;\n"
+        " adcw $0,%0;\n"
+        "0:"
+        : "=r" (a)
+        : "0" (a), "ir" (b)
+        : "cc"
+    );
+    return a;
+#elif defined(__GNUC__)  &&  defined(__arm5__)
+    int16_t result;
+
+    __asm__ __volatile__(
+        " sadd16 %0,%1,%2;\n"
+        : "=r" (result)
+        : "0" (a), "ir" (b)
+    );
+    return result;
+#else
+    return saturate((int32_t) a + (int32_t) b);
+#endif
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int32_t saturated_add32(int32_t a, int32_t b)
+{
+#if defined(__GNUC__)  &&  (defined(__i386__)  ||  defined(__x86_64__))
+    __asm__ __volatile__(
+        " addl %2,%0;\n"
+        " jno 0f;\n"
+        " movl $0x7fffffff,%0;\n"
+        " adcl $0,%0;\n"
+        "0:"
+        : "=r" (a)
+        : "0" (a), "ir" (b)
+        : "cc"
+    );
+    return a;
+#elif defined(__GNUC__)  &&  defined(__arm5__)
+    int32_t result;
+
+    __asm__ __volatile__(
+        " qadd %0,%1,%2;\n"
+        : "=r" (result)
+        : "0" (a), "ir" (b)
+    );
+    return result;
+#else
+    int32_t sum;
+
+    sum = a + b;
+    if ((a ^ b) >= 0)
+    {
+        if ((sum ^ a) < 0)
+            sum = (a < 0)  ?  INT32_MIN  :  INT32_MAX;
+    }
+    return sum;
+#endif
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t saturated_sub16(int16_t a, int16_t b)
+{
+#if defined(__GNUC__)  &&  (defined(__i386__)  ||  defined(__x86_64__))
+    __asm__ __volatile__(
+        " subw %2,%0;\n"
+        " jno 0f;\n"
+        " movw $0x8000,%0;\n"
+        " sbbw $0,%0;\n"
+        "0:"
+        : "=r" (a)
+        : "0" (a), "ir" (b)
+        : "cc"
+    );
+    return a;
+#elif defined(__GNUC__)  &&  defined(__arm5__)
+    int16_t result;
+
+    __asm__ __volatile__(
+        " ssub16 %0,%1,%2;\n"
+        : "=r" (result)
+        : "0" (a), "ir" (b)
+    );
+    return result;
+#else
+    return saturate((int32_t) a - (int32_t) b);
+#endif
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int32_t saturated_sub32(int32_t a, int32_t b)
+{
+#if defined(__GNUC__)  &&  (defined(__i386__)  ||  defined(__x86_64__))
+    __asm__ __volatile__(
+        " subl %2,%0;\n"
+        " jno 0f;\n"
+        " movl $0x80000000,%0;\n"
+        " sbbl $0,%0;\n"
+        "0:"
+        : "=r" (a)
+        : "0" (a), "ir" (b)
+        : "cc"
+    );
+    return a;
+#elif defined(__GNUC__)  &&  defined(__arm5__)
+    int32_t result;
+
+    __asm__ __volatile__(
+        " qsub %0,%1,%2;\n"
+        : "=r" (result)
+        : "0" (a), "ir" (b)
+    );
+    return result;
+#else
+    int32_t diff;
+
+    diff = a - b;
+    if ((a ^ b) < 0)
+    {
+        if ((diff ^ a) & INT32_MIN)
+            diff = (a < 0L)  ?  INT32_MIN  :  INT32_MAX;
+    }
+    return diff;
+#endif
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t saturated_mul16(int16_t a, int16_t b)
+{
+    if (a == INT16_MIN  &&  b == INT16_MIN)
+        return INT16_MAX;
+    /*endif*/
+    return (int16_t) (((int32_t) a*(int32_t) b) >> 15);
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int32_t saturated_mul16_32(int16_t a, int16_t b)
+{
+    return ((int32_t) a*(int32_t) b) << 1;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int16_t saturated_abs16(int16_t a)
+{
+    return (a == INT16_MIN)  ?  INT16_MAX  :  (int16_t) abs(a);
+}
+/*- End of function --------------------------------------------------------*/
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/telephony.h b/src/codec/spandsp/src/spandsp/telephony.h
new file mode 100644 (file)
index 0000000..f6998e0
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * telephony.h - some very basic telephony definitions
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2003 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#if !defined(_SPANDSP_TELEPHONY_H_)
+#define _SPANDSP_TELEPHONY_H_
+
+#if defined(_M_IX86)  ||  defined(_M_X64)
+#if defined(LIBSPANDSP_EXPORTS)
+#define SPAN_DECLARE(type)              __declspec(dllexport) type __stdcall
+#define SPAN_DECLARE_NONSTD(type)       __declspec(dllexport) type __cdecl
+#define SPAN_DECLARE_DATA               __declspec(dllexport)
+#else
+#define SPAN_DECLARE(type)              __declspec(dllimport) type __stdcall
+#define SPAN_DECLARE_NONSTD(type)       __declspec(dllimport) type __cdecl
+#define SPAN_DECLARE_DATA               __declspec(dllimport)
+#endif
+#elif defined(SPANDSP_USE_EXPORT_CAPABILITY)  &&  (defined(__GNUC__)  ||  defined(__SUNCC__))
+#define SPAN_DECLARE(type)              __attribute__((visibility("default"))) type
+#define SPAN_DECLARE_NONSTD(type)       __attribute__((visibility("default"))) type
+#define SPAN_DECLARE_DATA               __attribute__((visibility("default")))
+#else
+#define SPAN_DECLARE(type)              /**/ type
+#define SPAN_DECLARE_NONSTD(type)       /**/ type
+#define SPAN_DECLARE_DATA               /**/
+#endif
+
+#define SAMPLE_RATE                 8000
+
+/* This is based on A-law, but u-law is only 0.03dB different */
+#define DBM0_MAX_POWER              (3.14f + 3.02f)
+#define DBM0_MAX_SINE_POWER         (3.14f)
+/* This is based on the ITU definition of dbOv in G.100.1 */
+#define DBOV_MAX_POWER              (0.0f)
+#define DBOV_MAX_SINE_POWER         (-3.02f)
+
+/*! \brief A handler for pure receive. The buffer cannot be altered. */
+typedef int (span_rx_handler_t)(void *s, const int16_t amp[], int len);
+
+/*! \brief A handler for receive, where the buffer can be altered. */
+typedef int (span_mod_handler_t)(void *s, int16_t amp[], int len);
+
+/*! \brief A handler for missing receive data fill-in. */
+typedef int (span_rx_fillin_handler_t)(void *s, int len);
+
+/*! \brief A handler for transmit, where the buffer will be filled. */
+typedef int (span_tx_handler_t)(void *s, int16_t amp[], int max_len);
+
+#define ms_to_samples(t)            ((t)*(SAMPLE_RATE/1000))
+#define us_to_samples(t)            ((t)/(1000000/SAMPLE_RATE))
+
+#if !defined(FALSE)
+#define FALSE 0
+#endif
+#if !defined(TRUE)
+#define TRUE (!FALSE)
+#endif
+
+#if defined(__cplusplus)
+/* C++ doesn't seem to have sane rounding functions/macros yet */
+#if !defined(WIN32)
+#define lrint(x) ((long int) (x))
+#define lrintf(x) ((long int) (x))
+#endif
+#endif
+
+#endif
+/*- End of file ------------------------------------------------------------*/
diff --git a/src/codec/spandsp/src/spandsp/vector_int.h b/src/codec/spandsp/src/spandsp/vector_int.h
new file mode 100644 (file)
index 0000000..c20f02a
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * SpanDSP - a series of DSP components for telephony
+ *
+ * vector_int.h
+ *
+ * Written by Steve Underwood <steveu@coppice.org>
+ *
+ * Copyright (C) 2003 Steve Underwood
+ *
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 2.1,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#if !defined(_SPANDSP_VECTOR_INT_H_)
+#define _SPANDSP_VECTOR_INT_H_
+
+#if defined(__cplusplus)
+extern "C"
+{
+#endif
+
+static __inline__ void vec_copyi(int z[], const int x[], int n)
+{
+    memcpy(z, x, n*sizeof(z[0]));
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_copyi16(int16_t z[], const int16_t x[], int n)
+{
+    memcpy(z, x, n*sizeof(z[0]));
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_copyi32(int32_t z[], const int32_t x[], int n)
+{
+    memcpy(z, x, n*sizeof(z[0]));
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_zeroi(int z[], int n)
+{
+    memset(z, 0, n*sizeof(z[0]));
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_zeroi16(int16_t z[], int n)
+{
+    memset(z, 0, n*sizeof(z[0]));
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_zeroi32(int32_t z[], int n)
+{
+    memset(z, 0, n*sizeof(z[0]));
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_seti(int z[], int x, int n)
+{
+    int i;
+    
+    for (i = 0;  i < n;  i++)
+        z[i] = x;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_seti16(int16_t z[], int16_t x, int n)
+{
+    int i;
+    
+    for (i = 0;  i < n;  i++)
+        z[i] = x;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_seti32(int32_t z[], int32_t x, int n)
+{
+    int i;
+    
+    for (i = 0;  i < n;  i++)
+        z[i] = x;
+}
+/*- End of function --------------------------------------------------------*/
+
+/*! \brief Find the dot product of two int16_t vectors.
+    \param x The first vector.
+    \param y The first vector.
+    \param n The number of elements in the vectors.
+    \return The dot product of the two vectors. */
+SPAN_DECLARE(int32_t) vec_dot_prodi16(const int16_t x[], const int16_t y[], int n);
+
+/*! \brief Find the dot product of two int16_t vectors, where the first is a circular buffer
+           with an offset for the starting position.
+    \param x The first vector.
+    \param y The first vector.
+    \param n The number of elements in the vectors.
+    \param pos The starting position in the x vector.
+    \return The dot product of the two vectors. */
+SPAN_DECLARE(int32_t) vec_circular_dot_prodi16(const int16_t x[], const int16_t y[], int n, int pos);
+
+SPAN_DECLARE(void) vec_lmsi16(const int16_t x[], int16_t y[], int n, int16_t error);
+
+SPAN_DECLARE(void) vec_circular_lmsi16(const int16_t x[], int16_t y[], int n, int pos, int16_t error);
+
+/*! \brief Find the minimum and maximum values in an int16_t vector.
+    \param x The vector to be searched.
+    \param n The number of elements in the vector.
+    \param out A two element vector. The first will receive the 
+           maximum. The second will receive the minimum. This parameter
+           may be set to NULL.
+    \return The absolute maximum value. Since the range of negative numbers
+            exceeds the range of positive one, the returned integer is longer
+            than the ones being searched. */
+SPAN_DECLARE(int32_t) vec_min_maxi16(const int16_t x[], int n, int16_t out[]);
+
+static __inline__ int vec_norm2i16(const int16_t *vec, int len)
+{
+    int i;
+    int sum;
+
+    sum = 0;
+    for (i = 0;  i < len;  i++)
+        sum += vec[i]*vec[i];
+    return sum;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ void vec_sari16(int16_t *vec, int len, int shift)
+{
+    int i;
+
+    for (i = 0;  i < len;  i++)
+        vec[i] >>= shift;
+}
+/*- End of function --------------------------------------------------------*/
+
+static __inline__ int vec_max_bitsi16(const int16_t *vec, int len)
+{
+    int i;
+    int max;
+    int v;
+    int b;
+
+    max = 0;
+    for (i = 0;  i < len;  i++)
+    {
+        v = abs(vec[i]);
+        if (v > max)
+            max = v;
+    }
+    b = 0;
+    while (max != 0)
+    {
+        b++;
+        max >>= 1;
+    }
+    return b;
+}
+/*- End of function --------------------------------------------------------*/
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif
+/*- End of file ------------------------------------------------------------*/