From 26e639e0ad49819a5c60f6f02c8545a16cb132b3 Mon Sep 17 00:00:00 2001 From: Roby Date: Fri, 27 Nov 2026 01:11:26 +0100 Subject: [PATCH] Add ambed source files --- .gitignore | 3 + README.md | 252 +++++ WinTypes.h | 154 +++ ambed.ini | 94 ++ cagc.cpp | 179 +++ cagc.h | 70 ++ cambepacket.cpp | 71 ++ cambepacket.h | 70 ++ cambeserver.cpp | 125 +++ cambeserver.h | 76 ++ cbuffer.cpp | 200 ++++ cbuffer.h | 68 ++ ccallsign.cpp | 196 ++++ ccallsign.h | 83 ++ cconfig.cpp | 336 ++++++ cconfig.h | 99 ++ ccontroller.cpp | 448 ++++++++ ccontroller.h | 99 ++ cfirfilter.cpp | 77 ++ cfirfilter.h | 51 + cfixedgain.cpp | 55 + cfixedgain.h | 45 + cftdidevicedescr.cpp | 600 ++++++++++ cftdidevicedescr.h | 97 ++ cip.cpp | 91 ++ cip.h | 59 + codec2/codebooks.cpp | 964 ++++++++++++++++ codec2/codec2.cpp | 1745 +++++++++++++++++++++++++++++ codec2/codec2.h | 100 ++ codec2/codec2_internal.h | 67 ++ codec2/defines.h | 127 +++ codec2/kiss_fft.cpp | 435 ++++++++ codec2/kiss_fft.h | 35 + codec2/lpc.cpp | 311 ++++++ codec2/lpc.h | 47 + codec2/nlp.cpp | 520 +++++++++ codec2/nlp.h | 87 ++ codec2/pack.cpp | 139 +++ codec2/qbase.cpp | 247 +++++ codec2/qbase.h | 39 + codec2/quantise.cpp | 897 +++++++++++++++ codec2/quantise.h | 68 ++ cpacket.cpp | 49 + cpacket.h | 62 ++ cpacketqueue.cpp | 60 + cpacketqueue.h | 55 + csampleblockprocessor.h | 38 + csignalprocessor.cpp | 252 +++++ csignalprocessor.h | 94 ++ cstream.cpp | 954 ++++++++++++++++ cstream.h | 142 +++ ctimepoint.cpp | 53 + ctimepoint.h | 55 + cudpsocket.cpp | 237 ++++ cudpsocket.h | 84 ++ cusb3000interface.cpp | 297 +++++ cusb3000interface.h | 80 ++ cusb3003df2etinterface.cpp | 164 +++ cusb3003df2etinterface.h | 57 + cusb3003hrinterface.cpp | 66 ++ cusb3003hrinterface.h | 55 + cusb3003interface.cpp | 324 ++++++ cusb3003interface.h | 80 ++ cusb3xxxinterface.cpp | 739 ++++++++++++ cusb3xxxinterface.h | 142 +++ cvocodecchannel.cpp | 659 +++++++++++ cvocodecchannel.h | 268 +++++ cvocodecinterface.cpp | 95 ++ cvocodecinterface.h | 76 ++ cvocodecs.cpp | 327 ++++++ cvocodecs.h | 80 ++ cvoicepacket.cpp | 71 ++ cvoicepacket.h | 68 ++ cxombeinterface.cpp | 225 ++++ cxombeinterface.h | 75 ++ ftd2xx.h | 1443 ++++++++++++++++++++++++ imbe/aux_sub.cc | 184 +++ imbe/aux_sub.h | 133 +++ imbe/basic_op.h | 85 ++ imbe/basicop2.cc | 2157 ++++++++++++++++++++++++++++++++++++ imbe/ch_decode.cc | 185 ++++ imbe/ch_decode.h | 32 + imbe/ch_encode.cc | 110 ++ imbe/ch_encode.h | 32 + imbe/dc_rmv.cc | 66 ++ imbe/dc_rmv.h | 46 + imbe/decode.cc | 112 ++ imbe/decode.h | 31 + imbe/dsp_sub.cc | 278 +++++ imbe/dsp_sub.h | 81 ++ imbe/encode.cc | 142 +++ imbe/encode.h | 33 + imbe/globals.h | 62 ++ imbe/imbe.h | 69 ++ imbe/imbe_vocoder.cc | 37 + imbe/imbe_vocoder.h | 33 + imbe/imbe_vocoder_impl.cc | 42 + imbe/imbe_vocoder_impl.h | 92 ++ imbe/math_sub.cc | 355 ++++++ imbe/math_sub.h | 130 +++ imbe/pe_lpf.cc | 74 ++ imbe/pe_lpf.h | 47 + imbe/pitch_est.cc | 350 ++++++ imbe/pitch_est.h | 29 + imbe/pitch_ref.cc | 167 +++ imbe/pitch_ref.h | 28 + imbe/qnt_sub.cc | 144 +++ imbe/qnt_sub.h | 86 ++ imbe/rand_gen.cc | 61 + imbe/rand_gen.h | 44 + imbe/sa_decode.cc | 200 ++++ imbe/sa_decode.h | 64 ++ imbe/sa_encode.cc | 296 +++++ imbe/sa_encode.h | 30 + imbe/sa_enh.cc | 202 ++++ imbe/sa_enh.h | 50 + imbe/tbls.cc | 368 ++++++ imbe/tbls.h | 99 ++ imbe/typedef.h | 74 ++ imbe/typedefs.h | 201 ++++ imbe/uv_synt.cc | 147 +++ imbe/uv_synt.h | 29 + imbe/v_synt.cc | 248 +++++ imbe/v_synt.h | 30 + imbe/v_uv_det.cc | 373 +++++++ imbe/v_uv_det.h | 28 + main.cpp | 127 +++ main.h | 191 ++++ makefile | 63 ++ run | 6 + syslog.h | 96 ++ 131 files changed, 25531 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 WinTypes.h create mode 100644 ambed.ini create mode 100644 cagc.cpp create mode 100644 cagc.h create mode 100644 cambepacket.cpp create mode 100644 cambepacket.h create mode 100644 cambeserver.cpp create mode 100644 cambeserver.h create mode 100644 cbuffer.cpp create mode 100644 cbuffer.h create mode 100644 ccallsign.cpp create mode 100644 ccallsign.h create mode 100644 cconfig.cpp create mode 100644 cconfig.h create mode 100644 ccontroller.cpp create mode 100644 ccontroller.h create mode 100644 cfirfilter.cpp create mode 100644 cfirfilter.h create mode 100644 cfixedgain.cpp create mode 100644 cfixedgain.h create mode 100644 cftdidevicedescr.cpp create mode 100644 cftdidevicedescr.h create mode 100644 cip.cpp create mode 100644 cip.h create mode 100644 codec2/codebooks.cpp create mode 100644 codec2/codec2.cpp create mode 100644 codec2/codec2.h create mode 100644 codec2/codec2_internal.h create mode 100644 codec2/defines.h create mode 100644 codec2/kiss_fft.cpp create mode 100644 codec2/kiss_fft.h create mode 100644 codec2/lpc.cpp create mode 100644 codec2/lpc.h create mode 100644 codec2/nlp.cpp create mode 100644 codec2/nlp.h create mode 100644 codec2/pack.cpp create mode 100644 codec2/qbase.cpp create mode 100644 codec2/qbase.h create mode 100644 codec2/quantise.cpp create mode 100644 codec2/quantise.h create mode 100644 cpacket.cpp create mode 100644 cpacket.h create mode 100644 cpacketqueue.cpp create mode 100644 cpacketqueue.h create mode 100644 csampleblockprocessor.h create mode 100644 csignalprocessor.cpp create mode 100644 csignalprocessor.h create mode 100644 cstream.cpp create mode 100644 cstream.h create mode 100644 ctimepoint.cpp create mode 100644 ctimepoint.h create mode 100644 cudpsocket.cpp create mode 100644 cudpsocket.h create mode 100644 cusb3000interface.cpp create mode 100644 cusb3000interface.h create mode 100644 cusb3003df2etinterface.cpp create mode 100644 cusb3003df2etinterface.h create mode 100644 cusb3003hrinterface.cpp create mode 100644 cusb3003hrinterface.h create mode 100644 cusb3003interface.cpp create mode 100644 cusb3003interface.h create mode 100644 cusb3xxxinterface.cpp create mode 100644 cusb3xxxinterface.h create mode 100644 cvocodecchannel.cpp create mode 100644 cvocodecchannel.h create mode 100644 cvocodecinterface.cpp create mode 100644 cvocodecinterface.h create mode 100644 cvocodecs.cpp create mode 100644 cvocodecs.h create mode 100644 cvoicepacket.cpp create mode 100644 cvoicepacket.h create mode 100644 cxombeinterface.cpp create mode 100644 cxombeinterface.h create mode 100644 ftd2xx.h create mode 100644 imbe/aux_sub.cc create mode 100644 imbe/aux_sub.h create mode 100644 imbe/basic_op.h create mode 100644 imbe/basicop2.cc create mode 100644 imbe/ch_decode.cc create mode 100644 imbe/ch_decode.h create mode 100644 imbe/ch_encode.cc create mode 100644 imbe/ch_encode.h create mode 100644 imbe/dc_rmv.cc create mode 100644 imbe/dc_rmv.h create mode 100644 imbe/decode.cc create mode 100644 imbe/decode.h create mode 100644 imbe/dsp_sub.cc create mode 100644 imbe/dsp_sub.h create mode 100644 imbe/encode.cc create mode 100644 imbe/encode.h create mode 100644 imbe/globals.h create mode 100644 imbe/imbe.h create mode 100644 imbe/imbe_vocoder.cc create mode 100644 imbe/imbe_vocoder.h create mode 100644 imbe/imbe_vocoder_impl.cc create mode 100644 imbe/imbe_vocoder_impl.h create mode 100644 imbe/math_sub.cc create mode 100644 imbe/math_sub.h create mode 100644 imbe/pe_lpf.cc create mode 100644 imbe/pe_lpf.h create mode 100644 imbe/pitch_est.cc create mode 100644 imbe/pitch_est.h create mode 100644 imbe/pitch_ref.cc create mode 100644 imbe/pitch_ref.h create mode 100644 imbe/qnt_sub.cc create mode 100644 imbe/qnt_sub.h create mode 100644 imbe/rand_gen.cc create mode 100644 imbe/rand_gen.h create mode 100644 imbe/sa_decode.cc create mode 100644 imbe/sa_decode.h create mode 100644 imbe/sa_encode.cc create mode 100644 imbe/sa_encode.h create mode 100644 imbe/sa_enh.cc create mode 100644 imbe/sa_enh.h create mode 100644 imbe/tbls.cc create mode 100644 imbe/tbls.h create mode 100644 imbe/typedef.h create mode 100644 imbe/typedefs.h create mode 100644 imbe/uv_synt.cc create mode 100644 imbe/uv_synt.h create mode 100644 imbe/v_synt.cc create mode 100644 imbe/v_synt.h create mode 100644 imbe/v_uv_det.cc create mode 100644 imbe/v_uv_det.h create mode 100644 main.cpp create mode 100644 main.h create mode 100644 makefile create mode 100644 run create mode 100644 syslog.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..06b97d1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.o +ambed +xombe/build/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb2a311 --- /dev/null +++ b/README.md @@ -0,0 +1,252 @@ +# AMBEd + +AMBEd is the transcoder daemon for XLXd. It converts voice between the digital +modes on a reflector, using DVSI hardware for AMBE and software vocoders for +Codec2 and IMBE. It also evens out levels, so stations sound alike whichever +mode they use. + +Version 1.5.0 + +## Codecs + +| Codec | Modes | Vocoder | +|---|---|---| +| AMBE+ | D-Star | DVSI hardware | +| AMBE2+ | DMR, YSF, NXDN | DVSI hardware | +| Codec2 3200 bps | M17 | Software | +| IMBE | P25 | Software | + +DMR, YSF and NXDN share a codec, so voice between them isn't transcoded and +AMBEd sees all three as DMR. + +## Transcoding paths + +| From | To | How | +|---|---|---| +| D-Star | DMR/YSF/NXDN | Hardware decode, hardware encode | +| DMR/YSF/NXDN | D-Star | Hardware decode, hardware encode | +| D-Star, DMR/YSF/NXDN | M17, P25 | Hardware decode, software encode | +| M17 | D-Star, DMR/YSF/NXDN | Software decode, hardware encode | +| M17 | P25 | Software decode, software encode | +| P25 | D-Star, DMR/YSF/NXDN | Software decode, hardware encode | +| P25 | M17 | Software decode, software encode | + +An M17 or P25 input uses 2 hardware channels, one for each AMBE encoder. + +## Hardware + +- DF2ET's [AMBE3003USB](https://github.com/phl0/AMBE3003USB) +- LX3JL's [USB-3006](https://github.com/lx3jl/usb-3006) +- DVSI USB-3000, USB-3003 and USB-3012 +- NWDR ThumbDV and ThumbDV-3 +- DVMEGA AMBE3000 and AMBE3003 + +| Device | Hardware channels | Transcoding channels | Software vocoders (IMBE and Codec2) | +|---|---|---|---| +| 3000 (pair) | 2 | 2 | 1 each | +| 3003 (single) | 3 | 2 | 1 each | +| 3003 (pair) | 6 | 6 | 3 each | +| 3003 + 3000 (pair) | 4 | 4 | 2 each | +| 3006 | 6 | 6 | 3 each | +| 3012 | 12 | 12 | 6 each | + +- USB-3000 devices must be used in pairs, or paired with a USB-3003. +- Several devices can be used at once. +- Avoid USB hubs, they can be unreliable. +- The maximum number of concurrent streams is worked out from the hardware. + +## Installation + +1. Install the FTDI D2XX drivers from the FTDI website and follow their + instructions. Tested on 1.4.6. + +2. Install the build tools: + + ```bash + apt-get install build-essential + ``` + +3. Build and install: + + ```bash + git clone https://github.com/LX3JL/xlxd.git + cd xlxd/ambed + make clean + make + make install + ``` + + This installs to `/ambed`. `ambed.ini` is only copied if there isn't one + already, so your tuning is kept. + +Always run `make clean` first after updating. The makefile doesn't track +header changes, so a plain `make` can link old and new code together. + +## Running + +``` +ambed [ambed.ini] +``` + +Everything is set in `ambed.ini`. Set `LISTEN_IP` first: `127.0.0.1` if xlxd is on +the same machine, otherwise the machine's own address. Without the file AMBEd +uses the defaults in `main.h` and listens on `127.0.0.1`. + +AMBEd must run as root because of the FTDI driver, and the kernel's own FTDI +driver, the `ftdi_sio` module, must be unloaded so it doesn't claim the +dongles. Plug in at least one device first. + +To run it as a service, copy `../scripts/ambed.service` to +`/etc/systemd/system/`: + +```ini +[Unit] +Description=AMBE Transcoder Daemon +Wants=network-online.target +After=network-online.target + +[Service] +Type=simple +User=root +Group=root +# free the dongles from the kernel's FTDI serial driver, so the FTDI D2XX +# driver can claim them +ExecStartPre=-/sbin/rmmod ftdi_sio +ExecStart=/ambed/ambed /ambed/ambed.ini +Restart=on-abnormal +RestartSec=5 + +[Install] +WantedBy=multi-user.target +``` + +Then enable and start it: + +```bash +systemctl daemon-reload +systemctl enable --now ambed +``` + +Or start it by hand with `/ambed/run`. + +At startup AMBEd finds and configures every device, then reports: + +``` +Starting AMBEd 1.5.0 +Codec interfaces initialized successfully : 6 channels available +Software vocoders : 3 IMBE (P25), 3 Codec2 (M17) +Max concurrent streams: 3 (from 6 vocoder channels) +AMBEd started and listening on 127.0.0.1:10100 +Voice packets marked as DSCP 46 +``` + +## Audio processing + +Every path runs through the same chain: + +``` +decode -> _TO_PCM -> bandpass filter -> AGC -> PCM_TO_ -> encode +``` + +- **`_TO_PCM`** corrects what each mode's decoder does to the level, so + every mode reaches the AGC at about the same level. +- **Bandpass filter** keeps 300-3400 Hz. +- **AGC** corrects what each station does to the level: mic gain, radio and + voice. +- **`PCM_TO_`** sets the level for each encoder. + +### AGC + +The AGC works like the one on an HF receiver: fast down, hold through gaps, then +up, faster the further a station is below the target. + +- It follows the speech peaks, the loud parts of words, so it levels the speaker + and leaves the shape of the speech alone for the vocoders. +- Pauses and noise below `AGC_GATE` leave the gain where it is. +- Each stream starts at 0 dB, so very short transmissions aren't fully levelled. +- A peak limiter leaves room for the highest `PCM_TO_`, so a boost can't + clip an encoder. + +## Tuning + +`ambed.ini` overrides the defaults in `main.h` without a rebuild. AMBEd checks it +every 3 minutes. Most changes apply from the next stream, so a transmission +already running keeps its levels, and DSCP changes apply at once. +`LISTEN_IP` and `LISTEN_PORT` need a restart. A setting left out uses its default. +A bad value is logged and ignored, and the value in use stays. + +| Setting | Default | Meaning | +|---|---|---| +| `LISTEN_IP` | 127.0.0.1 | IP to bind to | +| `LISTEN_PORT` | 10100 | UDP port, xlxd's `TRANSCODER_PORT` must match | +| `DSCP_MARKING_ENABLE` | 1 | Mark voice packets for QoS | +| `DSCP_VALUE` | 46 | DSCP value, 0-63, 46 is EF | +| `STREAM_ACTIVITY_TIMEOUT` | 3 s | Close a stream after this long with no packets | +| `TUNING_LOG` | 1 | Log levels when a stream closes | +| `DSTAR_TO_PCM` | -10 dB | D-Star decode gain | +| `DMR_TO_PCM` | -1.5 dB | DMR, YSF and NXDN decode gain | +| `M17_TO_PCM` | -10.75 dB | M17 decode gain | +| `P25_TO_PCM` | -3.75 dB | P25 decode gain | +| `PCM_TO_DSTAR` | +11.5 dB | D-Star encode gain | +| `PCM_TO_DMR` | 0 dB | DMR, YSF and NXDN encode gain | +| `PCM_TO_M17` | +5.25 dB | M17 encode gain | +| `PCM_TO_P25` | +0.75 dB | P25 encode gain | +| `USE_AGC` | 1 | AGC on or off | +| `AGC_TARGET` | -41 dBFS | Speech peak level to aim for | +| `AGC_CLAMPING` | 9 dB | Most the gain can move either way, 0 leaves the audio alone | +| `AGC_ATTACK` | 150 ms | How fast the gain comes down | +| `AGC_HANG` | 1000 ms | How long the gain holds before it can rise | +| `AGC_RECOVERY` | 2 | How fast the gain rises, dB/s for each dB below the target | +| `AGC_RECOVERY_MIN` | 3 dB/s | Slowest rise | +| `AGC_RECOVERY_MAX` | 20 dB/s | Fastest rise | +| `AGC_GATE` | -60 dBFS | Frames quieter than this don't move the gain | +| `USE_BANDPASSFILTER` | 1 | Bandpass filter on or off | + +### Tuning log + +When a stream closes, AMBEd logs the voice level at each stage. Pauses aren't +counted, and a level is the mean absolute sample value. Set `TUNING_LOG=0` to +turn this off. + +``` +Tuning: stream 1 XLX672 M17 input, 440 voice frames of 540 +Tuning: decoded level -30.5 dBFS peak -8.9 dBFS clipped 0.00% +Tuning: M17_TO_PCM -10.75 level -45.6 dBFS peak -19.9 dBFS clipped 0.00% +Tuning: AGC target -41.0 dBFS speech peaks -43.6 dBFS gain average -3.7 dB, -4.5 to +0.4 dB at limit 0.0% high 0.0% low limiter 0.00% +Tuning: after AGC level -49.3 dBFS peak -23.7 dBFS clipped 0.00% +Tuning: PCM_TO_DSTAR +11.50 level -37.8 dBFS peak -12.2 dBFS clipped 0.00% +Tuning: PCM_TO_DMR +0.00 level -49.3 dBFS peak -23.7 dBFS clipped 0.00% +Tuning: PCM_TO_P25 +0.75 level -48.5 dBFS peak -22.9 dBFS clipped 0.00% +``` + +The callsign shown is the reflector's, as AMBEd isn't told who is talking. + +### How to tune + +For a step-by-step guide covering AMBEd and XLXd's gains together, see the +[Audio Tuning Guide](../AUDIO-TUNING.md). In short: + +1. Look at several stations on each mode, not just your own radio. +2. Set each `_TO_PCM` so typical stations on that mode average near 0 dB + of AGC gain. +3. If most modes sit high or low, move `AGC_TARGET`. +4. A station at one limit for most of a stream is too far off for the AGC to + correct. +5. Use `PCM_TO_` to match how each mode sounds on air, and back one off if + it shows clipping. + +To see levels without changing the audio, set `AGC_CLAMPING=0`. Speech peaks are +still logged. + +## Build-time options + +These are in `main.h`: + +| Setting | Default | Meaning | +|---|---|---| +| `CONFIG_RELOAD_PERIOD` | 180 s | How often `ambed.ini` is checked | + +## License + +Created by Jean-Luc Deltombe (LX3JL). AMBEd is part of xlxd, free software under +the GNU General Public License v3 or later. diff --git a/WinTypes.h b/WinTypes.h new file mode 100644 index 0000000..88e500e --- /dev/null +++ b/WinTypes.h @@ -0,0 +1,154 @@ +#ifndef __WINDOWS_TYPES__ +#define __WINDOWS_TYPES__ + +#define WINAPI + +typedef unsigned int DWORD; +typedef unsigned int ULONG; +typedef unsigned short USHORT; +typedef unsigned short SHORT; +typedef unsigned char UCHAR; +typedef unsigned short WORD; +typedef unsigned short WCHAR; +typedef unsigned char BYTE; +typedef BYTE *LPBYTE; +typedef unsigned int BOOL; +typedef unsigned char BOOLEAN; +typedef unsigned char CHAR; +typedef BOOL *LPBOOL; +typedef UCHAR *PUCHAR; +typedef const char *LPCSTR; +typedef char *PCHAR; +typedef void *PVOID; +typedef void *HANDLE; +typedef unsigned int LONG; +typedef int INT; +typedef unsigned int UINT; +typedef char *LPSTR; +typedef char *LPTSTR; +typedef const char *LPCTSTR; +typedef DWORD *LPDWORD; +typedef WORD *LPWORD; +typedef ULONG *PULONG; +typedef LONG *LPLONG; +typedef PVOID LPVOID; +typedef void VOID; +typedef USHORT *PUSHORT; +typedef unsigned long long int ULONGLONG; + +typedef struct _OVERLAPPED { + DWORD Internal; + DWORD InternalHigh; + union { + struct{ + DWORD Offset; + DWORD OffsetHigh; + }; + PVOID Pointer; + }; + HANDLE hEvent; +} OVERLAPPED, *LPOVERLAPPED; + +typedef struct _SECURITY_ATTRIBUTES { + DWORD nLength; + LPVOID lpSecurityDescriptor; + BOOL bInheritHandle; +} SECURITY_ATTRIBUTES , *LPSECURITY_ATTRIBUTES; + +#include +// Substitute for HANDLE returned by Windows CreateEvent API. +// FT_SetEventNotification expects parameter 3 to be the address +// of one of these structures. +typedef struct _EVENT_HANDLE +{ + pthread_cond_t eCondVar; + pthread_mutex_t eMutex; + int iVar; +} EVENT_HANDLE; + +typedef struct timeval SYSTEMTIME; +typedef struct timeval FILETIME; + +// WaitForSingleObject return values. +#define WAIT_ABANDONED 0x00000080L +#define WAIT_OBJECT_0 0x00000000L +#define WAIT_TIMEOUT 0x00000102L +#define WAIT_FAILED 0xFFFFFFFF +// Special value for WaitForSingleObject dwMilliseconds parameter +#define INFINITE 0xFFFFFFFF // Infinite timeout + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif +#ifndef CONST +#define CONST const +#endif +// +// Modem Status Flags +// +#define MS_CTS_ON ((DWORD)0x0010) +#define MS_DSR_ON ((DWORD)0x0020) +#define MS_RING_ON ((DWORD)0x0040) +#define MS_RLSD_ON ((DWORD)0x0080) + +// +// Error Flags +// +#define CE_RXOVER 0x0001 // Receive Queue overflow +#define CE_OVERRUN 0x0002 // Receive Overrun Error +#define CE_RXPARITY 0x0004 // Receive Parity Error +#define CE_FRAME 0x0008 // Receive Framing error +#define CE_BREAK 0x0010 // Break Detected +#define CE_TXFULL 0x0100 // TX Queue is full +#define CE_PTO 0x0200 // LPTx Timeout +#define CE_IOE 0x0400 // LPTx I/O Error +#define CE_DNS 0x0800 // LPTx Device not selected +#define CE_OOP 0x1000 // LPTx Out-Of-Paper +#define CE_MODE 0x8000 // Requested mode unsupported + +// +// Events +// +#define EV_RXCHAR 0x0001 // Any Character received +#define EV_RXFLAG 0x0002 // Received certain character +#define EV_TXEMPTY 0x0004 // Transmit Queue Empty +#define EV_CTS 0x0008 // CTS changed state +#define EV_DSR 0x0010 // DSR changed state +#define EV_RLSD 0x0020 // RLSD changed state +#define EV_BREAK 0x0040 // BREAK received +#define EV_ERR 0x0080 // Line status error occurred +#define EV_RING 0x0100 // Ring signal detected +#define EV_PERR 0x0200 // Printer error occured +#define EV_RX80FULL 0x0400 // Receive buffer is 80 percent full +#define EV_EVENT1 0x0800 // Provider specific event 1 +#define EV_EVENT2 0x1000 // Provider specific event 2 + +// +// Escape Functions +// +#define SETXOFF 1 // Simulate XOFF received +#define SETXON 2 // Simulate XON received +#define SETRTS 3 // Set RTS high +#define CLRRTS 4 // Set RTS low +#define SETDTR 5 // Set DTR high +#define CLRDTR 6 // Set DTR low +#define RESETDEV 7 // Reset device if possible +#define SETBREAK 8 // Set the device break line. +#define CLRBREAK 9 // Clear the device break line. + +// +// PURGE function flags. +// +#define PURGE_TXABORT 0x0001 // Kill the pending/current writes to the comm port. +#define PURGE_RXABORT 0x0002 // Kill the pending/current reads to the comm port. +#define PURGE_TXCLEAR 0x0004 // Kill the transmit queue if there. +#define PURGE_RXCLEAR 0x0008 // Kill the typeahead buffer if there. + +#ifndef INVALID_HANDLE_VALUE +#define INVALID_HANDLE_VALUE 0xFFFFFFFF +#endif + +#endif /* __WINDOWS_TYPES__ */ diff --git a/ambed.ini b/ambed.ini new file mode 100644 index 0000000..a2ff60d --- /dev/null +++ b/ambed.ini @@ -0,0 +1,94 @@ +# ambed.ini - AMBEd settings +# +# Usage: ambed /ambed/ambed.ini +# Reloaded: every 3 minutes, most settings apply from the next stream +# Left out: uses the default in main.h +# Bad value: logged and ignored +# +# Audio path: +# decode -> _TO_PCM -> bandpass filter -> AGC -> PCM_TO_ -> encode +# +# DMR covers YSF and NXDN too, they share a codec. + +[Network] +# IP to bind to, 127.0.0.1 if xlxd is on this machine. Needs a restart. +LISTEN_IP=127.0.0.1 + +# UDP port, 1 to 65000. xlxd's TRANSCODER_PORT must match. Needs a restart. +LISTEN_PORT=10100 + +# Mark voice packets for QoS: 1 or 0 +DSCP_MARKING_ENABLE=1 + +# DSCP value, 0 to 63. 46 is EF, highest priority voice +DSCP_VALUE=46 + +# Close a stream after this long with no packets, seconds, 1 to 60 +STREAM_ACTIVITY_TIMEOUT=3 + +[Logging] +# Log levels when a stream closes: 1 or 0 +TUNING_LOG=1 + +[Gain] +# Decode gains, in dB, -40 to +40. Bring every mode to the same level. +DSTAR_TO_PCM=-10 +DMR_TO_PCM=-1.5 +M17_TO_PCM=-10.75 +P25_TO_PCM=-3.75 + +# Encode gains, in dB, -40 to +40. Set each mode's level on air. +PCM_TO_DSTAR=11.5 +PCM_TO_DMR=0 +PCM_TO_M17=5.25 +PCM_TO_P25=0.75 + +[AGC] +# ------------------------------------------------------------------------ +# Automatic gain control +# +# Evens out stations: a quiet radio comes up, a loud one comes down. +# It levels the speaker, not the syllable, so it should drift, never pump. +# Works like an HF receiver: fast down, hold through gaps, then up. +# Pauses and noise leave the gain alone. +# ------------------------------------------------------------------------ + +# AGC on or off: 1 or 0 +USE_AGC=1 + +# Speech peak level to aim for, dBFS, -60 to -3 +AGC_TARGET=-41 + +# Most the gain can move either way, dB, 0 to 20 +# 0 leaves the audio alone and still logs speech peaks +AGC_CLAMPING=9 + +# How fast the gain comes down, ms, 10 to 2000 +AGC_ATTACK=150 + +# How long the gain holds before it can rise, ms, 0 to 10000 +AGC_HANG=1000 + +# How fast the gain rises, dB/s per dB below target, 0.1 to 10 +# Far off comes up quickly, close eases in +AGC_RECOVERY=2 + +# Slowest rise, dB/s, 0.5 to 50 +AGC_RECOVERY_MIN=3 + +# Fastest rise, dB/s, 0.5 to 100 +AGC_RECOVERY_MAX=20 + +# Frames quieter than this don't move the gain, dBFS, -80 to -20 +# Keep it above background noise +AGC_GATE=-60 + +[Filter] +# 300-3400 Hz bandpass on or off: 1 or 0 +USE_BANDPASSFILTER=1 + +[Xombe] +# 0 = auto (CPU cores, 2..8), or 1..16. Needs a restart. +XOMBE_THREADS=4 +# Bidirectional channel pairs per thread, 1..16. Needs a restart. +XOMBE_PAIRS_PER_THREAD=6 diff --git a/cagc.cpp b/cagc.cpp new file mode 100644 index 0000000..4962326 --- /dev/null +++ b/cagc.cpp @@ -0,0 +1,179 @@ +// +// cagc.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// AGC with hang, replaces the sample by sample loop by Geoffrey Merck +// F4FXL / KC3FRA that was inspired by Liquid DSP +// +// Works like the AGC on an HF receiver: fast down, hold through gaps, then up. +// The further a station is below the target the faster the gain rises, easing +// off as it gets close. +// It follows the peaks of the speech over tens of ms, so the gain moves between +// syllables and the shape of the speech and pitch is left alone for the +// vocoders. Silence doesn't count, so pauses leave the gain where it is. + +#include +#include "cagc.h" +#include "main.h" + +// Speech peak envelope, falling share per 20 ms frame: about 50 ms +#define AGC_PEAK_DECAY 0.33f +// Voice frames at the start of a stream before the gain may rise +#define AGC_START_HANG 5 +// Recent peak fall per 20 ms frame: 12 dB/s +#define AGC_RECENT_DECAY 0.973f +// Peaks within this of the target still hold the gain, in dB, so ordinary +// softer words don't lift it +#define AGC_HANG_MARGIN 1.5f +// A station this far below the target doesn't wait for the hang, in dB +#define AGC_NO_HANG_ERROR 6.0f +// Limiter recovery: 6 dB in 100 ms at 8 kHz +#define AGC_LIMITER_RECOVERY 1.000867f + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CAGC::CAGC(float targetdB, float clampingdB, float attackMs, float hangMs, + float recovery, float recoveryMin, float recoveryMax, float gatedB, float limitdB) +{ + m_Enabled = (clampingdB > 0.0f); + m_TargetdB = targetdB; + m_ClampingdB = clampingdB; + m_AttackCoef = 1.0f - exp(-20.0f / attackMs); + m_HangFrames = (int)(hangMs / 20.0f); + m_Recovery = recovery * 0.02f; + m_RecoveryMin = recoveryMin * 0.02f; + m_RecoveryMax = recoveryMax * 0.02f; + m_GateLevel = 32768.0f * pow(10.0f, gatedB/20.0f); + m_LimitLevel = 32768.0f * pow(10.0f, limitdB/20.0f); + + m_SpeechPeak = 0.0f; + m_RecentPeak = 0.0f; + m_bVoice = false; + m_HangLeft = AGC_START_HANG; + + m_GaindB = 0.0f; + m_Gain = 1.0f; + m_Limiter = 1.0f; + m_LimitedSamples = 0; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// get + +float CAGC::GetGain() +{ + return m_GaindB; +} + +float CAGC::GetSpeechPeak() +{ + return (m_SpeechPeak > 0.0f) ? 20.0f * log10(m_SpeechPeak / 32768.0f) : -96.0f; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// process + +void CAGC::ProcessSampleBlock(uint8* voice, int length) +{ + int samples = length / 2; + if(samples == 0) + { + return; + } + + float sum = 0.0f; + for(int i = 0; i < length; i += 2) + { + sum += fabs((float)(short)MAKEWORD(voice[i+1], voice[i])); + } + float level = sum / samples; + + // follow the speech peaks, measured even with the gain off for tuning + m_bVoice = (level >= m_GateLevel); + if(m_bVoice) + { + m_SpeechPeak = MAX(level, m_SpeechPeak + (level - m_SpeechPeak) * AGC_PEAK_DECAY); + m_RecentPeak = MAX(m_SpeechPeak, m_RecentPeak * AGC_RECENT_DECAY); + } + + if(!m_Enabled) + { + return; + } + + // only voice moves the gain + if(m_bVoice) + { + float wanted = m_TargetdB - 20.0f * log10(m_RecentPeak / 32768.0f); + wanted = MAX(-m_ClampingdB, MIN(m_ClampingdB, wanted)); + float error = wanted - m_GaindB; + + if(error < 0.0f) + { + m_GaindB += error * m_AttackCoef; + m_HangLeft = MAX(m_HangLeft, m_HangFrames); + } + else if(error < AGC_HANG_MARGIN) + { + m_HangLeft = m_HangFrames; + } + else if(m_HangLeft > 0 && error < AGC_NO_HANG_ERROR) + { + m_HangLeft--; + } + else + { + // quick when far off, easing in as it gets close + float step = MAX(m_RecoveryMin, MIN(m_RecoveryMax, error * m_Recovery)); + m_GaindB = MIN(wanted, m_GaindB + step); + } + } + + // ramp across the frame so a gain change can't click + float gain = m_Gain; + float newGain = pow(10.0f, m_GaindB/20.0f); + float ramp = (newGain - gain) / samples; + + for(int i = 0; i < length; i += 2) + { + gain += ramp; + float output = (float)(short)MAKEWORD(voice[i+1], voice[i]) * gain * m_Limiter; + + // the limiter pulls a peak down at once and recovers slowly + if(fabs(output) > m_LimitLevel) + { + float reduction = m_LimitLevel / fabs(output); + m_Limiter *= reduction; + output *= reduction; + m_LimitedSamples++; + } + m_Limiter = MIN(1.0f, m_Limiter * AGC_LIMITER_RECOVERY); + + //write processed sample back, clamp to short range + if (output > 32767.0f) output = 32767.0f; + else if (output < -32768.0f) output = -32768.0f; + voice[i] = HIBYTE((short)output); + voice[i+1] = LOBYTE((short)output); + } + m_Gain = newGain; +} diff --git a/cagc.h b/cagc.h new file mode 100644 index 0000000..a5c89ad --- /dev/null +++ b/cagc.h @@ -0,0 +1,70 @@ +// +// cagc.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 26/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// AGC with hang, replaces the sample by sample loop by Geoffrey Merck +// F4FXL / KC3FRA that was inspired by Liquid DSP + +#ifndef cagc_h +#define cagc_h + +#include "csampleblockprocessor.h" + +class CAGC : CSampleBlockProcessor +{ +public: + //Constructor, levels in dBFS and gains in dB, attack and hang in ms, + //recovery in dB/s for each dB below the target, between recoveryMin and recoveryMax in dB/s + CAGC(float targetdB, float clampingdB, float attackMs, float hangMs, + float recovery, float recoveryMin, float recoveryMax, float gatedB, float limitdB); + + //methods + void ProcessSampleBlock(uint8* voice, int length); + float GetGain();//gets current gain in dB + float GetSpeechPeak();//gets the speech peak level in, in dBFS + bool IsVoice() { return m_bVoice; }//did the last frame pass the gate + long GetLimitedSamples() { return m_LimitedSamples; } + +private: + bool m_Enabled; // a clamping of 0 measures but leaves the audio alone + float m_TargetdB; // speech peak level to aim for + float m_ClampingdB; + float m_AttackCoef; // share of the way down per frame + int m_HangFrames; + float m_Recovery; // dB per frame, for each dB below the target + float m_RecoveryMin; // dB per frame + float m_RecoveryMax; // dB per frame + float m_GateLevel; // quieter frames aren't voice and leave the gain alone + float m_LimitLevel; // no sample goes above this + + float m_SpeechPeak; // envelope of the frame levels + float m_RecentPeak; // the same, falling slowly so a word's tail isn't a quiet station + bool m_bVoice; + int m_HangLeft; // frames until the gain may rise + + float m_GaindB; // current gain + float m_Gain; // the same, linear + float m_Limiter; // peak limiter gain, 1.0 when idle + long m_LimitedSamples; +}; + +#endif /* cagc_h */ diff --git a/cambepacket.cpp b/cambepacket.cpp new file mode 100644 index 0000000..e5fe175 --- /dev/null +++ b/cambepacket.cpp @@ -0,0 +1,71 @@ +// +// cambepacket.cpp +// ambed +// +// cpacketqueue.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "cambepacket.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CAmbePacket::CAmbePacket() +{ + m_uiCodec = CODEC_NONE; + ::memset(m_uiAmbe, 0, AMBE_SIZE); +} + +CAmbePacket::CAmbePacket(uint8 uiPid, uint8 uiCodec, const uint8 *Ambe) + : CPacket(uiPid) +{ + m_uiCodec = uiCodec; + ::memcpy(m_uiAmbe, Ambe, AMBE_SIZE); +} + +CAmbePacket::CAmbePacket(const CAmbePacket &packet) + : CPacket(packet) +{ + m_uiCodec = packet.m_uiCodec; + ::memcpy(m_uiAmbe, packet.m_uiAmbe, sizeof(m_uiAmbe)); +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CAmbePacket::~CAmbePacket() +{ +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Set + +void CAmbePacket::SetAmbe(const uint8 *p) +{ + ::memcpy(m_uiAmbe, p, AMBE_SIZE); +} + diff --git a/cambepacket.h b/cambepacket.h new file mode 100644 index 0000000..f6ae00a --- /dev/null +++ b/cambepacket.h @@ -0,0 +1,70 @@ +// +// cambepacket.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cambepacket_h +#define cambepacket_h + +#include "cpacket.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + + +// frame sizes +#define AMBE_SIZE 9 + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CAmbePacket : public CPacket +{ +public: + // constructors + CAmbePacket(); + CAmbePacket(uint8, uint8, const uint8 *); + CAmbePacket(const CAmbePacket &); + + // destructor + virtual ~CAmbePacket(); + + // identity + bool IsAmbe(void) const { return true; } + + // get + uint8 GetCodec(void) const { return m_uiCodec; } + uint8 *GetAmbe(void) { return m_uiAmbe; } + int GetAmbeSize(void) const { return AMBE_SIZE; } + + // set + void SetCodec(uint8 c) { m_uiCodec = c; } + void SetAmbe(const uint8 *); + +protected: + // data + uint8 m_uiCodec; + uint8 m_uiAmbe[AMBE_SIZE]; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cambepacket_h */ diff --git a/cambeserver.cpp b/cambeserver.cpp new file mode 100644 index 0000000..9ce1da2 --- /dev/null +++ b/cambeserver.cpp @@ -0,0 +1,125 @@ +// +// cambeserver.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 15/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "ctimepoint.h" +#include "ccontroller.h" +#include "cvocodecs.h" +#include "cambeserver.h" + +//////////////////////////////////////////////////////////////////////////////////////// + +CAmbeServer g_AmbeServer; + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CAmbeServer::CAmbeServer() +{ + m_bStopThreads = false; + m_pThread = NULL; +#ifdef DEBUG_DUMPFILE + m_DebugFile.open("/Users/jeanluc/Desktop/ambed.txt"); +#endif +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CAmbeServer::~CAmbeServer() +{ + m_bStopThreads = true; + if ( m_pThread != NULL ) + { + m_pThread->join(); + delete m_pThread; + } +#ifdef DEBUG_DUMPFILE + m_DebugFile.close(); +#endif +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operation + +bool CAmbeServer::Start(void) +{ + bool ok = true; + + // init interfaces & controller + std::cout << "Initializing vocodecs:" << std::endl; + ok &= g_Vocodecs.Init(); + std::cout << std::endl; + std::cout << "Initializing controller" << std::endl; + ok &= m_Controller.Init(); + std::cout << std::endl; + + // if ok, start threads + if ( ok ) + { + // + m_pThread = new std::thread(CAmbeServer::Thread, this); + } + + // done + return ok; +} + +void CAmbeServer::Stop(void) +{ + // stop controller + m_Controller.Close(); + + // stop & delete all threads + m_bStopThreads = true; + + // stop & delete report threads + if ( m_pThread != NULL ) + { + m_pThread->join(); + delete m_pThread; + m_pThread = NULL; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// thread + +void CAmbeServer::Thread(CAmbeServer *This) +{ + while ( !This->m_bStopThreads ) + { + This->Task(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// task + +void CAmbeServer::Task(void) +{ + // and wait a bit + CTimePoint::TaskSleepFor(10000); +} diff --git a/cambeserver.h b/cambeserver.h new file mode 100644 index 0000000..2791b6f --- /dev/null +++ b/cambeserver.h @@ -0,0 +1,76 @@ +// +// cambeserver.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 13/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cambeserver_h +#define cambeserver_h + +#include "ccontroller.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CAmbeServer +{ +public: + // constructors + CAmbeServer(); + + // destructor + virtual ~CAmbeServer(); + + // operation + bool Start(void); + void Stop(void); + + // task + static void Thread(CAmbeServer *); + void Task(void); + + // get + const CIp &GetListenIp(void) const { return m_Controller.GetListenIp(); } + + // set + void SetListenIp(const CIp &ip) { m_Controller.SetListenIp(ip); } + + + // operator + //bool operator ==(const CIp &) const; + //operator const char *() const; + +protected: + // objects + CController m_Controller; + + // threads + std::atomic m_bStopThreads; + std::thread *m_pThread; + +public: +#ifdef DEBUG_DUMPFILE + std::ofstream m_DebugFile; +#endif +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cambeserver_h */ diff --git a/cbuffer.cpp b/cbuffer.cpp new file mode 100644 index 0000000..b8bc279 --- /dev/null +++ b/cbuffer.cpp @@ -0,0 +1,200 @@ +// +// cbuffer.cpp +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 02/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "cbuffer.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CBuffer::CBuffer(uint8 *buffer, int len) +{ + resize(len); + ::memcpy(data(), buffer, len); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// set + +void CBuffer::Set(uint8 *buffer, int len) +{ + resize(len); + ::memcpy(data(), buffer, len); +} + +void CBuffer::Set(const char *sz) +{ + resize(::strlen(sz)+1); + ::strcpy((char *)data(), sz); +} + +void CBuffer::Append(uint8 *buffer, int len) +{ + int n = (int)size(); + resize(n+len); + ::memcpy(&(data()[n]), buffer, len); +} + +void CBuffer::Append(uint8 ui, int len) +{ + int n = (int)size(); + resize(n+len); + ::memset(&(data()[n]), ui, len); +} + +void CBuffer::Append(uint8 ui) +{ + int n = (int)size(); + resize(n+sizeof(uint8)); + ::memcpy(&(data()[n]), &ui, sizeof(uint8)); +} + +void CBuffer::Append(uint16 ui) +{ + int n = (int)size(); + resize(n+sizeof(uint16)); + ::memcpy(&(data()[n]), &ui, sizeof(uint16)); +} + +void CBuffer::Append(uint32 ui) +{ + int n = (int)size(); + resize(n+sizeof(uint32)); + ::memcpy(&(data()[n]), &ui, sizeof(uint32)); +} + +void CBuffer::Append(const char *sz) +{ + Append((uint8 *)sz, (int)strlen(sz)); + Append((uint8)0x00); +} + +void CBuffer::ReplaceAt(int i, uint8 ui) +{ + if ( size() < (i+sizeof(uint8)) ) + { + resize(i+sizeof(uint8)); + } + *(uint8 *)(&(data()[i])) = ui; +} + +void CBuffer::ReplaceAt(int i, uint16 ui) +{ + if ( size() < (i+sizeof(uint16)) ) + { + resize(i+sizeof(uint16)); + } + ::memcpy(&(data()[i]), &ui, sizeof(uint16)); +} + +void CBuffer::ReplaceAt(int i, uint32 ui) +{ + if ( size() < (i+sizeof(uint32)) ) + { + resize(i+sizeof(uint32)); + } + ::memcpy(&(data()[i]), &ui, sizeof(uint32)); +} + +void CBuffer::ReplaceAt(int i, const uint8 *ptr, int len) +{ + if ( size() < (i+len) ) + { + resize(i+len); + } + ::memcpy(&(data()[i]), ptr, len); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operation + +int CBuffer::Compare(uint8 *buffer, int len) const +{ + int result = -1; + if ( size() >= len ) + { + result = ::memcmp(data(), buffer, len); + } + return result; +} + +int CBuffer::Compare(uint8 *buffer, int off, int len) const +{ + int result = -1; + if ( size() >= (off+len) ) + { + result = ::memcmp(&(data()[off]), buffer, len); + } + return result; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// operator + +bool CBuffer::operator ==(const CBuffer &Buffer) const +{ + if ( size() == Buffer.size() ) + { + return (::memcmp((const char *)data(), (const char *)Buffer.data(), size()) == 0); + } + return false; +} + +bool CBuffer::operator ==(const char *sz) const +{ + if ( size() == ::strlen(sz) ) + { + return (::memcmp((const char *)data(), sz, size()) == 0); + } + return false; +} + +CBuffer::operator const char *() const +{ + return (const char *)data(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// debug + +void CBuffer::DebugDump(std::ofstream &debugout) +{ + for ( int i = 0; i < size(); i++ ) + { + char sz[16]; + sprintf(sz, "%02X", data()[i]); + debugout << sz; + if ( i == size()-1 ) + { + debugout << std::endl; + } + else + { + debugout << ','; + } + } +} + diff --git a/cbuffer.h b/cbuffer.h new file mode 100644 index 0000000..5762a85 --- /dev/null +++ b/cbuffer.h @@ -0,0 +1,68 @@ +// +// cbuffer.h +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 02/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cbuffer_h +#define cbuffer_h + +//////////////////////////////////////////////////////////////////////////////////////// + +class CBuffer : public std::vector +{ +public: + // constructor + CBuffer() {}; + CBuffer(uint8 *, int); + + // destructor + virtual ~CBuffer() {}; + + // set + void Set(uint8 *, int); + void Set(const char *); + void Append(uint8 *, int); + void Append(uint8, int); + void Append(uint8); + void Append(uint16); + void Append(uint32); + void Append(const char *); + void ReplaceAt(int, uint8); + void ReplaceAt(int, uint16); + void ReplaceAt(int, uint32); + void ReplaceAt(int, const uint8 *, int); + + // operation + int Compare(uint8 *, int) const; + int Compare(uint8 *, int, int) const; + + // operator + bool operator ==(const CBuffer &) const; + bool operator ==(const char *) const; + operator const char *() const; + + // debug + void DebugDump(std::ofstream &); +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cbuffer_h */ diff --git a/ccallsign.cpp b/ccallsign.cpp new file mode 100644 index 0000000..4af8c12 --- /dev/null +++ b/ccallsign.cpp @@ -0,0 +1,196 @@ +// +// ccallsign.cpp +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include +#include "ccallsign.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructors + +CCallsign::CCallsign() +{ + // blank all + ::memset(m_Callsign, ' ', sizeof(m_Callsign)); +} + +CCallsign::CCallsign(const char *sz) +{ + ::memset(m_Callsign, ' ', sizeof(m_Callsign)); + ::memcpy(m_Callsign, sz, MIN(strlen(sz), sizeof(m_Callsign))); +} + +CCallsign::CCallsign(const CCallsign &callsign) +{ + ::memcpy(m_Callsign, callsign.m_Callsign, sizeof(m_Callsign)); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// status + +bool CCallsign::IsValid(void) const +{ + bool valid = true; + int i; + + // callsign + // first 3 chars are letter or number but cannot be all number + int iNum = 0; + for ( i = 0; i < 3; i++ ) + { + valid &= IsLetter(m_Callsign[i]) || IsNumber(m_Callsign[i]); + if ( IsNumber(m_Callsign[i]) ) + { + iNum++; + } + } + valid &= (iNum < 3); + // all remaining char are letter, number or space + for ( ; i < CALLSIGN_LEN; i++) + { + valid &= IsLetter(m_Callsign[i]) || IsNumber(m_Callsign[i]) || IsSpace(m_Callsign[i]); + } + + // done + return valid; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// set + +void CCallsign::SetCallsign(const char *sz) +{ + // set callsign + ::memset(m_Callsign, ' ', sizeof(m_Callsign)); + ::memcpy(m_Callsign, sz, MIN(strlen(sz), sizeof(m_Callsign))); +} + +void CCallsign::SetCallsign(const uint8 *buffer, int len) +{ + // set callsign + ::memset(m_Callsign, ' ', sizeof(m_Callsign)); + ::memcpy(m_Callsign, buffer, MIN(len, sizeof(m_Callsign))); + for ( int i = 0; i < sizeof(m_Callsign); i++ ) + { + if ( m_Callsign[i] == 0 ) + { + m_Callsign[i] = ' '; + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// modify + +void CCallsign::PatchCallsign(int off, const uint8 *patch, int len) +{ + if ( off < sizeof(m_Callsign) ) + { + ::memcpy(m_Callsign, patch, MIN(len, sizeof(m_Callsign) - off)); + } +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// get + +void CCallsign::GetCallsign(uint8 *buffer) const +{ + ::memcpy(buffer, m_Callsign, sizeof(m_Callsign)); +} + +void CCallsign::GetCallsignString(char *sz) const +{ + int i; + for ( i = 0; (i < sizeof(m_Callsign)) && (m_Callsign[i] != ' '); i++ ) + { + sz[i] = m_Callsign[i]; + } + sz[i] = 0; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// compare + +bool CCallsign::HasSameCallsign(const CCallsign &Callsign) const +{ + return (::memcmp(m_Callsign, Callsign.m_Callsign, sizeof(m_Callsign)) == 0); +} + +bool CCallsign::HasSameCallsignWithWildcard(const CCallsign &callsign) const +{ + bool same = true; + bool done = false; + + for ( int i = 0; (i < sizeof(m_Callsign)) && same && !done; i++ ) + { + if ( !(done = ((m_Callsign[i] == '*') || (callsign[i] == '*'))) ) + { + same &= (m_Callsign[i] == callsign[i]); + } + } + return same; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// operators + +bool CCallsign::operator ==(const CCallsign &callsign) const +{ + return (::memcmp(callsign.m_Callsign, m_Callsign, sizeof(m_Callsign)) == 0); +} + +CCallsign::operator const char *() const +{ + // empty + ::memset(m_sz, 0, sizeof(m_sz)); + // callsign + m_sz[CALLSIGN_LEN] = 0; + ::memcpy(m_sz, m_Callsign, sizeof(m_Callsign)); + + // done + return m_sz; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// helper + +bool CCallsign::IsNumber(char c) const +{ + return ((c >= '0') && (c <= '9')); +} + +bool CCallsign::IsLetter(char c) const +{ + return ((c >= 'A') && (c <= 'Z')); +} + +bool CCallsign::IsSpace(char c) const +{ + return (c == ' '); +} diff --git a/ccallsign.h b/ccallsign.h new file mode 100644 index 0000000..fe04ec5 --- /dev/null +++ b/ccallsign.h @@ -0,0 +1,83 @@ +// +// ccallsign.h +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef ccallsign_h +#define ccallsign_h + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +#define CALLSIGN_LEN 8 + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CCallsign +{ +public: + // contructors + CCallsign(); + CCallsign(const char *); + CCallsign(const CCallsign &); + + // destructor + virtual ~CCallsign() {}; + + // status + bool IsValid(void) const; + + // set + void SetCallsign(const char *); + void SetCallsign(const uint8 *, int); + + // modify + void PatchCallsign(int, const uint8 *, int); + + // get + void GetCallsign(uint8 *) const; + void GetCallsignString(char *) const; + + // compare + bool HasSameCallsign(const CCallsign &) const; + bool HasSameCallsignWithWildcard(const CCallsign &) const; + + // operators + bool operator ==(const CCallsign &) const; + operator const char *() const; + +protected: + // helper + bool IsNumber(char) const; + bool IsLetter(char) const; + bool IsSpace(char) const; + +protected: + // data + char m_Callsign[CALLSIGN_LEN]; + mutable char m_sz[CALLSIGN_LEN+1]; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* ccallsign_h */ diff --git a/cconfig.cpp b/cconfig.cpp new file mode 100644 index 0000000..b2484f7 --- /dev/null +++ b/cconfig.cpp @@ -0,0 +1,336 @@ +// +// cconfig.cpp +// ambed +// +// Created by Andy Taylor (MW0MWZ) on 31/10/2026. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include "cconfig.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// global objects + +CConfig g_Config; + +//////////////////////////////////////////////////////////////////////////////////////// +// keys, the defaults are the values in main.h + +struct SConfigKey +{ + const char *name; + float fDefault; + float fMin; + float fMax; + bool bInteger; +}; + +static const SConfigKey g_ConfigKeys[] = +{ + { "LISTEN_PORT", LISTEN_PORT, 1.0f, 65000.0f, true }, + { "DSCP_MARKING_ENABLE", DSCP_MARKING_ENABLE, 0.0f, 1.0f, true }, + { "DSCP_VALUE", DSCP_VALUE, 0.0f, 63.0f, true }, + { "DSTAR_TO_PCM", DSTAR_TO_PCM, -40.0f, 40.0f, false }, + { "DMR_TO_PCM", DMR_TO_PCM, -40.0f, 40.0f, false }, + { "M17_TO_PCM", M17_TO_PCM, -40.0f, 40.0f, false }, + { "P25_TO_PCM", P25_TO_PCM, -40.0f, 40.0f, false }, + { "PCM_TO_DSTAR", PCM_TO_DSTAR, -40.0f, 40.0f, false }, + { "PCM_TO_DMR", PCM_TO_DMR, -40.0f, 40.0f, false }, + { "PCM_TO_M17", PCM_TO_M17, -40.0f, 40.0f, false }, + { "PCM_TO_P25", PCM_TO_P25, -40.0f, 40.0f, false }, + { "USE_AGC", USE_AGC, 0.0f, 1.0f, true }, + { "AGC_TARGET", AGC_TARGET, -60.0f, -3.0f, false }, + { "AGC_CLAMPING", AGC_CLAMPING, 0.0f, 20.0f, false }, + { "AGC_ATTACK", AGC_ATTACK, 10.0f, 2000.0f, false }, + { "AGC_HANG", AGC_HANG, 0.0f, 10000.0f, false }, + { "AGC_RECOVERY", AGC_RECOVERY, 0.1f, 10.0f, false }, + { "AGC_RECOVERY_MIN", AGC_RECOVERY_MIN, 0.5f, 50.0f, false }, + { "AGC_RECOVERY_MAX", AGC_RECOVERY_MAX, 0.5f, 100.0f, false }, + { "AGC_GATE", AGC_GATE, -80.0f, -20.0f, false }, + { "USE_BANDPASSFILTER", USE_BANDPASSFILTER, 0.0f, 1.0f, true }, + { "STREAM_ACTIVITY_TIMEOUT", STREAM_ACTIVITY_TIMEOUT, 1.0f, 60.0f, true }, + { "TUNING_LOG", TUNING_LOG, 0.0f, 1.0f, true }, + { "XOMBE_THREADS", XOMBE_THREADS, 0.0f, 16.0f, true }, + { "XOMBE_PAIRS_PER_THREAD", XOMBE_PAIRS_PER_THREAD, 1.0f, 16.0f, true }, +}; + +static const SConfigKey *FindKey(const std::string &name) +{ + for ( const SConfigKey &key : g_ConfigKeys ) + { + if ( name == key.name ) + { + return &key; + } + } + return NULL; +} + +static std::string Trim(const std::string &str) +{ + size_t first = str.find_first_not_of(" \t\r"); + if ( first == std::string::npos ) + { + return ""; + } + return str.substr(first, str.find_last_not_of(" \t\r") - first + 1); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CConfig::CConfig() +{ + for ( const SConfigKey &key : g_ConfigKeys ) + { + m_Values[key.name] = key.fDefault; + } + m_IpValue = LISTEN_IP; + m_ListenIp = LISTEN_IP; + m_ListenPort = LISTEN_PORT; + m_XombeThreads = XOMBE_THREADS; + m_XombePairsPerThread = XOMBE_PAIRS_PER_THREAD; + m_VoiceTos = -1; + m_LastModified = 0; + m_bFileMissing = false; + Apply(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// load + +void CConfig::Load(const char *filename) +{ + std::lock_guard lock(m_Mutex); + m_Filename = filename; + + struct stat st; + if ( ::stat(m_Filename.c_str(), &st) == 0 ) + { + m_LastModified = st.st_mtime; + ReadFile(); + } + else + { + std::cout << "Config: cannot read " << m_Filename << ", using main.h defaults" << std::endl; + m_bFileMissing = true; + } + m_ListenIp = m_IpValue; + m_ListenPort = (uint16)m_Values.at("LISTEN_PORT"); + m_XombeThreads = (int)m_Values.at("XOMBE_THREADS"); + m_XombePairsPerThread = (int)m_Values.at("XOMBE_PAIRS_PER_THREAD"); + Apply(); + Report(); +} + +void CConfig::Reload(void) +{ + std::lock_guard lock(m_Mutex); + if ( m_Filename.empty() ) + { + return; + } + + struct stat st; + if ( ::stat(m_Filename.c_str(), &st) != 0 ) + { + if ( !m_bFileMissing ) + { + std::cout << "Config: cannot read " << m_Filename << ", keeping current values" << std::endl; + m_bFileMissing = true; + } + return; + } + + if ( m_bFileMissing || st.st_mtime != m_LastModified ) + { + m_bFileMissing = false; + m_LastModified = st.st_mtime; + std::cout << "Config: reloading " << m_Filename << ", changes apply from the next stream" << std::endl; + ReadFile(); + Apply(); + Report(); + if ( m_IpValue != m_ListenIp || (uint16)m_Values.at("LISTEN_PORT") != m_ListenPort ) + { + std::cout << "Config: LISTEN_IP and LISTEN_PORT changes need a restart" << std::endl; + } + if ( (int)m_Values.at("XOMBE_THREADS") != m_XombeThreads || + (int)m_Values.at("XOMBE_PAIRS_PER_THREAD") != m_XombePairsPerThread ) + { + std::cout << "Config: XOMBE_THREADS and XOMBE_PAIRS_PER_THREAD changes need a restart" << std::endl; + } + } +} + +// DSCP can follow the file, it is read for every voice packet +void CConfig::Apply(void) +{ + bool enabled = (m_Values.at("DSCP_MARKING_ENABLE") != 0.0f); + m_VoiceTos = enabled ? ((int)m_Values.at("DSCP_VALUE") << 2) : -1; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// parsing + +void CConfig::ReadFile(void) +{ + std::ifstream file(m_Filename); + if ( !file.is_open() ) + { + std::cout << "Config: cannot open " << m_Filename << ", keeping current values" << std::endl; + return; + } + + // a key left out of the file goes back to its default + std::map values; + for ( const SConfigKey &key : g_ConfigKeys ) + { + values[key.name] = key.fDefault; + } + + std::string ip = LISTEN_IP; + + std::string line; + int lineNumber = 0; + while ( std::getline(file, line) ) + { + lineNumber++; + line = Trim(line.substr(0, line.find_first_of("#;"))); + if ( line.empty() || line[0] == '[' ) + { + continue; + } + + size_t equals = line.find('='); + + // the one setting that isn't a number + if ( equals != std::string::npos && Trim(line.substr(0, equals)) == "LISTEN_IP" ) + { + std::string text = Trim(line.substr(equals + 1)); + if ( IsValidIp(text) ) + { + ip = text; + } + else + { + std::cout << "Config: line " << lineNumber << " ignored, bad value for LISTEN_IP: " << text << std::endl; + ip = m_IpValue; + } + continue; + } + + const SConfigKey *key = (equals == std::string::npos) ? NULL : FindKey(Trim(line.substr(0, equals))); + if ( key == NULL ) + { + std::cout << "Config: line " << lineNumber << " ignored, unknown setting: " << line << std::endl; + continue; + } + + // a bad value keeps the value already in use, not the default + values[key->name] = m_Values[key->name]; + + std::string text = Trim(line.substr(equals + 1)); + char *end = NULL; + float value = ::strtof(text.c_str(), &end); + if ( text.empty() || *end != '\0' || !std::isfinite(value) || + value < key->fMin || value > key->fMax || (key->bInteger && value != floorf(value)) ) + { + std::cout << "Config: line " << lineNumber << " ignored, bad value for " << key->name + << " (" << key->fMin << " to " << key->fMax << "): " << text << std::endl; + continue; + } + values[key->name] = value; + } + + m_Values = values; + m_IpValue = ip; +} + +bool CConfig::IsValidIp(const std::string &ip) const +{ + struct in_addr addr; + return ::inet_pton(AF_INET, ip.c_str(), &addr) == 1; +} + +void CConfig::Report(void) const +{ + std::cout << "Config: LISTEN_IP=" << m_IpValue; + for ( const SConfigKey &key : g_ConfigKeys ) + { + std::cout << " " << key.name << "=" << m_Values.at(key.name); + } + std::cout << std::endl; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// get + +CTuning CConfig::GetTuning(void) const +{ + std::lock_guard lock(m_Mutex); + CTuning tuning; + + tuning.fToPcm[CODEC_NONE] = 0.0f; + tuning.fToPcm[CODEC_AMBEPLUS] = m_Values.at("DSTAR_TO_PCM"); + tuning.fToPcm[CODEC_AMBE2PLUS] = m_Values.at("DMR_TO_PCM"); + tuning.fToPcm[CODEC_CODEC2] = m_Values.at("M17_TO_PCM"); + tuning.fToPcm[CODEC_IMBE] = m_Values.at("P25_TO_PCM"); + + tuning.fFromPcm[CODEC_NONE] = 0.0f; + tuning.fFromPcm[CODEC_AMBEPLUS] = m_Values.at("PCM_TO_DSTAR"); + tuning.fFromPcm[CODEC_AMBE2PLUS] = m_Values.at("PCM_TO_DMR"); + tuning.fFromPcm[CODEC_CODEC2] = m_Values.at("PCM_TO_M17"); + tuning.fFromPcm[CODEC_IMBE] = m_Values.at("PCM_TO_P25"); + + tuning.bUseAgc = (m_Values.at("USE_AGC") != 0.0f); + tuning.fAgcTarget = m_Values.at("AGC_TARGET"); + tuning.fAgcClamping = m_Values.at("AGC_CLAMPING"); + tuning.fAgcAttack = m_Values.at("AGC_ATTACK"); + tuning.fAgcHang = m_Values.at("AGC_HANG"); + tuning.fAgcRecovery = m_Values.at("AGC_RECOVERY"); + tuning.fAgcRecoveryMin = m_Values.at("AGC_RECOVERY_MIN"); + tuning.fAgcRecoveryMax = m_Values.at("AGC_RECOVERY_MAX"); + tuning.fAgcGate = m_Values.at("AGC_GATE"); + tuning.bUseFilter = (m_Values.at("USE_BANDPASSFILTER") != 0.0f); + tuning.iStreamTimeout = (int)m_Values.at("STREAM_ACTIVITY_TIMEOUT"); + tuning.bTuningLog = (m_Values.at("TUNING_LOG") != 0.0f); + + return tuning; +} + +std::string CConfig::GetListenIp(void) const +{ + std::lock_guard lock(m_Mutex); + return m_ListenIp; +} + +const char *CConfig::GetModeName(uint8 uiCodec) +{ + switch ( uiCodec ) + { + case CODEC_AMBEPLUS: return "DSTAR"; + case CODEC_AMBE2PLUS: return "DMR"; + case CODEC_CODEC2: return "M17"; + case CODEC_IMBE: return "P25"; + default: return "NONE"; + } +} diff --git a/cconfig.h b/cconfig.h new file mode 100644 index 0000000..5c98e22 --- /dev/null +++ b/cconfig.h @@ -0,0 +1,99 @@ +// +// cconfig.h +// ambed +// +// Created by Andy Taylor (MW0MWZ) on 31/10/2026. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +#ifndef cconfig_h +#define cconfig_h + +#include +#include +#include +#include +#include +#include "main.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// tuning values, indexed by codec where they are per codec + +struct CTuning +{ + float fToPcm[NB_OF_CODECS]; // _TO_PCM, in dB + float fFromPcm[NB_OF_CODECS]; // PCM_TO_, in dB + bool bUseAgc; + float fAgcTarget; // in dBFS + float fAgcClamping; // in dB + float fAgcAttack; // in ms + float fAgcHang; // in ms + float fAgcRecovery; // in dB/s for each dB below the target + float fAgcRecoveryMin; // in dB/s + float fAgcRecoveryMax; // in dB/s + float fAgcGate; // in dBFS + bool bUseFilter; + int iStreamTimeout; // in seconds + bool bTuningLog; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CConfig +{ +public: + // constructor + CConfig(); + + // load, Reload does nothing until the file changes + void Load(const char *); + void Reload(void); + + // get, a copy so a stream keeps its values however long it runs + CTuning GetTuning(void) const; + std::string GetListenIp(void) const; + uint16 GetListenPort(void) const { return m_ListenPort; } + int GetVoiceTos(void) const { return m_VoiceTos; } + int GetXombeThreads(void) const { return m_XombeThreads; } + int GetXombePairsPerThread(void) const { return m_XombePairsPerThread; } + bool IsValidIp(const std::string &) const; + static const char *GetModeName(uint8); + +protected: + // parsing + void ReadFile(void); + void Report(void) const; + void Apply(void); + +protected: + // data + mutable std::mutex m_Mutex; + std::map m_Values; + std::string m_IpValue; // as read, the socket keeps the one it started with + std::string m_ListenIp; + uint16 m_ListenPort; + int m_XombeThreads; + int m_XombePairsPerThread; + std::atomic m_VoiceTos; // TOS byte for voice packets, -1 for no marking + std::string m_Filename; + time_t m_LastModified; + bool m_bFileMissing; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cconfig_h */ diff --git a/ccontroller.cpp b/ccontroller.cpp new file mode 100644 index 0000000..da50d35 --- /dev/null +++ b/ccontroller.cpp @@ -0,0 +1,448 @@ +// +// ccontroller.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 15/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "ctimepoint.h" +#include "cvocodecs.h" +#include "ccontroller.h" +#include "cconfig.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CController::CController() +{ + m_bStopThread = false; + m_pThread = NULL; + m_Ip = CIp("127.0.0.1"); + m_uiLastStreamId = 0; + m_uiMaxStreams = 0; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CController::~CController() +{ + Close(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// initialization + +bool CController::Init(void) +{ + bool ok; + + // reset stop flag + m_bStopThread = false; + + // calculate max streams from available vocoder channels + // Codec2/IMBE input modes use 2 channels per stream, so divide by 2 + int nbChannels = g_Vocodecs.GetNbChannels(); + m_uiMaxStreams = (nbChannels > 0) ? (nbChannels / 2) : 0; + if ( m_uiMaxStreams == 0 && nbChannels > 0 ) + { + m_uiMaxStreams = 1; // at least 1 stream if we have any channels + } + std::cout << "Max concurrent streams: " << m_uiMaxStreams << " (from " << nbChannels << " vocoder channels)" << std::endl; + + // create our socket + ok = m_Socket.Open(m_Ip, g_Config.GetListenPort()); + if ( ok ) + { + // start thread; + m_pThread = new std::thread(CController::Thread, this); + } + else + { + std::cout << "Error opening socket on port UDP" << g_Config.GetListenPort() << " on ip " << m_Ip << std::endl; + } + + // done + return ok; +} + +void CController::Close(void) +{ + // Idempotent: if thread already stopped, Close() was already called + if ( m_pThread == NULL ) + return; + + m_bStopThread = true; + m_Socket.Close(); + m_pThread->join(); + delete m_pThread; + m_pThread = NULL; + + // Close all streams now that the controller thread is stopped + for ( int i = 0; i < m_Streams.size(); i++ ) + { + delete m_Streams[i]; + } + m_Streams.clear(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// thread + +void CController::Thread(CController *This) +{ + while ( !This->m_bStopThread ) + { + This->Task(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// task + +void CController::Task(void) +{ + CBuffer Buffer; + CIp Ip; + CCallsign Callsign; + uint8 CodecIn; + uint8 CodecOut1; + uint8 CodecOut2; + uint8 CodecOut3; + uint16 StreamId; + CStream *Stream; + + // anything coming in from codec client ? + if ( m_Socket.Receive(&Buffer, &Ip, 20) != -1 ) + { + // crack packet + if ( IsValidOpenstreamPacket(Buffer, &Callsign, &CodecIn, &CodecOut1, &CodecOut2, &CodecOut3) ) + { + std::cout << "Stream Open from " << Callsign << " at " << Ip + << " CodecIn=" << (int)CodecIn + << " Out1=" << (int)CodecOut1 + << " Out2=" << (int)CodecOut2 + << " Out3=" << (int)CodecOut3 << std::endl; + + // try create the stream + Stream = OpenStream(Callsign, Ip, CodecIn, CodecOut1, CodecOut2, CodecOut3); + + // send back details + if ( Stream != NULL ) + { + EncodeStreamDescrPacket(&Buffer, *Stream); + } + else + { + EncodeNoStreamAvailablePacket(&Buffer); + } + m_Socket.Send(Buffer, Ip); + } + else if ( IsValidClosestreamPacket(Buffer, &StreamId) ) + { + // close the stream + CloseStream(StreamId); + + std::cout << "Stream " << (int)StreamId << " closed" << std::endl; + } + else if ( IsValidKeepAlivePacket(Buffer, &Callsign) ) + { + //std::cout << "ping - " << Callsign << std::endl; + // pong back + EncodeKeepAlivePacket(&Buffer); + m_Socket.Send(Buffer, Ip); + } + } + + + // HandleTimout/keepalive + bool timeout; + do + { + // init loop stuffs + timeout = false; + CStream *stream = NULL; + + // any inactive streams? + Lock(); + { + for ( int i = 0; (i < m_Streams.size()) && !timeout; i++ ) + { + if ( !(m_Streams[i]->IsActive()) ) + { + timeout = true; + stream = m_Streams[i]; + std::cout << "Stream " << (int)m_Streams[i]->GetId() << " activity timeout " << std::endl; + } + } + } + Unlock(); + + // if any streams timeout, close it + // this cannot be done in above loop as it suppress it from array + if ( timeout ) + { + CloseStream(stream); + } + } while (timeout); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// streams management + +CStream *CController::OpenStream(const CCallsign &Callsign, const CIp &Ip, uint8 CodecIn, uint8 CodecOut1, uint8 CodecOut2, uint8 CodecOut3) +{ + CStream *stream = NULL; + + // check capacity + if ( m_Streams.size() >= (size_t)m_uiMaxStreams ) + { + std::cout << "Max streams reached (" << m_uiMaxStreams << "), rejecting" << std::endl; + return NULL; + } + + // pick the next stream id whose port is free: a long stream can still + // hold the id the round robin comes back to, and reusing it fails with + // "Error opening socket" although other ids are free + bool found = false; + for ( int n = 0; (n < (int)m_uiMaxStreams) && !found; n++ ) + { + m_uiLastStreamId = (m_uiLastStreamId + 1); + m_uiLastStreamId = (m_uiLastStreamId > m_uiMaxStreams) ? 1 : m_uiLastStreamId; + found = true; + Lock(); + for ( size_t i = 0; i < m_Streams.size(); i++ ) + { + if ( m_Streams[i]->GetId() == m_uiLastStreamId ) + { + found = false; + break; + } + } + Unlock(); + } + if ( !found ) + { + std::cout << "No free stream id, rejecting" << std::endl; + return NULL; + } + + // create a new stream + stream = new CStream(m_uiLastStreamId, Callsign, Ip, CodecIn, CodecOut1, CodecOut2, CodecOut3); + if ( stream->Init(g_Config.GetListenPort()+m_uiLastStreamId) ) + { + std::cout << "Opened stream " << m_uiLastStreamId << std::endl; + // and store it + Lock(); + m_Streams.push_back(stream); + Unlock(); + } + else + { + delete stream; + stream = NULL; + } + + // done + return stream; +} + +void CController::CloseStream(CStream *stream) +{ + CStream *found = NULL; + Lock(); + { + for ( int i = 0; i < m_Streams.size(); i++ ) + { + if ( m_Streams[i] == stream ) + { + found = m_Streams[i]; + m_Streams.erase(m_Streams.begin()+i); + break; + } + } + } + Unlock(); + + // Close and delete outside the lock to avoid blocking other stream operations + if ( found != NULL ) + { + found->Close(); + delete found; + } +} + +void CController::CloseStream(uint16 StreamId) +{ + CStream *found = NULL; + Lock(); + { + for ( int i = 0; i < m_Streams.size(); i++ ) + { + if ( m_Streams[i]->GetId() == StreamId ) + { + found = m_Streams[i]; + m_Streams.erase(m_Streams.begin()+i); + break; + } + } + } + Unlock(); + + // Close and delete outside the lock to avoid blocking other stream operations + if ( found != NULL ) + { + found->Close(); + delete found; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// packet decoding helpers + +bool CController::IsValidKeepAlivePacket(const CBuffer &Buffer, CCallsign *Callsign) +{ + uint8 tag[] = { 'A','M','B','E','D','P','I','N','G' }; + + bool valid = false; + if ( (Buffer.size() == 17) && (Buffer.Compare(tag, sizeof(tag)) == 0) ) + { + // get callsign here + Callsign->SetCallsign(&(Buffer.data()[9]), 8); + valid = Callsign->IsValid(); + } + return valid; +} + +bool CController::IsValidOpenstreamPacket(const CBuffer &Buffer, CCallsign *Callsign, uint8 *CodecIn, uint8 *CodecOut1, uint8 *CodecOut2, uint8 *CodecOut3) +{ + uint8 tag[] = { 'A','M','B','E','D','O','S' }; + + bool valid = false; + // New format: 19 bytes with 3 output codecs + if ( (Buffer.size() == 19) && (Buffer.Compare(tag, sizeof(tag)) == 0) ) + { + // get callsign here + Callsign->SetCallsign(&(Buffer.data()[7]), 8); + *CodecIn = Buffer.data()[15]; + *CodecOut1 = Buffer.data()[16]; + *CodecOut2 = Buffer.data()[17]; + *CodecOut3 = Buffer.data()[18]; + + // valid ? + valid = Callsign->IsValid() && IsValidCodecIn(*CodecIn) && IsValidCodecOut(*CodecOut1) && IsValidCodecOut(*CodecOut2); + // CodecOut3 is optional (can be CODEC_NONE) + if (*CodecOut3 != CODEC_NONE) + { + valid = valid && IsValidCodecOut(*CodecOut3); + } + } + // 2 output codecs format: 18 bytes + else if ( (Buffer.size() == 18) && (Buffer.Compare(tag, sizeof(tag)) == 0) ) + { + // get callsign here + Callsign->SetCallsign(&(Buffer.data()[7]), 8); + *CodecIn = Buffer.data()[15]; + *CodecOut1 = Buffer.data()[16]; + *CodecOut2 = Buffer.data()[17]; + *CodecOut3 = CODEC_NONE; // no third output codec + + // valid ? + valid = Callsign->IsValid() && IsValidCodecIn(*CodecIn) && IsValidCodecOut(*CodecOut1) && IsValidCodecOut(*CodecOut2); + } + // Legacy format: 17 bytes with 1 output codec (backward compatibility) + else if ( (Buffer.size() == 17) && (Buffer.Compare(tag, sizeof(tag)) == 0) ) + { + // get callsign here + Callsign->SetCallsign(&(Buffer.data()[7]), 8); + *CodecIn = Buffer.data()[15]; + *CodecOut1 = Buffer.data()[16]; + *CodecOut2 = CODEC_NONE; // no second output codec + *CodecOut3 = CODEC_NONE; // no third output codec + + // valid ? + valid = Callsign->IsValid() && IsValidCodecIn(*CodecIn) && IsValidCodecOut(*CodecOut1); + } + return valid; +} + +bool CController::IsValidClosestreamPacket(const CBuffer &Buffer, uint16 *StreamId) +{ + uint8 tag[] = { 'A','M','B','E','D','C','S' }; + + bool valid = false; + if ( (Buffer.size() >= 9) && (Buffer.Compare(tag, sizeof(tag)) == 0) ) + { + // get stream id + ::memcpy(StreamId, &Buffer.data()[7], sizeof(uint16)); + valid = true; + } + return valid; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// packet encoding helpers + +void CController::EncodeKeepAlivePacket(CBuffer *Buffer) +{ + uint8 tag[] = { 'A','M','B','E','D','P','O','N','G' }; + + Buffer->Set(tag, sizeof(tag)); +} + +void CController::EncodeStreamDescrPacket(CBuffer *Buffer, const CStream &Stream) +{ + uint8 tag[] = { 'A','M','B','E','D','S','T','D' }; + + Buffer->Set(tag, sizeof(tag)); + // id + Buffer->Append((uint16)Stream.GetId()); + // port + Buffer->Append((uint16)Stream.GetPort()); + // codecin + Buffer->Append((uint8)Stream.GetCodecIn()); + // codecout + Buffer->Append((uint8)Stream.GetCodecOut()); +} + +void CController::EncodeNoStreamAvailablePacket(CBuffer *Buffer) +{ + uint8 tag[] = { 'A','M','B','E','D','B','U','S','Y' }; + + Buffer->Set(tag, sizeof(tag)); +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// codec helpers + +bool CController::IsValidCodecIn(uint8 codec) +{ + return ((codec == CODEC_AMBEPLUS) || (codec == CODEC_AMBE2PLUS) || (codec == CODEC_CODEC2) || (codec == CODEC_IMBE)); +} + +bool CController::IsValidCodecOut(uint8 codec) +{ + return ((codec == CODEC_AMBEPLUS) || (codec == CODEC_AMBE2PLUS) || (codec == CODEC_CODEC2) || (codec == CODEC_IMBE)); +} + diff --git a/ccontroller.h b/ccontroller.h new file mode 100644 index 0000000..2899794 --- /dev/null +++ b/ccontroller.h @@ -0,0 +1,99 @@ +// +// ccontroller.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 15/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef ccontroller_h +#define ccontroller_h + +#include "ccallsign.h" +#include "cstream.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CController +{ +public: + // constructors + CController(); + + // destructor + virtual ~CController(); + + // initialization + bool Init(void); + void Close(void); + + // locks + void Lock(void) { m_Mutex.lock(); } + void Unlock(void) { m_Mutex.unlock(); } + + // get + const CIp &GetListenIp(void) const { return (const CIp &)m_Ip; } + + // set + void SetListenIp(const CIp &ip) { m_Ip = ip; } + + // streams management + CStream *OpenStream(const CCallsign &, const CIp &, uint8, uint8, uint8, uint8); + void CloseStream(CStream *); + void CloseStream(uint16); + + // task + static void Thread(CController *); + void Task(void); + +protected: + // packet decoding helpers + bool IsValidKeepAlivePacket(const CBuffer &, CCallsign *); + bool IsValidOpenstreamPacket(const CBuffer &, CCallsign *, uint8 *, uint8 *, uint8 *, uint8 *); + bool IsValidClosestreamPacket(const CBuffer &, uint16 *); + + // packet encoding helpers + void EncodeKeepAlivePacket(CBuffer *); + void EncodeStreamDescrPacket(CBuffer *, const CStream &); + void EncodeNoStreamAvailablePacket(CBuffer *); + + // codec helpers + bool IsValidCodecIn(uint8); + bool IsValidCodecOut(uint8); + +protected: + // control socket + CIp m_Ip; + CUdpSocket m_Socket; + + // streams + uint16 m_uiLastStreamId; + uint16 m_uiMaxStreams; + std::mutex m_Mutex; + std::vector m_Streams; + + // thread + std::atomic m_bStopThread; + std::thread *m_pThread; + +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* ccontroller_h */ diff --git a/cfirfilter.cpp b/cfirfilter.cpp new file mode 100644 index 0000000..8e06c19 --- /dev/null +++ b/cfirfilter.cpp @@ -0,0 +1,77 @@ +// +// cfirfilter.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 26/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// FIRFilter by Geoffrey Merck F4FXL / KC3FRA + +#include "cfirfilter.h" +#include + +CFIRFilter::CFIRFilter(const float* taps, int tapsLength) +{ + m_taps = new float[tapsLength]; + m_buffer = new float[tapsLength]; + m_tapsLength = tapsLength; + + ::memcpy(m_taps, taps, tapsLength * sizeof(float)); + ::memset(m_buffer, 0, tapsLength * sizeof(float)); + m_currentBufferPosition = 0; +} + +CFIRFilter::~CFIRFilter() +{ + delete[] m_taps; + delete[] m_buffer; +} + +void CFIRFilter::ProcessSampleBlock(uint8* voice, int length) +{ + for(int i = 0; i < length; i += 2) + { + float input = (float)(short)MAKEWORD(voice[i+1], voice[i]); + float output = 0.0f; + int iTaps = 0; + + // Buffer latest sample into delay line + m_buffer[m_currentBufferPosition] = input; + + for(int j = m_currentBufferPosition; j >= 0; j--) + { + output += m_taps[iTaps++] * m_buffer[j]; + } + + for(int j = m_tapsLength - 1; j > m_currentBufferPosition; j--) + { + output += m_taps[iTaps++] * m_buffer[j]; + } + + m_currentBufferPosition = (m_currentBufferPosition + 1) % m_tapsLength; + + //write processed sample back, clamp to short range + if (output > 32767.0f) output = 32767.0f; + else if (output < -32768.0f) output = -32768.0f; + voice[i] = HIBYTE((short)output); + voice[i+1] = LOBYTE((short)output); + } +} + + diff --git a/cfirfilter.h b/cfirfilter.h new file mode 100644 index 0000000..85026fb --- /dev/null +++ b/cfirfilter.h @@ -0,0 +1,51 @@ +// +// cfirfilter.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 26/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// FIRFilter by Geoffrey Merck F4FXL / KC3FRA + +#ifndef cfirfilter_h +#define cfirfilter_h + +#include "csampleblockprocessor.h" + +class CFIRFilter : CSampleBlockProcessor +{ +public : + //Constructor + CFIRFilter(const float* taps, int tapsLength); + + // Destructor + ~CFIRFilter(); + + // Processing + void ProcessSampleBlock(uint8* voice, int length); + +private: + float* m_taps; + int m_tapsLength; + float* m_buffer; + int m_currentBufferPosition; +}; + +#endif //cfirfilter_h + diff --git a/cfixedgain.cpp b/cfixedgain.cpp new file mode 100644 index 0000000..28fa771 --- /dev/null +++ b/cfixedgain.cpp @@ -0,0 +1,55 @@ +// +// cfixedgain.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// Geoffrey Merck F4FXL / KC3FRA AGC + +#include "cfixedgain.h" +#include + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CFixedGain::CFixedGain(float gaindB) +{ + m_gaindB = gaindB; + m_gainLinear = pow(10.0f, m_gaindB/20.0f); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// processing + +void CFixedGain::ProcessSampleBlock(uint8* voice, int length) +{ + for(int i = 0; i < length; i += 2) + { + float input = (float)(short)MAKEWORD(voice[i+1], voice[i]); + //apply gain + float output = input * m_gainLinear; + + //write processed sample back, clamp to short range + if (output > 32767.0f) output = 32767.0f; + else if (output < -32768.0f) output = -32768.0f; + voice[i] = HIBYTE((short)output); + voice[i+1] = LOBYTE((short)output); + } +} \ No newline at end of file diff --git a/cfixedgain.h b/cfixedgain.h new file mode 100644 index 0000000..eadac47 --- /dev/null +++ b/cfixedgain.h @@ -0,0 +1,45 @@ +// +// cfixedgain.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 26/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// Geoffrey Merck F4FXL / KC3FRA + +#ifndef cfixedgain_h +#define cfixedgain_h + +#include "csampleblockprocessor.h" + +class CFixedGain : CSampleBlockProcessor +{ +public: + //Constructor + CFixedGain(float gaindB); + + //processing + void ProcessSampleBlock(uint8* voice, int length); + +private: + float m_gaindB; //gain in dB + float m_gainLinear; //linearized gain +}; + +#endif /* cfixedgain_h */ \ No newline at end of file diff --git a/cftdidevicedescr.cpp b/cftdidevicedescr.cpp new file mode 100644 index 0000000..1bfb330 --- /dev/null +++ b/cftdidevicedescr.cpp @@ -0,0 +1,600 @@ +// +// cftdidevicedescr.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 02/06/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "cusb3000interface.h" +#include "cusb3003interface.h" +#include "cusb3003hrinterface.h" +#include "cusb3003df2etinterface.h" +#include "cftdidevicedescr.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CFtdiDeviceDescr::CFtdiDeviceDescr(void) +{ + m_bUsed = false; + m_uiVid = 0; + m_uiPid = 0; + ::memset(m_szDescription, 0, sizeof(m_szDescription)); + ::memset(m_szSerial, 0, sizeof(m_szSerial)); +} + +CFtdiDeviceDescr::CFtdiDeviceDescr(uint32 uiVid, uint32 uiPid, const char *szDescription, const char *szSerial) +{ + m_bUsed = false; + m_uiVid = uiVid; + m_uiPid = uiPid; + ::strncpy(m_szDescription, szDescription, sizeof(m_szDescription) - 1); + m_szDescription[sizeof(m_szDescription) - 1] = '\0'; + ::strncpy(m_szSerial, szSerial, sizeof(m_szSerial) - 1); + m_szSerial[sizeof(m_szSerial) - 1] = '\0'; +} + +CFtdiDeviceDescr::CFtdiDeviceDescr(const CFtdiDeviceDescr &descr) +{ + m_bUsed = descr.m_bUsed; + m_uiVid = descr.m_uiVid; + m_uiPid = descr.m_uiPid; + ::memcpy(m_szDescription, descr.m_szDescription, sizeof(m_szDescription)); + ::memcpy(m_szSerial, descr.m_szSerial, sizeof(m_szSerial)); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// interface factory + +int CFtdiDeviceDescr::CreateInterface(CFtdiDeviceDescr *descr, std::vector*channels) +{ + int iNbChs = 0; + + // single channel devices cannot be created alone + // three channels devices + if ( (::strcmp(descr->GetDescription(), "USB-3003") == 0) || // DVSI's USB-3003 + (::strcmp(descr->GetDescription(), "DF2ET-3003") == 0) || // DF2ET's USB-3003 opensource device + (::strcmp(descr->GetDescription(), "DVstick-33") == 0) || // DVMEGA USB-3003 device + (::strcmp(descr->GetDescription(), "ThumbDV-3") == 0) ) // ThumbDV-3 + { + iNbChs = CreateUsb3003(descr, channels); + } + // six channels devices + else if ( (::strcmp(descr->GetDescription(), "USB-3006 A") == 0) ) // LX3JL's USB-3006 opensource device + { + iNbChs = CreateUsb3006(descr, channels); + } + // twelves channels devices + else if ( (::strcmp(descr->GetDescription(), "USB-3012 A") == 0) ) // DVSI's USB-3012 + { + iNbChs = CreateUsb3012(descr, channels); + } + // done + return iNbChs; +} + +int CFtdiDeviceDescr::CreateInterfacePair(CFtdiDeviceDescr *descr1, CFtdiDeviceDescr *descr2, std::vector*channels) +{ + int iNbChs = 0; + + // create interface objects + if ( (descr1->GetNbChannels() == 1) && (descr2->GetNbChannels() == 1) ) + { + // create 3000-3000 pair + CUsb3000Interface *Usb3000A = InstantiateUsb3000(descr1); + CUsb3000Interface *Usb3000B = InstantiateUsb3000(descr2); + iNbChs = CreatePair(Usb3000A, Usb3000B, channels); + } + else if ( (descr1->GetNbChannels() == 3) && (descr2->GetNbChannels() == 1) ) + { + // create 3003-3000 pair + CUsb3003Interface *Usb3003 = InstantiateUsb3003(descr1); + CUsb3000Interface *Usb3000 = InstantiateUsb3000(descr2); + iNbChs = CreatePair(Usb3003, Usb3000, channels); + } + else if ( (descr1->GetNbChannels() == 1) && (descr2->GetNbChannels() == 3) ) + { + // create 3000-3003 pair + CUsb3000Interface *Usb3000 = InstantiateUsb3000(descr1); + CUsb3003Interface *Usb3003 = InstantiateUsb3003(descr2); + iNbChs = CreatePair(Usb3003, Usb3000, channels); + } + else if ( (descr1->GetNbChannels() == 3) && (descr2->GetNbChannels() == 3) ) + { + // create 3003-3003 pair + CUsb3003Interface *Usb3003A = InstantiateUsb3003(descr1); + CUsb3003Interface *Usb3003B = InstantiateUsb3003(descr2); + iNbChs = CreatePair(Usb3003A, Usb3003B, channels); + } + + // done + return iNbChs; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// get + +const char * CFtdiDeviceDescr::GetChannelDescription(int ch) const +{ + static char descr[FTDI_MAX_STRINGLENGTH]; + char tag[3] = "_X"; + + ::snprintf(descr, sizeof(descr), "%s", GetDescription()); + size_t len = ::strlen(descr); + if ( len >= 2 ) + { + descr[len - 2] = 0x00; + tag[1] = (char)ch + 'A'; + ::strncat(descr, tag, sizeof(descr) - ::strlen(descr) - 1); + } + return descr; +} + +const char * CFtdiDeviceDescr::GetChannelSerialNumber(int ch) const +{ + static char serial[FTDI_MAX_STRINGLENGTH]; + + ::snprintf(serial, sizeof(serial), "%s", GetSerialNumber()); + size_t len = ::strlen(serial); + if ( len >= 1 ) + { + serial[len - 1] = (char)ch + 'A'; + } + return serial; +} + +int CFtdiDeviceDescr::GetNbChannels(void) const +{ + int iNbChs = 0; + + // single channel devices + if ( (::strcmp(m_szDescription, "USB-3000") == 0) || // DVSI's USB-3000 + (::strcmp(m_szDescription, "DVstick-30") == 0) || // DVMEGA AMBE3000 device + (::strcmp(m_szDescription, "ThumbDV") == 0) ) // ThumbDV + { + iNbChs = 1; + } + // three channels devices + else if ( (::strcmp(m_szDescription, "USB-3003") == 0) || // DVSI's USB-3003 + (::strcmp(m_szDescription, "DF2ET-3003") == 0) || // DF2ET's USB-3003 opensource device + (::strcmp(m_szDescription, "DVstick-33") == 0) || // DVMEGA AMBE 3003 device + (::strcmp(m_szDescription, "ThumbDV-3") == 0) ) // ThumbDV-3 + { + iNbChs = 3; + } + // six channels devices + else if ( (::strcmp(m_szDescription, "USB-3006 A") == 0) ) // LX3JL's USB-3006 opensource device + { + iNbChs = 6; + } + // twelves channels devices + else if ( (::strcmp(m_szDescription, "USB-3012 A") == 0) ) // DVSI's USB-3012 + { + iNbChs = 12; + } + + // done + return iNbChs; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// DVSI's USB-3012 factory helper +// +// This device uses 3 AMBE3003 connected on a single FTDI 4 channels +// USB to serial interface. The reset mechanism is based +// on DTR and SetBreak. Baudrate is 921600 +// + +int CFtdiDeviceDescr::CreateUsb3012(CFtdiDeviceDescr *descr, std::vector*channels) +{ + int nStreams = 0; + + // create the interfaces for the four 3003 chips + CUsb3003HRInterface *Usb3003A = + new CUsb3003HRInterface(descr->GetVid(), descr->GetPid(), descr->GetChannelDescription(0), descr->GetChannelSerialNumber(0)); + CUsb3003HRInterface *Usb3003B = + new CUsb3003HRInterface(descr->GetVid(), descr->GetPid(), descr->GetChannelDescription(1), descr->GetChannelSerialNumber(1)); + CUsb3003HRInterface *Usb3003C = + new CUsb3003HRInterface(descr->GetVid(), descr->GetPid(), descr->GetChannelDescription(2), descr->GetChannelSerialNumber(2)); + CUsb3003HRInterface *Usb3003D = + new CUsb3003HRInterface(descr->GetVid(), descr->GetPid(), descr->GetChannelDescription(3), descr->GetChannelSerialNumber(3)); + + // init the interfaces + if ( Usb3003A->Init(CODEC_AMBEPLUS) && Usb3003B->Init(CODEC_AMBE2PLUS) && + Usb3003C->Init(CODEC_AMBEPLUS) && Usb3003D->Init(CODEC_AMBE2PLUS) ) + { + CVocodecChannel *Channel; + // create all channels + { + // ch1 + Channel = new CVocodecChannel(Usb3003A, 0, Usb3003A, 1); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + // ch2 + Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + // ch3 + Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1); + channels->push_back(Channel); + Usb3003B->AddChannel(Channel); + // ch4 + Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0); + channels->push_back(Channel); + Usb3003B->AddChannel(Channel); + // ch5 + Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + Usb3003B->AddChannel(Channel); + // ch6 + Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + Usb3003B->AddChannel(Channel); + // ch7 + Channel = new CVocodecChannel(Usb3003C, 0, Usb3003C, 1); + channels->push_back(Channel); + Usb3003C->AddChannel(Channel); + // ch8 + Channel = new CVocodecChannel(Usb3003C, 1, Usb3003C, 0); + channels->push_back(Channel); + Usb3003C->AddChannel(Channel); + // ch9 + Channel = new CVocodecChannel(Usb3003D, 0, Usb3003D, 1); + channels->push_back(Channel); + Usb3003D->AddChannel(Channel); + // ch10 + Channel = new CVocodecChannel(Usb3003D, 1, Usb3003D, 0); + channels->push_back(Channel); + Usb3003D->AddChannel(Channel); + // ch11 + Channel = new CVocodecChannel(Usb3003C, 2, Usb3003D, 2); + channels->push_back(Channel); + Usb3003C->AddChannel(Channel); + Usb3003D->AddChannel(Channel); + // ch12 + Channel = new CVocodecChannel(Usb3003D, 2, Usb3003C, 2); + channels->push_back(Channel); + Usb3003C->AddChannel(Channel); + Usb3003D->AddChannel(Channel); + //done + nStreams = 12; + } + } + else + { + // cleanup + delete Usb3003A; + delete Usb3003B; + delete Usb3003C; + delete Usb3003D; + } + + // done + return nStreams; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// LX3JL's USB-3006 factory helper +// +// This device uses 2 AMBE3003 connected on a single FTDI 2 channels +// USB to serial interface. The reset mechanism is based +// on DTR and software reset. Baudrate is 921600 +// +int CFtdiDeviceDescr::CreateUsb3006(CFtdiDeviceDescr *descr, std::vector*channels) +{ + int nStreams = 0; + + // create the interfaces for the two 3003 chips + CUsb3003Interface *Usb3003A = + new CUsb3003Interface(descr->GetVid(), descr->GetPid(), descr->GetChannelDescription(0), descr->GetChannelSerialNumber(0)); + CUsb3003Interface *Usb3003B = + new CUsb3003Interface(descr->GetVid(), descr->GetPid(), descr->GetChannelDescription(1), descr->GetChannelSerialNumber(1)); + + // init the interfaces + if ( Usb3003A->Init(CODEC_AMBEPLUS) && Usb3003B->Init(CODEC_AMBE2PLUS) ) + { + CVocodecChannel *Channel; + // create all channels + { + // ch1 + Channel = new CVocodecChannel(Usb3003A, 0, Usb3003A, 1); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + // ch2 + Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + // ch3 + Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1); + channels->push_back(Channel); + Usb3003B->AddChannel(Channel); + // ch4 + Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0); + channels->push_back(Channel); + Usb3003B->AddChannel(Channel); + // ch5 + Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + Usb3003B->AddChannel(Channel); + // ch6 + Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + Usb3003B->AddChannel(Channel); + //done + nStreams = 6; + } + } + else + { + // cleanup + delete Usb3003A; + delete Usb3003B; + } + + // done + return nStreams; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// USB-3003 factory helpers +// DVSI +// DF2ET +// ThumbDV +// DVMEGA +// +// These devices uses a AMBE3003 connected on a single FTDI +// USB to serial interface. The reset mechanism is based +// on DTR and SetBreak, or software. Baudrate is 921600 +// +int CFtdiDeviceDescr::CreateUsb3003(CFtdiDeviceDescr *descr, std::vector*channels) +{ + int nStreams = 0; + + // create the interfaces for the 3003 chip + CUsb3003Interface *Usb3003 = InstantiateUsb3003(descr); + + // init the interface + if ( (Usb3003 != NULL) && Usb3003->Init(CODEC_NONE) ) + { + CVocodecChannel *Channel; + // create all channels + { + // ch1 + Channel = new CVocodecChannel(Usb3003, 0, Usb3003, 1); + channels->push_back(Channel); + Usb3003->AddChannel(Channel); + // ch2 + Channel = new CVocodecChannel(Usb3003, 1, Usb3003, 0); + channels->push_back(Channel); + Usb3003->AddChannel(Channel); + // done + nStreams = 2; + } + } + else + { + // cleanup + delete Usb3003; + } + + // done + return nStreams; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// 1 ch + 1 ch pair creation + +int CFtdiDeviceDescr::CreatePair(CUsb3000Interface *Usb3000A, CUsb3000Interface *Usb3000B, std::vector*channels) +{ + int nStreams = 0; + + // init the interfaces + if ( Usb3000A->Init(CODEC_AMBEPLUS) && Usb3000B->Init(CODEC_AMBE2PLUS) ) + { + CVocodecChannel *Channel; + // create all channels + { + // ch1 + Channel = new CVocodecChannel(Usb3000A, 0, Usb3000B, 0); + channels->push_back(Channel); + Usb3000A->AddChannel(Channel); + Usb3000B->AddChannel(Channel); + // ch2 + Channel = new CVocodecChannel(Usb3000B, 0, Usb3000A, 0); + channels->push_back(Channel); + Usb3000A->AddChannel(Channel); + Usb3000B->AddChannel(Channel); + // done + nStreams = 2; + } + } + else + { + // cleanup + delete Usb3000A; + delete Usb3000B; + } + + // done + return nStreams; + +} + +//////////////////////////////////////////////////////////////////////////////////////// +// 3 ch + 3 ch pair creation + +int CFtdiDeviceDescr::CreatePair(CUsb3003Interface *Usb3003A, CUsb3003Interface *Usb3003B, std::vector*channels) +{ + int nStreams = 0; + + // init the interfaces + if ( Usb3003A->Init(CODEC_AMBEPLUS) && Usb3003B->Init(CODEC_AMBE2PLUS) ) + { + CVocodecChannel *Channel; + // create all channels + { + // ch1 + Channel = new CVocodecChannel(Usb3003A, 0, Usb3003A, 1); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + // ch2 + Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + // ch3 + Channel = new CVocodecChannel(Usb3003B, 0, Usb3003B, 1); + channels->push_back(Channel); + Usb3003B->AddChannel(Channel); + // ch4 + Channel = new CVocodecChannel(Usb3003B, 1, Usb3003B, 0); + channels->push_back(Channel); + Usb3003B->AddChannel(Channel); + // ch5 + Channel = new CVocodecChannel(Usb3003A, 2, Usb3003B, 2); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + Usb3003B->AddChannel(Channel); + // ch6 + Channel = new CVocodecChannel(Usb3003B, 2, Usb3003A, 2); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + Usb3003B->AddChannel(Channel); + // done + nStreams = 6; + } + } + else + { + // cleanup + delete Usb3003A; + delete Usb3003B; + } + + // done + return nStreams; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// 3 ch + 1 ch pair creation + +int CFtdiDeviceDescr::CreatePair(CUsb3003Interface *Usb3003A, CUsb3000Interface *Usb3000B, std::vector*channels) +{ + int nStreams = 0; + + // init the interfaces + if ( Usb3003A->Init(CODEC_AMBEPLUS) && Usb3000B->Init(CODEC_AMBE2PLUS) ) + { + CVocodecChannel *Channel; + // create all channels + { + // ch1 + Channel = new CVocodecChannel(Usb3003A, 0, Usb3003A, 1); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + // ch2 + Channel = new CVocodecChannel(Usb3003A, 1, Usb3003A, 0); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + // ch3 + Channel = new CVocodecChannel(Usb3003A, 2, Usb3000B, 0); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + Usb3000B->AddChannel(Channel); + // ch4 + Channel = new CVocodecChannel(Usb3000B, 0, Usb3003A, 2); + channels->push_back(Channel); + Usb3003A->AddChannel(Channel); + Usb3000B->AddChannel(Channel); + // done + nStreams = 4; + } + } + else + { + // cleanup + delete Usb3003A; + delete Usb3000B; + } + + // done + return nStreams; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// interface instantiation helpers + +CUsb3003Interface *CFtdiDeviceDescr::InstantiateUsb3003(CFtdiDeviceDescr *descr) +{ + CUsb3003Interface *Usb3003 = NULL; + + // intstantiate the proper version of USB-3003 + if ( (::strcmp(descr->GetDescription(), "USB-3003") == 0) ) // DVSI's USB-3003 + { + // hardware reset, 921600 bps + Usb3003 = new CUsb3003HRInterface + (descr->GetVid(), descr->GetPid(), descr->GetDescription(), descr->GetSerialNumber()); + } + else if ( (::strcmp(descr->GetDescription(), "DF2ET-3003") == 0) ) // DF2ET's USB-3003 opensource device + { + // specific hardware reset, 921600 bps + Usb3003 = new CUsb3003DF2ETInterface + (descr->GetVid(), descr->GetPid(), descr->GetDescription(), descr->GetSerialNumber()); + } + else if ( (::strcmp(descr->GetDescription(), "ThumbDV-3") == 0) ) // ThumbDV-3 + { + // software reset, 921600 bps + Usb3003 = new CUsb3003Interface + (descr->GetVid(), descr->GetPid(), descr->GetDescription(), descr->GetSerialNumber()); + } + else if ( (::strcmp(descr->GetDescription(), "DVstick-33") == 0) ) // DVMEGA AMBE3003 device + { + // specific fardware reset, 921600 bps + Usb3003 = new CUsb3003DF2ETInterface + (descr->GetVid(), descr->GetPid(), descr->GetDescription(), descr->GetSerialNumber()); + } + + // done + return Usb3003; +} + +CUsb3000Interface *CFtdiDeviceDescr::InstantiateUsb3000(CFtdiDeviceDescr *descr) +{ + CUsb3000Interface *Usb3000 = NULL; + + // intstantiate the proper version of USB-3000 + if ( (::strcmp(descr->GetDescription(), "USB-3000") == 0) || // DVSI's USB-3000 + (::strcmp(descr->GetDescription(), "DVstick-30")== 0) || // DVMEGA AMBE3000 device + (::strcmp(descr->GetDescription(), "ThumbDV") == 0) ) // ThumbDV + { + Usb3000 = new CUsb3000Interface + (descr->GetVid(), descr->GetPid(), descr->GetDescription(), descr->GetSerialNumber()); + } + // done + return Usb3000; +} diff --git a/cftdidevicedescr.h b/cftdidevicedescr.h new file mode 100644 index 0000000..15fa362 --- /dev/null +++ b/cftdidevicedescr.h @@ -0,0 +1,97 @@ +// +// cftdidevicedescr.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 02/06/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cftdidevicedescr_h +#define cftdidevicedescr_h + +#include +#include "ftd2xx.h" +#include "cvocodecchannel.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +#define FTDI_MAX_STRINGLENGTH 256 + + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CUsb3000Interface; +class CUsb3003Interface; + +class CFtdiDeviceDescr +{ +public: + // constructors + CFtdiDeviceDescr(void); + CFtdiDeviceDescr(uint32, uint32, const char *, const char *); + CFtdiDeviceDescr(const CFtdiDeviceDescr &); + + // destructor + virtual ~CFtdiDeviceDescr() {} + + // interface factory + static int CreateInterface(CFtdiDeviceDescr *, std::vector*); + static int CreateInterfacePair(CFtdiDeviceDescr *, CFtdiDeviceDescr *, std::vector*); + + // get + bool IsUsed(void) const { return m_bUsed; } + int GetNbChannels(void) const; + uint32 GetVid(void) const { return m_uiVid; } + uint32 GetPid(void) const { return m_uiPid; } + const char *GetDescription(void) const { return m_szDescription; } + const char *GetSerialNumber(void) const { return m_szSerial; } + const char * GetChannelDescription(int) const; + const char * GetChannelSerialNumber(int) const; + + + // set + void SetUsed(bool used) { m_bUsed = used; } + +protected: + // factory helper + static int CreateUsb3012(CFtdiDeviceDescr *, std::vector*); + static int CreateUsb3006(CFtdiDeviceDescr *, std::vector*); + static int CreateUsb3003(CFtdiDeviceDescr *, std::vector*); + static int CreatePair(CUsb3003Interface *, CUsb3003Interface *, std::vector*); + static int CreatePair(CUsb3003Interface *, CUsb3000Interface *, std::vector*); + static int CreatePair(CUsb3000Interface *, CUsb3000Interface *, std::vector*); + static CUsb3003Interface *InstantiateUsb3003(CFtdiDeviceDescr *); + static CUsb3000Interface *InstantiateUsb3000(CFtdiDeviceDescr *); + +protected: + // status + bool m_bUsed; + + // data + uint32 m_uiVid; + uint32 m_uiPid; + char m_szDescription[FTDI_MAX_STRINGLENGTH]; + char m_szSerial[FTDI_MAX_STRINGLENGTH]; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cftdidevicedescr_h */ diff --git a/cip.cpp b/cip.cpp new file mode 100644 index 0000000..5cec9b5 --- /dev/null +++ b/cip.cpp @@ -0,0 +1,91 @@ +// +// cip.cpp +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "cip.h" + +#include + +//////////////////////////////////////////////////////////////////////////////////////// +// constructors + +CIp::CIp() +{ + ::memset(&m_Addr, 0, sizeof(m_Addr)); + m_Addr.sin_family = AF_INET; +} + +CIp::CIp(const char *sz) +{ + ::memset(&m_Addr, 0, sizeof(m_Addr)); + m_Addr.sin_family = AF_INET; + // try xxx.xxx.xxx.xxxx first + m_Addr.sin_addr.s_addr = inet_addr(sz); + if ( m_Addr.sin_addr.s_addr == INADDR_NONE ) + { + // otherwise try to resolve via dns + hostent *record = gethostbyname(sz); + if( record != NULL ) + { + m_Addr.sin_addr.s_addr = ((in_addr * )record->h_addr)->s_addr; + } + } +} + +CIp::CIp(const struct sockaddr_in *sa) +{ + ::memcpy(&m_Addr, sa, sizeof(m_Addr)); +} + + +CIp::CIp(const CIp &ip) +{ + ::memcpy(&m_Addr, &ip.m_Addr, sizeof(m_Addr)); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// set + +void CIp::SetSockAddr(struct sockaddr_in *sa) +{ + ::memcpy(&m_Addr, sa, sizeof(m_Addr)); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operator + +bool CIp::operator ==(const CIp &ip) const +{ + return ( (ip.m_Addr.sin_family == m_Addr.sin_family) && + (ip.m_Addr.sin_addr.s_addr == m_Addr.sin_addr.s_addr) && + (ip.m_Addr.sin_port == m_Addr.sin_port)) ; +} + +CIp::operator const char *() const +{ + return ::inet_ntoa(m_Addr.sin_addr); +} + + diff --git a/cip.h b/cip.h new file mode 100644 index 0000000..3a65fd6 --- /dev/null +++ b/cip.h @@ -0,0 +1,59 @@ +// +// cip.h +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cip_h +#define cip_h + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CIp +{ +public: + // constructors + CIp(); + //CIp(uint8, uint8, uint8, uint8); + CIp(const struct sockaddr_in *); + CIp(const char *); + CIp(const CIp &); + + // destructor + virtual ~CIp() {}; + + // sockaddr + void SetSockAddr(struct sockaddr_in *); + struct sockaddr_in *GetSockAddr(void) { return &m_Addr; } + + // operator + bool operator ==(const CIp &) const; + operator const char *() const; + +protected: + // data + struct sockaddr_in m_Addr; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cip_h */ diff --git a/codec2/codebooks.cpp b/codec2/codebooks.cpp new file mode 100644 index 0000000..bf319ce --- /dev/null +++ b/codec2/codebooks.cpp @@ -0,0 +1,964 @@ +/* + * This intermediary file and the files that used to create it are under + * The LGPL. See the file COPYING. + */ + +#include "defines.h" + +/* codebook/lsp1.txt */ +static float codes00[] = +{ + 225, + 250, + 275, + 300, + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600 +}; +/* codebook/lsp2.txt */ +static float codes01[] = +{ + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600, + 625, + 650, + 675, + 700 +}; +/* codebook/lsp3.txt */ +static float codes02[] = +{ + 500, + 550, + 600, + 650, + 700, + 750, + 800, + 850, + 900, + 950, + 1000, + 1050, + 1100, + 1150, + 1200, + 1250 +}; +/* codebook/lsp4.txt */ +static float codes03[] = +{ + 700, + 800, + 900, + 1000, + 1100, + 1200, + 1300, + 1400, + 1500, + 1600, + 1700, + 1800, + 1900, + 2000, + 2100, + 2200 +}; +/* codebook/lsp5.txt */ +static float codes04[] = +{ + 950, + 1050, + 1150, + 1250, + 1350, + 1450, + 1550, + 1650, + 1750, + 1850, + 1950, + 2050, + 2150, + 2250, + 2350, + 2450 +}; +/* codebook/lsp6.txt */ +static float codes05[] = +{ + 1100, + 1200, + 1300, + 1400, + 1500, + 1600, + 1700, + 1800, + 1900, + 2000, + 2100, + 2200, + 2300, + 2400, + 2500, + 2600 +}; +/* codebook/lsp7.txt */ +static float codes06[] = +{ + 1500, + 1600, + 1700, + 1800, + 1900, + 2000, + 2100, + 2200, + 2300, + 2400, + 2500, + 2600, + 2700, + 2800, + 2900, + 3000 +}; +/* codebook/lsp8.txt */ +static float codes07[] = +{ + 2300, + 2400, + 2500, + 2600, + 2700, + 2800, + 2900, + 3000 +}; +/* codebook/lsp9.txt */ +static float codes08[] = +{ + 2500, + 2600, + 2700, + 2800, + 2900, + 3000, + 3100, + 3200 +}; +/* codebook/lsp10.txt */ +static float codes09[] = +{ + 2900, + 3100, + 3300, + 3500 +}; + +const struct lsp_codebook lsp_cb[] = +{ + /* codebook/lsp1.txt */ + { + 1, + 4, + 16, + codes00 + }, + /* codebook/lsp2.txt */ + { + 1, + 4, + 16, + codes01 + }, + /* codebook/lsp3.txt */ + { + 1, + 4, + 16, + codes02 + }, + /* codebook/lsp4.txt */ + { + 1, + 4, + 16, + codes03 + }, + /* codebook/lsp5.txt */ + { + 1, + 4, + 16, + codes04 + }, + /* codebook/lsp6.txt */ + { + 1, + 4, + 16, + codes05 + }, + /* codebook/lsp7.txt */ + { + 1, + 4, + 16, + codes06 + }, + /* codebook/lsp8.txt */ + { + 1, + 3, + 8, + codes07 + }, + /* codebook/lsp9.txt */ + { + 1, + 3, + 8, + codes08 + }, + /* codebook/lsp10.txt */ + { + 1, + 2, + 4, + codes09 + }, + { 0, 0, 0, 0 } +}; + +/* codebook/dlsp1.txt */ +static float codes10[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 225, + 250, + 275, + 300, + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600, + 625, + 650, + 675, + 700, + 725, + 750, + 775, + 800 +}; +/* codebook/dlsp2.txt */ +static float codes11[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 225, + 250, + 275, + 300, + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600, + 625, + 650, + 675, + 700, + 725, + 750, + 775, + 800 +}; +/* codebook/dlsp3.txt */ +static float codes12[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 225, + 250, + 275, + 300, + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600, + 625, + 650, + 675, + 700, + 725, + 750, + 775, + 800 +}; +/* codebook/dlsp4.txt */ +static float codes13[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 250, + 300, + 350, + 400, + 450, + 500, + 550, + 600, + 650, + 700, + 750, + 800, + 850, + 900, + 950, + 1000, + 1050, + 1100, + 1150, + 1200, + 1250, + 1300, + 1350, + 1400 +}; +/* codebook/dlsp5.txt */ +static float codes14[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 250, + 300, + 350, + 400, + 450, + 500, + 550, + 600, + 650, + 700, + 750, + 800, + 850, + 900, + 950, + 1000, + 1050, + 1100, + 1150, + 1200, + 1250, + 1300, + 1350, + 1400 +}; +/* codebook/dlsp6.txt */ +static float codes15[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 250, + 300, + 350, + 400, + 450, + 500, + 550, + 600, + 650, + 700, + 750, + 800, + 850, + 900, + 950, + 1000, + 1050, + 1100, + 1150, + 1200, + 1250, + 1300, + 1350, + 1400 +}; +/* codebook/dlsp7.txt */ +static float codes16[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 225, + 250, + 275, + 300, + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600, + 625, + 650, + 675, + 700, + 725, + 750, + 775, + 800 +}; +/* codebook/dlsp8.txt */ +static float codes17[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 225, + 250, + 275, + 300, + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600, + 625, + 650, + 675, + 700, + 725, + 750, + 775, + 800 +}; +/* codebook/dlsp9.txt */ +static float codes18[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 225, + 250, + 275, + 300, + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600, + 625, + 650, + 675, + 700, + 725, + 750, + 775, + 800 +}; +/* codebook/dlsp10.txt */ +static float codes19[] = +{ + 25, + 50, + 75, + 100, + 125, + 150, + 175, + 200, + 225, + 250, + 275, + 300, + 325, + 350, + 375, + 400, + 425, + 450, + 475, + 500, + 525, + 550, + 575, + 600, + 625, + 650, + 675, + 700, + 725, + 750, + 775, + 800 +}; + +const struct lsp_codebook lsp_cbd[] = +{ + /* codebook/dlsp1.txt */ + { + 1, + 5, + 32, + codes10 + }, + /* codebook/dlsp2.txt */ + { + 1, + 5, + 32, + codes11 + }, + /* codebook/dlsp3.txt */ + { + 1, + 5, + 32, + codes12 + }, + /* codebook/dlsp4.txt */ + { + 1, + 5, + 32, + codes13 + }, + /* codebook/dlsp5.txt */ + { + 1, + 5, + 32, + codes14 + }, + /* codebook/dlsp6.txt */ + { + 1, + 5, + 32, + codes15 + }, + /* codebook/dlsp7.txt */ + { + 1, + 5, + 32, + codes16 + }, + /* codebook/dlsp8.txt */ + { + 1, + 5, + 32, + codes17 + }, + /* codebook/dlsp9.txt */ + { + 1, + 5, + 32, + codes18 + }, + /* codebook/dlsp10.txt */ + { + 1, + 5, + 32, + codes19 + }, + { 0, 0, 0, 0 } +}; + + +/* codebook/gecb.txt */ +static float codes30[] = +{ + 2.71, 12.0184, + 0.04675, -2.73881, + 0.120993, 8.38895, + -1.58028, -0.892307, + 1.19307, -1.91561, + 0.187101, -3.27679, + 0.332251, -7.66455, + -1.47944, 31.2461, + 1.52761, 27.7095, + -0.524379, 5.25012, + 0.55333, 7.4388, + -0.843451, -1.95299, + 2.26389, 8.61029, + 0.143143, 2.36549, + 0.616506, 1.28427, + -1.71133, 22.0967, + 1.00813, 17.3965, + -0.106718, 1.41891, + -0.136246, 14.2736, + -1.70909, -20.5319, + 1.65787, -3.39107, + 0.138049, -4.95785, + 0.536729, -1.94375, + 0.196307, 36.8519, + 1.27248, 22.5565, + -0.670219, -1.90604, + 0.382092, 6.40113, + -0.756911, -4.90102, + 1.82931, 4.6138, + 0.318794, 0.73683, + 0.612815, -2.07505, + -0.410151, 24.7871, + 1.77602, 13.1909, + 0.106457, -0.104492, + 0.192206, 10.1838, + -1.82442, -7.71565, + 0.931346, 4.34835, + 0.308813, -4.086, + 0.397143, -11.8089, + -0.048715, 41.2273, + 0.877342, 35.8503, + -0.759794, 0.476634, + 0.978593, 7.67467, + -1.19506, 3.03883, + 2.63989, -3.41106, + 0.191127, 3.60351, + 0.402932, 1.0843, + -2.15202, 18.1076, + 1.5468, 8.32271, + -0.143089, -4.07592, + -0.150142, 5.86674, + -1.40844, -3.2507, + 1.56615, -10.4132, + 0.178171, -10.2267, + 0.362164, -0.028556, + -0.070125, 24.3907, + 0.594752, 17.4828, + -0.28698, -6.90407, + 0.464818, 10.2055, + -1.00684, -14.3572, + 2.32957, -3.69161, + 0.335745, 2.40714, + 1.01966, -3.15565, + -1.25945, 7.9919, + 2.38369, 19.6806, + -0.094947, -2.41374, + 0.20933, 6.66477, + -2.22103, 1.37986, + 1.29239, 2.04633, + 0.243626, -0.890741, + 0.428773, -7.19366, + -1.11374, 41.3414, + 2.6098, 31.1405, + -0.446468, 2.53419, + 0.490104, 4.62757, + -1.11723, -3.24174, + 1.79156, 8.41493, + 0.156012, 0.183336, + 0.532447, 3.15455, + -0.764484, 18.514, + 0.952395, 11.7713, + -0.332567, 0.346987, + 0.202165, 14.7168, + -2.12924, -15.559, + 1.35358, -1.92679, + -0.010963, -16.3364, + 0.399053, -2.79057, + 0.750657, 31.1483, + 0.655743, 24.4819, + -0.45321, -0.735879, + 0.2869, 6.5467, + -0.715673, -12.3578, + 1.54849, 3.87217, + 0.271874, 0.802339, + 0.502073, -4.85485, + -0.497037, 17.7619, + 1.19116, 13.9544, + 0.01563, 1.33157, + 0.341867, 8.93537, + -2.31601, -5.39506, + 0.75861, 1.9645, + 0.24132, -3.23769, + 0.267151, -11.2344, + -0.273126, 32.6248, + 1.75352, 40.432, + -0.784011, 3.04576, + 0.705987, 5.66118, + -1.3864, 1.35356, + 2.37646, 1.67485, + 0.242973, 4.73218, + 0.491227, 0.354061, + -1.60676, 8.65895, + 1.16711, 5.9871, + -0.137601, -12.0417, + -0.251375, 10.3972, + -1.43151, -8.90411, + 0.98828, -13.209, + 0.261484, -6.35497, + 0.395932, -0.702529, + 0.283704, 26.8996, + 0.420959, 15.4418, + -0.355804, -13.7278, + 0.527372, 12.3985, + -1.16956, -15.9985, + 1.90669, -5.81605, + 0.354492, 3.85157, + 0.82576, -4.16264, + -0.49019, 13.0572, + 2.25577, 13.5264, + -0.004956, -3.23713, + 0.026709, 7.86645, + -1.81037, -0.451183, + 1.08383, -0.18362, + 0.135836, -2.26658, + 0.375812, -5.51225, + -1.96644, 38.6829, + 1.97799, 24.5655, + -0.704656, 6.35881, + 0.480786, 7.05175, + -0.976417, -2.42273, + 2.50215, 6.75935, + 0.083588, 3.2588, + 0.543629, 0.910013, + -1.23196, 23.0915, + 0.785492, 14.807, + -0.213554, 1.688, + 0.004748, 18.1718, + -1.54719, -16.1168, + 1.50104, -3.28114, + 0.080133, -4.63472, + 0.476592, -2.18093, + 0.44247, 40.304, + 1.07277, 27.592, + -0.594738, -4.16681, + 0.42248, 7.61609, + -0.927521, -7.27441, + 1.99162, 1.29636, + 0.291307, 2.39878, + 0.721081, -1.95062, + -0.804256, 24.9295, + 1.64839, 19.1197, + 0.060852, -0.590639, + 0.266085, 9.10325, + -1.9574, -2.88461, + 1.11693, 2.6724, + 0.35458, -2.74854, + 0.330733, -14.1561, + -0.527851, 39.5756, + 0.991152, 43.195, + -0.589619, 1.26919, + 0.787401, 8.73071, + -1.0138, 1.02507, + 2.8254, 1.89538, + 0.24089, 2.74557, + 0.427195, 2.54446, + -1.95311, 12.244, + 1.44862, 12.0607, + -0.210492, -3.37906, + -0.056713, 10.204, + -1.65237, -5.10274, + 1.29475, -12.2708, + 0.111608, -8.67592, + 0.326634, -1.16763, + 0.021781, 31.1258, + 0.455335, 21.4684, + -0.37544, -3.37121, + 0.39362, 11.302, + -0.851456, -19.4149, + 2.10703, -2.22886, + 0.373233, 1.92406, + 0.884438, -1.72058, + -0.975127, 9.84013, + 2.0033, 17.3954, + -0.036915, -1.11137, + 0.148456, 5.39997, + -1.91441, 4.77382, + 1.44791, 0.537122, + 0.194979, -1.03818, + 0.495771, -9.95502, + -1.05899, 32.9471, + 2.01122, 32.4544, + -0.30965, 4.71911, + 0.436082, 4.63552, + -1.23711, -1.25428, + 2.02274, 9.42834, + 0.190342, 1.46077, + 0.479017, 2.48479, + -1.07848, 16.2217, + 1.20764, 9.65421, + -0.258087, -1.67236, + 0.071852, 13.416, + -1.87723, -16.072, + 1.28957, -4.87118, + 0.067713, -13.4427, + 0.435551, -4.1655, + 0.46614, 30.5895, + 0.904895, 21.598, + -0.518369, -2.53205, + 0.337363, 5.63726, + -0.554975, -17.4005, + 1.69188, 1.14574, + 0.227934, 0.889297, + 0.587303, -5.72973, + -0.262133, 18.6666, + 1.39505, 17.0029, + -0.01909, 4.30838, + 0.304235, 12.6699, + -2.07406, -6.46084, + 0.920546, 1.21296, + 0.284927, -1.78547, + 0.209724, -16.024, + -0.636067, 31.5768, + 1.34989, 34.6775, + -0.971625, 5.30086, + 0.590249, 4.44971, + -1.56787, 3.60239, + 2.1455, 4.51666, + 0.296022, 4.12017, + 0.445299, 0.868772, + -1.44193, 14.1284, + 1.35575, 6.0074, + -0.012814, -7.49657, + -0.43, 8.50012, + -1.20469, -7.11326, + 1.10102, -6.83682, + 0.196463, -6.234, + 0.436747, -1.12979, + 0.141052, 22.8549, + 0.290821, 18.8114, + -0.529536, -7.73251, + 0.63428, 10.7898, + -1.33472, -20.3258, + 1.81564, -1.90332, + 0.394778, 3.79758, + 0.732682, -8.18382, + -0.741244, 11.7683 +}; + +const struct lsp_codebook ge_cb[] = +{ + /* codebook/gecb.txt */ + { + 2, + 8, + 256, + codes30 + }, + { 0, 0, 0, 0 } +}; diff --git a/codec2/codec2.cpp b/codec2/codec2.cpp new file mode 100644 index 0000000..9adbe59 --- /dev/null +++ b/codec2/codec2.cpp @@ -0,0 +1,1745 @@ +/*---------------------------------------------------------------------------*\ + + FILE........: codec2.c + AUTHOR......: David Rowe + DATE CREATED: 21/8/2010 + + Codec2 fully quantised encoder and decoder functions. If you want use + codec2, the codec2_xxx functions are for you. + +\*---------------------------------------------------------------------------*/ + +/* + Copyright (C) 2010 David Rowe + + 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 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, see . +*/ + +#include +#include +#include +#include +#include +#include + +#include "nlp.h" +#include "lpc.h" +#include "quantise.h" +#include "codec2.h" +#include "codec2_internal.h" + +#define HPF_BETA 0.125 +#define BPF_N 101 + +CKissFFT kiss; + +/*---------------------------------------------------------------------------* \ + + FUNCTION HEADERS + +\*---------------------------------------------------------------------------*/ + + + + +/*---------------------------------------------------------------------------*\ + + FUNCTIONS + +\*---------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: codec2_create + AUTHOR......: David Rowe + DATE CREATED: 21/8/2010 + + Create and initialise an instance of the codec. Returns a pointer + to the codec states or NULL on failure. One set of states is + sufficient for a full duuplex codec (i.e. an encoder and decoder). + You don't need separate states for encoders and decoders. See + c2enc.c and c2dec.c for examples. + +\*---------------------------------------------------------------------------*/ + +CCodec2::CCodec2(bool is_3200) +{ + c2.mode = is_3200 ? 3200 : 1600; + + /* store constants in a few places for convenience */ + + c2.c2const = c2const_create(8000, N_S); + c2.Fs = c2.c2const.Fs; + int n_samp = c2.n_samp = c2.c2const.n_samp; + int m_pitch = c2.m_pitch = c2.c2const.m_pitch; + + c2.Pn.resize(2*n_samp); + c2.Sn_.resize(2*n_samp); + c2.w.resize(m_pitch); + c2.Sn.resize(m_pitch); + + for(int i=0; i Aw[FFT_ENC]; + + /* only need to zero these out due to (unused) snr calculation */ + + for(i=0; i<2; i++) + for(j=1; j<=MAX_AMP; j++) + model[i].A[j] = 0.0; + + /* unpack bits from channel ------------------------------------*/ + + /* this will partially fill the model params for the 2 x 10ms + frames */ + + model[0].voiced = qt.unpack(bits, &nbit, 1); + model[1].voiced = qt.unpack(bits, &nbit, 1); + + Wo_index = qt.unpack(bits, &nbit, WO_BITS); + model[1].Wo = qt.decode_Wo(&c2.c2const, Wo_index, WO_BITS); + model[1].L = PI/model[1].Wo; + + e_index = qt.unpack(bits, &nbit, E_BITS); + e[1] = qt.decode_energy(e_index, E_BITS); + + for(i=0; i Aw[FFT_ENC]; + + /* only need to zero these out due to (unused) snr calculation */ + + for(i=0; i<4; i++) + for(j=1; j<=MAX_AMP; j++) + model[i].A[j] = 0.0; + + /* unpack bits from channel ------------------------------------*/ + + /* this will partially fill the model params for the 4 x 10ms + frames */ + + model[0].voiced = qt.unpack(bits, &nbit, 1); + + model[1].voiced = qt.unpack(bits, &nbit, 1); + Wo_index = qt.unpack(bits, &nbit, WO_BITS); + model[1].Wo = qt.decode_Wo(&c2.c2const, Wo_index, WO_BITS); + model[1].L = PI/model[1].Wo; + + e_index = qt.unpack(bits, &nbit, E_BITS); + e[1] = qt.decode_energy(e_index, E_BITS); + + model[2].voiced = qt.unpack(bits, &nbit, 1); + + model[3].voiced = qt.unpack(bits, &nbit, 1); + Wo_index = qt.unpack(bits, &nbit, WO_BITS); + model[3].Wo = qt.decode_Wo(&c2.c2const, Wo_index, WO_BITS); + model[3].L = PI/model[3].Wo; + + e_index = qt.unpack(bits, &nbit, E_BITS); + e[3] = qt.decode_energy(e_index, E_BITS); + + for(i=0; i Aw[], float gain) +{ + int i; + + /* LPC based phase synthesis */ + std::complex H[MAX_AMP+1]; + sample_phase(model, H, Aw); + phase_synth_zero_order(c2.n_samp, model, &c2.ex_phase, H); + + postfilter(model, &c2.bg_est); + synthesise(c2.n_samp, &(c2.fftr_inv_cfg), c2.Sn_.data(), model, c2.Pn.data(), 1); + + for(i=0; i 32767.0) + speech[i] = 32767; + else if (c2.Sn_[i] < -32767.0) + speech[i] = -32767; + else + speech[i] = c2.Sn_[i]; + } + +} + + +/*---------------------------------------------------------------------------* \ + + FUNCTION....: analyse_one_frame() + AUTHOR......: David Rowe + DATE CREATED: 23/8/2010 + + Extract sinusoidal model parameters from 80 speech samples (10ms of + speech). + +\*---------------------------------------------------------------------------*/ + +void CCodec2::analyse_one_frame(MODEL *model, const short *speech) +{ + std::complex Sw[FFT_ENC]; + float pitch; + int i; + int n_samp = c2.n_samp; + int m_pitch = c2.m_pitch; + + /* Read input speech */ + + for(i=0; iWo = TWO_PI/pitch; + model->L = PI/model->Wo; + + /* estimate model parameters */ + two_stage_pitch_refinement(&c2.c2const, model, Sw); + + /* estimate phases when doing ML experiments */ + estimate_amplitudes(model, Sw, 0); + est_voicing_mbe(&c2.c2const, model, Sw, c2.W); +} + + +/*---------------------------------------------------------------------------* \ + + FUNCTION....: ear_protection() + AUTHOR......: David Rowe + DATE CREATED: Nov 7 2012 + + Limits output level to protect ears when there are bit errors or the input + is overdriven. This doesn't correct or mask bit errors, just reduces the + worst of their damage. + +\*---------------------------------------------------------------------------*/ + +void CCodec2::ear_protection(float in_out[], int n) +{ + float max_sample, over, gain; + int i; + + /* find maximum sample in frame */ + + max_sample = 0.0; + for(i=0; i max_sample) + max_sample = in_out[i]; + + /* determine how far above set point */ + + over = max_sample/30000.0; + + /* If we are x dB over set point we reduce level by 2x dB, this + attenuates major excursions in amplitude (likely to be caused + by bit errors) more than smaller ones */ + + if (over > 1.0) + { + gain = 1.0/(over*over); + for(i=0; i H[], + std::complex A[] /* LPC analysis filter in freq domain */ +) +{ + int m, b; + float r; + + r = TWO_PI/(FFT_ENC); + + /* Sample phase at harmonics */ + + for(m=1; m<=model->L; m++) + { + b = (int)(m*model->Wo/r + 0.5); + H[m] = std::conj(A[b]); + } +} + + +/*---------------------------------------------------------------------------*\ + + phase_synth_zero_order() + + Synthesises phases based on SNR and a rule based approach. No phase + parameters are required apart from the SNR (which can be reduced to a + 1 bit V/UV decision per frame). + + The phase of each harmonic is modelled as the phase of a synthesis + filter excited by an impulse. In many Codec 2 modes the synthesis + filter is a LPC filter. Unlike the first order model the position + of the impulse is not transmitted, so we create an excitation pulse + train using a rule based approach. + + Consider a pulse train with a pulse starting time n=0, with pulses + repeated at a rate of Wo, the fundamental frequency. A pulse train + in the time domain is equivalent to harmonics in the frequency + domain. We can make an excitation pulse train using a sum of + sinsusoids: + + for(m=1; m<=L; m++) + ex[n] = cos(m*Wo*n) + + Note: the Octave script ../octave/phase.m is an example of this if + you would like to try making a pulse train. + + The phase of each excitation harmonic is: + + arg(E[m]) = mWo + + where E[m] are the complex excitation (freq domain) samples, + arg(x), just returns the phase of a complex sample x. + + As we don't transmit the pulse position for this model, we need to + synthesise it. Now the excitation pulses occur at a rate of Wo. + This means the phase of the first harmonic advances by N_SAMP samples + over a synthesis frame of N_SAMP samples. For example if Wo is pi/20 + (200 Hz), then over a 10ms frame (N_SAMP=80 samples), the phase of the + first harmonic would advance (pi/20)*80 = 4*pi or two complete + cycles. + + We generate the excitation phase of the fundamental (first + harmonic): + + arg[E[1]] = Wo*N_SAMP; + + We then relate the phase of the m-th excitation harmonic to the + phase of the fundamental as: + + arg(E[m]) = m*arg(E[1]) + + This E[m] then gets passed through the LPC synthesis filter to + determine the final harmonic phase. + + Comparing to speech synthesised using original phases: + + - Through headphones speech synthesised with this model is not as + good. Through a loudspeaker it is very close to original phases. + + - If there are voicing errors, the speech can sound clicky or + staticy. If V speech is mistakenly declared UV, this model tends to + synthesise impulses or clicks, as there is usually very little shift or + dispersion through the LPC synthesis filter. + + - When combined with LPC amplitude modelling there is an additional + drop in quality. I am not sure why, theory is interformant energy + is raised making any phase errors more obvious. + + NOTES: + + 1/ This synthesis model is effectively the same as a simple LPC-10 + vocoders, and yet sounds much better. Why? Conventional wisdom + (AMBE, MELP) says mixed voicing is required for high quality + speech. + + 2/ I am pretty sure the Lincoln Lab sinusoidal coding guys (like xMBE + also from MIT) first described this zero phase model, I need to look + up the paper. + + 3/ Note that this approach could cause some discontinuities in + the phase at the edge of synthesis frames, as no attempt is made + to make sure that the phase tracks are continuous (the excitation + phases are continuous, but not the final phases after filtering + by the LPC spectra). Technically this is a bad thing. However + this may actually be a good thing, disturbing the phase tracks a + bit. More research needed, e.g. test a synthesis model that adds + a small delta-W to make phase tracks line up for voiced + harmonics. + +\*---------------------------------------------------------------------------*/ + +void CCodec2::phase_synth_zero_order( + int n_samp, + MODEL *model, + float *ex_phase, /* excitation phase of fundamental */ + std::complex H[] /* L synthesis filter freq domain samples */ + +) +{ + int m; + float new_phi; + std::complex Ex[MAX_AMP+1]; /* excitation samples */ + std::complex A_[MAX_AMP+1]; /* synthesised harmonic samples */ + + /* + Update excitation fundamental phase track, this sets the position + of each pitch pulse during voiced speech. After much experiment + I found that using just this frame's Wo improved quality for UV + sounds compared to interpolating two frames Wo like this: + + ex_phase[0] += (*prev_Wo+model->Wo)*N_SAMP/2; + */ + + ex_phase[0] += (model->Wo)*n_samp; + ex_phase[0] -= TWO_PI*floorf(ex_phase[0]/TWO_PI + 0.5); + + for(m=1; m<=model->L; m++) + { + + /* generate excitation */ + + if (model->voiced) + { + Ex[m] = std::polar(1.0f, ex_phase[0] * m); + } + else + { + + /* When a few samples were tested I found that LPC filter + phase is not needed in the unvoiced case, but no harm in + keeping it. + */ + float phi = TWO_PI*(float)codec2_rand()/CODEC2_RAND_MAX; + Ex[m] = std::polar(1.0f, phi); + } + + /* filter using LPC filter */ + + A_[m].real(H[m].real() * Ex[m].real() - H[m].imag() * Ex[m].imag()); + A_[m].imag(H[m].imag() * Ex[m].real() + H[m].real() * Ex[m].imag()); + + /* modify sinusoidal phase */ + + new_phi = atan2f(A_[m].imag(), A_[m].real()+1E-12); + model->phi[m] = new_phi; + } + +} + +/*---------------------------------------------------------------------------*\ + + postfilter() + + The post filter is designed to help with speech corrupted by + background noise. The zero phase model tends to make speech with + background noise sound "clicky". With high levels of background + noise the low level inter-formant parts of the spectrum will contain + noise rather than speech harmonics, so modelling them as voiced + (i.e. a continuous, non-random phase track) is inaccurate. + + Some codecs (like MBE) have a mixed voicing model that breaks the + spectrum into voiced and unvoiced regions. Several bits/frame + (5-12) are required to transmit the frequency selective voicing + information. Mixed excitation also requires accurate voicing + estimation (parameter estimators always break occasionally under + exceptional conditions). + + In our case we use a post filter approach which requires no + additional bits to be transmitted. The decoder measures the average + level of the background noise during unvoiced frames. If a harmonic + is less than this level it is made unvoiced by randomising it's + phases. + + This idea is rather experimental. Some potential problems that may + happen: + + 1/ If someone says "aaaaaaaahhhhhhhhh" will background estimator track + up to speech level? This would be a bad thing. + + 2/ If background noise suddenly dissapears from the source speech does + estimate drop quickly? What is noise suddenly re-appears? + + 3/ Background noise with a non-flat sepctrum. Current algorithm just + comsiders spectrum as a whole, but this could be broken up into + bands, each with their own estimator. + + 4/ Males and females with the same level of background noise. Check + performance the same. Changing Wo affects width of each band, may + affect bg energy estimates. + + 5/ Not sure what happens during long periods of voiced speech + e.g. "sshhhhhhh" + +\*---------------------------------------------------------------------------*/ + +#define BG_THRESH 40.0 // only consider low levels signals for bg_est +#define BG_BETA 0.1 // averaging filter constant +#define BG_MARGIN 6.0 // harmonics this far above BG noise are + // randomised. Helped make bg noise less + // spikey (impulsive) for mmt1, but speech was + // perhaps a little rougher. + +void CCodec2::postfilter( MODEL *model, float *bg_est ) +{ + int m, uv; + float e, thresh; + + /* determine average energy across spectrum */ + + e = 1E-12; + for(m=1; m<=model->L; m++) + e += model->A[m]*model->A[m]; + + assert(e > 0.0); + e = 10.0*log10f(e/model->L); + + /* If beneath threhold, update bg estimate. The idea + of the threshold is to prevent updating during high level + speech. */ + + if ((e < BG_THRESH) && !model->voiced) + *bg_est = *bg_est*(1.0 - BG_BETA) + e*BG_BETA; + + /* now mess with phases during voiced frames to make any harmonics + less then our background estimate unvoiced. + */ + + uv = 0; + thresh = powf(10.0f, (*bg_est + BG_MARGIN)/20.0f); + if (model->voiced) + for(m=1; m<=model->L; m++) + if (model->A[m] < thresh) + { + model->phi[m] = (TWO_PI/CODEC2_RAND_MAX)*(float)codec2_rand(); + uv++; + } +} + +C2CONST CCodec2::c2const_create(int Fs, float framelength_s) +{ + C2CONST c2const; + + assert((Fs == 8000) || (Fs == 16000)); + c2const.Fs = Fs; + c2const.n_samp = round(Fs*framelength_s); + c2const.max_amp = floor(Fs*P_MAX_S/2); + c2const.p_min = floor(Fs*P_MIN_S); + c2const.p_max = floor(Fs*P_MAX_S); + c2const.m_pitch = floor(Fs*M_PITCH_S); + c2const.Wo_min = TWO_PI/c2const.p_max; + c2const.Wo_max = TWO_PI/c2const.p_min; + + if (Fs == 8000) + { + c2const.nw = 279; + } + else + { + c2const.nw = 511; /* actually a bit shorter in time but lets us maintain constant FFT size */ + } + + c2const.tw = Fs*TW_S; + + /* + fprintf(stderr, "max_amp: %d m_pitch: %d\n", c2const.n_samp, c2const.m_pitch); + fprintf(stderr, "p_min: %d p_max: %d\n", c2const.p_min, c2const.p_max); + fprintf(stderr, "Wo_min: %f Wo_max: %f\n", c2const.Wo_min, c2const.Wo_max); + fprintf(stderr, "nw: %d tw: %d\n", c2const.nw, c2const.tw); + */ + + return c2const; +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: make_analysis_window + AUTHOR......: David Rowe + DATE CREATED: 11/5/94 + + Init function that generates the time domain analysis window and it's DFT. + +\*---------------------------------------------------------------------------*/ + +void CCodec2::make_analysis_window(C2CONST *c2const, FFT_STATE *fft_fwd_cfg, float w[], float W[]) +{ + float m; + std::complex wshift[FFT_ENC]; + int i,j; + int m_pitch = c2const->m_pitch; + int nw = c2const->nw; + + /* + Generate Hamming window centered on M-sample pitch analysis window + + 0 M/2 M-1 + |-------------|-------------| + |-------|-------| + nw samples + + All our analysis/synthsis is centred on the M/2 sample. + */ + + m = 0.0; + for(i=0; i temp[FFT_ENC]; + + for(i=0; i(0.0f, 0.0f); + } + for(i=0; i Sw[], float Sn[], float w[]) +{ + int i; + int m_pitch = c2const->m_pitch; + int nw = c2const->nw; + + for(i=0; i(0.0f, 0.0f); + } + + /* Centre analysis window on time axis, we need to arrange input + to FFT this way to make FFT phases correct */ + + /* move 2nd half to start of FFT input vector */ + + for(i=0; i Sw[]) +{ + float pmin,pmax,pstep; /* pitch refinment minimum, maximum and step */ + + /* Coarse refinement */ + + pmax = TWO_PI/model->Wo + 5; + pmin = TWO_PI/model->Wo - 5; + pstep = 1.0; + hs_pitch_refinement(model, Sw, pmin, pmax, pstep); + + /* Fine refinement */ + + pmax = TWO_PI/model->Wo + 1; + pmin = TWO_PI/model->Wo - 1; + pstep = 0.25; + hs_pitch_refinement(model,Sw,pmin,pmax,pstep); + + /* Limit range */ + + if (model->Wo < TWO_PI/c2const->p_max) + model->Wo = TWO_PI/c2const->p_max; + if (model->Wo > TWO_PI/c2const->p_min) + model->Wo = TWO_PI/c2const->p_min; + + model->L = floorf(PI/model->Wo); + + /* trap occasional round off issues with floorf() */ + if (model->Wo*model->L >= 0.95*PI) + { + model->L--; + } + assert(model->Wo*model->L < PI); +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: hs_pitch_refinement + AUTHOR......: David Rowe + DATE CREATED: 27/5/94 + + Harmonic sum pitch refinement function. + + pmin pitch search range minimum + pmax pitch search range maximum + step pitch search step size + model current pitch estimate in model.Wo + + model refined pitch estimate in model.Wo + +\*---------------------------------------------------------------------------*/ + +void CCodec2::hs_pitch_refinement(MODEL *model, std::complex Sw[], float pmin, float pmax, float pstep) +{ + int m; /* loop variable */ + int b; /* bin for current harmonic centre */ + float E; /* energy for current pitch*/ + float Wo; /* current "test" fundamental freq. */ + float Wom; /* Wo that maximises E */ + float Em; /* mamimum energy */ + float r, one_on_r; /* number of rads/bin */ + float p; /* current pitch */ + + /* Initialisation */ + + model->L = PI/model->Wo; /* use initial pitch est. for L */ + Wom = model->Wo; + Em = 0.0; + r = TWO_PI/FFT_ENC; + one_on_r = 1.0/r; + + /* Determine harmonic sum for a range of Wo values */ + + for(p=pmin; p<=pmax; p+=pstep) + { + E = 0.0; + Wo = TWO_PI/p; + + /* Sum harmonic magnitudes */ + for(m=1; m<=model->L; m++) + { + b = (int)(m*Wo*one_on_r + 0.5); + E += Sw[b].real() * Sw[b].real() + Sw[b].imag() * Sw[b].imag(); + } + /* Compare to see if this is a maximum */ + + if (E > Em) + { + Em = E; + Wom = Wo; + } + } + + model->Wo = Wom; +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: estimate_amplitudes + AUTHOR......: David Rowe + DATE CREATED: 27/5/94 + + Estimates the complex amplitudes of the harmonics. + +\*---------------------------------------------------------------------------*/ + +void CCodec2::estimate_amplitudes(MODEL *model, std::complex Sw[], int est_phase) +{ + int i,m; /* loop variables */ + int am,bm; /* bounds of current harmonic */ + float den; /* denominator of amplitude expression */ + + float r = TWO_PI/FFT_ENC; + float one_on_r = 1.0/r; + + for(m=1; m<=model->L; m++) + { + /* Estimate ampltude of harmonic */ + + den = 0.0; + am = (int)((m - 0.5)*model->Wo*one_on_r + 0.5); + bm = (int)((m + 0.5)*model->Wo*one_on_r + 0.5); + + for(i=am; iA[m] = sqrtf(den); + + if (est_phase) + { + int b = (int)(m*model->Wo/r + 0.5); /* DFT bin of centre of current harmonic */ + + /* Estimate phase of harmonic, this is expensive in CPU for + embedded devicesso we make it an option */ + + model->phi[m] = atan2f(Sw[b].imag(), Sw[b].real()); + } + } +} + +/*---------------------------------------------------------------------------*\ + + est_voicing_mbe() + + Returns the error of the MBE cost function for a fiven F0. + + Note: I think a lot of the operations below can be simplified as + W[].imag = 0 and has been normalised such that den always equals 1. + +\*---------------------------------------------------------------------------*/ + +float CCodec2::est_voicing_mbe( C2CONST *c2const, MODEL *model, std::complex Sw[], float W[]) +{ + int l,al,bl,m; /* loop variables */ + std::complex Am; /* amplitude sample for this band */ + int offset; /* centers Hw[] about current harmonic */ + float den; /* denominator of Am expression */ + float error; /* accumulated error between original and synthesised */ + float Wo; + float sig, snr; + float elow, ehigh, eratio; + float sixty; + std::complex Ew(0, 0); + + int l_1000hz = model->L*1000.0/(c2const->Fs/2); + sig = 1E-4; + for(l=1; l<=l_1000hz; l++) + { + sig += model->A[l]*model->A[l]; + } + + Wo = model->Wo; + error = 1E-4; + + /* Just test across the harmonics in the first 1000 Hz */ + + for(l=1; l<=l_1000hz; l++) + { + Am = std::complex(0.0f, 0.0f); + den = 0.0; + al = ceilf((l - 0.5)*Wo*FFT_ENC/TWO_PI); + bl = ceilf((l + 0.5)*Wo*FFT_ENC/TWO_PI); + + /* Estimate amplitude of harmonic assuming harmonic is totally voiced */ + + offset = FFT_ENC/2 - l*Wo*FFT_ENC/TWO_PI + 0.5; + for(m=al; m V_THRESH) + model->voiced = 1; + else + model->voiced = 0; + + /* post processing, helps clean up some voicing errors ------------------*/ + + /* + Determine the ratio of low freqency to high frequency energy, + voiced speech tends to be dominated by low frequency energy, + unvoiced by high frequency. This measure can be used to + determine if we have made any gross errors. + */ + + int l_2000hz = model->L*2000.0/(c2const->Fs/2); + int l_4000hz = model->L*4000.0/(c2const->Fs/2); + elow = ehigh = 1E-4; + for(l=1; l<=l_2000hz; l++) + { + elow += model->A[l]*model->A[l]; + } + for(l=l_2000hz; l<=l_4000hz; l++) + { + ehigh += model->A[l]*model->A[l]; + } + eratio = 10.0*log10f(elow/ehigh); + + /* Look for Type 1 errors, strongly V speech that has been + accidentally declared UV */ + + if (model->voiced == 0) + if (eratio > 10.0) + model->voiced = 1; + + /* Look for Type 2 errors, strongly UV speech that has been + accidentally declared V */ + + if (model->voiced == 1) + { + if (eratio < -10.0) + model->voiced = 0; + + /* A common source of Type 2 errors is the pitch estimator + gives a low (50Hz) estimate for UV speech, which gives a + good match with noise due to the close harmoonic spacing. + These errors are much more common than people with 50Hz3 + pitch, so we have just a small eratio threshold. */ + + sixty = 60.0*TWO_PI/c2const->Fs; + if ((eratio < -4.0) && (model->Wo <= sixty)) + model->voiced = 0; + } + //printf(" v: %d snr: %f eratio: %3.2f %f\n",model->voiced,snr,eratio,dF0); + + return snr; +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: make_synthesis_window + AUTHOR......: David Rowe + DATE CREATED: 11/5/94 + + Init function that generates the trapezoidal (Parzen) sythesis window. + +\*---------------------------------------------------------------------------*/ + +void CCodec2::make_synthesis_window(C2CONST *c2const, float Pn[]) +{ + int i; + float win; + int n_samp = c2const->n_samp; + int tw = c2const->tw; + + /* Generate Parzen window in time domain */ + + win = 0.0; + for(i=0; i Sw_[FFT_DEC/2+1]; /* DFT of synthesised signal */ + float sw_[FFT_DEC]; /* synthesised signal */ + + if (shift) + { + /* Update memories */ + for(i=0; iL; l++) + { + b = (int)(l*model->Wo*FFT_DEC/TWO_PI + 0.5); + if (b > ((FFT_DEC/2)-1)) + { + b = (FFT_DEC/2)-1; + } + Sw_[b] = std::polar(model->A[l], model->phi[l]); + } + + /* Perform inverse DFT */ + + kiss.fftri(*fftr_inv_cfg, Sw_,sw_); + + /* Overlap add to previous samples */ + + for(i=0; ivoiced && !prev->voiced && !next->voiced) + { + interp->voiced = 0; + } + + /* Wo depends on voicing of this and adjacent frames */ + + if (interp->voiced) + { + if (prev->voiced && next->voiced) + interp->Wo = (1.0 - weight)*prev->Wo + weight*next->Wo; + if (!prev->voiced && next->voiced) + interp->Wo = next->Wo; + if (prev->voiced && !next->voiced) + interp->Wo = prev->Wo; + } + else + { + interp->Wo = Wo_min; + } + interp->L = PI/interp->Wo; +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: interp_energy() + AUTHOR......: David Rowe + DATE CREATED: 22 May 2012 + + Interpolates centre 10ms sample of energy given two samples 20ms + apart. + +\*---------------------------------------------------------------------------*/ + +float CCodec2::interp_energy(float prev_e, float next_e) +{ + //return powf(10.0, (log10f(prev_e) + log10f(next_e))/2.0); + return sqrtf(prev_e * next_e); //looks better is math. identical and faster math +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: interpolate_lsp_ver2() + AUTHOR......: David Rowe + DATE CREATED: 22 May 2012 + + Weighted interpolation of LSPs. + +\*---------------------------------------------------------------------------*/ + +void CCodec2::interpolate_lsp_ver2(float interp[], float prev[], float next[], float weight, int order) +{ + int i; + + for(i=0; i. +*/ + +#ifndef __CODEC2__ +#define __CODEC2__ + +#include + +#include "codec2_internal.h" +#include "defines.h" +#include "kiss_fft.h" +#include "nlp.h" +#include "quantise.h" + +#define CODEC2_MODE_3200 0 +#define CODEC2_MODE_1600 2 + +#ifndef CODEC2_MODE_EN_DEFAULT +#define CODEC2_MODE_EN_DEFAULT 1 +#endif + +#define CODEC2_RAND_MAX 32767 + +class CCodec2 +{ +public: + CCodec2(bool is_3200); + ~CCodec2(); + void codec2_encode(unsigned char *bits, const short *speech_in); + void codec2_decode(short *speech_out, const unsigned char *bits); + void codec2_set_mode(bool); + bool codec2_get_mode() {return (c2.mode == 3200); }; + int codec2_samples_per_frame(); + int codec2_bits_per_frame(); + +private: + // merged from other files + void sample_phase(MODEL *model, std::complex filter_phase[], std::complex A[]); + void phase_synth_zero_order(int n_samp, MODEL *model, float *ex_phase, std::complex filter_phase[]); + void postfilter(MODEL *model, float *bg_est); + + C2CONST c2const_create(int Fs, float framelength_ms); + + void make_analysis_window(C2CONST *c2const, FFT_STATE *fft_fwd_cfg, float w[], float W[]); + void dft_speech(C2CONST *c2const, FFT_STATE &fft_fwd_cfg, std::complex Sw[], float Sn[], float w[]); + void two_stage_pitch_refinement(C2CONST *c2const, MODEL *model, std::complex Sw[]); + void estimate_amplitudes(MODEL *model, std::complex Sw[], int est_phase); + float est_voicing_mbe(C2CONST *c2const, MODEL *model, std::complex Sw[], float W[]); + void make_synthesis_window(C2CONST *c2const, float Pn[]); + void synthesise(int n_samp, FFTR_STATE *fftr_inv_cfg, float Sn_[], MODEL *model, float Pn[], int shift); + int codec2_rand(void); + void hs_pitch_refinement(MODEL *model, std::complex Sw[], float pmin, float pmax, float pstep); + + void interp_Wo(MODEL *interp, MODEL *prev, MODEL *next, float Wo_min); + void interp_Wo2(MODEL *interp, MODEL *prev, MODEL *next, float weight, float Wo_min); + float interp_energy(float prev, float next); + void interpolate_lsp_ver2(float interp[], float prev[], float next[], float weight, int order); + + void analyse_one_frame(MODEL *model, const short *speech); + void synthesise_one_frame(short speech[], MODEL *model, std::complex Aw[], float gain); + void codec2_encode_3200(unsigned char *bits, const short *speech); + void codec2_encode_1600(unsigned char *bits, const short *speech); + void codec2_decode_3200(short *speech, const unsigned char *bits); + void codec2_decode_1600(short *speech, const unsigned char *bits); + void ear_protection(float in_out[], int n); + void lsp_to_lpc(float *freq, float *ak, int lpcrdr); + + void (CCodec2::*encode)(unsigned char *bits, const short *speech); + void (CCodec2::*decode)(short *speech, const unsigned char *bits); + Cnlp nlp; + CQuantize qt; + CODEC2 c2; +}; + +#endif diff --git a/codec2/codec2_internal.h b/codec2/codec2_internal.h new file mode 100644 index 0000000..1b037e1 --- /dev/null +++ b/codec2/codec2_internal.h @@ -0,0 +1,67 @@ +/*---------------------------------------------------------------------------*\ + + FILE........: codec2_internal.h + AUTHOR......: David Rowe + DATE CREATED: April 16 2012 + + Header file for Codec2 internal states, exposed via this header + file to assist in testing. + +\*---------------------------------------------------------------------------*/ + +/* + Copyright (C) 2012 David Rowe + + 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 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, see . +*/ + +#ifndef __CODEC2_INTERNAL__ +#define __CODEC2_INTERNAL__ + +#include "kiss_fft.h" + +using CODEC2 = struct codec2_tag { + int mode; + int Fs; + int n_samp; + int m_pitch; + int gray; /* non-zero for gray encoding */ + int lpc_pf; /* LPC post filter on */ + int bass_boost; /* LPC post filter bass boost */ + int smoothing; /* enable smoothing for channels with errors */ + float ex_phase; /* excitation model phase track */ + float bg_est; /* background noise estimate for post filter */ + float prev_f0_enc; /* previous frame's f0 estimate */ + float prev_e_dec; /* previous frame's LPC energy */ + float beta; /* LPC post filter parameters */ + float gamma; + float xq_enc[2]; /* joint pitch and energy VQ states */ + float xq_dec[2]; + float W[FFT_ENC]; /* DFT of w[] */ + float hpf_states[2]; /* high pass filter states */ + float prev_lsps_dec[LPC_ORD]; /* previous frame's LSPs */ + float *softdec; /* optional soft decn bits from demod */ + MODEL prev_model_dec; /* previous frame's model parameters */ + C2CONST c2const; + FFT_STATE fft_fwd_cfg; /* forward FFT config */ + FFTR_STATE fftr_fwd_cfg; /* forward real FFT config */ + FFTR_STATE fftr_inv_cfg; /* inverse FFT config */ + std::vector w; /* [m_pitch] time domain hamming window */ + std::vector Pn; /* [2*n_samp] trapezoidal synthesis window */ + std::vector Sn; /* [m_pitch] input speech */ + std::vector Sn_; /* [2*n_samp] synthesised output speech */ + std::vector bpf_buf; /* buffer for band pass filter */ +}; + +#endif diff --git a/codec2/defines.h b/codec2/defines.h new file mode 100644 index 0000000..f201313 --- /dev/null +++ b/codec2/defines.h @@ -0,0 +1,127 @@ +/*---------------------------------------------------------------------------*\ + + FILE........: defines.h + AUTHOR......: David Rowe + DATE CREATED: 23/4/93 + + Defines and structures used throughout the codec. + +\*---------------------------------------------------------------------------*/ + +/* + Copyright (C) 2009 David Rowe + + 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 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, see . +*/ + +#ifndef __DEFINES__ +#define __DEFINES__ + +#include +#include + +/*---------------------------------------------------------------------------*\ + + DEFINES + +\*---------------------------------------------------------------------------*/ + +/* General defines */ + +#define N_S 0.01 /* internal proc frame length in secs */ +#define TW_S 0.005 /* trapezoidal synth window overlap */ +#define MAX_AMP 160 /* maximum number of harmonics */ +#ifndef PI +#define PI 3.141592654 /* mathematical constant */ +#endif +#define TWO_PI 6.283185307 /* mathematical constant */ +#define MAX_STR 2048 /* maximum string size */ + +#define FFT_ENC 512 /* size of FFT used for encoder */ +#define FFT_DEC 512 /* size of FFT used in decoder */ +#define V_THRESH 6.0 /* voicing threshold in dB */ +#define LPC_ORD 10 /* LPC order */ +#define LPC_ORD_LOW 6 /* LPC order for lower rates */ + +/* Pitch estimation defines */ + +#define M_PITCH_S 0.0400 /* pitch analysis window in s */ +#define P_MIN_S 0.0025 /* minimum pitch period in s */ +#define P_MAX_S 0.0200 /* maximum pitch period in s */ +#define MAXFACTORS 32 // e.g. an fft of length 128 has 4 factors + // as far as kissfft is concerned 4*4*4*2 + +/*---------------------------------------------------------------------------*\ + + TYPEDEFS + +\*---------------------------------------------------------------------------*/ + +/* Structure to hold constants calculated at run time based on sample rate */ + +using C2CONST = struct c2const_tag +{ + int Fs; /* sample rate of this instance */ + int n_samp; /* number of samples per 10ms frame at Fs */ + int max_amp; /* maximum number of harmonics */ + int m_pitch; /* pitch estimation window size in samples */ + int p_min; /* minimum pitch period in samples */ + int p_max; /* maximum pitch period in samples */ + float Wo_min; + float Wo_max; + int nw; /* analysis window size in samples */ + int tw; /* trapezoidal synthesis window overlap */ +}; + +/* Structure to hold model parameters for one frame */ + +using MODEL = struct model_tag +{ + float Wo; /* fundamental frequency estimate in radians */ + int L; /* number of harmonics */ + float A[MAX_AMP+1]; /* amplitiude of each harmonic */ + float phi[MAX_AMP+1]; /* phase of each harmonic */ + int voiced; /* non-zero if this frame is voiced */ +}; + +/* describes each codebook */ + +struct lsp_codebook +{ + int k; /* dimension of vector */ + int log2m; /* number of bits in m */ + int m; /* elements in codebook */ + float *cb; /* The elements */ +}; + +using FFT_STATE = struct fft_state_tag +{ + int nfft; + bool inverse; + int factors[2*MAXFACTORS]; + std::vector> twiddles; +}; + +using FFTR_STATE = struct fftr_state_tag +{ + FFT_STATE substate; + std::vector> tmpbuf; + std::vector> super_twiddles; +}; + +extern const struct lsp_codebook lsp_cb[]; +extern const struct lsp_codebook lsp_cbd[]; +extern const struct lsp_codebook ge_cb[]; + +#endif diff --git a/codec2/kiss_fft.cpp b/codec2/kiss_fft.cpp new file mode 100644 index 0000000..cefb846 --- /dev/null +++ b/codec2/kiss_fft.cpp @@ -0,0 +1,435 @@ +/* +Copyright (c) 2003-2010, Mark Borgerding + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include + +#include "defines.h" +#include "kiss_fft.h" + +void CKissFFT::kf_bfly2(std::complex *Fout, const size_t fstride, FFT_STATE &st, int m) +{ + std::complex *Fout2; + std::complex *tw1 = st.twiddles.data(); + std::complex t; + Fout2 = Fout + m; + do + { + t = *Fout2 * *tw1; + tw1 += fstride; + *Fout2 = *Fout - t; + *Fout += t; + ++Fout2; + ++Fout; + } + while (--m); +} + +void CKissFFT::kf_bfly3(std::complex * Fout, const size_t fstride, FFT_STATE &st, int m) +{ + const size_t m2 = 2 * m; + std::complex *tw1,*tw2; + std::complex scratch[5]; + std::complex epi3; + epi3 = st.twiddles[fstride*m]; + + tw1 = tw2 = st.twiddles.data(); + + do + { + scratch[1] = Fout[m] * *tw1; + scratch[2] = Fout[m2] * *tw2; + + scratch[3] = scratch[1] + scratch[2]; + scratch[0] = scratch[1] - scratch[2]; + tw1 += fstride; + tw2 += fstride*2; + + Fout[m] = *Fout - (0.5f * scratch[3]); + + scratch[0] *= epi3.imag(); + + *Fout += scratch[3]; + + Fout[m2].real(Fout[m].real() + scratch[0].imag()); + Fout[m2].imag(Fout[m].imag() - scratch[0].real()); + + Fout[m].real(Fout[m].real() - scratch[0].imag()); + Fout[m].imag(Fout[m].imag() + scratch[0].real()); + + ++Fout; + } + while(--m); +} + +void CKissFFT::kf_bfly4(std::complex *Fout, const size_t fstride, FFT_STATE &st, int m) +{ + std::complex *tw1,*tw2,*tw3; + std::complex scratch[6]; + int k = m; + const int m2 = 2 * m; + const int m3 = 3 * m; + + + tw3 = tw2 = tw1 = st.twiddles.data(); + + do + { + scratch[0] = Fout[m] * *tw1; + scratch[1] = Fout[m2] * *tw2; + scratch[2] = Fout[m3] * *tw3; + + scratch[5] = *Fout - scratch[1]; + *Fout += scratch[1]; + scratch[3] = scratch[0] + scratch[2]; + scratch[4] = scratch[0] - scratch[2]; + Fout[m2] = *Fout - scratch[3]; + tw1 += fstride; + tw2 += fstride*2; + tw3 += fstride*3; + *Fout += scratch[3]; + + if(st.inverse) + { + Fout[m].real(scratch[5].real() - scratch[4].imag()); + Fout[m].imag(scratch[5].imag() + scratch[4].real()); + Fout[m3].real(scratch[5].real() + scratch[4].imag()); + Fout[m3].imag(scratch[5].imag() - scratch[4].real()); + } + else + { + Fout[m].real(scratch[5].real() + scratch[4].imag()); + Fout[m].imag(scratch[5].imag() - scratch[4].real()); + Fout[m3].real(scratch[5].real() - scratch[4].imag()); + Fout[m3].imag(scratch[5].imag() + scratch[4].real()); + } + ++Fout; + } + while(--k); +} + +void CKissFFT::kf_bfly5(std::complex * Fout, const size_t fstride, FFT_STATE &st, int m) +{ + std::complex scratch[13]; + std::complex *twiddles = st.twiddles.data(); + auto ya = twiddles[fstride*m]; + auto yb = twiddles[fstride*2*m]; + + auto Fout0 = Fout; + auto Fout1 = Fout0 + m; + auto Fout2 = Fout0 + 2 * m; + auto Fout3 = Fout0 + 3 * m; + auto Fout4 = Fout0 + 4 * m; + + auto tw = st.twiddles.data(); + for (int u=0; u *Fout, const size_t fstride, FFT_STATE &st, int m, int p) +{ + auto twiddles = st.twiddles.data(); + std::complex t; + int Norig = st.nfft; + + std::vector> scratch(p); + + for (int u=0; u= Norig) twidx-=Norig; + t = scratch[q] * twiddles[twidx]; + Fout[k] += t; + } + k += m; + } + } + scratch.clear(); +} + +void CKissFFT::kf_work(std::complex *Fout, const std::complex *f, const size_t fstride, int in_stride, int *factors, FFT_STATE &st) +{ + auto Fout_beg = Fout; + const int p = *factors++; /* the radix */ + const int m = *factors++; /* stage's fft length/p */ + const std::complex *Fout_end = Fout + p*m; + + if (m==1) + { + do + { + *Fout = *f; + f += fstride*in_stride; + } + while( ++Fout != Fout_end ); + } + else + { + do + { + // recursive call: + // DFT of size m*p performed by doing + // p instances of smaller DFTs of size m, + // each one takes a decimated version of the input + kf_work( Fout, f, fstride*p, in_stride, factors, st); + f += fstride*in_stride; + } + while( (Fout += m) != Fout_end ); + } + + Fout=Fout_beg; + + // recombine the p smaller DFTs + switch (p) + { + case 2: + kf_bfly2(Fout,fstride,st,m); + break; + case 3: + kf_bfly3(Fout,fstride,st,m); + break; + case 4: + kf_bfly4(Fout,fstride,st,m); + break; + case 5: + kf_bfly5(Fout,fstride,st,m); + break; + default: + kf_bfly_generic(Fout,fstride,st,m,p); + break; + } +} + +/* facbuf is populated by p1,m1,p2,m2, ... + where + p[i] * m[i] = m[i-1] + m0 = n */ +void CKissFFT::kf_factor(int n,int * facbuf) +{ + int p=4; + double floor_sqrt; + floor_sqrt = floorf( sqrtf((double)n) ); + + /*factor out powers of 4, powers of 2, then any remaining primes */ + do + { + while (n % p) + { + switch (p) + { + case 4: + p = 2; + break; + case 2: + p = 3; + break; + default: + p += 2; + break; + } + if (p > floor_sqrt) + p = n; /* no more factors, skip to end */ + } + n /= p; + *facbuf++ = p; + *facbuf++ = n; + } + while (n > 1); +} + +void CKissFFT::fft_alloc(FFT_STATE &state, const int nfft, bool inverse_fft) +{ + state.twiddles.resize(nfft); + + state.nfft = nfft; + state.inverse = inverse_fft; + + for (int i=0; i *fin, std::complex *fout, int in_stride) +{ + if (fin == fout) + { + //NOTE: this is not really an in-place FFT algorithm. + //It just performs an out-of-place FFT into a temp buffer + std::vector> tmpbuf(st.nfft); + kf_work(tmpbuf.data(), fin, true, in_stride, st.factors, st); + memcpy(fout, tmpbuf.data(), sizeof(std::complex)*st.nfft); + tmpbuf.clear(); + } + else + { + kf_work(fout, fin, 1, in_stride, st.factors, st); + } +} + +void CKissFFT::fft(FFT_STATE &cfg, const std::complex *fin, std::complex *fout) +{ + fft_stride(cfg, fin, fout, 1); +} + +int CKissFFT::fft_next_fast_size(int n) +{ + while(1) + { + int m = n; + while ( (m % 2) == 0 ) m /= 2; + while ( (m % 3) == 0 ) m /= 3; + while ( (m % 5) == 0 ) m /= 5; + if (m <= 1) + break; /* n is completely factorable by twos, threes, and fives */ + n++; + } + return n; +} + +void CKissFFT::fftr_alloc(FFTR_STATE &st, int nfft, const bool inverse_fft) +{ + nfft >>= 1; + + fft_alloc(st.substate, nfft, inverse_fft); + st.tmpbuf.resize(nfft); + st.super_twiddles.resize(nfft); + + for (int i=0; i *freqdata) +{ + assert(st.substate.inverse == false); + + auto ncfft = st.substate.nfft; + + /*perform the parallel fft of two real signals packed in real,imag*/ + fft( st.substate, (const std::complex*)timedata, st.tmpbuf.data()); + /* The real part of the DC element of the frequency spectrum in st->tmpbuf + * contains the sum of the even-numbered elements of the input time sequence + * The imag part is the sum of the odd-numbered elements + * + * The sum of tdc.r and tdc.i is the sum of the input time sequence. + * yielding DC of input time sequence + * The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1... + * yielding Nyquist bin of input time sequence + */ + + auto tdc = st.tmpbuf[0]; + freqdata[0].real(tdc.real() + tdc.imag()); + freqdata[ncfft].real(tdc.real() - tdc.imag()); + freqdata[ncfft].imag(0.f); + freqdata[0].imag(0.f); + + for (int k=1; k <= ncfft/2; ++k) + { + auto fpk = st.tmpbuf[k]; + auto fpnk = std::conj(st.tmpbuf[ncfft-k]); + + auto f1k = fpk + fpnk; + auto f2k = fpk - fpnk; + auto tw = f2k * st.super_twiddles[k-1]; + + freqdata[k] = 0.5f * (f1k + tw); + freqdata[ncfft-k].real(0.5f * (f1k.real() - tw.real())); + freqdata[ncfft-k].imag(0.5f * (tw.imag() - f1k.imag())); + } +} + +void CKissFFT::fftri(FFTR_STATE &st, const std::complex *freqdata, float *timedata) +{ + assert(st.substate.inverse == true); + + auto ncfft = st.substate.nfft; + + st.tmpbuf[0].real(freqdata[0].real() + freqdata[ncfft].real()); + st.tmpbuf[0].imag(freqdata[0].real() - freqdata[ncfft].real()); + + for (int k=1; k <= ncfft/2; ++k) + { + auto fk = freqdata[k]; + auto fnkc = std::conj(freqdata[ncfft - k]); + + auto fek = fk + fnkc; + auto tmp = fk - fnkc; + auto fok = tmp * st.super_twiddles[k-1]; + st.tmpbuf[k] = fek + fok; + st.tmpbuf[ncfft - k] = std::conj(fek - fok); + } + fft (st.substate, st.tmpbuf.data(), (std::complex *)timedata); +} diff --git a/codec2/kiss_fft.h b/codec2/kiss_fft.h new file mode 100644 index 0000000..7626617 --- /dev/null +++ b/codec2/kiss_fft.h @@ -0,0 +1,35 @@ +#ifndef KISS_FFT_H +#define KISS_FFT_H + +#include + +#include +#include +#include +#include + +#include "defines.h" + +/* for real ffts, we need an even size */ +#define kiss_fftr_next_fast_size_real(n) (kiss_fft_next_fast_size( ((n)+1) >> 1) << 1 ) + +class CKissFFT +{ +public: + void fft_alloc(FFT_STATE &state, const int nfft, const bool inverse_fft); + void fft(FFT_STATE &cfg, const std::complex *fin, std::complex *fout); + void fft_stride(FFT_STATE &cfg, const std::complex *fin, std::complex *fout, int fin_stride); + int fft_next_fast_size(int n); + void fftr_alloc(FFTR_STATE &state, int nfft, const bool inverse_fft); + void fftr(FFTR_STATE &cfg,const float *timedata,std::complex *freqdata); + void fftri(FFTR_STATE &cfg,const std::complex *freqdata,float *timedata); +private: + void kf_bfly2(std::complex *Fout, const size_t fstride, FFT_STATE &st, int m); + void kf_bfly3(std::complex *Fout, const size_t fstride, FFT_STATE &st, int m); + void kf_bfly4(std::complex *Fout, const size_t fstride, FFT_STATE &st, int m); + void kf_bfly5(std::complex *Fout, const size_t fstride, FFT_STATE &st, int m); + void kf_bfly_generic(std::complex *Fout, const size_t fstride, FFT_STATE &st, int m, int p); + void kf_work(std::complex *Fout, const std::complex *f, const size_t fstride, int in_stride, int *factors, FFT_STATE &st); + void kf_factor(int n, int *facbuf); +}; +#endif diff --git a/codec2/lpc.cpp b/codec2/lpc.cpp new file mode 100644 index 0000000..10f2c09 --- /dev/null +++ b/codec2/lpc.cpp @@ -0,0 +1,311 @@ +/*---------------------------------------------------------------------------*\ + + FILE........: lpc.c + AUTHOR......: David Rowe + DATE CREATED: 30 Sep 1990 (!) + + Linear Prediction functions written in C. + +\*---------------------------------------------------------------------------*/ + +/* + Copyright (C) 2009-2012 David Rowe + + 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 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, see . +*/ + +#define LPC_MAX_N 512 /* maximum no. of samples in frame */ +#define PI 3.141592654 /* mathematical constant */ + +#define ALPHA 1.0 +#define BETA 0.94 + +#include +#include +#include "defines.h" +#include "lpc.h" + +/*---------------------------------------------------------------------------*\ + + pre_emp() + + Pre-emphasise (high pass filter with zero close to 0 Hz) a frame of + speech samples. Helps reduce dynamic range of LPC spectrum, giving + greater weight and hense a better match to low energy formants. + + Should be balanced by de-emphasis of the output speech. + +\*---------------------------------------------------------------------------*/ + +void Clpc::pre_emp( + float Sn_pre[], /* output frame of speech samples */ + float Sn[], /* input frame of speech samples */ + float *mem, /* Sn[-1]single sample memory */ + int Nsam /* number of speech samples to use */ +) +{ + int i; + + for(i=0; i 1.0) + k = 0.0; + + a[i][i] = k; + + for(j=1; j<=i-1; j++) + a[i][j] = a[i-1][j] + k*a[i-1][i-j]; /* Equation 38c, Makhoul */ + + e *= (1-k*k); /* Equation 38d, Makhoul */ + } + + for(i=1; i<=order; i++) + lpcs[i] = a[order][i]; + lpcs[0] = 1.0; +} + +/*---------------------------------------------------------------------------*\ + + inverse_filter() + + Inverse Filter, A(z). Produces an array of residual samples from an array + of input samples and linear prediction coefficients. + + The filter memory is stored in the first order samples of the input array. + +\*---------------------------------------------------------------------------*/ + +void Clpc::inverse_filter( + float Sn[], /* Nsam input samples */ + float a[], /* LPCs for this frame of samples */ + int Nsam, /* number of samples */ + float res[], /* Nsam residual samples */ + int order /* order of LPC */ +) +{ + int i,j; /* loop variables */ + + for(i=0; i. +*/ + +#ifndef __LPC__ +#define __LPC__ + +#define LPC_MAX_ORDER 20 + +class Clpc { +public: + void autocorrelate(float Sn[], float Rn[], int Nsam, int order); + void levinson_durbin(float R[], float lpcs[], int order); +private: + void pre_emp(float Sn_pre[], float Sn[], float *mem, int Nsam); + void de_emp(float Sn_se[], float Sn[], float *mem, int Nsam); + void hanning_window(float Sn[], float Wn[], int Nsam); + void inverse_filter(float Sn[], float a[], int Nsam, float res[], int order); + void synthesis_filter(float res[], float a[], int Nsam, int order, float Sn_[]); + void find_aks(float Sn[], float a[], int Nsam, int order, float *E); + void weight(float ak[], float gamma, int order, float akw[]); +}; + +#endif diff --git a/codec2/nlp.cpp b/codec2/nlp.cpp new file mode 100644 index 0000000..753e96b --- /dev/null +++ b/codec2/nlp.cpp @@ -0,0 +1,520 @@ +/*---------------------------------------------------------------------------*\ + + FILE........: nlp.c + AUTHOR......: David Rowe + DATE CREATED: 23/3/93 + + Non Linear Pitch (NLP) estimation functions. + +\*---------------------------------------------------------------------------*/ + +/* + Copyright (C) 2009 David Rowe + + 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 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, see . +*/ + +#include +#include +#include + +#include "defines.h" +#include "nlp.h" +#include "kiss_fft.h" + +extern CKissFFT kiss; + +/*---------------------------------------------------------------------------*\ + + GLOBALS + +\*---------------------------------------------------------------------------*/ + +/* 48 tap 600Hz low pass FIR filter coefficients */ + +static const float nlp_fir[] = +{ + -1.0818124e-03, + -1.1008344e-03, + -9.2768838e-04, + -4.2289438e-04, + 5.5034190e-04, + 2.0029849e-03, + 3.7058509e-03, + 5.1449415e-03, + 5.5924666e-03, + 4.3036754e-03, + 8.0284511e-04, + -4.8204610e-03, + -1.1705810e-02, + -1.8199275e-02, + -2.2065282e-02, + -2.0920610e-02, + -1.2808831e-02, + 3.2204775e-03, + 2.6683811e-02, + 5.5520624e-02, + 8.6305944e-02, + 1.1480192e-01, + 1.3674206e-01, + 1.4867556e-01, + 1.4867556e-01, + 1.3674206e-01, + 1.1480192e-01, + 8.6305944e-02, + 5.5520624e-02, + 2.6683811e-02, + 3.2204775e-03, + -1.2808831e-02, + -2.0920610e-02, + -2.2065282e-02, + -1.8199275e-02, + -1.1705810e-02, + -4.8204610e-03, + 8.0284511e-04, + 4.3036754e-03, + 5.5924666e-03, + 5.1449415e-03, + 3.7058509e-03, + 2.0029849e-03, + 5.5034190e-04, + -4.2289438e-04, + -9.2768838e-04, + -1.1008344e-03, + -1.0818124e-03 +}; + +static const float fdmdv_os_filter[]= { + -0.0008215855034550382, + -0.0007833023901802921, + 0.001075563790768233, + 0.001199092367787555, + -0.001765309502928316, + -0.002055372115328064, + 0.002986877604154257, + 0.003462567920638414, + -0.004856570111126334, + -0.005563143845031497, + 0.007533613299748122, + 0.008563932468880897, + -0.01126857129039911, + -0.01280782411693687, + 0.01651443896361847, + 0.01894875110322284, + -0.02421604439474981, + -0.02845107338464062, + 0.03672973563400258, + 0.04542046150312214, + -0.06189165826716491, + -0.08721876380763803, + 0.1496157094199961, + 0.4497962274137046, + 0.4497962274137046, + 0.1496157094199961, + -0.08721876380763803, + -0.0618916582671649, + 0.04542046150312216, + 0.03672973563400257, + -0.02845107338464062, + -0.02421604439474984, + 0.01894875110322284, + 0.01651443896361848, + -0.01280782411693687, + -0.0112685712903991, + 0.008563932468880899, + 0.007533613299748123, + -0.005563143845031501, + -0.004856570111126346, + 0.003462567920638419, + 0.002986877604154259, + -0.002055372115328063, + -0.001765309502928318, + 0.001199092367787557, + 0.001075563790768233, + -0.0007833023901802925, + -0.0008215855034550383 +}; + +/*---------------------------------------------------------------------------*\ + + nlp_create() + + Initialisation function for NLP pitch estimator. + +\*---------------------------------------------------------------------------*/ + +void Cnlp::nlp_create(C2CONST *c2const) +{ + int i; + int m = c2const->m_pitch; + int Fs = c2const->Fs; + + assert((Fs == 8000) || (Fs == 16000)); + snlp.Fs = Fs; + + snlp.m = m; + + /* if running at 16kHz allocate storage for decimating filter memory */ + + if (Fs == 16000) + { + snlp.Sn16k.resize(FDMDV_OS_TAPS_16K + c2const->n_samp); + for(i=0; i Sw[], /* Freq domain version of Sn[] */ +// float W[], /* Freq domain window */ + float *prev_f0 /* previous pitch f0 in Hz, memory for pitch tracking */ +) +{ + float notch; /* current notch filter output */ + std::complex Fw[PE_FFT_SIZE]; /* DFT of squared signal (input/output) */ + float gmax; + int gmax_bin; + int m, i, j; + float best_f0; + + m = snlp.m; + + /* Square, notch filter at DC, and LP filter vector */ + + /* If running at 16 kHz decimate to 8 kHz, as NLP ws designed for + Fs = 8kHz. The decimating filter introduces about 3ms of delay, + that shouldn't be a problem as pitch changes slowly. */ + + if (snlp.Fs == 8000) + { + /* Square latest input samples */ + + for(i=m-n; i gmax) + { + gmax = Fw[i].real(); + gmax_bin = i; + } + } + + best_f0 = post_process_sub_multiples(Fw, pmax, gmax, gmax_bin, prev_f0); + + /* Shift samples in buffer to make room for new samples */ + + for(i=0; i Fw[], int pmax, float gmax, int gmax_bin, float *prev_f0) +{ + int min_bin, cmax_bin; + int mult; + float thresh, best_f0; + int b, bmin, bmax, lmax_bin; + float lmax; + int prev_f0_bin; + + /* post process estimate by searching submultiples */ + + mult = 2; + min_bin = PE_FFT_SIZE*DEC/pmax; + cmax_bin = gmax_bin; + prev_f0_bin = *prev_f0*(PE_FFT_SIZE*DEC)/SAMPLE_RATE; + + while(gmax_bin/mult >= min_bin) + { + + b = gmax_bin/mult; /* determine search interval */ + bmin = 0.8*b; + bmax = 1.2*b; + if (bmin < min_bin) + bmin = min_bin; + + /* lower threshold to favour previous frames pitch estimate, + this is a form of pitch tracking */ + + if ((prev_f0_bin > bmin) && (prev_f0_bin < bmax)) + thresh = CNLP*0.5*gmax; + else + thresh = CNLP*gmax; + + lmax = 0; + lmax_bin = bmin; + for (b=bmin; b<=bmax; b++) /* look for maximum in interval */ + if (Fw[b].real() > lmax) + { + lmax = Fw[b].real(); + lmax_bin = b; + } + + if (lmax > thresh) + if ((lmax > Fw[lmax_bin-1].real()) && (lmax > Fw[lmax_bin+1].real())) + { + cmax_bin = lmax_bin; + } + + mult++; + } + + best_f0 = (float)cmax_bin*SAMPLE_RATE/(PE_FFT_SIZE*DEC); + + return best_f0; +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: fdmdv_16_to_8() + AUTHOR......: David Rowe + DATE CREATED: 9 May 2012 + + Changes the sample rate of a signal from 16 to 8 kHz. + + n is the number of samples at the 8 kHz rate, there are FDMDV_OS*n + samples at the 48 kHz rate. As above however a memory of + FDMDV_OS_TAPS samples is reqd for in16k[] (see t16_8.c unit test as example). + + Low pass filter the 16 kHz signal at 4 kHz using the same filter as + the upsampler, then just output every FDMDV_OS-th filtered sample. + + Note: this function copied from fdmdv.c, included in nlp.c as a convenience + to avoid linking with another source file. + +\*---------------------------------------------------------------------------*/ + +void Cnlp::fdmdv_16_to_8(float out8k[], float in16k[], int n) +{ + float acc; + int i,j,k; + + for(i=0, k=0; k *inout) +{ + std::complex in[512]; + // decide whether to use the local stack based buffer for in + // or to allow kiss_fft to allocate RAM + // second part is just to play safe since first method + // is much faster and uses less RAM + if (cfg.nfft <= 512) + { + memcpy(in, inout, cfg.nfft*sizeof(std::complex)); + kiss.fft(cfg, in, inout); + } + else + { + kiss.fft(cfg, inout, inout); + } +} diff --git a/codec2/nlp.h b/codec2/nlp.h new file mode 100644 index 0000000..f480b24 --- /dev/null +++ b/codec2/nlp.h @@ -0,0 +1,87 @@ +/*---------------------------------------------------------------------------*\ + + FILE........: nlp.c + AUTHOR......: David Rowe + DATE CREATED: 23/3/93 + + Non Linear Pitch (NLP) estimation functions. + +\*---------------------------------------------------------------------------*/ + +/* + Copyright (C) 2009 David Rowe + + 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 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, see . +*/ + +#ifndef __NLP__ +#define __NLP__ + +#include +#include + +#include "defines.h" + +/*---------------------------------------------------------------------------*\ + + DEFINES + +\*---------------------------------------------------------------------------*/ + +#define PMAX_M 320 /* maximum NLP analysis window size */ +#define COEFF 0.95 /* notch filter parameter */ +#define PE_FFT_SIZE 512 /* DFT size for pitch estimation */ +#define DEC 5 /* decimation factor */ +#define SAMPLE_RATE 8000 +#define PI 3.141592654 /* mathematical constant */ +//#define T 0.1 /* threshold for local minima candidate */ +#define F0_MAX 500 +#define CNLP 0.3 /* post processor constant */ +#define NLP_NTAP 48 /* Decimation LPF order */ + +/* 8 to 16 kHz sample rate conversion */ + +#define FDMDV_OS 2 /* oversampling rate */ +#define FDMDV_OS_TAPS_16K 48 /* number of OS filter taps at 16kHz */ +#define FDMDV_OS_TAPS_8K (FDMDV_OS_TAPS_16K/FDMDV_OS) /* number of OS filter taps at 8kHz */ + + +using NLP = struct nlp_tag +{ + int Fs; /* sample rate in Hz */ + int m; + float w[PMAX_M/DEC]; /* DFT window */ + float sq[PMAX_M]; /* squared speech samples */ + float mem_x,mem_y; /* memory for notch filter */ + float mem_fir[NLP_NTAP]; /* decimation FIR filter memory */ + FFT_STATE fft_cfg; /* kiss FFT config */ + std::vector Sn16k; /* Fs=16kHz input speech vector */ +}; + + +class Cnlp { +public: + void nlp_create(C2CONST *c2const); + void nlp_destroy(); + float nlp(float Sn[], int n, float *pitch_samples, float *prev_f0); + void codec2_fft_inplace(FFT_STATE &cfg, std::complex *inout); + +private: + float post_process_sub_multiples(std::complex Fw[], int pmax, float gmax, int gmax_bin, float *prev_f0); + void fdmdv_16_to_8(float out8k[], float in16k[], int n); + + NLP snlp; +}; + +#endif diff --git a/codec2/pack.cpp b/codec2/pack.cpp new file mode 100644 index 0000000..8382f95 --- /dev/null +++ b/codec2/pack.cpp @@ -0,0 +1,139 @@ +/* + Copyright (C) 2010 Perens LLC + + 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 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, see . +*/ + +#include "defines.h" +#include "quantise.h" +#include + +/* Compile-time constants */ +/* Size of unsigned char in bits. Assumes 8 bits-per-char. */ +static const unsigned int WordSize = 8; + +/* Mask to pick the bit component out of bitIndex. */ +static const unsigned int IndexMask = 0x7; + +/* Used to pick the word component out of bitIndex. */ +static const unsigned int ShiftRight = 3; + +/** Pack a bit field into a bit string, encoding the field in Gray code. + * + * The output is an array of unsigned char data. The fields are efficiently + * packed into the bit string. The Gray coding is a naive attempt to reduce + * the effect of single-bit errors, we expect to do a better job as the + * codec develops. + * + * This code would be simpler if it just set one bit at a time in the string, + * but would hit the same cache line more often. I'm not sure the complexity + * gains us anything here. + * + * Although field is currently of int type rather than unsigned for + * compatibility with the rest of the code, indices are always expected to + * be >= 0. + */ +void CQuantize::pack( + unsigned char *bitArray, /* The output bit string. */ + unsigned int *bitIndex, /* Index into the string in BITS, not bytes.*/ + int field, /* The bit field to be packed. */ + unsigned int fieldWidth /* Width of the field in BITS, not bytes. */ +) +{ + pack_natural_or_gray(bitArray, bitIndex, field, fieldWidth, 1); +} + +void CQuantize::pack_natural_or_gray( + unsigned char *bitArray, /* The output bit string. */ + unsigned int *bitIndex, /* Index into the string in BITS, not bytes.*/ + int field, /* The bit field to be packed. */ + unsigned int fieldWidth, /* Width of the field in BITS, not bytes. */ + unsigned int gray /* non-zero for gray coding */ +) +{ + if (gray) + { + /* Convert the field to Gray code */ + field = (field >> 1) ^ field; + } + + do + { + unsigned int bI = *bitIndex; + unsigned int bitsLeft = WordSize - (bI & IndexMask); + unsigned int sliceWidth = bitsLeft < fieldWidth ? bitsLeft : fieldWidth; + unsigned int wordIndex = bI >> ShiftRight; + + bitArray[wordIndex] |= ((unsigned char)((field >> (fieldWidth - sliceWidth)) << (bitsLeft - sliceWidth))); + + *bitIndex = bI + sliceWidth; + fieldWidth -= sliceWidth; + } + while ( fieldWidth != 0 ); +} + +/** Unpack a field from a bit string, converting from Gray code to binary. + * + */ +int CQuantize::unpack( + const unsigned char *bitArray, /* The input bit string. */ + unsigned int *bitIndex, /* Index into the string in BITS, not bytes.*/ + unsigned int fieldWidth/* Width of the field in BITS, not bytes. */ +) +{ + return unpack_natural_or_gray(bitArray, bitIndex, fieldWidth, 1); +} + +/** Unpack a field from a bit string, to binary, optionally using + * natural or Gray code. + * + */ +int CQuantize::unpack_natural_or_gray( + const unsigned char *bitArray, /* The input bit string. */ + unsigned int *bitIndex, /* Index into the string in BITS, not bytes.*/ + unsigned int fieldWidth,/* Width of the field in BITS, not bytes. */ + unsigned int gray /* non-zero for Gray coding */ +) +{ + unsigned int field = 0; + unsigned int t; + + do + { + unsigned int bI = *bitIndex; + unsigned int bitsLeft = WordSize - (bI & IndexMask); + unsigned int sliceWidth = bitsLeft < fieldWidth ? bitsLeft : fieldWidth; + + field |= (((bitArray[bI >> ShiftRight] >> (bitsLeft - sliceWidth)) & ((1 << sliceWidth) - 1)) << (fieldWidth - sliceWidth)); + + *bitIndex = bI + sliceWidth; + fieldWidth -= sliceWidth; + } + while ( fieldWidth != 0 ); + + if (gray) + { + /* Convert from Gray code to binary. Works for maximum 8-bit fields. */ + t = field ^ (field >> 8); + t ^= (t >> 4); + t ^= (t >> 2); + t ^= (t >> 1); + } + else + { + t = field; + } + + return t; +} diff --git a/codec2/qbase.cpp b/codec2/qbase.cpp new file mode 100644 index 0000000..b821656 --- /dev/null +++ b/codec2/qbase.cpp @@ -0,0 +1,247 @@ +#include +#include + +#include "qbase.h" + +/*---------------------------------------------------------------------------*\ + + quantise + + Quantises vec by choosing the nearest vector in codebook cb, and + returns the vector index. The squared error of the quantised vector + is added to se. + +\*---------------------------------------------------------------------------*/ + +long CQbase::quantise(const float *cb, float vec[], float w[], int k, int m, float *se) +/* float cb[][K]; current VQ codebook */ +/* float vec[]; vector to quantise */ +/* float w[]; weighting vector */ +/* int k; dimension of vectors */ +/* int m; size of codebook */ +/* float *se; accumulated squared error */ +{ + float e; /* current error */ + long besti; /* best index so far */ + float beste; /* best error so far */ + long j; + int i; + float diff; + + besti = 0; + beste = 1E32; + for(j=0; jWo/PI)*4000.0/50.0)/log10f(2); + x[1] = 10.0*log10f(1e-4 + e); + + compute_weights2(x, xq, w); + for (i=0; iWo_min; + float Wo_max = c2const->Wo_max; + + for (i=0; iWo = powf(2.0, xq[0])*(PI*50.0)/4000.0; + + /* bit errors can make us go out of range leading to all sorts of + probs like seg faults */ + + if (model->Wo > Wo_max) model->Wo = Wo_max; + if (model->Wo < Wo_min) model->Wo = Wo_min; + + model->L = PI/model->Wo; /* if we quantise Wo re-compute L */ + + *e = powf(10.0f, xq[1]/10.0f); +} + +void CQbase::compute_weights2(const float *x, const float *xp, float *w) +{ + w[0] = 30; + w[1] = 1; + if (x[1]<0) + { + w[0] *= .6; + w[1] *= .3; + } + if (x[1]<-10) + { + w[0] *= .3; + w[1] *= .3; + } + /* Higher weight if pitch is stable */ + if (fabsf(x[0]-xp[0])<.2) + { + w[0] *= 2; + w[1] *= 1.5; + } + else if (fabsf(x[0]-xp[0])>.5) /* Lower if not stable */ + { + w[0] *= .5; + } + + /* Lower weight for low energy */ + if (x[1] < xp[1]-10) + { + w[1] *= .5; + } + if (x[1] < xp[1]-20) + { + w[1] *= .5; + } + + //w[0] = 30; + //w[1] = 1; + + /* Square the weights because it's applied on the squared error */ + w[0] *= w[0]; + w[1] *= w[1]; + +} + +int CQbase::find_nearest_weighted(const float *codebook, int nb_entries, float *x, const float *w, int ndim) +{ + int i, j; + float min_dist = 1e15; + int nearest = 0; + + for (i=0; iWo_min; + float Wo_max = c2const->Wo_max; + float norm; + + norm = (log10f(Wo) - log10f(Wo_min))/(log10f(Wo_max) - log10f(Wo_min)); + index = floorf(Wo_levels * norm + 0.5); + if (index < 0 ) index = 0; + if (index > (Wo_levels-1)) index = Wo_levels-1; + + return index; +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: decode_log_Wo() + AUTHOR......: David Rowe + DATE CREATED: 22/8/2010 + + Decodes Wo using a WO_LEVELS quantiser in the log domain. + +\*---------------------------------------------------------------------------*/ + +float CQbase::decode_log_Wo(C2CONST *c2const, int index, int bits) +{ + float Wo_min = c2const->Wo_min; + float Wo_max = c2const->Wo_max; + float step; + float Wo; + int Wo_levels = 1<. + +*/ + +#include +#include +#include +#include +#include +#include + +#include "defines.h" +#include "quantise.h" +#include "lpc.h" +#include "kiss_fft.h" + +extern CKissFFT kiss; + +#define LSP_DELTA1 0.01 /* grid spacing for LSP root searches */ + +/*---------------------------------------------------------------------------*\ + + FUNCTIONS + +\*---------------------------------------------------------------------------*/ + +int CQuantize::lsp_bits(int i) +{ + return lsp_cb[i].log2m; +} + +int CQuantize::lspd_bits(int i) +{ + return lsp_cbd[i].log2m; +} + + + +/*---------------------------------------------------------------------------*\ + + encode_lspds_scalar() + + Scalar/VQ LSP difference quantiser. + +\*---------------------------------------------------------------------------*/ + +void CQuantize::encode_lspds_scalar(int indexes[], float lsp[], int order) +{ + int i,k,m; + float lsp_hz[order]; + float lsp__hz[order]; + float dlsp[order]; + float dlsp_[order]; + float wt[order]; + const float *cb; + float se; + + for(i=0; i Ww[FFT_ENC/2+1]; /* weighting spectrum */ + float Rw[FFT_ENC/2+1]; /* R = WA */ + float e_before, e_after, gain; + float Pfw; + float max_Rw, min_Rw; + float coeff; + + /* Determine weighting filter spectrum W(exp(jw)) ---------------*/ + + for(i=0; i max_Rw) + max_Rw = Rw[i]; + if (Rw[i] < min_Rw) + min_Rw = Rw[i]; + + } + + /* create post filter mag spectrum and apply ------------------*/ + + /* measure energy before post filtering */ + + e_before = 1E-4; + for(i=0; i Aw[] /* output power spectrum */ +) +{ + int i,m; /* loop variables */ + int am,bm; /* limits of current band */ + float r; /* no. rads/bin */ + float Em; /* energy in band */ + float Am; /* spectral amplitude sample */ + float signal, noise; + + r = TWO_PI/(FFT_ENC); + + /* Determine DFT of A(exp(jw)) --------------------------------------------*/ + { + float a[FFT_ENC]; /* input to FFT for power spectrum */ + + for(i=0; iL; m++) + { + am = (int)((m - 0.5)*model->Wo/r + 0.5); + bm = (int)((m + 0.5)*model->Wo/r + 0.5); + + // FIXME: With arm_rfft_fast_f32 we have to use this + // otherwise sometimes a to high bm is calculated + // which causes trouble later in the calculation + // chain + // it seems for some reason model->Wo is calculated somewhat too high + if (bm>FFT_ENC/2) + { + bm = FFT_ENC/2; + } + Em = 0.0; + + for(i=am; iA[m]*model->A[m]; + noise += (model->A[m] - Am)*(model->A[m] - Am); + + /* This code significantly improves perf of LPC model, in + particular when combined with phase0. The LPC spectrum tends + to track just under the peaks of the spectral envelope, and + just above nulls. This algorithm does the reverse to + compensate - raising the amplitudes of spectral peaks, while + attenuating the null. This enhances the formants, and + supresses the energy between formants. */ + + if (sim_pf) + { + if (Am > model->A[m]) + Am *= 0.7; + if (Am < model->A[m]) + Am *= 1.4; + } + model->A[m] = Am; + } + *snr = 10.0*log10f(signal/noise); +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: encode_Wo() + AUTHOR......: David Rowe + DATE CREATED: 22/8/2010 + + Encodes Wo using a WO_LEVELS quantiser. + +\*---------------------------------------------------------------------------*/ + +int CQuantize::encode_Wo(C2CONST *c2const, float Wo, int bits) +{ + int index, Wo_levels = 1<Wo_min; + float Wo_max = c2const->Wo_max; + float norm; + + norm = (Wo - Wo_min)/(Wo_max - Wo_min); + index = floorf(Wo_levels * norm + 0.5); + if (index < 0 ) index = 0; + if (index > (Wo_levels-1)) index = Wo_levels-1; + + return index; +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: decode_Wo() + AUTHOR......: David Rowe + DATE CREATED: 22/8/2010 + + Decodes Wo using a WO_LEVELS quantiser. + +\*---------------------------------------------------------------------------*/ + +float CQuantize::decode_Wo(C2CONST *c2const, int index, int bits) +{ + float Wo_min = c2const->Wo_min; + float Wo_max = c2const->Wo_max; + float step; + float Wo; + int Wo_levels = 1<Wo < (PI*150.0/4000)) + { + model->A[1] *= 0.032; + } +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: encode_energy() + AUTHOR......: David Rowe + DATE CREATED: 22/8/2010 + + Encodes LPC energy using an E_LEVELS quantiser. + +\*---------------------------------------------------------------------------*/ + +int CQuantize::encode_energy(float e, int bits) +{ + int index, e_levels = 1< (e_levels-1)) index = e_levels-1; + + return index; +} + +/*---------------------------------------------------------------------------*\ + + FUNCTION....: decode_energy() + AUTHOR......: David Rowe + DATE CREATED: 22/8/2010 + + Decodes energy using a E_LEVELS quantiser. + +\*---------------------------------------------------------------------------*/ + +float CQuantize::decode_energy(int index, int bits) +{ + float e_min = E_MIN_DB; + float e_max = E_MAX_DB; + float step; + float e; + int e_levels = 1<= -1.0)) + { + xr = xl - delta ; /* interval spacing */ + psumr = cheb_poly_eva(pt,xr,order);/* poly(xl-delta_x) */ + temp_psumr = psumr; + temp_xr = xr; + + /* if no sign change increment xr and re-evaluate + poly(xr). Repeat til sign change. if a sign change has + occurred the interval is bisected and then checked again + for a sign change which determines in which interval the + zero lies in. If there is no sign change between poly(xm) + and poly(xl) set interval between xm and xr else set + interval between xl and xr and repeat till root is located + within the specified limits */ + + if(((psumr*psuml)<0.0) || (psumr == 0.0)) + { + roots++; + + psumm=psuml; + for(k=0; k<=nb; k++) + { + xm = (xl+xr)/2; /* bisect the interval */ + psumm=cheb_poly_eva(pt,xm,order); + if(psumm*psuml>0.) + { + psuml=psumm; + xl=xm; + } + else + { + psumr=psumm; + xr=xm; + } + } + + /* once zero is found, reset initial interval to xr */ + freq[j] = (xm); + xl = xm; + flag = 0; /* reset flag for next search */ + } + else + { + psuml=temp_psumr; + xl=temp_xr; + } + } + } + + /* convert from x domain to radians */ + + for(i=0; i. +*/ + +#ifndef __QUANTISE__ +#define __QUANTISE__ + +#include + +#include "qbase.h" + +class CQuantize : public CQbase { +public: + void aks_to_M2(FFTR_STATE *fftr_fwd_cfg, float ak[], int order, MODEL *model, float E, float *snr, int sim_pf, int pf, int bass_boost, float beta, float gamma, std::complex Aw[]); + + int encode_Wo(C2CONST *c2const, float Wo, int bits); + float decode_Wo(C2CONST *c2const, int index, int bits); + void encode_lsps_scalar(int indexes[], float lsp[], int order); + void decode_lsps_scalar(float lsp[], int indexes[], int order); + void encode_lspds_scalar(int indexes[], float lsp[], int order); + void decode_lspds_scalar(float lsp[], int indexes[], int order); + + int encode_energy(float e, int bits); + float decode_energy(int index, int bits); + + void pack(unsigned char * bits, unsigned int *nbit, int index, unsigned int index_bits); + void pack_natural_or_gray(unsigned char * bits, unsigned int *nbit, int index, unsigned int index_bits, unsigned int gray); + int unpack(const unsigned char * bits, unsigned int *nbit, unsigned int index_bits); + int unpack_natural_or_gray(const unsigned char * bits, unsigned int *nbit, unsigned int index_bits, unsigned int gray); + + int lsp_bits(int i); + int lspd_bits(int i); + + void apply_lpc_correction(MODEL *model); + float speech_to_uq_lsps(float lsp[], float ak[], float Sn[], float w[], int m_pitch, int order); + int check_lsp_order(float lsp[], int lpc_order); + void bw_expand_lsps(float lsp[], int order, float min_sep_low, float min_sep_high); + +private: + void compute_weights(const float *x, float *w, int ndim); + int find_nearest(const float *codebook, int nb_entries, float *x, int ndim); + void lpc_post_filter(FFTR_STATE *fftr_fwd_cfg, float Pw[], float ak[], int order, float beta, float gamma, int bass_boost, float E); + int lpc_to_lsp (float *a, int lpcrdr, float *freq, int nb, float delta); + float cheb_poly_eva(float *coef,float x,int order); +}; + +#endif diff --git a/cpacket.cpp b/cpacket.cpp new file mode 100644 index 0000000..a661984 --- /dev/null +++ b/cpacket.cpp @@ -0,0 +1,49 @@ +// +// cpacket.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "cpacket.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructors + +CPacket::CPacket() +{ + m_iCh = 0; + m_uiPid = 0; +}; + +CPacket::CPacket(uint8 uiPid) +{ + m_iCh = 0; + m_uiPid = uiPid; +} + +CPacket::CPacket(const CPacket &packet) +{ + m_iCh = packet.m_iCh; + m_uiPid = packet.m_uiPid; +}; + diff --git a/cpacket.h b/cpacket.h new file mode 100644 index 0000000..a7768c0 --- /dev/null +++ b/cpacket.h @@ -0,0 +1,62 @@ +// +// cpacket.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 24/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cpacket_h +#define cpacket_h + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CPacket +{ +public: + // constructors + CPacket(); + CPacket(uint8); + CPacket(const CPacket &); + + // destructor + virtual ~CPacket() {}; + + // identity + virtual bool IsVoice(void) const { return false; } + virtual bool IsAmbe(void) const { return false; } + + // get + int GetChannel(void) const { return m_iCh; } + uint8 GetPid(void) const { return m_uiPid; } + + // set + void SetChannel(int i) { m_iCh = i; } + void SetPid(uint8 ui) { m_uiPid = ui; } + +protected: + // data + int m_iCh; + uint8 m_uiPid; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cpacket_h */ diff --git a/cpacketqueue.cpp b/cpacketqueue.cpp new file mode 100644 index 0000000..ff14dcb --- /dev/null +++ b/cpacketqueue.cpp @@ -0,0 +1,60 @@ +// +// cpacketqueue.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "cpacketqueue.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CPacketQueue::CPacketQueue() +{ +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CPacketQueue::~CPacketQueue() +{ + // empty codec queue + while ( !empty() ) + { + delete front(); + pop(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// purge + +void CPacketQueue::Purge(void) +{ + // this assume queue is already locked + while ( !empty() ) + { + delete front(); + pop(); + } +} diff --git a/cpacketqueue.h b/cpacketqueue.h new file mode 100644 index 0000000..cb7144d --- /dev/null +++ b/cpacketqueue.h @@ -0,0 +1,55 @@ +// +// cpacketqueue.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 24/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cpacketqueue_h +#define cpacketqueue_h + +#include "cpacket.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CPacketQueue : public std::queue +{ +public: + // constructor + CPacketQueue(); + + // destructor + ~CPacketQueue(); + + // lock + void Lock() { m_Mutex.lock(); } + void Unlock() { m_Mutex.unlock(); } + + // purge + void Purge(void); + +protected: + // status + std::mutex m_Mutex; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cpacketqueue_h */ diff --git a/csampleblockprocessor.h b/csampleblockprocessor.h new file mode 100644 index 0000000..2c57f5f --- /dev/null +++ b/csampleblockprocessor.h @@ -0,0 +1,38 @@ +// +// csampleprocessor.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 26/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// Geoffrey Merck F4FXL / KC3FRA + +#ifndef csamplebloclprocessor_h +#define csamplebloclprocessor_h + +#include "main.h" + +class CSampleBlockProcessor +{ +public: + //processing + virtual void ProcessSampleBlock(uint8* voice, int length) = 0; +}; + +#endif /* csampleprocessor_h */ \ No newline at end of file diff --git a/csignalprocessor.cpp b/csignalprocessor.cpp new file mode 100644 index 0000000..e54e792 --- /dev/null +++ b/csignalprocessor.cpp @@ -0,0 +1,252 @@ +// +// cagc.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// Geoffrey Merck F4FXL / KC3FRA AGC + +#include +#include +#include +#include "main.h" +#include "csignalprocessor.h" +#include "cagc.h" +#include "cfixedgain.h" +#include "cfirfilter.h" + +// within this of the clamp, the AGC is at its limit +#define AGC_LIMIT_MARGIN 0.05f + +static float ToDbfs(double level) +{ + return (level > 0.0) ? (float)(20.0 * log10(level / 32768.0)) : -96.0f; +} + +// a gain in the report, as DMR_TO_PCM -1.50 +static std::string GainLabel(const std::string& name, float gain) +{ + std::ostringstream label; + label << name << " " << std::showpos << std::fixed << std::setprecision(2) << gain; + return label.str(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// level meter + +CLevelMeter::CLevelMeter() +{ + m_Sum = 0.0; + m_Samples = 0; + m_Clipped = 0; + m_Peak = 0; +} + +void CLevelMeter::Add(const uint8* voice, int length) +{ + for(int i = 0; i < length; i += 2) + { + int sample = abs((int)(short)MAKEWORD(voice[i+1], voice[i])); + m_Sum += sample; + m_Samples++; + m_Peak = MAX(m_Peak, sample); + if(sample >= 32767) + { + m_Clipped++; + } + } +} + +void CLevelMeter::Report(const std::string& label) const +{ + if(m_Samples == 0) + { + return; + } + std::cout << "Tuning: " << std::left << std::setw(22) << label << std::right + << "level " << std::setw(6) << std::setprecision(1) << ToDbfs(m_Sum / m_Samples) << " dBFS" + << " peak " << std::setw(6) << ToDbfs(m_Peak) << " dBFS" + << " clipped " << std::setprecision(2) << (100.0 * m_Clipped / m_Samples) << "%" << std::endl; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CSignalProcessor::CSignalProcessor(uint8 uiCodecIn) +{ + m_uiCodecIn = uiCodecIn; + m_Tuning = g_Config.GetTuning(); + + m_pDecodeGain = new CFixedGain(m_Tuning.fToPcm[uiCodecIn]); + m_pFilter = m_Tuning.bUseFilter ? new CFIRFilter(FILTER_TAPS, FILTER_TAPS_LENGTH) : NULL; + // The encode gains come after the AGC, so leave room for the highest one + float limit = AGC_CEILING; + for(int i = 0; i < NB_OF_CODECS; i++) + { + limit = MIN(limit, AGC_CEILING - m_Tuning.fFromPcm[i]); + } + m_pAgc = m_Tuning.bUseAgc ? new CAGC(m_Tuning.fAgcTarget, m_Tuning.fAgcClamping, m_Tuning.fAgcAttack, m_Tuning.fAgcHang, + m_Tuning.fAgcRecovery, m_Tuning.fAgcRecoveryMin, m_Tuning.fAgcRecoveryMax, + m_Tuning.fAgcGate, limit) : NULL; + for(int i = 0; i < NB_OF_CODECS; i++) + { + m_pEncodeGain[i] = new CFixedGain(m_Tuning.fFromPcm[i]); + } + + m_bVoice = false; + m_Frames = 0; + m_VoiceFrames = 0; + m_AgcSum = 0.0; + m_AgcMin = 0.0f; + m_AgcMax = 0.0f; + m_AgcAtMax = 0; + m_AgcAtMin = 0; + m_SpeechPeakSum = 0.0; + m_SpeechPeakFrames = 0; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CSignalProcessor::~CSignalProcessor() +{ + delete m_pDecodeGain; + delete m_pFilter; + delete m_pAgc; + for(int i = 0; i < NB_OF_CODECS; i++) + { + delete m_pEncodeGain[i]; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// processing + +void CSignalProcessor::Process(uint8* voice, int length) +{ + // Only voice counts towards the report, pauses would pull the levels down + double sum = 0.0; + for(int i = 0; i < length; i += 2) + { + sum += abs((int)(short)MAKEWORD(voice[i+1], voice[i])); + } + m_bVoice = (length > 0) && (ToDbfs(sum / (length / 2)) >= TUNING_SILENCE_LEVEL); + + m_Frames++; + if(m_bVoice) + { + m_VoiceFrames++; + m_Decoded.Add(voice, length); + } + + m_pDecodeGain->ProcessSampleBlock(voice, length); + if(m_pFilter != NULL) + { + m_pFilter->ProcessSampleBlock(voice, length); + } + + if(m_bVoice) + { + m_ToAgc.Add(voice, length); + } + + if(m_pAgc != NULL) + { + m_pAgc->ProcessSampleBlock(voice, length); + + if(m_bVoice) + { + float gain = m_pAgc->GetGain(); + m_AgcMin = (m_VoiceFrames == 1) ? gain : MIN(m_AgcMin, gain); + m_AgcMax = (m_VoiceFrames == 1) ? gain : MAX(m_AgcMax, gain); + m_AgcSum += gain; + if(m_pAgc->IsVoice()) + { + m_SpeechPeakSum += m_pAgc->GetSpeechPeak(); + m_SpeechPeakFrames++; + } + if(m_Tuning.fAgcClamping > 0.0f && gain >= m_Tuning.fAgcClamping - AGC_LIMIT_MARGIN) + { + m_AgcAtMax++; + } + else if(m_Tuning.fAgcClamping > 0.0f && gain <= -m_Tuning.fAgcClamping + AGC_LIMIT_MARGIN) + { + m_AgcAtMin++; + } + } + } + + if(m_bVoice) + { + m_FromAgc.Add(voice, length); + } +} + +void CSignalProcessor::ProcessOutput(uint8 uiCodecOut, uint8* voice, int length) +{ + m_pEncodeGain[uiCodecOut]->ProcessSampleBlock(voice, length); + if(m_bVoice) + { + m_Output[uiCodecOut].Add(voice, length); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// tuning report + +void CSignalProcessor::Report(uint16 uiStreamId, const std::string& callsign) const +{ + if(!m_Tuning.bTuningLog || m_VoiceFrames == 0) + { + return; + } + + std::ios::fmtflags flags = std::cout.flags(); + std::streamsize precision = std::cout.precision(); + std::cout << std::fixed; + + std::string mode = CConfig::GetModeName(m_uiCodecIn); + std::cout << "Tuning: stream " << uiStreamId << " " << callsign << " " << mode << " input, " + << m_VoiceFrames << " voice frames of " << m_Frames << std::endl; + + m_Decoded.Report("decoded"); + m_ToAgc.Report(GainLabel(mode + "_TO_PCM", m_Tuning.fToPcm[m_uiCodecIn])); + + if(m_pAgc != NULL) + { + std::cout << "Tuning: " << std::left << std::setw(22) << "AGC" << std::right << std::setprecision(1) + << "target " << m_Tuning.fAgcTarget << " dBFS speech peaks " + << ((m_SpeechPeakFrames > 0) ? (float)(m_SpeechPeakSum / m_SpeechPeakFrames) : -96.0f) << " dBFS gain average " << std::showpos << (m_AgcSum / m_VoiceFrames) + << " dB, " << m_AgcMin << " to " << m_AgcMax << " dB" << std::noshowpos + << " at limit " << (100.0 * m_AgcAtMax / m_VoiceFrames) << "% high " + << (100.0 * m_AgcAtMin / m_VoiceFrames) << "% low" + << " limiter " << std::setprecision(2) << (100.0 * m_pAgc->GetLimitedSamples() / (m_Frames * 160)) << "%" << std::endl; + m_FromAgc.Report("after AGC"); + } + + for(int i = 0; i < NB_OF_CODECS; i++) + { + m_Output[i].Report(GainLabel(std::string("PCM_TO_") + CConfig::GetModeName((uint8)i), m_Tuning.fFromPcm[i])); + } + + std::cout.flags(flags); + std::cout.precision(precision); +} diff --git a/csignalprocessor.h b/csignalprocessor.h new file mode 100644 index 0000000..822f5e1 --- /dev/null +++ b/csignalprocessor.h @@ -0,0 +1,94 @@ +// +// csignalprocessor.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 26/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// Geoffrey Merck F4FXL / KC3FRA + +#ifndef csignalprocessor_h +#define csignalprocessor_h + +#include +#include "cconfig.h" +#include "csampleblockprocessor.h" + +class CAGC; +class CFixedGain; +class CFIRFilter; + +// voice level at one point of the chain, for the tuning report +class CLevelMeter +{ +public: + CLevelMeter(); + + void Add(const uint8* voice, int length); + void Report(const std::string& label) const; + +private: + double m_Sum; // sum of absolute sample values + long m_Samples; + long m_Clipped; + int m_Peak; +}; + +class CSignalProcessor +{ +public: + //Constructor, takes the input codec and the current ambed.ini values + CSignalProcessor(uint8 uiCodecIn); + + //Destructor + ~CSignalProcessor(); + + //Processing + void Process(uint8* voice, int length); //decode gain, filter, AGC + void ProcessOutput(uint8 uiCodecOut, uint8* voice, int length); //encode gain + + //Tuning report, logged when the stream closes + void Report(uint16 uiStreamId, const std::string& callsign) const; + +private: + uint8 m_uiCodecIn; + CTuning m_Tuning; + CFixedGain *m_pDecodeGain; + CFIRFilter *m_pFilter; + CAGC *m_pAgc; + CFixedGain *m_pEncodeGain[NB_OF_CODECS]; + + // tuning report + bool m_bVoice; //is the current frame voice + long m_Frames; + long m_VoiceFrames; + CLevelMeter m_Decoded; + CLevelMeter m_ToAgc; + CLevelMeter m_FromAgc; + CLevelMeter m_Output[NB_OF_CODECS]; + double m_AgcSum; + float m_AgcMin; + float m_AgcMax; + long m_AgcAtMax; + long m_AgcAtMin; + double m_SpeechPeakSum; + long m_SpeechPeakFrames; +}; + +#endif /* csignalprocessor_h */ diff --git a/cstream.cpp b/cstream.cpp new file mode 100644 index 0000000..a3fc5f6 --- /dev/null +++ b/cstream.cpp @@ -0,0 +1,954 @@ +// +// cstream.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 15/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include +#include "ctimepoint.h" +#include "cambeserver.h" +#include "cvocodecs.h" +#include "cambepacket.h" +#include "cvoicepacket.h" +#include "cstream.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +// DVSI hardware expects big-endian PCM, as does the signal processor +static void PcmToBytes(const int16_t *pcm, uint8 *bytes) +{ + for (int i = 0; i < 160; i++) + { + bytes[i*2] = (uint8)(((uint16_t)pcm[i] >> 8) & 0xFF); + bytes[i*2 + 1] = (uint8)((uint16_t)pcm[i] & 0xFF); + } +} + +static void BytesToPcm(const uint8 *bytes, int16_t *pcm) +{ + for (int i = 0; i < 160; i++) + { + pcm[i] = (int16_t)((bytes[i*2] << 8) | bytes[i*2 + 1]); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CStream::CStream() +{ + m_uiId = 0; + m_uiPort = 0; + m_uiCodecIn = CODEC_NONE; + m_uiCodecOut1 = CODEC_NONE; + m_uiCodecOut2 = CODEC_NONE; + m_uiCodecOut3 = CODEC_NONE; + m_iActivityTimeout = g_Config.GetTuning().iStreamTimeout; + m_bStopThread = false; + m_pThread = NULL; + m_VocodecChannel = NULL; + m_EncoderChannel1 = NULL; + m_EncoderChannel2 = NULL; + m_pCodec2Decoder = NULL; + m_pSignalProcessor = NULL; + m_pImbeEncoder = NULL; + m_pImbeDecoder = NULL; + m_pCodec2Encoder = NULL; + m_pStagedPacket = NULL; + m_LastActivity.Now(); + m_iTotalPackets = 0; + m_iLostPackets = 0; + m_nImbeQueueSize = 0; + m_nCodec2QueueSize = 0; +} + +CStream::CStream(uint16 uiId, const CCallsign &Callsign, const CIp &Ip, uint8 uiCodecIn, uint8 uiCodecOut1, uint8 uiCodecOut2, uint8 uiCodecOut3) +{ + m_uiId = uiId; + m_Callsign = Callsign; + m_Ip = Ip; + m_uiPort = 0; + m_uiCodecIn = uiCodecIn; + m_uiCodecOut1 = uiCodecOut1; + m_uiCodecOut2 = uiCodecOut2; + m_uiCodecOut3 = uiCodecOut3; + m_iActivityTimeout = g_Config.GetTuning().iStreamTimeout; + m_bStopThread = false; + m_pThread = NULL; + m_VocodecChannel = NULL; + m_EncoderChannel1 = NULL; + m_EncoderChannel2 = NULL; + m_pCodec2Decoder = NULL; + m_pSignalProcessor = NULL; + m_pImbeEncoder = NULL; + m_pImbeDecoder = NULL; + m_pCodec2Encoder = NULL; + m_LastActivity.Now(); + m_iTotalPackets = 0; + m_iLostPackets = 0; + m_pStagedPacket = NULL; + m_nImbeQueueSize = 0; + m_nCodec2QueueSize = 0; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CStream::~CStream() +{ + Close(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// initialization + +bool CStream::Init(uint16 uiPort) +{ + bool ok; + + // reset stop flag + m_bStopThread = false; + + // create our socket + ok = m_Socket.Open(g_AmbeServer.GetListenIp(), uiPort); + if ( ok ) + { + // Codec2 input mode: need two encoder channels + software decoder + software IMBE encoder + if (m_uiCodecIn == CODEC_CODEC2) + { + // Create Codec2 software decoder + m_pCodec2Decoder = new CCodec2(true); // true = 3200bps mode + + // Create IMBE software encoder for P25 output + m_pImbeEncoder = new imbe_vocoder(); + + // Open two encoder channels for AMBE+ and AMBE2+ output + m_EncoderChannel1 = g_Vocodecs.OpenEncoderChannel(m_uiCodecOut1); + m_EncoderChannel2 = g_Vocodecs.OpenEncoderChannel(m_uiCodecOut2); + + ok = (m_EncoderChannel1 != NULL) && (m_EncoderChannel2 != NULL); + + if ( ok ) + { + // store port + m_uiPort = uiPort; + + m_pSignalProcessor = new CSignalProcessor(CODEC_CODEC2); + + std::cout << "Codec2 input mode: software decode -> hardware encode (AMBE+ & AMBE2+) + software encode (IMBE)" << std::endl; + + // start thread + m_pThread = new std::thread(CStream::Thread, this); + + // init timeout system + m_LastActivity.Now(); + m_iTotalPackets = 0; + m_iLostPackets = 0; + } + else + { + std::cout << "Error opening stream : no suitable encoder channels available for Codec2 input" << std::endl; + // Clean up partial allocations + if (m_EncoderChannel1 != NULL) { m_EncoderChannel1->Close(); m_EncoderChannel1 = NULL; } + if (m_EncoderChannel2 != NULL) { m_EncoderChannel2->Close(); m_EncoderChannel2 = NULL; } + delete m_pCodec2Decoder; + m_pCodec2Decoder = NULL; + delete m_pImbeEncoder; + m_pImbeEncoder = NULL; + } + } + else if (m_uiCodecIn == CODEC_IMBE) + { + // IMBE input mode: need two encoder channels + software IMBE decoder + software Codec2 encoder + // Create IMBE software decoder + m_pImbeDecoder = new imbe_vocoder(); + + // Create Codec2 software encoder for 3rd output + m_pCodec2Encoder = new CCodec2(true); // true = 3200bps mode + + // Open two encoder channels for AMBE+ and AMBE2+ output + m_EncoderChannel1 = g_Vocodecs.OpenEncoderChannel(m_uiCodecOut1); + m_EncoderChannel2 = g_Vocodecs.OpenEncoderChannel(m_uiCodecOut2); + + ok = (m_EncoderChannel1 != NULL) && (m_EncoderChannel2 != NULL); + + if ( ok ) + { + // store port + m_uiPort = uiPort; + + m_pSignalProcessor = new CSignalProcessor(CODEC_IMBE); + + std::cout << "IMBE input mode: software decode -> hardware encode (AMBE+ & AMBE2+) + software encode (Codec2)" << std::endl; + std::cout << " Encoder ch1 (D-Star): in=" << m_EncoderChannel1->GetChannelIn() + << " out=" << m_EncoderChannel1->GetChannelOut() + << " codecOut=" << (int)m_EncoderChannel1->GetCodecOut() << std::endl; + std::cout << " Encoder ch2 (DMR): in=" << m_EncoderChannel2->GetChannelIn() + << " out=" << m_EncoderChannel2->GetChannelOut() + << " codecOut=" << (int)m_EncoderChannel2->GetCodecOut() << std::endl; + + // start thread + m_pThread = new std::thread(CStream::Thread, this); + + // init timeout system + m_LastActivity.Now(); + m_iTotalPackets = 0; + m_iLostPackets = 0; + } + else + { + std::cout << "Error opening stream : no suitable encoder channels available for IMBE input" << std::endl; + // Clean up partial allocations + if (m_EncoderChannel1 != NULL) { m_EncoderChannel1->Close(); m_EncoderChannel1 = NULL; } + if (m_EncoderChannel2 != NULL) { m_EncoderChannel2->Close(); m_EncoderChannel2 = NULL; } + delete m_pImbeDecoder; + m_pImbeDecoder = NULL; + delete m_pCodec2Encoder; + m_pCodec2Encoder = NULL; + } + } + else + { + // Normal AMBE input mode: open a VocodecChannel for hardware transcoding + ok &= ((m_VocodecChannel = g_Vocodecs.OpenChannel(m_uiCodecIn, m_uiCodecOut1)) != NULL); + + if ( ok ) + { + // store port + m_uiPort = uiPort; + + // Enable Codec2 encoding if second output is Codec2 + if (m_uiCodecOut2 == CODEC_CODEC2) + { + m_VocodecChannel->EnableCodec2(true); + std::cout << "Codec2 software encoding enabled for stream" << std::endl; + } + + // Enable IMBE encoding if third output is IMBE + if (m_uiCodecOut3 == CODEC_IMBE) + { + m_VocodecChannel->EnableImbe(true); + std::cout << "IMBE software encoding enabled for stream" << std::endl; + } + + // start thread + m_pThread = new std::thread(CStream::Thread, this); + + // init timeout system + m_LastActivity.Now(); + m_iTotalPackets = 0; + m_iLostPackets = 0; + } + else + { + std::cout << "Error opening stream : no suitable channel available" << std::endl; + } + } + + // if init failed after socket was opened, close the socket + if ( !ok ) + { + m_Socket.Close(); + } + } + else + { + std::cout << "Error opening socket on port UDP" << uiPort << " on ip " << g_AmbeServer.GetListenIp() << std::endl; + } + + // done + return ok; +} + +void CStream::Close(void) +{ + // Idempotent: if thread already stopped, Close() was already called + if ( m_pThread == NULL ) + return; + + // For IMBE/Codec2 input modes, wait for encoder queues to drain + // This ensures packets still in DVSI hardware FIFOs get processed and sent back + // The thread must keep running during drain to collect hardware responses + if ( (m_uiCodecIn == CODEC_IMBE || m_uiCodecIn == CODEC_CODEC2) && + m_EncoderChannel1 != NULL && m_EncoderChannel2 != NULL ) + { + const int MAX_DRAIN_MS = 500; + const int DRAIN_POLL_MS = 10; + const int HW_LATENCY_MS = 100; + int waitedMs = 0; + + // Wait for voice queues to drain (PCM waiting to be sent to hardware) + while ( waitedMs < MAX_DRAIN_MS ) + { + CPacketQueue *v1 = m_EncoderChannel1->GetVoiceQueue(); + bool v1e = v1->empty(); + m_EncoderChannel1->ReleaseVoiceQueue(); + + CPacketQueue *v2 = m_EncoderChannel2->GetVoiceQueue(); + bool v2e = v2->empty(); + m_EncoderChannel2->ReleaseVoiceQueue(); + + if ( v1e && v2e ) + break; + + std::this_thread::sleep_for(std::chrono::milliseconds(DRAIN_POLL_MS)); + waitedMs += DRAIN_POLL_MS; + } + + // Wait for hardware latency - frames already in DVSI hardware need time to return + std::this_thread::sleep_for(std::chrono::milliseconds(HW_LATENCY_MS)); + + // Now wait for output queues to drain (encoded AMBE coming back from hardware) + // Use atomic counters for software queue checks (thread-safe, relaxed ordering + // is sufficient — stale reads only cause slightly over-waiting) + waitedMs = 0; + while ( waitedMs < MAX_DRAIN_MS ) + { + CPacketQueue *q1 = m_EncoderChannel1->GetPacketQueueOut(); + bool q1e = q1->empty(); + m_EncoderChannel1->ReleasePacketQueueOut(); + + CPacketQueue *q2 = m_EncoderChannel2->GetPacketQueueOut(); + bool q2e = q2->empty(); + m_EncoderChannel2->ReleasePacketQueueOut(); + + bool swQueueEmpty; + if (m_uiCodecIn == CODEC_CODEC2) + swQueueEmpty = (m_nImbeQueueSize.load() == 0); + else + swQueueEmpty = (m_nCodec2QueueSize.load() == 0); + + if ( q1e && q2e && swQueueEmpty ) + break; + + std::this_thread::sleep_for(std::chrono::milliseconds(DRAIN_POLL_MS)); + waitedMs += DRAIN_POLL_MS; + } + } + // Plain AMBE input mode (hardware-native transcoding): drain the DVSI + // pipeline before stopping the thread and closing the channel. Without + // this, frames still inside the hardware at close time were lost when + // CVocodecChannel::Close → PurgeAllQueues() fired below — observable as + // "N packets lost at stream close" / "drain stalled" warnings on the + // xlxd side, cutting 20–40ms off the tail of the audio. + // + // Symmetric with the IMBE/Codec2 drain above but sized for the AMBE + // hardware path: no intermediate PCM voice queue (the VocodecChannel's + // PacketQueueIn feeds the USB pump thread directly), HW latency + // observed in the 15–65ms range so the 100ms cap has comfortable + // headroom. Phase 3 also waits on m_pStagedPacket because AMBE streams + // with secondary Codec2/IMBE outputs (M17/P25 cross-mode listeners) + // stage the hardware packet in Task() while the software encoder + // catches up — we must not stop the thread until that last packet + // has been sent. + else if ( m_VocodecChannel != NULL ) + { + const int MAX_DRAIN_MS = 500; + const int DRAIN_POLL_MS = 10; + const int HW_LATENCY_MS = 100; + int waitedMs = 0; + + // Phase 1: wait for the packet-in queue (packets xlxd sent that + // the USB pump hasn't yet handed to the DVSI hardware) to drain. + // The pump thread is an independent consumer of this queue; the + // Task thread only writes to it. + while ( waitedMs < MAX_DRAIN_MS ) + { + CPacketQueue *qIn = m_VocodecChannel->GetPacketQueueIn(); + bool empty = qIn->empty(); + m_VocodecChannel->ReleasePacketQueueIn(); + if ( empty ) break; + std::this_thread::sleep_for(std::chrono::milliseconds(DRAIN_POLL_MS)); + waitedMs += DRAIN_POLL_MS; + } + + // Phase 2: hard sleep for DVSI DSP latency. Frames already inside + // the hardware pipeline need wall-clock time to emerge — we cannot + // poll our way out of this, the hardware is asynchronous. + std::this_thread::sleep_for(std::chrono::milliseconds(HW_LATENCY_MS)); + + // Phase 3: wait for the packet-out queue (transcoded AMBE from HW, + // awaiting forwarding to xlxd) to drain AND for any staged packet + // to be sent. The Task thread is still running during this wait + // and is what pops from the queue and sends via m_Socket.SendVoice(). + waitedMs = 0; + while ( waitedMs < MAX_DRAIN_MS ) + { + CPacketQueue *qOut = m_VocodecChannel->GetPacketQueueOut(); + bool empty = qOut->empty(); + m_VocodecChannel->ReleasePacketQueueOut(); + if ( empty && (m_pStagedPacket == NULL) ) break; + std::this_thread::sleep_for(std::chrono::milliseconds(DRAIN_POLL_MS)); + waitedMs += DRAIN_POLL_MS; + } + } + + // Stop thread — must complete before any pointer nulling below + m_bStopThread = true; + m_pThread->join(); + delete m_pThread; + m_pThread = NULL; + + // Close socket + m_Socket.Close(); + + // Capture PID-FIFO desync drop counts BEFORE closing the channels — + // CVocodecChannel::Close calls PurgeAllQueues which resets the + // counters. We want to report the values that accumulated during + // this stream's lifetime, not 0. + uint32 totalOrphanDrops = 0; + uint32 totalOverflowDrops = 0; + if ( m_VocodecChannel != NULL ) + { + totalOrphanDrops += m_VocodecChannel->GetPidFifoOrphanDrops(); + totalOverflowDrops += m_VocodecChannel->GetPidFifoOverflowDrops(); + } + if ( m_EncoderChannel1 != NULL ) + { + totalOrphanDrops += m_EncoderChannel1->GetPidFifoOrphanDrops(); + totalOverflowDrops += m_EncoderChannel1->GetPidFifoOverflowDrops(); + } + if ( m_EncoderChannel2 != NULL ) + { + totalOrphanDrops += m_EncoderChannel2->GetPidFifoOrphanDrops(); + totalOverflowDrops += m_EncoderChannel2->GetPidFifoOverflowDrops(); + } + + // Tuning report, the thread has stopped and the channel is still open + std::string callsign = (const char *)m_Callsign; + if ( m_pSignalProcessor != NULL ) + { + m_pSignalProcessor->Report(m_uiId, callsign); + } + if ( m_VocodecChannel != NULL ) + { + m_VocodecChannel->ReportSignal(m_uiId, callsign); + } + + // Close and null vocodec channels + if ( m_VocodecChannel != NULL ) + { + m_VocodecChannel->EnableCodec2(false); + m_VocodecChannel->EnableImbe(false); + m_VocodecChannel->Close(); + m_VocodecChannel = NULL; + } + if ( m_EncoderChannel1 != NULL ) { m_EncoderChannel1->Close(); m_EncoderChannel1 = NULL; } + if ( m_EncoderChannel2 != NULL ) { m_EncoderChannel2->Close(); m_EncoderChannel2 = NULL; } + + // Delete and null software objects + if ( m_pCodec2Decoder != NULL ) { delete m_pCodec2Decoder; m_pCodec2Decoder = NULL; } + if ( m_pSignalProcessor != NULL ) { delete m_pSignalProcessor; m_pSignalProcessor = NULL; } + if ( m_pImbeEncoder != NULL ) { delete m_pImbeEncoder; m_pImbeEncoder = NULL; } + if ( m_pImbeDecoder != NULL ) { delete m_pImbeDecoder; m_pImbeDecoder = NULL; } + if ( m_pCodec2Encoder != NULL ) { delete m_pCodec2Encoder; m_pCodec2Encoder = NULL; } + + // Delete staged packet if still pending + if ( m_pStagedPacket != NULL ) + { + delete m_pStagedPacket; + m_pStagedPacket = NULL; + } + + // Clear software queues and reset counters + while ( !m_ImbeQueue.empty() ) m_ImbeQueue.pop(); + while ( !m_Codec2Queue.empty() ) m_Codec2Queue.pop(); + m_nImbeQueueSize = 0; + m_nCodec2QueueSize = 0; + + // Report + std::cout << m_iLostPackets << " of " << m_iTotalPackets << " packets lost" << std::endl; + + // PID-FIFO desync summary. Only logged when non-zero — healthy + // deployments produce nothing (avoids log spam). Real-time + // first-occurrence warnings are emitted from PushPid/PopPid in + // CVocodecChannel; this is the per-stream cumulative summary. + if ( totalOrphanDrops > 0 || totalOverflowDrops > 0 ) + { + std::cout << "PID FIFO desync summary: " + << totalOrphanDrops << " orphan drops, " + << totalOverflowDrops << " overflow drops" + << std::endl; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// thread + +void CStream::Thread(CStream *This) +{ + while ( !This->m_bStopThread ) + { + This->Task(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// task + +void CStream::Task(void) +{ + // Route to appropriate task handler based on input codec + if (m_uiCodecIn == CODEC_CODEC2) + { + TaskCodec2Input(); + } + else if (m_uiCodecIn == CODEC_IMBE) + { + TaskImbeInput(); + } + else + { + // Normal AMBE input mode + CBuffer Buffer; + CIp Ip; + uint8 uiPid; + uint8 Ambe[AMBE_FRAME_SIZE]; + uint8 Codec2[CODEC2_FRAME_SIZE]; + uint8 Imbe[IMBE_FRAME_SIZE]; + CAmbePacket *packet; + CPacketQueue *queue; + + // anything coming in from codec client ? + if ( m_Socket.Receive(&Buffer, &Ip, 1) != -1 ) + { + // crack packet + if ( IsValidDvFramePacket(Buffer, &uiPid, Ambe) ) + { + // transcode AMBE here + m_LastActivity.Now(); + m_iTotalPackets++; + + // post packet to VocoderChannel + packet = new CAmbePacket(uiPid, m_uiCodecIn, Ambe); + queue = m_VocodecChannel->GetPacketQueueIn(); + queue->push(packet); + m_VocodecChannel->ReleasePacketQueueIn(); + } + } + + // Check if we have a staged packet waiting for software codecs + if ( m_pStagedPacket != NULL ) + { + bool codec2Ready = (m_uiCodecOut2 != CODEC_CODEC2) || m_VocodecChannel->HasCodec2Data(); + bool imbeReady = (m_uiCodecOut3 != CODEC_IMBE) || m_VocodecChannel->HasImbeData(); + + if ( codec2Ready && imbeReady ) + { + // software codecs caught up — get the data and send + ::memset(Codec2, 0, CODEC2_FRAME_SIZE); + ::memset(Imbe, 0, IMBE_FRAME_SIZE); + if (m_uiCodecOut2 == CODEC_CODEC2) + m_VocodecChannel->GetCodec2Data(Codec2); + if (m_uiCodecOut3 == CODEC_IMBE) + m_VocodecChannel->GetImbeData(Imbe); + + EncodeDvFramePacket(&Buffer, m_pStagedPacket->GetPid(), m_pStagedPacket->GetAmbe(), Codec2, Imbe); + m_Socket.SendVoice(Buffer, m_Ip, m_uiPort); + delete m_pStagedPacket; + m_pStagedPacket = NULL; + } + else if ( m_StagedPacketTime.DurationSinceNow() > 1.0 ) + { + // software encoder stalled — drop after 1s to avoid blocking + m_iLostPackets++; + delete m_pStagedPacket; + m_pStagedPacket = NULL; + } + } + + // Pop from hardware output queue only if no packet is staged + if ( m_pStagedPacket == NULL ) + { + queue = m_VocodecChannel->GetPacketQueueOut(); + while ( !queue->empty() ) + { + packet = (CAmbePacket *)queue->front(); + queue->pop(); + + // check if software codecs are ready (peek, don't consume) + bool codec2Ready = (m_uiCodecOut2 != CODEC_CODEC2) || m_VocodecChannel->HasCodec2Data(); + bool imbeReady = (m_uiCodecOut3 != CODEC_IMBE) || m_VocodecChannel->HasImbeData(); + + if ( codec2Ready && imbeReady ) + { + // all codecs ready — get the data and send immediately + ::memset(Codec2, 0, CODEC2_FRAME_SIZE); + ::memset(Imbe, 0, IMBE_FRAME_SIZE); + if (m_uiCodecOut2 == CODEC_CODEC2) + m_VocodecChannel->GetCodec2Data(Codec2); + if (m_uiCodecOut3 == CODEC_IMBE) + m_VocodecChannel->GetImbeData(Imbe); + + EncodeDvFramePacket(&Buffer, packet->GetPid(), packet->GetAmbe(), Codec2, Imbe); + m_Socket.SendVoice(Buffer, m_Ip, m_uiPort); + delete packet; + } + else + { + // software codecs not ready — stage this packet and stop popping + m_pStagedPacket = packet; + m_StagedPacketTime.Now(); + break; + } + } + m_VocodecChannel->ReleasePacketQueueOut(); + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Codec2 input handling + +void CStream::TaskCodec2Input(void) +{ + CBuffer Buffer; + CIp Ip; + uint8 uiPid; + uint8 Codec2Data[CODEC2_FRAME_SIZE]; + int16_t pcmAudio[160]; // 160 samples = 20ms at 8kHz + uint8 ImbeData[IMBE_FRAME_SIZE]; + + // anything coming in from codec client ? + if ( m_Socket.Receive(&Buffer, &Ip, 1) != -1 ) + { + // crack Codec2 packet + if ( IsValidCodec2FramePacket(Buffer, &uiPid, Codec2Data) ) + { + m_LastActivity.Now(); + m_iTotalPackets++; + + // Software decode Codec2 to PCM + m_pCodec2Decoder->codec2_decode(pcmAudio, Codec2Data); + + // Big-endian PCM through the decode gain, filter and AGC + uint8 pcmBytes[320]; + PcmToBytes(pcmAudio, pcmBytes); + m_pSignalProcessor->Process(pcmBytes, 320); + + // Software encode PCM to IMBE for P25 output (3rd codec) + uint8 pcmForImbe[320]; + ::memcpy(pcmForImbe, pcmBytes, 320); + m_pSignalProcessor->ProcessOutput(CODEC_IMBE, pcmForImbe, 320); + BytesToPcm(pcmForImbe, pcmAudio); + m_pImbeEncoder->encode_4400(pcmAudio, ImbeData); + + // Queue the IMBE data for later retrieval when hardware encoders return + // Drop oldest if queue exceeds max depth (hardware stall protection) + if ( m_ImbeQueue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) + { + m_ImbeQueue.pop(); + m_nImbeQueueSize--; + } + std::vector imbeVec(ImbeData, ImbeData + IMBE_FRAME_SIZE); + m_ImbeQueue.push(imbeVec); + m_nImbeQueueSize++; + + // PID-preservation: push the input packet's PID into both + // encoder channels' FIFOs so the matching pops in the USB + // interface (when the AMBE responses arrive from hardware) + // can re-attach the correct PID to the output packets. The + // response builder below uses packet1->GetPid() for the + // outbound response, so channel 1's pid is the one that + // matters; channel 2's is pushed for symmetry / future- + // proofing in case any future code path reads packet2's pid. + m_EncoderChannel1->PushPid(uiPid); + m_EncoderChannel2->PushPid(uiPid); + + // Push to the encoder channels (AMBE+ and AMBE2+) + PushEncoderPcm(m_EncoderChannel1, m_uiCodecOut1, pcmBytes); + PushEncoderPcm(m_EncoderChannel2, m_uiCodecOut2, pcmBytes); + } + } + + // Check for encoded output from both hardware channels and IMBE queue + // We need output from all three before we can send a response + // Each queue lock is acquired and released independently to prevent ABBA deadlock + // TOCTOU safety: only this thread pops from these queues; USB threads only push + bool ready; + do { + ready = false; + + bool q1has, q2has; + { + CPacketQueue *q = m_EncoderChannel1->GetPacketQueueOut(); + q1has = !q->empty(); + m_EncoderChannel1->ReleasePacketQueueOut(); + } + { + CPacketQueue *q = m_EncoderChannel2->GetPacketQueueOut(); + q2has = !q->empty(); + m_EncoderChannel2->ReleasePacketQueueOut(); + } + + if ( q1has && q2has && !m_ImbeQueue.empty() ) + { + CAmbePacket *packet1; + { + CPacketQueue *q = m_EncoderChannel1->GetPacketQueueOut(); + packet1 = (CAmbePacket *)q->front(); + q->pop(); + m_EncoderChannel1->ReleasePacketQueueOut(); + } + CAmbePacket *packet2; + { + CPacketQueue *q = m_EncoderChannel2->GetPacketQueueOut(); + packet2 = (CAmbePacket *)q->front(); + q->pop(); + m_EncoderChannel2->ReleasePacketQueueOut(); + } + + std::vector imbeData = m_ImbeQueue.front(); + m_ImbeQueue.pop(); + m_nImbeQueueSize--; + + Buffer.clear(); + Buffer.Append((uint8)m_uiCodecOut1); + Buffer.Append((uint8)packet1->GetPid()); + Buffer.Append(packet1->GetAmbe(), AMBE_FRAME_SIZE); + Buffer.Append((uint8)m_uiCodecOut2); + Buffer.Append(packet2->GetAmbe(), AMBE_FRAME_SIZE); + Buffer.Append((uint8)m_uiCodecOut3); + Buffer.Append(imbeData.data(), IMBE_FRAME_SIZE); + + m_Socket.SendVoice(Buffer, m_Ip, m_uiPort); + + delete packet1; + delete packet2; + ready = true; + } + } while (ready); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Codec2 and IMBE input: PCM to the hardware encoders + +void CStream::PushEncoderPcm(CVocodecChannel *Channel, uint8 uiCodecOut, const uint8 *pcmBytes) +{ + // One copy for each encoder, each at its own level + uint8 pcm[320]; + ::memcpy(pcm, pcmBytes, 320); + m_pSignalProcessor->ProcessOutput(uiCodecOut, pcm, 320); + + CVoicePacket *voicePacket = new CVoicePacket(pcm, 320); + voicePacket->SetChannel(Channel->GetChannelOut()); + + CPacketQueue *queue = Channel->GetVoiceQueue(); + queue->push(voicePacket); + Channel->ReleaseVoiceQueue(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// IMBE input handling + +void CStream::TaskImbeInput(void) +{ + CBuffer Buffer; + CIp Ip; + uint8 uiPid; + uint8 ImbeData[IMBE_FRAME_SIZE]; + int16_t pcmAudio[160]; // 160 samples = 20ms at 8kHz + uint8 Codec2Data[CODEC2_FRAME_SIZE]; + + // anything coming in from codec client ? + if ( m_Socket.Receive(&Buffer, &Ip, 1) != -1 ) + { + // crack IMBE packet + if ( IsValidImbeFramePacket(Buffer, &uiPid, ImbeData) ) + { + m_LastActivity.Now(); + m_iTotalPackets++; + + // Software decode IMBE to PCM + // imbe_vocoder::decode_4400(int16_t *snd, uint8_t *imbe) + m_pImbeDecoder->decode_4400(pcmAudio, ImbeData); + + // Big-endian PCM through the decode gain, filter and AGC + uint8 pcmBytes[320]; + PcmToBytes(pcmAudio, pcmBytes); + m_pSignalProcessor->Process(pcmBytes, 320); + + // Software encode PCM to Codec2 for M17 output (3rd codec) + uint8 pcmForCodec2[320]; + ::memcpy(pcmForCodec2, pcmBytes, 320); + m_pSignalProcessor->ProcessOutput(CODEC_CODEC2, pcmForCodec2, 320); + BytesToPcm(pcmForCodec2, pcmAudio); + m_pCodec2Encoder->codec2_encode(Codec2Data, pcmAudio); + + // Queue the Codec2 data for later retrieval when hardware encoders return + // Drop oldest if queue exceeds max depth (hardware stall protection) + if ( m_Codec2Queue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) + { + m_Codec2Queue.pop(); + m_nCodec2QueueSize--; + } + std::vector c2vec(Codec2Data, Codec2Data + CODEC2_FRAME_SIZE); + m_Codec2Queue.push(c2vec); + m_nCodec2QueueSize++; + + // PID-preservation: push the input packet's PID into both + // encoder channels' FIFOs so the matching pops in the USB + // interface (when the AMBE responses arrive from hardware) + // can re-attach the correct PID. Same rationale as + // TaskCodec2Input above. + m_EncoderChannel1->PushPid(uiPid); + m_EncoderChannel2->PushPid(uiPid); + + // Push to the encoder channels (AMBE+ and AMBE2+) + PushEncoderPcm(m_EncoderChannel1, m_uiCodecOut1, pcmBytes); + PushEncoderPcm(m_EncoderChannel2, m_uiCodecOut2, pcmBytes); + } + } + + // Check for encoded output from both hardware channels and Codec2 queue + // Each queue lock is acquired and released independently to prevent ABBA deadlock + // TOCTOU safety: only this thread pops from these queues; USB threads only push + bool ready; + do { + ready = false; + + bool q1has, q2has; + { + CPacketQueue *q = m_EncoderChannel1->GetPacketQueueOut(); + q1has = !q->empty(); + m_EncoderChannel1->ReleasePacketQueueOut(); + } + { + CPacketQueue *q = m_EncoderChannel2->GetPacketQueueOut(); + q2has = !q->empty(); + m_EncoderChannel2->ReleasePacketQueueOut(); + } + + if ( q1has && q2has && !m_Codec2Queue.empty() ) + { + CAmbePacket *packet1; + { + CPacketQueue *q = m_EncoderChannel1->GetPacketQueueOut(); + packet1 = (CAmbePacket *)q->front(); + q->pop(); + m_EncoderChannel1->ReleasePacketQueueOut(); + } + CAmbePacket *packet2; + { + CPacketQueue *q = m_EncoderChannel2->GetPacketQueueOut(); + packet2 = (CAmbePacket *)q->front(); + q->pop(); + m_EncoderChannel2->ReleasePacketQueueOut(); + } + + std::vector c2data = m_Codec2Queue.front(); + m_Codec2Queue.pop(); + m_nCodec2QueueSize--; + + Buffer.clear(); + Buffer.Append((uint8)m_uiCodecOut1); + Buffer.Append((uint8)packet1->GetPid()); + Buffer.Append(packet1->GetAmbe(), AMBE_FRAME_SIZE); + Buffer.Append((uint8)m_uiCodecOut2); + Buffer.Append(packet2->GetAmbe(), AMBE_FRAME_SIZE); + Buffer.Append((uint8)m_uiCodecOut3); + Buffer.Append(c2data.data(), CODEC2_FRAME_SIZE); + + m_Socket.SendVoice(Buffer, m_Ip, m_uiPort); + + delete packet1; + delete packet2; + ready = true; + } + } while (ready); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// packet decoding helpers + +bool CStream::IsValidDvFramePacket(const CBuffer &Buffer, uint8 *pid, uint8 *ambe) +{ + bool valid = false; + + if ( Buffer.size() == 11 ) + { + uint8 codec = Buffer.data()[0]; + *pid = Buffer.data()[1]; + ::memcpy(ambe, &(Buffer.data()[2]), 9); + valid = (codec == GetCodecIn()); + } + + return valid; +} + +bool CStream::IsValidCodec2FramePacket(const CBuffer &Buffer, uint8 *pid, uint8 *codec2) +{ + bool valid = false; + + // Codec2 packet format: codec(1) + pid(1) + codec2_data(8) = 10 bytes + if ( Buffer.size() == 10 ) + { + uint8 codec = Buffer.data()[0]; + *pid = Buffer.data()[1]; + ::memcpy(codec2, &(Buffer.data()[2]), CODEC2_FRAME_SIZE); + valid = (codec == CODEC_CODEC2); + } + + return valid; +} + +bool CStream::IsValidImbeFramePacket(const CBuffer &Buffer, uint8 *pid, uint8 *imbe) +{ + bool valid = false; + + // IMBE packet format: codec(1) + pid(1) + imbe_data(11) = 13 bytes + if ( Buffer.size() == 13 ) + { + uint8 codec = Buffer.data()[0]; + *pid = Buffer.data()[1]; + ::memcpy(imbe, &(Buffer.data()[2]), IMBE_FRAME_SIZE); + valid = (codec == CODEC_IMBE); + } + + return valid; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// packet encoding helpers + +void CStream::EncodeDvFramePacket(CBuffer *Buffer, uint8 Pid, uint8 *Ambe, uint8 *Codec2, uint8 *Imbe) +{ + Buffer->clear(); + + // Combined response format: + // codec1(1) + pid(1) + ambe1(9) + codec2(1) + codec2_data(8) + codec3(1) + imbe(11) = 32 bytes + // First output codec (AMBE+ or AMBE2+) + Buffer->Append((uint8)GetCodecOut1()); + Buffer->Append((uint8)Pid); + Buffer->Append(Ambe, AMBE_FRAME_SIZE); + + // Second output codec (Codec2 for M17) + Buffer->Append((uint8)GetCodecOut2()); + Buffer->Append(Codec2, CODEC2_FRAME_SIZE); + + // Third output codec (IMBE for P25) + Buffer->Append((uint8)GetCodecOut3()); + Buffer->Append(Imbe, IMBE_FRAME_SIZE); +} + diff --git a/cstream.h b/cstream.h new file mode 100644 index 0000000..f34424d --- /dev/null +++ b/cstream.h @@ -0,0 +1,142 @@ +// +// cstream.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 15/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cstream_h +#define cstream_h + +#include +#include +#include "cudpsocket.h" +#include "ccallsign.h" +#include "cambepacket.h" +#include "cvocodecchannel.h" +#include "csignalprocessor.h" +#include "codec2/codec2.h" +#include "imbe/imbe_vocoder.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CStream +{ +public: + // constructors + CStream(); + CStream(uint16, const CCallsign &, const CIp &, uint8, uint8, uint8, uint8); + + // destructor + virtual ~CStream(); + + // initialization + bool Init(uint16); + void Close(void); + + // get + uint16 GetId(void) const { return m_uiId; } + uint16 GetPort(void) const { return m_uiPort; } + uint8 GetCodecIn(void) const { return m_uiCodecIn; } + uint8 GetCodecOut(void) const { return m_uiCodecOut1; } + uint8 GetCodecOut1(void) const { return m_uiCodecOut1; } + uint8 GetCodecOut2(void) const { return m_uiCodecOut2; } + uint8 GetCodecOut3(void) const { return m_uiCodecOut3; } + + // activity timer + bool IsActive(void) const { return m_LastActivity.DurationSinceNow() <= m_iActivityTimeout; } + + // task + static void Thread(CStream *); + void Task(void); + +protected: + // packet decoding helpers + bool IsValidDvFramePacket(const CBuffer &, uint8 *, uint8 *); + bool IsValidCodec2FramePacket(const CBuffer &, uint8 *, uint8 *); + bool IsValidImbeFramePacket(const CBuffer &, uint8 *, uint8 *); + + // packet encoding helpers + void EncodeDvFramePacket(CBuffer *, uint8, uint8 *, uint8 *, uint8 *); + + // Codec2 input handling + void TaskCodec2Input(void); + + // IMBE input handling + void TaskImbeInput(void); + + // Codec2 and IMBE input: PCM to the hardware encoders + void PushEncoderPcm(CVocodecChannel *, uint8 uiCodecOut, const uint8 *pcmBytes); + +protected: + // data + uint16 m_uiId; + CUdpSocket m_Socket; + uint16 m_uiPort; + uint8 m_uiCodecIn; + uint8 m_uiCodecOut1; + uint8 m_uiCodecOut2; + uint8 m_uiCodecOut3; + CVocodecChannel *m_VocodecChannel; + + // Codec2 input mode: two encoder channels + decoder + signal processors + IMBE encoder + CVocodecChannel *m_EncoderChannel1; // AMBE+ encoder + CVocodecChannel *m_EncoderChannel2; // AMBE2+ encoder + CCodec2 *m_pCodec2Decoder; // Software Codec2 decoder + CSignalProcessor *m_pSignalProcessor; // Decode gain, filter, AGC and encode gains + imbe_vocoder *m_pImbeEncoder; // Software IMBE encoder for Codec2 input + std::queue> m_ImbeQueue; // Queue for IMBE data in Codec2 input mode + + // IMBE input mode: IMBE decoder + Codec2 encoder + imbe_vocoder *m_pImbeDecoder; // Software IMBE decoder + CCodec2 *m_pCodec2Encoder; // Software Codec2 encoder for IMBE input + std::queue> m_Codec2Queue; // Queue for Codec2 data in IMBE input mode + + // Atomic counters for software queue sizes (for thread-safe drain checks in Close()) + std::atomic m_nImbeQueueSize; + std::atomic m_nCodec2QueueSize; + + // activity timeout, in seconds + int m_iActivityTimeout; + + // client details + CCallsign m_Callsign; + CIp m_Ip; + + // counters + std::atomic m_iTotalPackets; + std::atomic m_iLostPackets; + + // staged packet waiting for software codecs to catch up + CAmbePacket *m_pStagedPacket; + CTimePoint m_StagedPacketTime; + + // activity timer + CTimePoint m_LastActivity; + + // thread + std::atomic m_bStopThread; + std::thread *m_pThread; + +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cstream_h */ diff --git a/ctimepoint.cpp b/ctimepoint.cpp new file mode 100644 index 0000000..41b59f0 --- /dev/null +++ b/ctimepoint.cpp @@ -0,0 +1,53 @@ +// +// ctimepoint.cpp +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 05/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "ctimepoint.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CTimePoint::CTimePoint() +{ + m_TimePoint = std::chrono::steady_clock::now(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// operation + +double CTimePoint::DurationSinceNow(void) const +{ + std::chrono::steady_clock::time_point Now = std::chrono::steady_clock::now(); + std::chrono::steady_clock::duration time_span = (Now - m_TimePoint); + return double(time_span.count()) * std::chrono::steady_clock::period::num / std::chrono::steady_clock::period::den; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// task + +void CTimePoint::TaskSleepFor(uint ms) +{ + std::chrono::milliseconds timespan(ms); + std::this_thread::sleep_for(timespan); +} diff --git a/ctimepoint.h b/ctimepoint.h new file mode 100644 index 0000000..9a9e5a2 --- /dev/null +++ b/ctimepoint.h @@ -0,0 +1,55 @@ +// +// ctimepoint.h +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 05/11/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef ctimepoint_h +#define ctimepoint_h + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CTimePoint : public std::chrono::steady_clock::time_point +{ +public: + // constructor + CTimePoint(); + + // destructor + virtual ~CTimePoint() {} + + // operation + void Now(void) { m_TimePoint = std::chrono::steady_clock::now(); } + double DurationSinceNow(void) const; + + // task + static void TaskSleepFor(uint); + +protected: + // data + std::chrono::steady_clock::time_point m_TimePoint; +}; + + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* ctimepoint_h */ diff --git a/cudpsocket.cpp b/cudpsocket.cpp new file mode 100644 index 0000000..68eed1e --- /dev/null +++ b/cudpsocket.cpp @@ -0,0 +1,237 @@ +// +// cudpsocket.cpp +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include +#include "cudpsocket.h" +#include "cconfig.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CUdpSocket::CUdpSocket() +{ + m_Socket = -1; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CUdpSocket::~CUdpSocket() +{ + if ( m_Socket != -1 ) + { + Close(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// open & close + +bool CUdpSocket::Open(const CIp &ListenIp, uint16 uiPort) +{ + bool open = false; + + // create socket + m_Socket = socket(PF_INET,SOCK_DGRAM,0); + if ( m_Socket != -1 ) + { + // initialize sockaddr struct + ::memset(&m_SocketAddr, 0, sizeof(struct sockaddr_in)); + m_SocketAddr.sin_family = AF_INET; + m_SocketAddr.sin_port = htons(uiPort); + m_SocketAddr.sin_addr.s_addr = inet_addr(ListenIp); + + if ( bind(m_Socket, (struct sockaddr *)&m_SocketAddr, sizeof(struct sockaddr_in)) == 0 ) + { + fcntl(m_Socket, F_SETFL, O_NONBLOCK); + open = true; + } + else + { + close(m_Socket); + m_Socket = -1; + } + } + + // done + return open; +} + +void CUdpSocket::Close(void) +{ + if ( m_Socket != -1 ) + { + close(m_Socket); + m_Socket = -1; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// read + +int CUdpSocket::Receive(CBuffer *Buffer, CIp *Ip, int timeout) +{ + struct sockaddr_in Sin; + fd_set FdSet; + unsigned int uiFromLen = sizeof(struct sockaddr_in); + int iRecvLen = -1; + struct timeval tv; + + // socket valid ? + if ( m_Socket != -1 ) + { + // control socket + FD_ZERO(&FdSet); + FD_SET(m_Socket, &FdSet); + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + select(m_Socket + 1, &FdSet, 0, 0, &tv); + + // allocate buffer + Buffer->resize(UDP_BUFFER_LENMAX); + + // read + iRecvLen = (int)recvfrom(m_Socket, + (void *)Buffer->data(), UDP_BUFFER_LENMAX, + 0, (struct sockaddr *)&Sin, &uiFromLen); + + // handle + if ( iRecvLen != -1 ) + { + // adjust buffer size + Buffer->resize(iRecvLen); + + // get IP + Ip->SetSockAddr(&Sin); + } + } + + // done + return iRecvLen; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// write + +int CUdpSocket::Send(const CBuffer &Buffer, const CIp &Ip) +{ + CIp temp(Ip); + return (int)::sendto(m_Socket, + (void *)Buffer.data(), Buffer.size(), + 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); +} + +int CUdpSocket::Send(const char *Buffer, const CIp &Ip) +{ + CIp temp(Ip); + return (int)::sendto(m_Socket, + (void *)Buffer, ::strlen(Buffer), + 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); +} + +int CUdpSocket::Send(const CBuffer &Buffer, const CIp &Ip, uint16 destport) +{ + CIp temp(Ip); + temp.GetSockAddr()->sin_port = htons(destport); + return (int)::sendto(m_Socket, + (void *)Buffer.data(), Buffer.size(), + 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); +} + +int CUdpSocket::Send(const char *Buffer, const CIp &Ip, uint16 destport) +{ + CIp temp(Ip); + temp.GetSockAddr()->sin_port = htons(destport); + return (int)::sendto(m_Socket, + (void *)Buffer, ::strlen(Buffer), + 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// write - voice packets with DSCP marking + +static void SetTos(int socket, int tos) +{ + setsockopt(socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); +} + +int CUdpSocket::SendVoice(const CBuffer &Buffer, const CIp &Ip) +{ + int tos = g_Config.GetVoiceTos(); + if ( tos < 0 ) + { + return Send(Buffer, Ip); + } + + SetTos(m_Socket, tos); + + CIp temp(Ip); + int result = (int)::sendto(m_Socket, + (void *)Buffer.data(), Buffer.size(), + 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); + + // Reset TOS for non-voice packets + SetTos(m_Socket, 0); + + return result; +} + +int CUdpSocket::SendVoice(const CBuffer &Buffer, const CIp &Ip, uint16 destport) +{ + int tos = g_Config.GetVoiceTos(); + if ( tos < 0 ) + { + return Send(Buffer, Ip, destport); + } + + SetTos(m_Socket, tos); + + CIp temp(Ip); + temp.GetSockAddr()->sin_port = htons(destport); + int result = (int)::sendto(m_Socket, + (void *)Buffer.data(), Buffer.size(), + 0, (struct sockaddr *)temp.GetSockAddr(), sizeof(struct sockaddr_in)); + + // Reset TOS for non-voice packets + SetTos(m_Socket, 0); + + return result; +} + +void CUdpSocket::LogDscpStatus(void) +{ + int tos = g_Config.GetVoiceTos(); + if ( tos < 0 ) + { + std::cout << "Voice packets not DSCP marked" << std::endl; + } + else + { + std::cout << "Voice packets marked as DSCP " << (tos >> 2) << std::endl; + } +} + diff --git a/cudpsocket.h b/cudpsocket.h new file mode 100644 index 0000000..eba1320 --- /dev/null +++ b/cudpsocket.h @@ -0,0 +1,84 @@ +// +// cudpsocket.h +// xlxd +// +// Created by Jean-Luc Deltombe (LX3JL) on 31/10/2015. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of xlxd. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cudpsocket_h +#define cudpsocket_h + +#include +//#include +#include +#include +#include +#include +#include + +#include "main.h" +#include "cip.h" +#include "cbuffer.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +#define UDP_BUFFER_LENMAX 1024 + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CUdpSocket +{ +public: + // constructor + CUdpSocket(); + + // destructor + ~CUdpSocket(); + + // open & close + bool Open(const CIp &, uint16); + void Close(void); + int GetSocket(void) { return m_Socket; } + + // read + int Receive(CBuffer *, CIp *, int); + + // write + int Send(const CBuffer &, const CIp &); + int Send(const CBuffer &, const CIp &, uint16); + int Send(const char *, const CIp &); + int Send(const char *, const CIp &, uint16); + + // write - voice packets with DSCP marking + int SendVoice(const CBuffer &, const CIp &); + int SendVoice(const CBuffer &, const CIp &, uint16); + static void LogDscpStatus(void); + +protected: + // data + int m_Socket; + struct sockaddr_in m_SocketAddr; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cudpsocket_h */ diff --git a/cusb3000interface.cpp b/cusb3000interface.cpp new file mode 100644 index 0000000..6080507 --- /dev/null +++ b/cusb3000interface.cpp @@ -0,0 +1,297 @@ +// +// cusb3000interface.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 21/08/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "ctimepoint.h" +#include "cambepacket.h" +#include "cusb3000interface.h" +#include "cvocodecs.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// configuration: +// +// PKT_CHANNEL0 = HYBRID + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CUsb3000Interface::CUsb3000Interface(uint32 uiVid, uint32 uiPid, const char *szDeviceName, const char *szDeviceSerial) +: CUsb3xxxInterface(uiVid, uiPid, szDeviceName, szDeviceSerial) +{ + m_uiChCodec = CODEC_NONE; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// initialization + +bool CUsb3000Interface::Init(uint8 uiOddCodec) +{ + bool ok = true; + + // init the odd channel + m_uiChCodec = uiOddCodec; + + // base class + ok &= CUsb3xxxInterface::Init(); + + // do not create our channels now + // this is delegated to caller (CVocodecs) as our channel + // may be hybrids between 2 interfaces in case of odd n' of channel device) + + // done + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// manage Channels + +uint8 CUsb3000Interface::GetChannelCodec(int iCh) const +{ + return (iCh == 0) ? m_uiChCodec : CODEC_NONE; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// manage vocodec channels + +CVocodecChannel *CUsb3000Interface::GetChannelWithChannelIn(int iCh) +{ + CVocodecChannel *Channel = NULL; + bool done = false; + for ( int i = 0; (i < m_Channels.size()) && !done; i++ ) + { + if ( iCh == 0 ) + { + if ( (m_Channels[i]->GetChannelIn() == iCh) && !(m_Channels[i]->IsInterfaceOut(this)) ) + { + Channel = m_Channels[i]; + done = true; + } + } + } + return Channel; +} + +CVocodecChannel *CUsb3000Interface::GetChannelWithChannelOut(int iCh) +{ + CVocodecChannel *Channel = NULL; + bool done = false; + for ( int i = 0; (i < m_Channels.size()) && !done; i++ ) + { + if ( (m_Channels[i]->GetChannelOut() == iCh) && (m_Channels[i]->IsInterfaceOut(this)) ) + { + Channel = m_Channels[i]; + done = true; + } + } + return Channel; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// decoder helper + +bool CUsb3000Interface::IsValidChannelPacket(const CBuffer &buffer, int *ch, CAmbePacket *packet) +{ + bool valid = false; + uint8 tag[] = { PKT_HEADER,0x00,0x0B,PKT_CHANNEL }; + + if ( (buffer.size() == 15) && (buffer.Compare(tag, sizeof(tag)) == 0)) + { + *ch = 0; + packet->SetCodec(m_uiChCodec); + packet->SetAmbe(&(buffer.data()[6])); + valid = (*ch < GetNbChannels()); + //std::cout << "CHAN " << *ch << " " << buffer.size() << " " << (int)buffer[6] << std::endl; + } + return valid; +} + +bool CUsb3000Interface::IsValidSpeechPacket(const CBuffer &buffer, int *ch, CVoicePacket *packet) +{ + bool valid = false; + + if ( (buffer.size() > 6) && + (buffer.data()[0] == PKT_HEADER) && (buffer.data()[3] == PKT_SPEECH) && + (buffer.data()[4] == PKT_SPEECHD) ) + { + *ch = 0; + packet->SetVoice(&(buffer.data()[6]), buffer.data()[5] * 2); + valid = (*ch < GetNbChannels()); + //std::cout << "SPCH " << *ch << " " << buffer.size() << std::endl; + } + return valid; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// encoder helpers + +void CUsb3000Interface::EncodeChannelPacket(CBuffer *buffer, int ch, CAmbePacket *packet) +{ + uint size = (uint16)packet->GetAmbeSize() + 2; + buffer->clear(); + buffer->Append((uint8)PKT_HEADER); + buffer->Append((uint8)HIBYTE(size)); + buffer->Append((uint8)LOBYTE(size)); + buffer->Append((uint8)PKT_CHANNEL); + buffer->Append((uint8)(PKT_CHAND)); + buffer->Append((uint8)(packet->GetAmbeSize()*8)); + buffer->Append(packet->GetAmbe(), packet->GetAmbeSize()); +} + +void CUsb3000Interface::EncodeSpeechPacket(CBuffer *buffer, int ch, CVoicePacket *packet) +{ + uint16 size = (uint16)packet->GetVoiceSize() + 2; + buffer->clear(); + buffer->Append((uint8)PKT_HEADER); + buffer->Append((uint8)HIBYTE(size)); + buffer->Append((uint8)LOBYTE(size)); + buffer->Append((uint8)PKT_SPEECH); + buffer->Append((uint8)PKT_SPEECHD); + buffer->Append((uint8)(packet->GetVoiceSize()/2)); + buffer->Append(packet->GetVoice(), packet->GetVoiceSize()); +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// low level + +bool CUsb3000Interface::OpenDevice(void) +{ + FT_STATUS ftStatus; + int baudrate = 460800; + + //sets serial VID/PID for a Standard Device NOTE: This is for legacy purposes only. This can be ommitted. + ftStatus = FT_SetVIDPID(m_uiVid, m_uiPid); + if (ftStatus != FT_OK) {FTDI_Error((char *)"FT_SetVIDPID", ftStatus ); return false; } + + ftStatus = FT_OpenEx((PVOID)m_szDeviceSerial, FT_OPEN_BY_SERIAL_NUMBER, &m_FtdiHandle); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_OpenEx", ftStatus ); return false; } + + CTimePoint::TaskSleepFor(50); + FT_Purge(m_FtdiHandle, FT_PURGE_RX | FT_PURGE_TX ); + CTimePoint::TaskSleepFor(50); + + ftStatus = FT_SetDataCharacteristics(m_FtdiHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE); + if ( ftStatus != FT_OK ) { FTDI_Error((char *)"FT_SetDataCharacteristics", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetFlowControl(m_FtdiHandle, FT_FLOW_RTS_CTS, 0x11, 0x13); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetFlowControl", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetRts (m_FtdiHandle); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetRts", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + //for usb-3012 pull DTR high to take AMBE3003 out of reset. + //for other devices noting is connected to DTR so it is a dont care + ftStatus = FT_ClrDtr(m_FtdiHandle); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_ClrDtr", ftStatus); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetBaudRate(m_FtdiHandle, baudrate ); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetBaudRate", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetLatencyTimer(m_FtdiHandle, 4); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetLatencyTimer", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetUSBParameters(m_FtdiHandle, USB3XXX_MAXPACKETSIZE, 0); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetUSBParameters", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetTimeouts(m_FtdiHandle, 200, 200 ); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetTimeouts", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + // done + return true; +} + +bool CUsb3000Interface::ResetDevice(void) +{ + bool ok = false; + int len; + char rxpacket[100]; + char zeropacket[10] = + { + 0,0,0,0,0,0,0,0,0,0 + }; + char txpacket[7] = + { + PKT_HEADER, + 0, + 3, + 0, + PKT_RESET, + PKT_PARITYBYTE, + 3 ^ PKT_RESET ^ PKT_PARITYBYTE + }; + + + //the chip might be in a state where it is waiting to receive bytes from a prior incomplete packet. + //first send 350 zeros in case, the chip's receive state is still waiting for characters + //if we send more than needed, the exta characters will just get discarded since they do not match the header byte + //after that we send PKT_RESET to reset the device + //As long as the AMBE3000 is able to receive via uart, this method will succeed in resetting it. + + for ( int i = 0; i < 35 ; i++ ) + { + FTDI_write_packet(m_FtdiHandle, zeropacket, sizeof(zeropacket)); + } + + + // write soft-reset packet + if ( FTDI_write_packet(m_FtdiHandle, txpacket, sizeof(txpacket)) ) + { + // read reply + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ); + ok = ((len == 5) && (rxpacket[4] == PKT_READY)); + if ( !ok ) + { + std::cout << "USB-3000 soft reset failed" << std::endl; + } + } + + // done + return ok; +} + +bool CUsb3000Interface::ConfigureDevice(void) +{ + bool ok = true; + uint8 pkt_ratep_ambeplus[] = { 0x01,0x30,0x07,0x63,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x48 }; + uint8 pkt_ratep_ambe2plus[] = { 0x04,0x31,0x07,0x54,0x24,0x00,0x00,0x00,0x00,0x00,0x6F,0x48 }; + + // configure the channel for desired codec + switch ( m_uiChCodec ) + { + case CODEC_AMBEPLUS: + ok &= ConfigureChannel(PKT_CHANNEL0, pkt_ratep_ambeplus, 0, 0); + break; + case CODEC_AMBE2PLUS: + ok &= ConfigureChannel(PKT_CHANNEL0, pkt_ratep_ambe2plus, 0, 0); + break; + case CODEC_NONE: + default: + break; + } + + // done + return ok; +} diff --git a/cusb3000interface.h b/cusb3000interface.h new file mode 100644 index 0000000..1968b7b --- /dev/null +++ b/cusb3000interface.h @@ -0,0 +1,80 @@ +// +// cusb3000interface.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 21/08/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cusb3000interface_h +#define cusb3000interface_h + + +#include "ftd2xx.h" +#include "cbuffer.h" +#include "cusb3xxxinterface.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +#define USB3000_NB_CH 1 + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CUsb3000Interface : public CUsb3xxxInterface +{ +public: + // constructors + CUsb3000Interface(uint32, uint32, const char *, const char *); + + // destructor + virtual ~CUsb3000Interface() {} + + // initialization + bool Init(uint8); + + // manage channels + int GetNbChannels(void) const { return USB3000_NB_CH; } + uint8 GetChannelCodec(int) const; + + // manage vocodec channels + CVocodecChannel *GetChannelWithChannelIn(int); + CVocodecChannel *GetChannelWithChannelOut(int); + +protected: + // decoder helper + bool IsValidChannelPacket(const CBuffer &, int *, CAmbePacket *); + bool IsValidSpeechPacket(const CBuffer &, int *, CVoicePacket *); + + // encoder helpers + void EncodeChannelPacket(CBuffer *, int, CAmbePacket *); + void EncodeSpeechPacket(CBuffer *, int, CVoicePacket *); + + // low level + bool OpenDevice(void); + bool ResetDevice(void); + bool ConfigureDevice(void); + + // data + uint8 m_uiChCodec; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cusb3000interface_h */ diff --git a/cusb3003df2etinterface.cpp b/cusb3003df2etinterface.cpp new file mode 100644 index 0000000..6dbc92a --- /dev/null +++ b/cusb3003df2etinterface.cpp @@ -0,0 +1,164 @@ +// +// cusb3003df2etinterface.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) and Florian Wolters (DF2ET) on 03/11/2017. +// Copyright © 2017 Jean-Luc Deltombe (LX3JL) and Florian Wolters (DF2ET). +// All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- +// Created by Florian Wolters (DF2ET) on 03/11/2017. +// Copyright © 2017 Florian Wolters (DF2ET). All rights reserved. + +#include "main.h" +#include "ctimepoint.h" +#include "cambepacket.h" +#include "cusb3003df2etinterface.h" +#include "cvocodecs.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CUsb3003DF2ETInterface::CUsb3003DF2ETInterface(uint32 uiVid, uint32 uiPid, const char *szDeviceName, const char *szDeviceSerial) +: CUsb3003Interface(uiVid, uiPid, szDeviceName, szDeviceSerial) +{ +} + +//////////////////////////////////////////////////////////////////////////////////////// +// low level + +bool CUsb3003DF2ETInterface::OpenDevice(void) +{ + FT_STATUS ftStatus; + int baudrate = 921600; + + //sets serial VID/PID for a Standard Device NOTE: This is for legacy purposes only. This can be ommitted. + ftStatus = FT_SetVIDPID(m_uiVid, m_uiPid); + if (ftStatus != FT_OK) {FTDI_Error((char *)"FT_SetVIDPID", ftStatus ); return false; } + + ftStatus = FT_OpenEx((PVOID)m_szDeviceSerial, FT_OPEN_BY_SERIAL_NUMBER, &m_FtdiHandle); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_OpenEx", ftStatus ); return false; } + + CTimePoint::TaskSleepFor(50); + FT_Purge(m_FtdiHandle, FT_PURGE_RX | FT_PURGE_TX ); + CTimePoint::TaskSleepFor(50); + + ftStatus = FT_SetDataCharacteristics(m_FtdiHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE); + if ( ftStatus != FT_OK ) { FTDI_Error((char *)"FT_SetDataCharacteristics", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetFlowControl(m_FtdiHandle, FT_FLOW_RTS_CTS, 0x11, 0x13); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetFlowControl", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetRts (m_FtdiHandle); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetRts", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + // for DF2ET-3003 interface pull DTR low to take AMBE3003 out of reset. + ftStatus = FT_SetDtr( m_FtdiHandle ); + CTimePoint::TaskSleepFor(50); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetDtr", ftStatus); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetBaudRate(m_FtdiHandle, baudrate ); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetBaudRate", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetLatencyTimer(m_FtdiHandle, 4); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetLatencyTimer", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetUSBParameters(m_FtdiHandle, USB3XXX_MAXPACKETSIZE, 0); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetUSBParameters", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetTimeouts(m_FtdiHandle, 200, 200 ); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetTimeouts", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + // done + return true; +} + +bool CUsb3003DF2ETInterface::ResetDevice(void) +{ + bool ok = false; + FT_STATUS ftStatus; + int len, i; + char rxpacket[100]; + + std::cout << "Trying DF2ET-3003 soft reset" << std::endl; + + DWORD n, b; + char txpacket[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + char reset_packet[7] = { PKT_HEADER, 0, 3, 0, PKT_RESET, PKT_PARITYBYTE, 3 ^ PKT_RESET ^ PKT_PARITYBYTE }; + char *p; + + for (i = 0; i < 35; i++) + { + p = &txpacket[0]; + n = 10; + do + { + ftStatus = FT_Write( m_FtdiHandle, p, n, &b); + if (FT_OK != ftStatus) + { + return false; + } + n -= b; + p += b; + } while (n > 0); + } + + p = &reset_packet[0]; + n = 7; + do + { + ftStatus = FT_Write( m_FtdiHandle, p, n, &b); + if (FT_OK != ftStatus) + { + return 1; + } + n -= b; + p += b; + } while (n > 0); + + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ); + ok = ((len == 7) && (rxpacket[4] == PKT_READY)); + if ( ok ) + { + std::cout << "DF2ET-3003 soft reset succeeded" << std::endl; + } + else + { + std::cout << "DF2ET-3003 soft reset failed" << std::endl; + + std::cout << "Trying DF2ET-3003 hard reset" << std::endl; + + ftStatus = FT_ClrDtr( m_FtdiHandle ); + CTimePoint::TaskSleepFor(10); + ftStatus = FT_SetDtr( m_FtdiHandle ); + CTimePoint::TaskSleepFor(10); + + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ); + ok = ((len == 7) && (rxpacket[4] == PKT_READY)); + if ( ok ) + { + std::cout << "DF2ET-3003 hard reset succeeded" << std::endl; + } + else + { + std::cout << "DF2ET-3003 hard reset failed" << std::endl; + } + } + return ok; +} + diff --git a/cusb3003df2etinterface.h b/cusb3003df2etinterface.h new file mode 100644 index 0000000..ad11cc3 --- /dev/null +++ b/cusb3003df2etinterface.h @@ -0,0 +1,57 @@ +// +// cusb3003df2etinterface.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) and Florian Wolters (DF2ET) on 03/11/2017. +// Copyright © 2017 Jean-Luc Deltombe (LX3JL) and Florian Wolters (DF2ET). +// All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cusb3003df2etinterface_h +#define cusb3003df2etinterface_h + + +#include "ftd2xx.h" +#include "cbuffer.h" +#include "cusb3003interface.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CUsb3003DF2ETInterface : public CUsb3003Interface +{ +public: + // constructors + CUsb3003DF2ETInterface(uint32, uint32, const char *, const char *); + + // destructor + virtual ~CUsb3003DF2ETInterface() {} + +protected: + // low level + bool OpenDevice(void); + bool ResetDevice(void); +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cusb3003df2etinterface_h */ diff --git a/cusb3003hrinterface.cpp b/cusb3003hrinterface.cpp new file mode 100644 index 0000000..f096d85 --- /dev/null +++ b/cusb3003hrinterface.cpp @@ -0,0 +1,66 @@ +// +// cusb3003hrinterface.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 30/10/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "ctimepoint.h" +#include "cambepacket.h" +#include "cusb3003hrinterface.h" +#include "cvocodecs.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CUsb3003HRInterface::CUsb3003HRInterface(uint32 uiVid, uint32 uiPid, const char *szDeviceName, const char *szDeviceSerial) +: CUsb3003Interface(uiVid, uiPid, szDeviceName, szDeviceSerial) +{ +} + +//////////////////////////////////////////////////////////////////////////////////////// +// low level + +bool CUsb3003HRInterface::ResetDevice(void) +{ + bool ok = false; + FT_STATUS ftStatus; + int len; + char rxpacket[100]; + + //if the device is a USB-3003, it supports reset via UART break signal + //printf("reset via uart break...\n"); + ftStatus = FT_SetBreakOn( m_FtdiHandle ); + CTimePoint::TaskSleepFor(10); + ftStatus = FT_SetBreakOff( m_FtdiHandle ); + //CTimePoint::TaskSleepFor(10); + + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ); + ok = ((len == 7) && (rxpacket[4] == PKT_READY)); + if ( !ok ) + { + std::cout << "USB-3003 hard reset failed" << std::endl; + } + + // done + return ok; +} + diff --git a/cusb3003hrinterface.h b/cusb3003hrinterface.h new file mode 100644 index 0000000..b045e14 --- /dev/null +++ b/cusb3003hrinterface.h @@ -0,0 +1,55 @@ +// +// cusb3003hrinterface.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 30/10/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cusb3003hrinterface_h +#define cusb3003hrinterface_h + + +#include "ftd2xx.h" +#include "cbuffer.h" +#include "cusb3003interface.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CUsb3003HRInterface : public CUsb3003Interface +{ +public: + // constructors + CUsb3003HRInterface(uint32, uint32, const char *, const char *); + + // destructor + virtual ~CUsb3003HRInterface() {} + +protected: + // low level + bool ResetDevice(void); +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cusb3003hrinterface_h */ diff --git a/cusb3003interface.cpp b/cusb3003interface.cpp new file mode 100644 index 0000000..4b3d4f2 --- /dev/null +++ b/cusb3003interface.cpp @@ -0,0 +1,324 @@ +// +// cusb3003interface.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 23/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "ctimepoint.h" +#include "cambepacket.h" +#include "cusb3003interface.h" +#include "cvocodecs.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// configuration: +// +// PKT_CHANNEL0 = DSTAR (AMBEPLUS) +// PKT_CHANNEL1 = DMR/C4FM (AMBE2PLUS) +// PKT_CHANNEL2 = UNUSED or HYBRID + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CUsb3003Interface::CUsb3003Interface(uint32 uiVid, uint32 uiPid, const char *szDeviceName, const char *szDeviceSerial) +: CUsb3xxxInterface(uiVid, uiPid, szDeviceName, szDeviceSerial) +{ + m_uiChCodecs[0]= CODEC_AMBEPLUS; + m_uiChCodecs[1]= CODEC_AMBE2PLUS; + m_uiChCodecs[2]= CODEC_NONE; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// initialization + +bool CUsb3003Interface::Init(uint8 uiOddCodec) +{ + bool ok = true; + + // init the odd channel + m_uiChCodecs[2] = uiOddCodec; + + // base class + ok &= CUsb3xxxInterface::Init(); + + // do not create our channels now + // this is delegated to caller (CVocodecs) as our channel + // may be hybrids between 2 interfaces in case of odd n' of channel device) + + // done + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// manage Channels + +uint8 CUsb3003Interface::GetChannelCodec(int iCh) const +{ + uint8 uiCodec = CODEC_NONE; + if ( (iCh >= 0) && (iCh < USB3003_NB_CH) ) + { + uiCodec = m_uiChCodecs[iCh]; + } + return uiCodec; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// manage vocodec channels + +CVocodecChannel *CUsb3003Interface::GetChannelWithChannelIn(int iCh) +{ + CVocodecChannel *Channel = NULL; + bool done = false; + for ( int i = 0; (i < m_Channels.size()) && !done; i++ ) + { + if ( iCh == 2 ) + { + if ( (m_Channels[i]->GetChannelIn() == iCh) && !(m_Channels[i]->IsInterfaceOut(this)) ) + { + Channel = m_Channels[i]; + done = true; + } + } + else + { + if ( (m_Channels[i]->GetChannelIn() == iCh) && (m_Channels[i]->IsInterfaceOut(this)) ) + { + Channel = m_Channels[i]; + done = true; + } + } + } + return Channel; +} + +CVocodecChannel *CUsb3003Interface::GetChannelWithChannelOut(int iCh) +{ + CVocodecChannel *Channel = NULL; + bool done = false; + for ( int i = 0; (i < m_Channels.size()) && !done; i++ ) + { + if ( (m_Channels[i]->GetChannelOut() == iCh) && (m_Channels[i]->IsInterfaceOut(this)) ) + { + Channel = m_Channels[i]; + done = true; + } + } + return Channel; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// decoder helper + +bool CUsb3003Interface::IsValidChannelPacket(const CBuffer &buffer, int *ch, CAmbePacket *packet) +{ + bool valid = false; + uint8 tag[] = { PKT_HEADER,0x00,0x0C,PKT_CHANNEL }; + + if ( (buffer.size() == 16) && (buffer.Compare(tag, sizeof(tag)) == 0)) + { + *ch = buffer.data()[4] - PKT_CHANNEL0; + if ( *ch == 0 ) + packet->SetCodec(CODEC_AMBEPLUS); + else if ( *ch == 1 ) + packet->SetCodec(CODEC_AMBE2PLUS); + else + packet->SetCodec(CODEC_NONE); + packet->SetAmbe(&(buffer.data()[7])); + valid = (*ch < GetNbChannels()); + //std::cout << "CHAN " << *ch << " " << buffer.size() << " " << (int)buffer[6] << std::endl; + } + return valid; +} + +bool CUsb3003Interface::IsValidSpeechPacket(const CBuffer &buffer, int *ch, CVoicePacket *packet) +{ + bool valid = false; + + if ( (buffer.size() > 6) && + (buffer.data()[0] == PKT_HEADER) && (buffer.data()[3] == PKT_SPEECH) && + (buffer.data()[5] == PKT_SPEECHD) ) + { + *ch = buffer.data()[4] - PKT_CHANNEL0; + packet->SetVoice(&(buffer.data()[7]), buffer.data()[6] * 2); + valid = (*ch < GetNbChannels()); + //std::cout << "SPCH " << *ch << " " << buffer.size() << std::endl; + } + return valid; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// encoder helpers + +void CUsb3003Interface::EncodeChannelPacket(CBuffer *buffer, int ch, CAmbePacket *packet) +{ + uint size = (uint16)packet->GetAmbeSize() + 3; + buffer->clear(); + buffer->Append((uint8)PKT_HEADER); + buffer->Append((uint8)HIBYTE(size)); + buffer->Append((uint8)LOBYTE(size)); + buffer->Append((uint8)PKT_CHANNEL); + buffer->Append((uint8)(PKT_CHANNEL0+ch)); + buffer->Append((uint8)(PKT_CHAND)); + buffer->Append((uint8)(packet->GetAmbeSize()*8)); + buffer->Append(packet->GetAmbe(), packet->GetAmbeSize()); +} + +void CUsb3003Interface::EncodeSpeechPacket(CBuffer *buffer, int ch, CVoicePacket *packet) +{ + uint16 size = (uint16)packet->GetVoiceSize() + 3; + buffer->clear(); + buffer->Append((uint8)PKT_HEADER); + buffer->Append((uint8)HIBYTE(size)); + buffer->Append((uint8)LOBYTE(size)); + buffer->Append((uint8)PKT_SPEECH); + buffer->Append((uint8)(PKT_CHANNEL0+ch)); + buffer->Append((uint8)PKT_SPEECHD); + buffer->Append((uint8)(packet->GetVoiceSize()/2)); + buffer->Append(packet->GetVoice(), packet->GetVoiceSize()); +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// low level + +bool CUsb3003Interface::OpenDevice(void) +{ + FT_STATUS ftStatus; + int baudrate = 921600; + + //sets serial VID/PID for a Standard Device NOTE: This is for legacy purposes only. This can be ommitted. + ftStatus = FT_SetVIDPID(m_uiVid, m_uiPid); + if (ftStatus != FT_OK) {FTDI_Error((char *)"FT_SetVIDPID", ftStatus ); return false; } + + ftStatus = FT_OpenEx((PVOID)m_szDeviceSerial, FT_OPEN_BY_SERIAL_NUMBER, &m_FtdiHandle); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_OpenEx", ftStatus ); return false; } + + CTimePoint::TaskSleepFor(50); + FT_Purge(m_FtdiHandle, FT_PURGE_RX | FT_PURGE_TX ); + CTimePoint::TaskSleepFor(50); + + ftStatus = FT_SetDataCharacteristics(m_FtdiHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE); + if ( ftStatus != FT_OK ) { FTDI_Error((char *)"FT_SetDataCharacteristics", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetFlowControl(m_FtdiHandle, FT_FLOW_RTS_CTS, 0x11, 0x13); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetFlowControl", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetRts (m_FtdiHandle); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetRts", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + //for usb-3012 pull DTR high to take AMBE3003 out of reset. + //for other devices noting is connected to DTR so it is a dont care + ftStatus = FT_ClrDtr(m_FtdiHandle); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_ClrDtr", ftStatus); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetBaudRate(m_FtdiHandle, baudrate ); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetBaudRate", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetLatencyTimer(m_FtdiHandle, 4); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetLatencyTimer", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetUSBParameters(m_FtdiHandle, USB3XXX_MAXPACKETSIZE, 0); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetUSBParameters", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + ftStatus = FT_SetTimeouts(m_FtdiHandle, 200, 200 ); + if (ftStatus != FT_OK) { FTDI_Error((char *)"FT_SetTimeouts", ftStatus ); FT_Close(m_FtdiHandle); return false; } + + // done + return true; +} + +bool CUsb3003Interface::ResetDevice(void) +{ + bool ok = false; + int len; + char rxpacket[100]; + char zeropacket[10] = + { + 0,0,0,0,0,0,0,0,0,0 + }; + char txpacket[7] = + { + PKT_HEADER, + 0, + 3, + 0, + PKT_RESET, + PKT_PARITYBYTE, + 3 ^ PKT_RESET ^ PKT_PARITYBYTE + }; + + + //the chip might be in a state where it is waiting to receive bytes from a prior incomplete packet. + //first send 350 zeros in case, the chip's receive state is still waiting for characters + //if we send more than needed, the exta characters will just get discarded since they do not match the header byte + //after that we send PKT_RESET to reset the device + //As long as the AMBE3000 is able to receive via uart, this method will succeed in resetting it. + + for ( int i = 0; i < 35 ; i++ ) + { + FTDI_write_packet(m_FtdiHandle, zeropacket, sizeof(zeropacket)); + } + + + // write soft-reset packet + if ( FTDI_write_packet(m_FtdiHandle, txpacket, sizeof(txpacket)) ) + { + // read reply + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ); + ok = ((len == 7) && (rxpacket[4] == PKT_READY)); + if ( !ok ) + { + std::cout << "USB-3003 soft reset failed" << std::endl; + } + } + + // done + return ok; +} + +bool CUsb3003Interface::ConfigureDevice(void) +{ + bool ok = true; + uint8 pkt_ratep_ambeplus[] = { 0x01,0x30,0x07,0x63,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x48 }; + uint8 pkt_ratep_ambe2plus[] = { 0x04,0x31,0x07,0x54,0x24,0x00,0x00,0x00,0x00,0x00,0x6F,0x48 }; + + // configure each channels for desired codec + for ( int i = 0; i < USB3003_NB_CH; i++ ) + { + switch ( m_uiChCodecs[i] ) + { + case CODEC_AMBEPLUS: + ok &= ConfigureChannel(PKT_CHANNEL0+i, pkt_ratep_ambeplus, 0, 0); + break; + case CODEC_AMBE2PLUS: + ok &= ConfigureChannel(PKT_CHANNEL0+i, pkt_ratep_ambe2plus, 0, 0); + break; + case CODEC_NONE: + default: + break; + } + } + + // done + return ok; +} + diff --git a/cusb3003interface.h b/cusb3003interface.h new file mode 100644 index 0000000..984130e --- /dev/null +++ b/cusb3003interface.h @@ -0,0 +1,80 @@ +// +// cusb3003interface.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 23/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cusb3003interface_h +#define cusb3003interface_h + +#include "ftd2xx.h" +#include "cbuffer.h" +#include "cusb3xxxinterface.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +#define USB3003_NB_CH 3 + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CUsb3003Interface : public CUsb3xxxInterface +{ +public: + // constructors + CUsb3003Interface(uint32, uint32, const char *, const char *); + + // destructor + virtual ~CUsb3003Interface() {} + + // initialization + bool Init(uint8); + + // manage channels + int GetNbChannels(void) const { return USB3003_NB_CH; } + uint8 GetChannelCodec(int) const; + + // manage vocodec channels + CVocodecChannel *GetChannelWithChannelIn(int); + CVocodecChannel *GetChannelWithChannelOut(int); + +protected: + // decoder helper + bool IsValidChannelPacket(const CBuffer &, int *, CAmbePacket *); + bool IsValidSpeechPacket(const CBuffer &, int *, CVoicePacket *); + + // encoder helpers + void EncodeChannelPacket(CBuffer *, int, CAmbePacket *); + void EncodeSpeechPacket(CBuffer *, int, CVoicePacket *); + + // low level + bool OpenDevice(void); + bool ResetDevice(void); + bool ConfigureDevice(void); + int GetDeviceFifoSize(void) const { return 2; } + + // data + uint8 m_uiChCodecs[USB3003_NB_CH]; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cusb3003interface_h */ diff --git a/cusb3xxxinterface.cpp b/cusb3xxxinterface.cpp new file mode 100644 index 0000000..6ff8fa6 --- /dev/null +++ b/cusb3xxxinterface.cpp @@ -0,0 +1,739 @@ +// +// cusb3xxxinterface.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 26/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "ctimepoint.h" +#include "cusb3xxxinterface.h" +#include "cvocodecchannel.h" +#include "cambeserver.h" + +// queues ID +#define QUEUE_CHANNEL 0 +#define QUEUE_SPEECH 1 + +// timeout +#define DEVICE_TIMEOUT 600 // in ms + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CUsb3xxxInterface::CUsb3xxxInterface(uint32 uiVid, uint32 uiPid, const char *szDeviceName, const char *szDeviceSerial) +{ + m_FtdiHandle = NULL; + m_uiVid = uiVid; + m_uiPid = uiPid; + ::strncpy(m_szDeviceName, szDeviceName, sizeof(m_szDeviceName) - 1); + m_szDeviceName[sizeof(m_szDeviceName) - 1] = '\0'; + ::strncpy(m_szDeviceSerial, szDeviceSerial, sizeof(m_szDeviceSerial) - 1); + m_szDeviceSerial[sizeof(m_szDeviceSerial) - 1] = '\0'; + m_iSpeechFifolLevel = 0; + m_iChannelFifolLevel = 0; + m_nRxBufLen = 0; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CUsb3xxxInterface::~CUsb3xxxInterface() +{ + // stop thread first + m_bStopThread = true; + if ( m_pThread != NULL ) + { + m_pThread->join(); + delete m_pThread; + m_pThread = NULL; + } + + // delete m_SpeechQueues + for ( int i = 0; i < m_SpeechQueues.size(); i++ ) + { + delete m_SpeechQueues[i]; + } + m_SpeechQueues.clear(); + + // delete m_ChannelQueues + for ( int i = 0; i < m_ChannelQueues.size(); i++ ) + { + delete m_ChannelQueues[i]; + } + m_ChannelQueues.clear(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// initialization + +bool CUsb3xxxInterface::Init(void) +{ + bool ok = true; + + // open USB device + std::cout << "Opening " << m_szDeviceName << ":" << m_szDeviceSerial << " device" << std::endl; + if ( ok &= OpenDevice() ) + { + // reset + //std::cout << "Reseting " << m_szDeviceName << "device" << std::endl; + if ( ok &= ResetDevice() ) + { + // read version + //std::cout << "Reading " << m_szDeviceName << " device version" << std::endl; + if ( ok &= ReadDeviceVersion() ) + { + // send configuration packet(s) + //std::cout << "Configuring " << m_szDeviceName << " device" << std::endl; + ok &= DisableParity(); + ok &= ConfigureDevice(); + } + } + } + std::cout << std::endl; + + // create queues and start thread only if device init succeeded + if ( ok ) + { + for ( int i = 0; i < GetNbChannels(); i++ ) + { + m_SpeechQueues.push_back(new CPacketQueue); + m_ChannelQueues.push_back(new CPacketQueue); + } + ok &= CVocodecInterface::Init(); + } + + // done + return ok; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// task + +void CUsb3xxxInterface::Task(void) +{ + CBuffer Buffer; + int iCh; + CPacketQueue *Queue; + CVocodecChannel *Channel; + CAmbePacket AmbePacket; + CVoicePacket VoicePacket; + bool done; + + // TODO : + // preserve packets PIDs, so the transcoded CAmbePacket returned + // to CStream client is garantied to have the same PID + // than the corresponding incoming packet + + // Phase 1: Batched read from USB device + // Only query hardware if we expect a response (FIFO has pending packets) + // or have partial data in the carry-over buffer + if ( m_iSpeechFifolLevel > 0 || m_iChannelFifolLevel > 0 || m_nRxBufLen > 0 ) + { + DWORD nAvail = 0; + if ( FT_GetQueueStatus(m_FtdiHandle, &nAvail) == FT_OK && nAvail > 0 ) + { + int nToRead = (int)nAvail; + if ( m_nRxBufLen + nToRead > (int)sizeof(m_rawRxBuf) ) + nToRead = (int)sizeof(m_rawRxBuf) - m_nRxBufLen; + + if ( nToRead > 0 ) + { + DWORD nRead = 0; + if ( FT_Read(m_FtdiHandle, (LPVOID)&m_rawRxBuf[m_nRxBufLen], nToRead, &nRead) == FT_OK ) + { + m_nRxBufLen += (int)nRead; + } + } + } + + // Parse complete DVSI packets from carry-over buffer + int pos = 0; + while ( pos < m_nRxBufLen ) + { + // need at least 4 bytes for header + if ( m_nRxBufLen - pos < 4 ) + break; + + // validate start byte and type byte + if ( (uint8)m_rawRxBuf[pos] != PKT_HEADER ) + { + std::cout << "Batched read: invalid header byte, purging" << std::endl; + FT_Purge(m_FtdiHandle, FT_PURGE_RX); + m_nRxBufLen = 0; + pos = 0; + break; + } + uint8 pktType = (uint8)m_rawRxBuf[pos + 3]; + if ( pktType != PKT_CONTROL && pktType != PKT_CHANNEL && pktType != PKT_SPEECH ) + { + std::cout << "Batched read: invalid packet type, purging" << std::endl; + FT_Purge(m_FtdiHandle, FT_PURGE_RX); + m_nRxBufLen = 0; + pos = 0; + break; + } + + // get payload length and total packet size + int plen = ((m_rawRxBuf[pos + 1] & 0xFF) << 8) | (m_rawRxBuf[pos + 2] & 0xFF); + if ( plen > USB3XXX_MAXPACKETSIZE - 4 ) + { + std::cout << "Batched read: implausible payload length " << plen << ", purging" << std::endl; + FT_Purge(m_FtdiHandle, FT_PURGE_RX); + m_nRxBufLen = 0; + pos = 0; + break; + } + int pktTotal = 4 + plen; + + // wait for complete packet + if ( m_nRxBufLen - pos < pktTotal ) + break; + + // extract complete packet into Buffer and dispatch + Buffer.clear(); + Buffer.resize(pktTotal); + ::memcpy(Buffer.data(), &m_rawRxBuf[pos], pktTotal); + pos += pktTotal; + + if ( IsValidSpeechPacket(Buffer, &iCh, &VoicePacket) ) + { + m_iChannelFifolLevel = MAX(0, m_iChannelFifolLevel-1); + + Channel = GetChannelWithChannelIn(iCh); + if ( Channel != NULL ) + { + CVoicePacket *clone = new CVoicePacket(VoicePacket); + Channel->ProcessSignal(*clone); + Queue = Channel->GetVoiceQueue(); + Queue->push(clone); + Channel->ReleaseVoiceQueue(); + } + } + else if ( IsValidChannelPacket(Buffer, &iCh, &AmbePacket) ) + { + m_iSpeechFifolLevel = MAX(0, m_iSpeechFifolLevel-1); + + Channel = GetChannelWithChannelOut(iCh); + if ( Channel != NULL ) + { + // Restore the PID that was on the corresponding input + // packet — the hardware response carries channel and + // codec data but not the original pid, so we recover + // it from the per-channel FIFO populated when the + // input packet was consumed (see input-side push + // below in this same Task() loop). FIFO ordering + // matches because the DVStick processes packets + // sequentially per physical channel. + CAmbePacket *clone = new CAmbePacket(AmbePacket); + clone->SetPid(Channel->PopPid()); + Queue = Channel->GetPacketQueueOut(); + Queue->push(clone); + Channel->ReleasePacketQueueOut(); + } + } + } + + // move residual bytes to front of buffer + if ( pos > 0 && pos < m_nRxBufLen ) + { + ::memmove(m_rawRxBuf, &m_rawRxBuf[pos], m_nRxBufLen - pos); + m_nRxBufLen -= pos; + } + else if ( pos >= m_nRxBufLen ) + { + m_nRxBufLen = 0; + } + } + + // process the streams (channels) incoming queue + // make sure that packets from different channels + // are interlaced so to keep the device fifo busy + do + { + done = true; + for ( int i = 0; i < m_Channels.size(); i++) + { + // get channel + Channel = m_Channels[i]; + + // any packet in voice queue ? + if ( Channel->IsInterfaceOut(this) ) + { + Queue = Channel->GetVoiceQueue(); + if ( !Queue->empty() ) + { + // get packet + CVoicePacket *Packet = (CVoicePacket *)Queue->front(); + Queue->pop(); + // this is second step of transcoding + // we just received from hardware a decoded speech packet + // post it to relevant channel encoder + int chIdx = Channel->GetChannelOut(); + Packet->SetChannel(chIdx); + m_SpeechQueues[chIdx]->push(Packet); + // done + done = false; + } + Channel->ReleaseVoiceQueue(); + } + + // any packet in ambe queue for us ? + if ( Channel->IsInterfaceIn(this) ) + { + Queue = Channel->GetPacketQueueIn(); + if ( !Queue->empty() ) + { + // get packet + CAmbePacket *Packet = (CAmbePacket *)Queue->front(); + Queue->pop(); + // PID-preservation push: capture the pid before the + // packet heads into the USB write path (where it + // gets freed). The matching pop happens above when + // the encoder-side hardware response arrives, so + // the pid round-trips correctly via the per-channel + // FIFO instead of via packet bytes (which the DVStick + // protocol doesn't preserve). + Channel->PushPid(Packet->GetPid()); + // this is first step of transcoding + // a fresh new packet to be transcoded is showing up + // post it to relevant channel decoder + int chIdx = Channel->GetChannelIn(); + Packet->SetChannel(chIdx); + m_ChannelQueues[chIdx]->push(Packet); + // done + done = false; + } + Channel->ReleasePacketQueueIn(); + } + } + } while (!done); + + // process device incoming queues (aka to device) + // interlace speech and channels packets + // and post to final device queue + do + { + done = true; + // loop on all channels + for ( int i = 0; i < GetNbChannels(); i++ ) + { + // speech + if ( !m_SpeechQueues[i]->empty() ) + { + // get packet + CPacket *Packet = m_SpeechQueues[i]->front(); + m_SpeechQueues[i]->pop(); + // and push to device queue + m_DeviceQueue.push(Packet); + // next + done = false; + } + // ambe + if ( !m_ChannelQueues[i]->empty() ) + { + // get packet + CPacket *Packet = m_ChannelQueues[i]->front(); + m_ChannelQueues[i]->pop(); + // and push to device queue + m_DeviceQueue.push(Packet); + // done = false; + } + } + + } while (!done); + + // Phase 4: Batched write to USB device + // Run timeout checks once per iteration + int fifoSize = GetDeviceFifoSize(); + if ( (m_iSpeechFifolLevel > 0) && (m_SpeechFifoLevelTimeout.DurationSinceNow() >= (DEVICE_TIMEOUT/1000.0f)) ) + { + std::cout << "Reseting " << m_szDeviceName << ":" << m_szDeviceSerial << " device fifo level due to timeout" << std::endl; + m_iSpeechFifolLevel = 0; + // Purge any stale data from hardware and carry-over buffer + FT_Purge(m_FtdiHandle, FT_PURGE_RX); + m_nRxBufLen = 0; + if ( CheckIfDeviceNeedsReOpen() ) + { + m_iChannelFifolLevel = 0; + } + } + if ( (m_iChannelFifolLevel > 0) && (m_ChannelFifoLevelTimeout.DurationSinceNow() >= (DEVICE_TIMEOUT/1000.0f)) ) + { + std::cout << "Reseting " << m_szDeviceName << ":" << m_szDeviceSerial << " device fifo level due to timeout" << std::endl; + m_iChannelFifolLevel = 0; + FT_Purge(m_FtdiHandle, FT_PURGE_RX); + m_nRxBufLen = 0; + if ( CheckIfDeviceNeedsReOpen() ) + { + m_iSpeechFifolLevel = 0; + } + } + + // Gather packets into a single TX batch + CBuffer txBatch; + int speechToSend = 0; + int channelToSend = 0; + bool gathering = true; + while ( gathering && !m_DeviceQueue.empty() ) + { + CPacket *Packet = m_DeviceQueue.front(); + + // check if channel is still open + Channel = NULL; + if ( Packet->IsVoice() ) + Channel = GetChannelWithChannelOut(Packet->GetChannel()); + else if ( Packet->IsAmbe() ) + Channel = GetChannelWithChannelIn(Packet->GetChannel()); + if ( (Channel != NULL) && !Channel->IsOpen() ) + { + m_DeviceQueue.pop(); + delete Packet; + continue; + } + + if ( Packet->IsVoice() ) + { + if ( m_iSpeechFifolLevel + speechToSend < fifoSize ) + { +#ifdef DEBUG_DUMPFILE + int dbgCh = Packet->GetChannel(); +#endif + EncodeSpeechPacket(&Buffer, Packet->GetChannel(), (CVoicePacket *)Packet); + txBatch.Append(Buffer.data(), (int)Buffer.size()); + m_DeviceQueue.pop(); + delete Packet; + speechToSend++; +#ifdef DEBUG_DUMPFILE + g_AmbeServer.m_DebugFile << m_szDeviceName << "\t" << "Sp" << dbgCh << "->" << std::endl; std::cout.flush(); +#endif + } + else + { + gathering = false; + } + } + else if ( Packet->IsAmbe() ) + { + if ( m_iChannelFifolLevel + channelToSend < fifoSize ) + { +#ifdef DEBUG_DUMPFILE + int dbgCh = Packet->GetChannel(); +#endif + EncodeChannelPacket(&Buffer, Packet->GetChannel(), (CAmbePacket *)Packet); + txBatch.Append(Buffer.data(), (int)Buffer.size()); + m_DeviceQueue.pop(); + delete Packet; + channelToSend++; +#ifdef DEBUG_DUMPFILE + g_AmbeServer.m_DebugFile << m_szDeviceName << "\t" << "Ch" << dbgCh << "->" << std::endl; std::cout.flush(); +#endif + } + else + { + gathering = false; + } + } + else + { + m_DeviceQueue.pop(); + delete Packet; + } + } + + // Single write for entire batch + if ( txBatch.size() > 0 ) + { + WriteBuffer(txBatch); + m_iSpeechFifolLevel += speechToSend; + m_iChannelFifolLevel += channelToSend; + if ( speechToSend > 0 ) + m_SpeechFifoLevelTimeout.Now(); + if ( channelToSend > 0 ) + m_ChannelFifoLevelTimeout.Now(); + } + + // Adaptive sleep: 1ms when work is pending, 10ms when idle + bool hasWork = (m_iSpeechFifolLevel > 0) || (m_iChannelFifolLevel > 0) || + !m_DeviceQueue.empty() || (m_nRxBufLen > 0); + if ( !hasWork ) + { + for ( int i = 0; i < GetNbChannels() && !hasWork; i++ ) + { + hasWork = !m_SpeechQueues[i]->empty() || !m_ChannelQueues[i]->empty(); + } + } + CTimePoint::TaskSleepFor(hasWork ? 1 : 10); +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// low level + +bool CUsb3xxxInterface::ReadDeviceVersion(void) +{ + bool ok = false; + int i, len; + char rxpacket[128]; + char txpacket[8] = + { + PKT_HEADER, + 0, + 4, + PKT_CONTROL, + PKT_PRODID, + PKT_VERSTRING, + PKT_PARITYBYTE, + 4 ^ PKT_CONTROL ^ PKT_PRODID ^ PKT_VERSTRING ^ PKT_PARITYBYTE + }; + + // write packet + if ( FTDI_write_packet(m_FtdiHandle, txpacket, sizeof(txpacket)) ) + { + // read reply + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ) - 4; + ok = (len > 0); + //we succeed in reading a packet, print it out + std::cout << "ReadDeviceVersion : "; + for ( i = 5; (i < len+4) && (rxpacket[i] != 0x00); i++ ) + { + std::cout << (char)(rxpacket[i] & 0x00ff); + } + std::cout << " "; + for ( i = i+2; (i < len+4) && (rxpacket[i] != 0x00); i++ ) + { + std::cout << (char)(rxpacket[i] & 0x00ff); + } + std::cout << std::endl; + } + return ok; +} + +bool CUsb3xxxInterface::DisableParity(void) +{ + bool ok = false; + int len; + char rxpacket[16]; + char txpacket[8] = + { + PKT_HEADER, + 0, + 4, + PKT_CONTROL, + PKT_PARITYMODE,0x00, + PKT_PARITYBYTE, + 4 ^ PKT_CONTROL ^ PKT_PARITYMODE ^ 0x00 ^ PKT_PARITYBYTE + }; + + // write packet + if ( FTDI_write_packet(m_FtdiHandle, txpacket, sizeof(txpacket)) ) + { + // read reply + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ) - 4; + ok = ((len == 2) && (rxpacket[4] == PKT_PARITYMODE) &&(rxpacket[5] == 0x00) ); + } + return ok; +} + +bool CUsb3xxxInterface::ConfigureChannel(uint8 pkt_ch, const uint8 *pkt_ratep, int in_gain, int out_gain) +{ + bool ok = false; + int len; + char rxpacket[64]; + char txpacket[] = + { + PKT_HEADER, + 0, + 33, + PKT_CONTROL, + 0x00, + PKT_ECMODE, 0x00,0x00, + PKT_DCMODE, 0x00,0x00, + PKT_COMPAND,0x00, + PKT_RATEP, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + PKT_CHANFMT,0x00,0x00, + PKT_SPCHFMT,0x00,0x00, + PKT_GAIN, 0x00,0x00, + PKT_INIT, 0x03 + }; + + // update packet content + txpacket[4] = pkt_ch; + :: memcpy(&(txpacket[14]), pkt_ratep, 12); + txpacket[33] = (uint8)(signed char)in_gain; + txpacket[34] = (uint8)(signed char)out_gain; + + // write packet + if ( FTDI_write_packet(m_FtdiHandle, txpacket, sizeof(txpacket)) ) + { + // read reply + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ) - 4; + ok = ((len == 18) && (rxpacket[20] == PKT_INIT) &&(rxpacket[21] == 0x00) ); + } + return ok; + +} + +bool CUsb3xxxInterface::CheckIfDeviceNeedsReOpen(void) +{ + bool ok = false; + int len; + char rxpacket[64]; + char txpacket[5] = + { + PKT_HEADER, + 0, + 1, + PKT_CONTROL, + PKT_PRODID + }; + + // write packet + if ( FTDI_write_packet(m_FtdiHandle, txpacket, sizeof(txpacket)) ) + { + // read reply + len = FTDI_read_packet( m_FtdiHandle, rxpacket, sizeof(rxpacket) ) - 4; + ok = ((len > 0) && (rxpacket[3] == PKT_CONTROL) && (rxpacket[4] == PKT_PRODID)); + } + + if ( !ok ) + { + std::cout << "Device " << m_szDeviceName << ":" << m_szDeviceSerial << " is unresponsive, trying to re-open it..." << std::endl; + FT_Close(m_FtdiHandle); + CTimePoint::TaskSleepFor(100); + if ( OpenDevice() ) + { + if ( ResetDevice() ) + { + DisableParity(); + ConfigureDevice(); + } + } + } + + return !ok; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// io level + +bool CUsb3xxxInterface::ReadBuffer(CBuffer *buffer) +{ + bool ok = false; + DWORD n; + + // any byte in tx queue ? + if ( FT_GetQueueStatus(m_FtdiHandle, &n) == FT_OK ) + { + if ( n != 0 ) + { + buffer->clear(); + buffer->resize(USB3XXX_MAXPACKETSIZE); + int len = FTDI_read_packet(m_FtdiHandle, (char *)buffer->data(), USB3XXX_MAXPACKETSIZE); + buffer->resize(len); + ok = (len != 0); + } + } + return ok; +} + +bool CUsb3xxxInterface::WriteBuffer(const CBuffer &buffer) +{ + return FTDI_write_packet(m_FtdiHandle, (const char *)buffer.data(), (int)buffer.size()); +} + +int CUsb3xxxInterface::FTDI_read_packet(FT_HANDLE ftHandle, char *pkt, int maxlen) +{ + int plen; + + // first read 4 bytes header + if ( FTDI_read_bytes(ftHandle, pkt, 4) ) + { + // ensure we got a valid packet header + if ( (pkt[0] != PKT_HEADER) || ((pkt[3] != PKT_CONTROL) && (pkt[3] != PKT_CHANNEL) && (pkt[3] != PKT_SPEECH)) ) + { + std::cout << "FTDI_read_packet invalid packet header" << std::endl; + FT_Purge(ftHandle, FT_PURGE_RX); + return 0; + } + // get payload length + plen = (pkt[1] & 0x00ff); + plen <<= 8; + plen += (pkt[2] & 0x00ff); + // check buffer length + if (plen+4 > maxlen) + { + std::cout << "FTDI_read_packet supplied buffer is not large enough for packet" << std::endl; + FT_Purge(ftHandle, FT_PURGE_RX); + return 0; + } + // and get payload + if ( FTDI_read_bytes(ftHandle, &pkt[4], plen) ) + { + return plen+4; + } + } + return 0; +} + +bool CUsb3xxxInterface::FTDI_read_bytes(FT_HANDLE ftHandle, char *buffer, int len) +{ + // this relies on FT_SetTimouts() mechanism + DWORD n; + bool ok = false; + + ok = (FT_Read(ftHandle, (LPVOID)buffer, len, &n) == FT_OK) && ((int)n == len); + if ( !ok ) + { + //FT_Purge(ftHandle, FT_PURGE_RX); + std::cout << "FTDI_read_bytes(" << len << ") failed : " << n << std::endl; + } + + return ok; +} + +bool CUsb3xxxInterface::FTDI_write_packet(FT_HANDLE ft_handle, const char *pkt, int len) +{ + FT_STATUS ftStatus; + bool ok = true; + DWORD nwritten; + + if ( len > 0 ) + { + ftStatus = FT_Write(ft_handle, (LPVOID)pkt, (DWORD)len, &nwritten); + ok = (ftStatus == FT_OK) && ((int)nwritten == len); + if ( !ok ) + { + FTDI_Error((char *)"FT_Write", ftStatus); + } + } + return ok; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// error reporting + +void CUsb3xxxInterface::FTDI_Error(char *func_string, FT_STATUS ftStatus) +{ + std::cout << "FTDI function " << func_string << " error " << (int)ftStatus << std::endl; +} diff --git a/cusb3xxxinterface.h b/cusb3xxxinterface.h new file mode 100644 index 0000000..39c110c --- /dev/null +++ b/cusb3xxxinterface.h @@ -0,0 +1,142 @@ +// +// cusb3xxxinterface.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 26/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cusb3xxxinterface_h +#define cusb3xxxinterface_h + + +#include "ftd2xx.h" +#include "cftdidevicedescr.h" +#include "cbuffer.h" +#include "cambepacket.h" +#include "cvoicepacket.h" +#include "cvocodecinterface.h" +#include "ctimepoint.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +#define USB3XXX_MAXPACKETSIZE 1024 // must be multiple of 64 + +#define PKT_HEADER 0x61 + +#define PKT_CONTROL 0x00 +#define PKT_CHANNEL 0x01 +#define PKT_SPEECH 0x02 + +#define PKT_SPEECHD 0x00 +#define PKT_CHAND 0x01 +#define PKT_RATET 0x09 +#define PKT_INIT 0x0b +#define PKT_PRODID 0x30 +#define PKT_VERSTRING 0x31 +#define PKT_PARITYBYTE 0x2F +#define PKT_RESET 0x33 +#define PKT_READY 0x39 +#define PKT_CHANNEL0 0x40 +#define PKT_CHANNEL1 0x41 +#define PKT_CHANNEL2 0x42 +#define PKT_PARITYMODE 0x3F +#define PKT_ECMODE 0x05 +#define PKT_DCMODE 0x06 +#define PKT_COMPAND 0x32 +#define PKT_RATEP 0x0A +#define PKT_CHANFMT 0x15 +#define PKT_SPCHFMT 0x16 +#define PKT_GAIN 0x4B + + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CUsb3xxxInterface : public CVocodecInterface +{ +public: + // constructors + CUsb3xxxInterface(uint32, uint32, const char *, const char *); + + // destructor + virtual ~CUsb3xxxInterface(); + + // initialization + bool Init(void); + + // get + const char *GetName(void) const { return m_szDeviceName; } + const char *GetSerial(void) const { return m_szDeviceSerial; } + + // task + void Task(void); + +protected: + // decoder helper + virtual bool IsValidChannelPacket(const CBuffer &, int *, CAmbePacket *) { return false; } + virtual bool IsValidSpeechPacket(const CBuffer &, int *, CVoicePacket *) { return false; } + + // encoder helpers + virtual void EncodeChannelPacket(CBuffer *, int, CAmbePacket *) {} + virtual void EncodeSpeechPacket(CBuffer *, int, CVoicePacket *) {} + + // low level + virtual bool OpenDevice(void) { return false; } + virtual bool ResetDevice(void) { return false; } + bool ReadDeviceVersion(void); + bool DisableParity(void); + virtual bool ConfigureDevice(void) { return false; } + bool ConfigureChannel(uint8, const uint8 *, int, int); + bool CheckIfDeviceNeedsReOpen(void); + virtual int GetDeviceFifoSize(void) const { return 1; } + + // io level + bool ReadBuffer(CBuffer *); + bool WriteBuffer(const CBuffer &); + int FTDI_read_packet(FT_HANDLE, char *, int); + bool FTDI_read_bytes(FT_HANDLE, char *, int); + bool FTDI_write_packet(FT_HANDLE, const char *, int); + + // error reporting + void FTDI_Error(char *, FT_STATUS); + +protected: + // data + uint32 m_uiVid; + uint32 m_uiPid; + char m_szDeviceName[FTDI_MAX_STRINGLENGTH]; + char m_szDeviceSerial[FTDI_MAX_STRINGLENGTH]; + FT_HANDLE m_FtdiHandle; + + // queue + std::vector m_SpeechQueues; + std::vector m_ChannelQueues; + CPacketQueue m_DeviceQueue; + int m_iSpeechFifolLevel; + int m_iChannelFifolLevel; + CTimePoint m_SpeechFifoLevelTimeout; + CTimePoint m_ChannelFifoLevelTimeout; + char m_rawRxBuf[2 * USB3XXX_MAXPACKETSIZE]; + int m_nRxBufLen; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cusb3xxxinterface_h */ diff --git a/cvocodecchannel.cpp b/cvocodecchannel.cpp new file mode 100644 index 0000000..8f078f6 --- /dev/null +++ b/cvocodecchannel.cpp @@ -0,0 +1,659 @@ +// +// cvocodecchannel.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 23/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include "ctimepoint.h" +#include "cvocodecchannel.h" +#include "cvocodecinterface.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CVocodecChannel::CVocodecChannel(CVocodecInterface *InterfaceIn, int iChIn, CVocodecInterface *InterfaceOut, int iChOut) +{ + m_bOpen = false; + m_InterfaceIn = InterfaceIn; + m_iChannelIn = iChIn; + m_InterfaceOut = InterfaceOut; + m_iChannelOut = iChOut; + m_signalProcessor = NULL; + + // Codec2 encoder starts disabled, enabled per-stream as needed + m_bCodec2Enabled = false; + m_pCodec2 = NULL; + m_pCodec2Thread = NULL; + m_bCodec2StopThread = false; + + // IMBE encoder starts disabled, enabled per-stream as needed + m_bImbeEnabled = false; + m_pImbe = NULL; + m_pImbeThread = NULL; + m_bImbeStopThread = false; + + // PID FIFO desync drop counters — reset by PurgeAllQueues at + // every Open/Close so each stream gets a fresh accounting epoch. + m_PidFifoOrphanDrops = 0; + m_PidFifoOverflowDrops = 0; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CVocodecChannel::~CVocodecChannel() +{ + // Stop Codec2 encoder thread first + if (m_pCodec2Thread != NULL) + { + m_bCodec2StopThread = true; + m_Codec2PcmCondition.notify_all(); + m_pCodec2Thread->join(); + delete m_pCodec2Thread; + m_pCodec2Thread = NULL; + } + + // Stop IMBE encoder thread + if (m_pImbeThread != NULL) + { + m_bImbeStopThread = true; + m_ImbePcmCondition.notify_all(); + m_pImbeThread->join(); + delete m_pImbeThread; + m_pImbeThread = NULL; + } + + PurgeAllQueues(); + delete m_signalProcessor; + if (m_pCodec2 != NULL) + { + delete m_pCodec2; + m_pCodec2 = NULL; + } + if (m_pImbe != NULL) + { + delete m_pImbe; + m_pImbe = NULL; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// open & close + +bool CVocodecChannel::Open(void) +{ + bool ok = false; + if ( !m_bOpen ) + { + m_bOpen = true; + ok = true; + PurgeAllQueues(); + { + // Each stream starts clean, with the current ambed.ini values + std::lock_guard lock(m_SignalMutex); + delete m_signalProcessor; + m_signalProcessor = new CSignalProcessor(GetCodecIn()); + } + std::cout << "Vocodec channel " << + m_InterfaceIn->GetName() << ":" << m_InterfaceIn->GetSerial() << ":" << (int)m_iChannelIn << " -> " << + m_InterfaceOut->GetName() << ":" << m_InterfaceOut->GetSerial() << ":" << (int)m_iChannelOut << " open" << std::endl; + } + return ok; +} + +void CVocodecChannel::Close(void) +{ + if ( m_bOpen ) + { + m_bOpen = false; + PurgeAllQueues(); + { + std::lock_guard lock(m_SignalMutex); + delete m_signalProcessor; + m_signalProcessor = NULL; + } + std::cout << "Vocodec channel " << + m_InterfaceIn->GetName() << ":" << m_InterfaceIn->GetSerial() << ":" << (int)m_iChannelIn << " -> " << + m_InterfaceOut->GetName() << ":" << m_InterfaceOut->GetSerial() << ":" << (int)m_iChannelOut << " closed" << std::endl; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// get + +uint8 CVocodecChannel::GetCodecIn(void) const +{ + return m_InterfaceIn->GetChannelCodec(m_iChannelIn); +} + +uint8 CVocodecChannel::GetCodecOut(void) const +{ + return m_InterfaceOut->GetChannelCodec(m_iChannelOut); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// processing + +void CVocodecChannel::ProcessSignal(CVoicePacket& voicePacket) +{ + std::lock_guard signalLock(m_SignalMutex); + if (m_signalProcessor == NULL) + { + return; + } + + uint8 *rawVoice = voicePacket.GetVoice(); + int voiceSize = voicePacket.GetVoiceSize(); + m_signalProcessor->Process(rawVoice, voiceSize); + + // Codec2 encoding runs in a separate thread to avoid blocking the hardware interface. + // Here we just queue the PCM data for async encoding. + if (m_bCodec2Enabled && m_pCodec2Thread != NULL && voiceSize >= 320) // 160 samples * 2 bytes + { + std::vector audio = OutputPcm(CODEC_CODEC2, rawVoice); + + // Push to PCM queue and notify encoder thread (drop oldest if full) + { + std::lock_guard lock(m_Codec2PcmMutex); + if ( m_Codec2PcmQueue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) + { + m_Codec2PcmQueue.pop(); + } + m_Codec2PcmQueue.push(audio); + } + m_Codec2PcmCondition.notify_one(); + } + + // IMBE encoding runs in a separate thread to avoid blocking the hardware interface. + // Here we just queue the PCM data for async encoding. + if (m_bImbeEnabled && m_pImbeThread != NULL && voiceSize >= 320) // 160 samples * 2 bytes + { + std::vector audio = OutputPcm(CODEC_IMBE, rawVoice); + + // Push to PCM queue and notify encoder thread (drop oldest if full) + { + std::lock_guard lock(m_ImbePcmMutex); + if ( m_ImbePcmQueue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) + { + m_ImbePcmQueue.pop(); + } + m_ImbePcmQueue.push(audio); + } + m_ImbePcmCondition.notify_one(); + } + + // The software encoders above have their copies, the packet goes on to the hardware encoder + m_signalProcessor->ProcessOutput(GetCodecOut(), rawVoice, voiceSize); +} + +// A copy of the frame at the level for this codec, big-endian PCM to native samples +std::vector CVocodecChannel::OutputPcm(uint8 uiCodecOut, const uint8 *voice) +{ + uint8 copy[320]; + ::memcpy(copy, voice, sizeof(copy)); + m_signalProcessor->ProcessOutput(uiCodecOut, copy, sizeof(copy)); + + std::vector audio(160); + for (int i = 0; i < 160; i++) + { + audio[i] = (int16_t)((copy[i*2] << 8) | copy[i*2 + 1]); + } + return audio; +} + +void CVocodecChannel::ReportSignal(uint16 uiStreamId, const std::string& callsign) +{ + std::lock_guard lock(m_SignalMutex); + if (m_signalProcessor != NULL) + { + m_signalProcessor->Report(uiStreamId, callsign); + } +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// Codec2 encoding control + +void CVocodecChannel::EnableCodec2(bool bEnable) +{ + if (bEnable && !m_bCodec2Enabled) + { + // Enable Codec2 encoding with async thread + if (m_pCodec2 == NULL) + { + m_pCodec2 = new CCodec2(true); // true = 3200bps mode (8 bytes per 20ms) + } + + // Start the async encoder thread + m_bCodec2StopThread = false; + m_pCodec2Thread = new std::thread(Codec2EncoderThread, this); + + m_bCodec2Enabled = true; + std::cout << "Codec2 async encoding enabled for channel" << std::endl; + } + else if (!bEnable && m_bCodec2Enabled) + { + // Disable Codec2 encoding + m_bCodec2Enabled = false; + + // Stop the encoder thread + if (m_pCodec2Thread != NULL) + { + m_bCodec2StopThread = true; + m_Codec2PcmCondition.notify_all(); + m_pCodec2Thread->join(); + delete m_pCodec2Thread; + m_pCodec2Thread = NULL; + } + + // Clear any pending data + { + std::lock_guard lock(m_Codec2Mutex); + while (!m_Codec2Queue.empty()) + { + m_Codec2Queue.pop(); + } + } + { + std::lock_guard lock(m_Codec2PcmMutex); + while (!m_Codec2PcmQueue.empty()) + { + m_Codec2PcmQueue.pop(); + } + } + std::cout << "Codec2 encoding disabled for channel" << std::endl; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Codec2 queue access + +bool CVocodecChannel::HasCodec2Data(void) +{ + std::lock_guard lock(m_Codec2Mutex); + return !m_Codec2Queue.empty(); +} + +bool CVocodecChannel::GetCodec2Data(uint8 *codec2) +{ + std::lock_guard lock(m_Codec2Mutex); + if (m_Codec2Queue.empty()) + { + return false; + } + std::vector &data = m_Codec2Queue.front(); + if (data.size() < 8) { m_Codec2Queue.pop(); return false; } + ::memcpy(codec2, data.data(), 8); + m_Codec2Queue.pop(); + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// IMBE encoding control + +void CVocodecChannel::EnableImbe(bool bEnable) +{ + if (bEnable && !m_bImbeEnabled) + { + // Enable IMBE encoding with async thread + if (m_pImbe == NULL) + { + m_pImbe = new imbe_vocoder(); + } + + // Start the async encoder thread + m_bImbeStopThread = false; + m_pImbeThread = new std::thread(ImbeEncoderThread, this); + + m_bImbeEnabled = true; + std::cout << "IMBE async encoding enabled for channel" << std::endl; + } + else if (!bEnable && m_bImbeEnabled) + { + // Disable IMBE encoding + m_bImbeEnabled = false; + + // Stop the encoder thread + if (m_pImbeThread != NULL) + { + m_bImbeStopThread = true; + m_ImbePcmCondition.notify_all(); + m_pImbeThread->join(); + delete m_pImbeThread; + m_pImbeThread = NULL; + } + + // Clear any pending data + { + std::lock_guard lock(m_ImbeMutex); + while (!m_ImbeQueue.empty()) + { + m_ImbeQueue.pop(); + } + } + { + std::lock_guard lock(m_ImbePcmMutex); + while (!m_ImbePcmQueue.empty()) + { + m_ImbePcmQueue.pop(); + } + } + std::cout << "IMBE encoding disabled for channel" << std::endl; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Async Codec2 encoder thread + +void CVocodecChannel::Codec2EncoderThread(CVocodecChannel *pChannel) +{ + while (true) + { + pChannel->Codec2EncoderTask(); + + // Check stop condition atomically with queue state under the same lock + { + std::lock_guard lock(pChannel->m_Codec2PcmMutex); + if (pChannel->m_bCodec2StopThread && pChannel->m_Codec2PcmQueue.empty()) + break; + } + } +} + +void CVocodecChannel::Codec2EncoderTask(void) +{ + std::vector pcmData; + + // Wait for PCM data to encode + { + std::unique_lock lock(m_Codec2PcmMutex); + m_Codec2PcmCondition.wait(lock, [this] { + return !m_Codec2PcmQueue.empty() || m_bCodec2StopThread; + }); + + // On stop, continue draining queue to avoid tail cutoff + if (!m_Codec2PcmQueue.empty()) + { + pcmData = m_Codec2PcmQueue.front(); + m_Codec2PcmQueue.pop(); + } + else if (m_bCodec2StopThread) + { + // Queue is empty and stop requested - exit now + return; + } + } + + // Encode PCM to Codec2 (outside the lock) + if (!pcmData.empty() && m_pCodec2 != NULL) + { + uint8 codec2[8]; // 64 bits = 8 bytes for Codec2 3200 + m_pCodec2->codec2_encode(codec2, pcmData.data()); + + // Push encoded Codec2 to output queue (drop oldest if full) + std::lock_guard lock(m_Codec2Mutex); + if ( m_Codec2Queue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) + { + m_Codec2Queue.pop(); + } + std::vector c2data(codec2, codec2 + 8); + m_Codec2Queue.push(c2data); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// IMBE queue access + +bool CVocodecChannel::HasImbeData(void) +{ + std::lock_guard lock(m_ImbeMutex); + return !m_ImbeQueue.empty(); +} + +bool CVocodecChannel::GetImbeData(uint8 *imbe) +{ + std::lock_guard lock(m_ImbeMutex); + if (m_ImbeQueue.empty()) + { + return false; + } + std::vector &data = m_ImbeQueue.front(); + if (data.size() < IMBE_FRAME_SIZE) { m_ImbeQueue.pop(); return false; } + ::memcpy(imbe, data.data(), IMBE_FRAME_SIZE); + m_ImbeQueue.pop(); + return true; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Async IMBE encoder thread + +void CVocodecChannel::ImbeEncoderThread(CVocodecChannel *pChannel) +{ + while (true) + { + pChannel->ImbeEncoderTask(); + + // Check stop condition atomically with queue state under the same lock + { + std::lock_guard lock(pChannel->m_ImbePcmMutex); + if (pChannel->m_bImbeStopThread && pChannel->m_ImbePcmQueue.empty()) + break; + } + } +} + +void CVocodecChannel::ImbeEncoderTask(void) +{ + std::vector pcmData; + + // Wait for PCM data to encode + { + std::unique_lock lock(m_ImbePcmMutex); + m_ImbePcmCondition.wait(lock, [this] { + return !m_ImbePcmQueue.empty() || m_bImbeStopThread; + }); + + // On stop, continue draining queue to avoid tail cutoff + if (!m_ImbePcmQueue.empty()) + { + pcmData = m_ImbePcmQueue.front(); + m_ImbePcmQueue.pop(); + } + else if (m_bImbeStopThread) + { + // Queue is empty and stop requested - exit now + return; + } + } + + // Encode PCM to IMBE (outside the lock) + if (!pcmData.empty() && m_pImbe != NULL) + { + uint8 imbe[IMBE_FRAME_SIZE]; + m_pImbe->encode_4400(pcmData.data(), imbe); + + // Push encoded IMBE to output queue (drop oldest if full) + std::lock_guard lock(m_ImbeMutex); + if ( m_ImbeQueue.size() >= SOFTWARE_QUEUE_MAX_DEPTH ) + { + m_ImbeQueue.pop(); + } + std::vector imbedata(imbe, imbe + IMBE_FRAME_SIZE); + m_ImbeQueue.push(imbedata); + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// queues helpers + +void CVocodecChannel::PurgeAllQueues(void) +{ + GetPacketQueueIn()->Purge(); + ReleasePacketQueueIn(); + GetPacketQueueOut()->Purge(); + ReleasePacketQueueOut(); + GetVoiceQueue()->Purge(); + ReleaseVoiceQueue(); + + // Clear Codec2 queue + { + std::lock_guard lock(m_Codec2Mutex); + while (!m_Codec2Queue.empty()) + { + m_Codec2Queue.pop(); + } + } + + // Clear Codec2 PCM queue + { + std::lock_guard lock(m_Codec2PcmMutex); + while (!m_Codec2PcmQueue.empty()) + { + m_Codec2PcmQueue.pop(); + } + } + + // Clear IMBE queue + { + std::lock_guard lock(m_ImbeMutex); + while (!m_ImbeQueue.empty()) + { + m_ImbeQueue.pop(); + } + } + + // Clear IMBE PCM queue + { + std::lock_guard lock(m_ImbePcmMutex); + while (!m_ImbePcmQueue.empty()) + { + m_ImbePcmQueue.pop(); + } + } + + // Clear PID-preservation FIFO and the desync drop counters. + // Important: any pids left in the FIFO here would mis-pair with + // future input/output once the channel re-opens, because the + // hardware response queue and FIFO push/pop would be one or more + // entries out of step. The counter reset gives each stream a + // fresh accounting epoch — the close-time stats line reports + // per-stream desync events, not cumulative since process start. + { + std::lock_guard lock(m_PidFifoMutex); + while ( !m_PidFifo.empty() ) + { + m_PidFifo.pop(); + } + m_PidFifoOrphanDrops = 0; + m_PidFifoOverflowDrops = 0; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// PID preservation FIFO + +// Push a pid + timestamp pair. If the FIFO has reached its memory- +// safety cap (PID_FIFO_MAX_DEPTH), drop the oldest entry first to +// bound RAM growth under sustained input overrun. Logs a one-line +// warning the first time overflow drops fire on this stream so an +// operator notices it in real time, then stays silent until the +// counters reset (PurgeAllQueues at next stream open/close). +void CVocodecChannel::PushPid(uint8 pid) +{ + std::lock_guard lock(m_PidFifoMutex); + + while ( m_PidFifo.size() >= PID_FIFO_MAX_DEPTH ) + { + m_PidFifo.pop(); + if ( m_PidFifoOverflowDrops == 0 ) + { + std::cout << "ambed WARNING: PID FIFO overflow drop on channel " + << m_iChannelIn << "->" << m_iChannelOut + << " (input rate exceeds DVStick throughput; further " + << "drops on this stream will be silent until close)" + << std::endl; + } + m_PidFifoOverflowDrops++; + } + + PidEntry e; + e.pid = pid; + e.pushedAt = std::chrono::steady_clock::now(); + m_PidFifo.push(e); +} + +// Pop the front pid. Before returning, prune any front entries that +// are older than PID_FIFO_TIMEOUT_MS — they're orphans whose +// hardware response never arrived (DVStick drop, transient USB +// fault). Without this the FIFO would be permanently off by one +// after any hardware drop, causing every subsequent response to +// pair with the wrong xlxd-side packet for the rest of the stream. +// +// Mid-window mis-pairing is still possible (a response arriving +// during the timeout window pops the stale front entry). The +// timeout bounds the window to ~PID_FIFO_TIMEOUT_MS rather than +// preventing the mis-pair entirely; see the design review trace +// for why a tighter timeout doesn't help. After the window, the +// FIFO re-aligns and pairing is correct again. +// +// Returns 0 if the FIFO is empty (matches pre-fix default behaviour +// — xlxd's lookup will miss and the response counts as "late", +// audio for the would-be-paired packet is unaffected because it's +// already left the jitter buffer). +uint8 CVocodecChannel::PopPid(void) +{ + std::lock_guard lock(m_PidFifoMutex); + + auto now = std::chrono::steady_clock::now(); + while ( !m_PidFifo.empty() ) + { + auto ageMs = std::chrono::duration_cast( + now - m_PidFifo.front().pushedAt).count(); + if ( ageMs <= PID_FIFO_TIMEOUT_MS ) + { + break; + } + // Front entry is orphaned — prune it. + m_PidFifo.pop(); + if ( m_PidFifoOrphanDrops == 0 ) + { + std::cout << "ambed WARNING: PID FIFO orphan drop on channel " + << m_iChannelIn << "->" << m_iChannelOut + << " (DVStick dropped a packet's response; further " + << "drops on this stream will be silent until close)" + << std::endl; + } + m_PidFifoOrphanDrops++; + } + + if ( m_PidFifo.empty() ) + { + return 0; + } + uint8 pid = m_PidFifo.front().pid; + m_PidFifo.pop(); + return pid; +} + + + diff --git a/cvocodecchannel.h b/cvocodecchannel.h new file mode 100644 index 0000000..aa244ab --- /dev/null +++ b/cvocodecchannel.h @@ -0,0 +1,268 @@ +// +// cvocodecchannel.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 23/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + + +#ifndef cvocodecchannel_h +#define cvocodecchannel_h + +#include +#include +#include +#include +#include +#include +#include +#include "cpacketqueue.h" +#include "csignalprocessor.h" +#include "cvoicepacket.h" +#include "codec2/codec2.h" +#include "imbe/imbe_vocoder.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// PID FIFO desync-recovery constants +// +// Max age of a FIFO entry before PopPid prunes it as orphaned. +// Healthy ambed RTT is 40-100 ms (max observed ~144 ms in production +// captures); 500 ms is well above that and well below conversational +// silences. After this many ms, the entry is assumed to correspond +// to an input packet whose hardware response was dropped, and is +// pruned to recover FIFO alignment. +#define PID_FIFO_TIMEOUT_MS 500 + +// Max FIFO occupancy before PushPid drops oldest. Bounds memory if +// xlxd ever sustains input above DVStick throughput. 200 = 4 seconds +// of frames at 50 fps; well above any realistic burst size (xlxd's +// pre-codec buffer is paced at ~50 fps after replay, and YSF/NXDN +// per-UDP burst sizes are 4-5 frames at most). +#define PID_FIFO_MAX_DEPTH 200 + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CVocodecInterface; + +class CVocodecChannel +{ +public: + // constructors + CVocodecChannel(CVocodecInterface *, int, CVocodecInterface *, int); + + // destructor + virtual ~CVocodecChannel(); + + // open & close + bool Open(void); + bool IsOpen(void) const { return m_bOpen; } + void Close(void); + + // get + uint8 GetCodecIn(void) const; + uint8 GetCodecOut(void) const; + int GetChannelIn(void) const { return m_iChannelIn; } + int GetChannelOut(void) const { return m_iChannelOut; } + + //Processing + void ProcessSignal(CVoicePacket& voicePacket); + void ReportSignal(uint16 uiStreamId, const std::string& callsign); + + // interfaces + bool IsInterfaceIn(const CVocodecInterface *interface) { return (interface == m_InterfaceIn); } + bool IsInterfaceOut(const CVocodecInterface *interface) { return (interface == m_InterfaceOut); } + + // queues + CPacketQueue *GetPacketQueueIn(void) { m_QueuePacketIn.Lock(); return &m_QueuePacketIn; } + void ReleasePacketQueueIn(void) { m_QueuePacketIn.Unlock(); } + CPacketQueue *GetPacketQueueOut(void) { m_QueuePacketOut.Lock(); return &m_QueuePacketOut; } + void ReleasePacketQueueOut(void) { m_QueuePacketOut.Unlock(); } + CPacketQueue *GetVoiceQueue(void) { m_QueueVoice.Lock(); return &m_QueueVoice; } + void ReleaseVoiceQueue(void) { m_QueueVoice.Unlock(); } + + // PID preservation through the DVStick pipeline. + // + // The hardware response parser (CUsb3xxx*Interface::IsValidChannelPacket) + // creates a fresh CAmbePacket from raw USB bytes and has no way to + // recover the PID that was on the corresponding input packet — the + // PID is lost the moment the input packet is consumed by the USB + // write path. Without preservation, every output packet has PID=0 + // and xlxd's PID-keyed response routing breaks (every response after + // the first looks like a stale duplicate). + // + // Approach: each CVocodecChannel holds a FIFO of (pid, pushedAt) + // entries. The USB interface pushes when consuming an input packet + // (decoder side for AMBE-input mode, encoder side for Codec2/IMBE- + // input modes) and pops when producing an output packet. The + // DVStick processes packets in FIFO order per physical channel, so + // pop order matches push order — pid round-trips correctly via + // FIFO pairing rather than via byte-in-the-packet preservation + // that the hardware protocol doesn't support. + // + // The pushedAt timestamp is used for desync recovery. If the + // hardware ever drops a packet (USB glitch, transient fault), the + // FIFO would be permanently off by one without intervention. + // Two protections: + // + // - PopPid prunes orphaned entries (front older than + // PID_FIFO_TIMEOUT_MS) before returning. This bounds the + // mis-pairing window after a hardware drop to ~timeout + // duration; without it, the desync would be permanent for + // the rest of the stream. Mid-window mis-pairing is still + // possible (a response arriving during the timeout window + // pops the stale front entry); see Q1 trace in the design + // review for why a tighter timeout doesn't help. 500 ms is + // well above healthy ambed RTT (40-100 ms) and well below + // conversational silences. + // + // - PushPid caps FIFO occupancy (drops oldest if size > + // PID_FIFO_MAX_DEPTH). Memory-safety belt; only fires under + // pathological sustained input overrun. + // + // Drops are tracked separately for diagnostics — orphan drops + // (timeout-pruned) and overflow drops (cap-pruned) have different + // operational meanings. + // + // PopPid returns 0 if the FIFO is empty (matches the + // pre-fix default-PID behaviour and guarantees PopPid never + // crashes on an unexpected hardware response). + void PushPid(uint8 pid); + uint8 PopPid(void); + + // Diagnostic getters for the close-time stats line. Use .load() + // because the counters are atomic — see the m_PidFifo* declaration + // block below for the rationale. + uint32 GetPidFifoOrphanDrops(void) const { return m_PidFifoOrphanDrops.load(); } + uint32 GetPidFifoOverflowDrops(void) const { return m_PidFifoOverflowDrops.load(); } + + // Codec2 queue (for software-encoded Codec2 data) + void EnableCodec2(bool bEnable); + bool HasCodec2Data(void); + bool GetCodec2Data(uint8 *codec2); + bool IsCodec2Enabled(void) const { return m_bCodec2Enabled; } + + // IMBE queue (for software-encoded IMBE data) + void EnableImbe(bool bEnable); + bool HasImbeData(void); + bool GetImbeData(uint8 *imbe); + bool IsImbeEnabled(void) const { return m_bImbeEnabled; } + + // operators + //virtual bool operator ==(const CVocodecChannel &) const { return false; } + +protected: + // queues helpers + void PurgeAllQueues(void); + +protected: + // status + std::atomic m_bOpen; + + // connected interfaces + CVocodecInterface *m_InterfaceIn; + int m_iChannelIn; + CVocodecInterface *m_InterfaceOut; + int m_iChannelOut; + + // ambe queues + CPacketQueue m_QueuePacketIn; + CPacketQueue m_QueuePacketOut; + // voice queue + CPacketQueue m_QueueVoice; + + // PID preservation FIFO — see PushPid/PopPid comment above the + // public methods. Touched by the USB interface Task() thread + // (push on input consume, pop on output produce) and cleared by + // PurgeAllQueues from Open/Close paths on potentially other + // threads, so a dedicated mutex guards it. + // + // Each entry carries a pushedAt timestamp (steady_clock so an NTP + // wall-clock step doesn't prune the entire FIFO) for the + // desync-recovery logic in PushPid/PopPid. + struct PidEntry + { + uint8 pid; + std::chrono::steady_clock::time_point pushedAt; + }; + std::queue m_PidFifo; + std::mutex m_PidFifoMutex; + + // Desync drop counters. orphan = entries pruned at PopPid because + // they exceeded PID_FIFO_TIMEOUT_MS (the response that should have + // popped them never arrived — hardware drop). overflow = entries + // pruned at PushPid because the FIFO exceeded PID_FIFO_MAX_DEPTH + // (sustained input overrun, memory-safety belt). Reset by + // PurgeAllQueues so each stream gets a fresh accounting epoch. + // + // Atomic because the close-time capture path in CStream::Close + // reads these from a different thread than the USB Task() thread + // that increments them. Increments still happen under + // m_PidFifoMutex (the increment site is bracketed by the mutex + // we already hold for the FIFO operations), so the atomic + // operations don't add new synchronisation cost — they just + // make the cross-thread read well-defined under the C++ memory + // model. + std::atomic m_PidFifoOrphanDrops; + std::atomic m_PidFifoOverflowDrops; + + // signal processing, rebuilt for each stream. Open and Close run on + // the stream's thread, ProcessSignal on the USB interface thread. + CSignalProcessor *m_signalProcessor; + std::mutex m_SignalMutex; + + // a copy of a processed frame at the level for this codec + std::vector OutputPcm(uint8 uiCodecOut, const uint8 *voice); + + // Codec2 encoding (software) - runs in separate thread to avoid blocking hardware + std::atomic m_bCodec2Enabled; + CCodec2 *m_pCodec2; + std::mutex m_Codec2Mutex; + std::queue> m_Codec2Queue; + + // Async Codec2 encoding thread + std::thread *m_pCodec2Thread; + std::atomic m_bCodec2StopThread; + std::mutex m_Codec2PcmMutex; + std::condition_variable m_Codec2PcmCondition; + std::queue> m_Codec2PcmQueue; // PCM samples waiting to be encoded + static void Codec2EncoderThread(CVocodecChannel *pChannel); + void Codec2EncoderTask(void); + + // IMBE encoding (software) - runs in separate thread to avoid blocking hardware + std::atomic m_bImbeEnabled; + imbe_vocoder *m_pImbe; + std::mutex m_ImbeMutex; + std::queue> m_ImbeQueue; + + // Async IMBE encoding thread + std::thread *m_pImbeThread; + std::atomic m_bImbeStopThread; + std::mutex m_ImbePcmMutex; + std::condition_variable m_ImbePcmCondition; + std::queue> m_ImbePcmQueue; // PCM samples waiting to be encoded + static void ImbeEncoderThread(CVocodecChannel *pChannel); + void ImbeEncoderTask(void); + +private: +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cvocodecchannel_h */ diff --git a/cvocodecinterface.cpp b/cvocodecinterface.cpp new file mode 100644 index 0000000..e730e09 --- /dev/null +++ b/cvocodecinterface.cpp @@ -0,0 +1,95 @@ +// +// cvocodecinterface.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 23/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "ctimepoint.h" +#include "cpacketqueue.h" +#include "cvocodecinterface.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CVocodecInterface::CVocodecInterface() +{ + m_Channels.reserve(5); + m_bStopThread = false; + m_pThread = NULL; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CVocodecInterface::~CVocodecInterface() +{ + // empty channel array + // chennels are deleted by their owner (CVocodecs) + m_Channels.clear(); + + // stop thread + m_bStopThread = true; + if ( m_pThread != NULL ) + { + m_pThread->join(); + delete m_pThread; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// initialization + +bool CVocodecInterface::Init(void) +{ + // reset stop flag + m_bStopThread = false; + + // start thread; + m_pThread = new std::thread(CVocodecInterface::Thread, this); + + // done + return true; +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// thread + +void CVocodecInterface::Thread(CVocodecInterface *This) +{ + while ( !This->m_bStopThread ) + { + This->Task(); + } +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// manage Channels + +void CVocodecInterface::AddChannel(CVocodecChannel *Channel) +{ + m_Channels.push_back(Channel); +} + + diff --git a/cvocodecinterface.h b/cvocodecinterface.h new file mode 100644 index 0000000..9043ed8 --- /dev/null +++ b/cvocodecinterface.h @@ -0,0 +1,76 @@ +// +// cvocodecinterface.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 23/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cvocodecinterface_h +#define cvocodecinterface_h + +#include "cvocodecchannel.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CVocodecs; + +class CVocodecInterface +{ +public: + // constructors + CVocodecInterface(); + + // destructor + virtual ~CVocodecInterface(); + + // initialization + virtual bool Init(void); + + // get + virtual const char *GetName(void) const { return ""; } + virtual const char *GetSerial(void) const { return ""; } + + // manage channels + virtual int GetNbChannels(void) const { return 0; } + virtual uint8 GetChannelCodec(int) const { return CODEC_NONE; } + void AddChannel(CVocodecChannel *); + virtual CVocodecChannel *GetChannelWithChannelIn(int) { return NULL; } + virtual CVocodecChannel *GetChannelWithChannelOut(int) { return NULL; } + + // task + static void Thread(CVocodecInterface *); + virtual void Task(void) {}; + + // operators + virtual bool operator ==(const CVocodecInterface &) const { return false; } + +protected: + // array of channels + std::vector m_Channels; + + // thread + std::atomic m_bStopThread; + std::thread *m_pThread; + +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cvocodecinterface_h */ diff --git a/cvocodecs.cpp b/cvocodecs.cpp new file mode 100644 index 0000000..b58ecaa --- /dev/null +++ b/cvocodecs.cpp @@ -0,0 +1,327 @@ +#include "cconfig.h" +#include "main.h" +#include +#include "cvocodecs.h" +#include "cxombeinterface.h" + +CVocodecs g_Vocodecs; + +CVocodecs::CVocodecs() +{ + m_Interfaces.reserve(10); + m_Channels.reserve(64); +#ifdef USE_FTDI + m_FtdiDeviceDescrs.reserve(10); +#endif +} + +CVocodecs::~CVocodecs() +{ + m_MutexChannels.lock(); + for ( size_t i = 0; i < m_Channels.size(); i++ ) + { + delete m_Channels[i]; + } + m_Channels.clear(); + m_MutexChannels.unlock(); + + m_MutexInterfaces.lock(); + for ( size_t i = 0; i < m_Interfaces.size(); i++ ) + { + delete m_Interfaces[i]; + } + m_Interfaces.clear(); + m_MutexInterfaces.unlock(); + +#ifdef USE_FTDI + for ( size_t i = 0; i < m_FtdiDeviceDescrs.size(); i++ ) + { + delete m_FtdiDeviceDescrs[i]; + } + m_FtdiDeviceDescrs.clear(); +#endif +} + +bool CVocodecs::Init(void) +{ + bool ok = true; + int iNbCh = 0; + +#ifdef USE_FTDI + DiscoverFtdiDevices(); + + std::vector Multi3003DevicesChs; + for ( size_t i = 0; i < m_FtdiDeviceDescrs.size(); i++ ) + { + CFtdiDeviceDescr *descr = m_FtdiDeviceDescrs[i]; + if ( !descr->IsUsed() && IsEven(descr->GetNbChannels()) ) + { + iNbCh += CFtdiDeviceDescr::CreateInterface(descr, &Multi3003DevicesChs); + descr->SetUsed(true); + } + } + + std::vector PairsOf3000DevicesChs; + for ( size_t i = 0; i < m_FtdiDeviceDescrs.size(); i++ ) + { + CFtdiDeviceDescr *descr1 = m_FtdiDeviceDescrs[i]; + CFtdiDeviceDescr *descr2 = NULL; + if ( !descr1->IsUsed() && (descr1->GetNbChannels() == 1) ) + { + bool found = false; + size_t j = i + 1; + while ( !found && (j < m_FtdiDeviceDescrs.size()) ) + { + descr2 = m_FtdiDeviceDescrs[j]; + found = (!descr2->IsUsed() && (descr2->GetNbChannels() == 1)); + j++; + } + if ( found ) + { + iNbCh += CFtdiDeviceDescr::CreateInterfacePair(descr1, descr2, &PairsOf3000DevicesChs); + descr1->SetUsed(true); + descr2->SetUsed(true); + } + } + } + + std::vector Single3003DeviceChannels; + for ( size_t i = 0; i < m_FtdiDeviceDescrs.size(); i++ ) + { + CFtdiDeviceDescr *descr1 = m_FtdiDeviceDescrs[i]; + CFtdiDeviceDescr *descr2 = NULL; + if ( !descr1->IsUsed() && (descr1->GetNbChannels() == 3) ) + { + bool found = false; + size_t j = i + 1; + while ( !found && (j < m_FtdiDeviceDescrs.size()) ) + { + descr2 = m_FtdiDeviceDescrs[j]; + found = (!descr2->IsUsed() && (descr2->GetNbChannels() == 3)); + j++; + } + if ( found ) + { + iNbCh += CFtdiDeviceDescr::CreateInterfacePair(descr1, descr2, &Multi3003DevicesChs); + descr1->SetUsed(true); + descr2->SetUsed(true); + } + } + } + + std::vector Combined3003And3000DeviceChannels; + for ( size_t i = 0; i < m_FtdiDeviceDescrs.size(); i++ ) + { + CFtdiDeviceDescr *descr1 = m_FtdiDeviceDescrs[i]; + CFtdiDeviceDescr *descr2 = NULL; + if ( !descr1->IsUsed() && (descr1->GetNbChannels() == 3) ) + { + bool found = false; + size_t j = 0; + while ( !found && (j < m_FtdiDeviceDescrs.size()) ) + { + descr2 = m_FtdiDeviceDescrs[j]; + found = ((descr1 != descr2) && !descr2->IsUsed() && (descr2->GetNbChannels() == 1)); + j++; + } + if ( found ) + { + iNbCh += CFtdiDeviceDescr::CreateInterfacePair(descr1, descr2, &Combined3003And3000DeviceChannels); + descr1->SetUsed(true); + descr2->SetUsed(true); + } + else + { + iNbCh += CFtdiDeviceDescr::CreateInterface(descr1, &Single3003DeviceChannels); + descr1->SetUsed(true); + } + } + } + + for ( size_t i = 0; i < PairsOf3000DevicesChs.size(); i++ ) + m_Channels.push_back(PairsOf3000DevicesChs.at(i)); + PairsOf3000DevicesChs.clear(); + + for ( size_t i = 0; i < Single3003DeviceChannels.size(); i++ ) + m_Channels.push_back(Single3003DeviceChannels.at(i)); + Single3003DeviceChannels.clear(); + + int n = (int)Multi3003DevicesChs.size() / 6; + for ( int i = 0; (i < 6) && (n != 0); i++ ) + for ( int j = 0; j < n; j++ ) + m_Channels.push_back(Multi3003DevicesChs.at((j * 6) + i)); + Multi3003DevicesChs.clear(); + + for ( size_t i = 0; i < Combined3003And3000DeviceChannels.size(); i++ ) + m_Channels.push_back(Combined3003And3000DeviceChannels.at(i)); + Combined3003And3000DeviceChannels.clear(); +#endif + +// Initialize software XOMBE vocoder pool if no hardware devices were found + if ( iNbCh == 0 ) + { + int iThreads = g_Config.GetXombeThreads(); + if ( iThreads <= 0 ) + { + iThreads = (int)std::thread::hardware_concurrency(); + if ( iThreads < 2 ) iThreads = 2; + if ( iThreads > 8 ) iThreads = 8; + } + int iPairsPerThread = g_Config.GetXombePairsPerThread(); + if ( iPairsPerThread < 1 ) iPairsPerThread = 1; + + std::cout << "Initializing XOMBE software vocoder pool: " + << iThreads << " threads x " << (iPairsPerThread * 2) + << " channels (round-robin)..." << std::endl; + + // 1. Create and initialize all worker interfaces first + std::vector xombeIfaces; + for ( int t = 0; t < iThreads; t++ ) + { + CXombeInterface *iface = new CXombeInterface(t, iPairsPerThread); + if ( iface->Init() ) + { + m_Interfaces.push_back(iface); + xombeIfaces.push_back(iface); + } + else + { + delete iface; + ok = false; + } + } + + // 2. Interlace channels round-robin across all worker threads + for ( int p = 0; p < iPairsPerThread; p++ ) + { + int chDstar = p * 2; + int chDmr = p * 2 + 1; + + for ( size_t t = 0; t < xombeIfaces.size(); t++ ) + { + CXombeInterface *iface = xombeIfaces[t]; + + // D-STAR (AMBE+) -> DMR (AMBE2+) + CVocodecChannel *chFwd = new CVocodecChannel(iface, chDstar, iface, chDmr); + iface->AddChannel(chFwd); + m_Channels.push_back(chFwd); + + // DMR (AMBE2+) -> D-STAR (AMBE+) + CVocodecChannel *chRev = new CVocodecChannel(iface, chDmr, iface, chDstar); + iface->AddChannel(chRev); + m_Channels.push_back(chRev); + + iNbCh += 2; + } + } + } + + if ( ok ) + { + std::cout << "Codec interfaces initialized successfully : " << iNbCh << " channels available" << std::endl; + int iSoftVocoders = iNbCh / 2; + std::cout << "Software vocoders : " << iSoftVocoders << " IMBE (P25), " << iSoftVocoders << " Codec2 (M17)" << std::endl; + } + else + { + std::cout << "At least one codec interfaces failed to initialize : " << iNbCh << " channels availables" << std::endl; + } + + return ok; +} + +#ifdef USE_FTDI +bool CVocodecs::DiscoverFtdiDevices(void) +{ + bool ok = false; + DWORD iNbDevices = 0; + FT_DEVICE_LIST_INFO_NODE *list; + + for ( size_t i = 0; i < m_FtdiDeviceDescrs.size(); i++ ) + { + delete m_FtdiDeviceDescrs[i]; + } + m_FtdiDeviceDescrs.clear(); + + if ( FT_CreateDeviceInfoList(&iNbDevices) == FT_OK ) + { + std::cout << "Detected " << iNbDevices << " USB-FTDI devices" << std::endl << std::endl; + ok = true; + if ( iNbDevices > 0 ) + { + list = new FT_DEVICE_LIST_INFO_NODE[iNbDevices]; + if ( FT_GetDeviceInfoList(list, &iNbDevices) == FT_OK ) + { + for ( DWORD i = 0; i < iNbDevices; i++ ) + { + std::cout << "Description : " << list[i].Description << "\t Serial : " << list[i].SerialNumber << std::endl; + CFtdiDeviceDescr *descr = new CFtdiDeviceDescr( + LOWORD(list[i].ID), HIWORD(list[i].ID), + list[i].Description, list[i].SerialNumber); + m_FtdiDeviceDescrs.push_back(descr); + } + std::cout << std::endl; + } + else + { + ok = false; + } + delete[] list; + } + } + + return ok; +} +#endif + +CVocodecChannel *CVocodecs::OpenChannel(uint8 uiCodecIn, uint8 uiCodecOut) +{ + CVocodecChannel *Channel = NULL; + bool done = false; + + m_MutexChannels.lock(); + for ( size_t i = 0; (i < m_Channels.size()) && !done; i++ ) + { + if ( !m_Channels[i]->IsOpen() && + (m_Channels[i]->GetCodecIn() == uiCodecIn) && + (m_Channels[i]->GetCodecOut() == uiCodecOut) ) + { + if ( m_Channels[i]->Open() ) + { + Channel = m_Channels[i]; + done = true; + } + } + } + m_MutexChannels.unlock(); + + return Channel; +} + +CVocodecChannel *CVocodecs::OpenEncoderChannel(uint8 uiCodecOut) +{ + CVocodecChannel *Channel = NULL; + bool done = false; + + m_MutexChannels.lock(); + for ( size_t i = 0; (i < m_Channels.size()) && !done; i++ ) + { + if ( !m_Channels[i]->IsOpen() && + (m_Channels[i]->GetCodecOut() == uiCodecOut) ) + { + if ( m_Channels[i]->Open() ) + { + Channel = m_Channels[i]; + done = true; + } + } + } + m_MutexChannels.unlock(); + + return Channel; +} + +void CVocodecs::CloseChannel(CVocodecChannel *Channel) +{ + Channel->Close(); +} diff --git a/cvocodecs.h b/cvocodecs.h new file mode 100644 index 0000000..e94ba0f --- /dev/null +++ b/cvocodecs.h @@ -0,0 +1,80 @@ +// +// cvocodecs.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 23/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cvocodecs_h +#define cvocodecs_h + +#include "cftdidevicedescr.h" +#include "cvocodecinterface.h" +#include "cvocodecchannel.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CVocodecs +{ +public: + // constructors + CVocodecs(); + + // destructor + virtual ~CVocodecs(); + + // initialization + bool Init(void); + + // manage interfaces + int GetNbInterfaces(void) const { return (int)m_Interfaces.size(); } + CVocodecInterface *GetInterface(int); + + // manage channels + int GetNbChannels(void) const { return (int)m_Channels.size(); } + CVocodecChannel *OpenChannel(uint8, uint8); + CVocodecChannel *OpenEncoderChannel(uint8 uiCodecOut); // encoder-only channel for Codec2 input + void AddChannel(CVocodecChannel *ch) { m_Channels.push_back(ch); } + void CloseChannel(CVocodecChannel *); + +protected: + // initialisation helpers + bool DiscoverFtdiDevices(void); + + // helpers + bool IsEven(int i) const { return ((i % 2) == 0); } + bool IsOdd(int i) const { return !IsEven(i); } + +protected: + // array of interfaces + std::mutex m_MutexInterfaces; + std::vector m_Interfaces; + + // array of channels + std::mutex m_MutexChannels; + std::vector m_Channels; + + // array of FTDI desciptors + std::vector m_FtdiDeviceDescrs; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cvocodecs_h */ diff --git a/cvoicepacket.cpp b/cvoicepacket.cpp new file mode 100644 index 0000000..3cfb66e --- /dev/null +++ b/cvoicepacket.cpp @@ -0,0 +1,71 @@ +// +// cvoicepacket.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include +#include +#include "cvoicepacket.h" + + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor + +CVoicePacket::CVoicePacket() +{ + m_iSize = 0; + ::memset(m_uiVoice, 0, sizeof(m_uiVoice)); +} + +CVoicePacket::CVoicePacket(const uint8 *voice, int size) +{ + m_iSize = MIN(size, sizeof(m_uiVoice)); + ::memset(m_uiVoice, 0, sizeof(m_uiVoice)); + ::memcpy(m_uiVoice, voice, m_iSize); +} + +CVoicePacket::CVoicePacket(const CVoicePacket &packet) + : CPacket(packet) +{ + m_iSize = packet.m_iSize; + ::memcpy(m_uiVoice, packet.m_uiVoice, sizeof(m_uiVoice)); +} + + +//////////////////////////////////////////////////////////////////////////////////////// +// destructor + +CVoicePacket::~CVoicePacket() +{ +} + +//////////////////////////////////////////////////////////////////////////////////////// +// Set + +void CVoicePacket::SetVoice(const uint8 *voice, int size) +{ + m_iSize = MIN(size, sizeof(m_uiVoice)); + ::memset(m_uiVoice, 0, sizeof(m_uiVoice)); + ::memcpy(m_uiVoice, voice, m_iSize); +} + diff --git a/cvoicepacket.h b/cvoicepacket.h new file mode 100644 index 0000000..bb8e6ce --- /dev/null +++ b/cvoicepacket.h @@ -0,0 +1,68 @@ +// +// cvoicepacket.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 28/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef cvoicepacket_h +#define cvoicepacket_h + + +#include "cpacket.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// define + +// frame sizes +#define VOICE_SIZEMAX 512 + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CVoicePacket : public CPacket +{ +public: + // constructors + CVoicePacket(); + CVoicePacket(const uint8 *, int); + CVoicePacket(const CVoicePacket &); + + // destructor + virtual ~CVoicePacket(); + + // identity + bool IsVoice(void) const { return true; } + + // get + uint8 *GetVoice(void) { return m_uiVoice; } + int GetVoiceSize(void) const { return m_iSize; } + + // set + void SetVoice(const uint8 *, int); + +protected: + // data + int m_iSize; + uint8 m_uiVoice[VOICE_SIZEMAX]; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cvoicepacket_h */ diff --git a/cxombeinterface.cpp b/cxombeinterface.cpp new file mode 100644 index 0000000..22e0d25 --- /dev/null +++ b/cxombeinterface.cpp @@ -0,0 +1,225 @@ +// +// cxombeinterface.cpp +// ambed +// +// Software vocoder interface powered by xombe (AMBE+ / AMBE2+) +// + +#include "main.h" +#include +#include +#include "cambepacket.h" +#include "cvoicepacket.h" +#include "cxombeinterface.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// constructor & destructor + +CXombeInterface::CXombeInterface(int iIndex, int iNbPairs) + : m_iIndex(iIndex), m_iNbPairs(iNbPairs) +{ + std::snprintf(m_szName, sizeof(m_szName), "XOMBE-SW-%d", m_iIndex); + std::snprintf(m_szSerial, sizeof(m_szSerial), "XOMBE%04d", m_iIndex); + m_Slots.resize(m_iNbPairs * 2); +} + +CXombeInterface::~CXombeInterface() +{ + m_bStopThread = true; + if ( m_pThread != NULL ) + { + m_pThread->join(); + delete m_pThread; + m_pThread = NULL; + } +} + +//////////////////////////////////////////////////////////////////////////////////////// +// initialization + +bool CXombeInterface::Init(void) +{ + if ( xombe_version() != XOMBE_VERSION ) + { + std::cerr << m_szName << ": xombe version mismatch (lib=" + << xombe_version() << ", header=" << XOMBE_VERSION << ")" << std::endl; + return false; + } + + // Start the worker thread via base class + return CVocodecInterface::Init(); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// channel mapping +// Even logical indices -> CODEC_AMBEPLUS (D-STAR) +// Odd logical indices -> CODEC_AMBE2PLUS (DMR / YSF-DN / NXDN) + +uint8 CXombeInterface::GetChannelCodec(int iCh) const +{ + return ((iCh % 2) == 0) ? CODEC_AMBEPLUS : CODEC_AMBE2PLUS; +} + +CVocodecChannel *CXombeInterface::GetChannelWithChannelIn(int iCh) +{ + for ( size_t i = 0; i < m_Channels.size(); i++ ) + { + if ( m_Channels[i]->GetChannelIn() == iCh ) + return m_Channels[i]; + } + return NULL; +} + +CVocodecChannel *CXombeInterface::GetChannelWithChannelOut(int iCh) +{ + for ( size_t i = 0; i < m_Channels.size(); i++ ) + { + if ( m_Channels[i]->GetChannelOut() == iCh ) + return m_Channels[i]; + } + return NULL; +} + +//////////////////////////////////////////////////////////////////////////////////////// +// xombe state reset (runs exclusively on this interface's worker thread) + +void CXombeInterface::ResetSlot(XombeSlot &slot, uint8 uiCodecIn, uint8 uiCodecOut) +{ + enum xombe_codec fromCodec = (uiCodecIn == CODEC_AMBEPLUS) ? XOMBE_DSTAR : XOMBE_DMR; + + // 1. Direct parameter-domain transcoder (shares m_QwsMem on this thread) + slot.xc = xombe_xc_init_shared(&slot.xcMem, fromCodec, &m_QwsMem); + + // 2. Decoder (AMBE -> PCM, used when M17/P25 output is enabled) + slot.dec = xombe_dec_init(&slot.decMem, fromCodec); + + // 3. Encoder (PCM -> AMBE, used when OpenEncoderChannel receives PCM on VoiceQueue) + xombe_enc_cfg encCfg; + xombe_enc_cfg_default(&encCfg); + encCfg.outputs = (uiCodecOut == CODEC_AMBEPLUS) ? XOMBE_ENC_DSTAR : XOMBE_ENC_DMR; + slot.enc = xombe_enc_init(&slot.encMem, &encCfg); +} + +//////////////////////////////////////////////////////////////////////////////////////// +// worker thread loop + +void CXombeInterface::Task(void) +{ + bool bDidWork = false; + + for ( size_t i = 0; i < m_Channels.size(); i++ ) + { + CVocodecChannel *ch = m_Channels[i]; + XombeSlot &slot = m_Slots[i]; + + bool bOpen = ch->IsOpen(); + if ( !bOpen ) + { + slot.wasOpen = false; + continue; + } + + if ( !slot.wasOpen ) + { + ResetSlot(slot, ch->GetCodecIn(), ch->GetCodecOut()); + slot.wasOpen = true; + } + + // --- PATH A: AMBE input (D-STAR <-> DMR, and optionally -> Codec2/IMBE) --- + CAmbePacket *pktIn = NULL; + CPacketQueue *qIn = ch->GetPacketQueueIn(); + if ( !qIn->empty() ) + { + pktIn = (CAmbePacket *)qIn->front(); + qIn->pop(); + } + ch->ReleasePacketQueueIn(); + + if ( pktIn != NULL ) + { + bDidWork = true; + uint8 outAmbe[XOMBE_FRAME_BYTES]; + + // Direct parameter-domain transcoding (0-frame delay) + if ( slot.xc != NULL && + xombe_xc_frame(slot.xc, pktIn->GetAmbe(), 0, outAmbe) == 1 ) + { + CAmbePacket *pktOut = new CAmbePacket(); + pktOut->SetPid(pktIn->GetPid()); + pktOut->SetCodec(ch->GetCodecOut()); + pktOut->SetAmbe(outAmbe); + + CPacketQueue *qOut = ch->GetPacketQueueOut(); + qOut->push(pktOut); + ch->ReleasePacketQueueOut(); + } + + // If Codec2 (M17) or IMBE (P25) output is active, also decode to PCM + // Convert xombe native int16_t PCM -> big-endian PCM expected by CSignalProcessor/OutputPcm + if ( (ch->IsCodec2Enabled() || ch->IsImbeEnabled()) && slot.dec != NULL ) + { + int16_t pcm[160]; + if ( xombe_dec_frame(slot.dec, pktIn->GetAmbe(), 0, pcm) == 1 ) + { + uint8 pcmBe[320]; + for ( int s = 0; s < 160; s++ ) + { + pcmBe[s * 2] = (uint8)((pcm[s] >> 8) & 0xFF); + pcmBe[s * 2 + 1] = (uint8)(pcm[s] & 0xFF); + } + CVoicePacket voicePkt(pcmBe, sizeof(pcmBe)); + ch->ProcessSignal(voicePkt); + } + } + + delete pktIn; + } + + // --- PATH B: PCM input on VoiceQueue (M17/P25 -> AMBE via OpenEncoderChannel) --- + CVoicePacket *voiceIn = NULL; + CPacketQueue *qVoice = ch->GetVoiceQueue(); + if ( !qVoice->empty() ) + { + voiceIn = (CVoicePacket *)qVoice->front(); + qVoice->pop(); + } + ch->ReleaseVoiceQueue(); + + if ( voiceIn != NULL ) + { + bDidWork = true; + if ( slot.enc != NULL && voiceIn->GetVoiceSize() >= 320 ) + { + uint8 dmrOut[XOMBE_FRAME_BYTES]; + uint8 dstarOut[XOMBE_FRAME_BYTES]; + const uint8 *rawBe = voiceIn->GetVoice(); + int16_t pcm[160]; + + // Convert big-endian PCM from VoiceQueue -> native int16_t for xombe + for ( int s = 0; s < 160; s++ ) + { + pcm[s] = (int16_t)((rawBe[s * 2] << 8) | rawBe[s * 2 + 1]); + } + + xombe_enc_frame(slot.enc, pcm, NULL, dmrOut, dstarOut); + + CAmbePacket *pktOut = new CAmbePacket(); + pktOut->SetPid(ch->PopPid()); + pktOut->SetCodec(ch->GetCodecOut()); + pktOut->SetAmbe((ch->GetCodecOut() == CODEC_AMBEPLUS) ? dstarOut : dmrOut); + + CPacketQueue *qOut = ch->GetPacketQueueOut(); + qOut->push(pktOut); + ch->ReleasePacketQueueOut(); + } + + delete voiceIn; + } + } + + // Avoid busy-spinning when all channels on this thread are idle + if ( !bDidWork ) + { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } +} diff --git a/cxombeinterface.h b/cxombeinterface.h new file mode 100644 index 0000000..12088d9 --- /dev/null +++ b/cxombeinterface.h @@ -0,0 +1,75 @@ +// +// cxombeinterface.h +// ambed +// +// Software vocoder interface powered by xombe (AMBE+ / AMBE2+) +// + +#ifndef cxombeinterface_h +#define cxombeinterface_h + +#include "cvocodecinterface.h" +#include "xombe.h" + +//////////////////////////////////////////////////////////////////////////////////////// +// class + +class CXombeInterface : public CVocodecInterface +{ +public: + // constructor: iIndex = thread/instance ID, iNbPairs = bidirectional channel pairs + CXombeInterface(int iIndex, int iNbPairs); + + // destructor + virtual ~CXombeInterface(); + + // initialization + bool Init(void) override; + + // get + const char *GetName(void) const override { return m_szName; } + const char *GetSerial(void) const override { return m_szSerial; } + + // manage channels + int GetNbChannels(void) const override { return m_iNbPairs * 2; } + uint8 GetChannelCodec(int iCh) const override; + CVocodecChannel *GetChannelWithChannelIn(int iCh) override; + CVocodecChannel *GetChannelWithChannelOut(int iCh) override; + + // task + void Task(void) override; + + // operators + bool operator ==(const CVocodecInterface &other) const override { return (this == &other); } + +protected: + // per-channel xombe state (allocated once, reset on channel open) + struct XombeSlot + { + bool wasOpen; + xombe_xc_shared_mem xcMem; + xombe_xc *xc; + xombe_dec_mem decMem; + xombe_dec *dec; + xombe_enc_mem encMem; + xombe_enc *enc; + + XombeSlot() : wasOpen(false), xc(NULL), dec(NULL), enc(NULL) {} + }; + + void ResetSlot(XombeSlot &slot, uint8 uiCodecIn, uint8 uiCodecOut); + void ProcessChannel(size_t idx); + +protected: + int m_iIndex; + int m_iNbPairs; + char m_szName[32]; + char m_szSerial[32]; + + // shared quantizer workspace for all xombe_xc instances on this thread + xombe_qws_mem m_QwsMem; + std::vector m_Slots; +}; + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* cxombeinterface_h */ diff --git a/ftd2xx.h b/ftd2xx.h new file mode 100644 index 0000000..e5bbb46 --- /dev/null +++ b/ftd2xx.h @@ -0,0 +1,1443 @@ +/*++ + +Copyright © 2001-2011 Future Technology Devices International Limited + +THIS SOFTWARE IS PROVIDED BY FUTURE TECHNOLOGY DEVICES INTERNATIONAL LIMITED "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +FUTURE TECHNOLOGY DEVICES INTERNATIONAL LIMITED BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT +OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +FTDI DRIVERS MAY BE USED ONLY IN CONJUNCTION WITH PRODUCTS BASED ON FTDI PARTS. + +FTDI DRIVERS MAY BE DISTRIBUTED IN ANY FORM AS LONG AS LICENSE INFORMATION IS NOT MODIFIED. + +IF A CUSTOM VENDOR ID AND/OR PRODUCT ID OR DESCRIPTION STRING ARE USED, IT IS THE +RESPONSIBILITY OF THE PRODUCT MANUFACTURER TO MAINTAIN ANY CHANGES AND SUBSEQUENT WHQL +RE-CERTIFICATION AS A RESULT OF MAKING THESE CHANGES. + + +Module Name: + +ftd2xx.h + +Abstract: + +Native USB device driver for FTDI FT232x, FT245x, FT2232x and FT4232x devices +FTD2XX library definitions + +Environment: + +kernel & user mode + + +--*/ + + +#ifndef FTD2XX_H +#define FTD2XX_H + +#ifdef _WIN32 +// Compiling on Windows +#include + +// The following ifdef block is the standard way of creating macros +// which make exporting from a DLL simpler. All files within this DLL +// are compiled with the FTD2XX_EXPORTS symbol defined on the command line. +// This symbol should not be defined on any project that uses this DLL. +// This way any other project whose source files include this file see +// FTD2XX_API functions as being imported from a DLL, whereas this DLL +// sees symbols defined with this macro as being exported. + +#ifdef FTD2XX_EXPORTS +#define FTD2XX_API __declspec(dllexport) +#elif defined(FTD2XX_STATIC) +// Avoid decorations when linking statically to D2XX. +#define FTD2XX_API +// Static D2XX depends on these Windows libs: +#pragma comment(lib, "setupapi.lib") +#pragma comment(lib, "advapi32.lib") +#pragma comment(lib, "user32.lib") +#else +#define FTD2XX_API __declspec(dllimport) +#endif + +#else // _WIN32 +// Compiling on non-Windows platform. +#include "WinTypes.h" +// No decorations needed. +#define FTD2XX_API + +#endif // _WIN32 + +typedef PVOID FT_HANDLE; +typedef ULONG FT_STATUS; + +// +// Device status +// +enum { + FT_OK, + FT_INVALID_HANDLE, + FT_DEVICE_NOT_FOUND, + FT_DEVICE_NOT_OPENED, + FT_IO_ERROR, + FT_INSUFFICIENT_RESOURCES, + FT_INVALID_PARAMETER, + FT_INVALID_BAUD_RATE, + + FT_DEVICE_NOT_OPENED_FOR_ERASE, + FT_DEVICE_NOT_OPENED_FOR_WRITE, + FT_FAILED_TO_WRITE_DEVICE, + FT_EEPROM_READ_FAILED, + FT_EEPROM_WRITE_FAILED, + FT_EEPROM_ERASE_FAILED, + FT_EEPROM_NOT_PRESENT, + FT_EEPROM_NOT_PROGRAMMED, + FT_INVALID_ARGS, + FT_NOT_SUPPORTED, + FT_OTHER_ERROR, + FT_DEVICE_LIST_NOT_READY, +}; + + +#define FT_SUCCESS(status) ((status) == FT_OK) + +// +// FT_OpenEx Flags +// + +#define FT_OPEN_BY_SERIAL_NUMBER 1 +#define FT_OPEN_BY_DESCRIPTION 2 +#define FT_OPEN_BY_LOCATION 4 + +#define FT_OPEN_MASK (FT_OPEN_BY_SERIAL_NUMBER | \ + FT_OPEN_BY_DESCRIPTION | \ + FT_OPEN_BY_LOCATION) + +// +// FT_ListDevices Flags (used in conjunction with FT_OpenEx Flags +// + +#define FT_LIST_NUMBER_ONLY 0x80000000 +#define FT_LIST_BY_INDEX 0x40000000 +#define FT_LIST_ALL 0x20000000 + +#define FT_LIST_MASK (FT_LIST_NUMBER_ONLY|FT_LIST_BY_INDEX|FT_LIST_ALL) + +// +// Baud Rates +// + +#define FT_BAUD_300 300 +#define FT_BAUD_600 600 +#define FT_BAUD_1200 1200 +#define FT_BAUD_2400 2400 +#define FT_BAUD_4800 4800 +#define FT_BAUD_9600 9600 +#define FT_BAUD_14400 14400 +#define FT_BAUD_19200 19200 +#define FT_BAUD_38400 38400 +#define FT_BAUD_57600 57600 +#define FT_BAUD_115200 115200 +#define FT_BAUD_230400 230400 +#define FT_BAUD_460800 460800 +#define FT_BAUD_921600 921600 + +// +// Word Lengths +// + +#define FT_BITS_8 (UCHAR) 8 +#define FT_BITS_7 (UCHAR) 7 + +// +// Stop Bits +// + +#define FT_STOP_BITS_1 (UCHAR) 0 +#define FT_STOP_BITS_2 (UCHAR) 2 + +// +// Parity +// + +#define FT_PARITY_NONE (UCHAR) 0 +#define FT_PARITY_ODD (UCHAR) 1 +#define FT_PARITY_EVEN (UCHAR) 2 +#define FT_PARITY_MARK (UCHAR) 3 +#define FT_PARITY_SPACE (UCHAR) 4 + +// +// Flow Control +// + +#define FT_FLOW_NONE 0x0000 +#define FT_FLOW_RTS_CTS 0x0100 +#define FT_FLOW_DTR_DSR 0x0200 +#define FT_FLOW_XON_XOFF 0x0400 + +// +// Purge rx and tx buffers +// +#define FT_PURGE_RX 1 +#define FT_PURGE_TX 2 + +// +// Events +// + +typedef void (*PFT_EVENT_HANDLER)(DWORD,DWORD); + +#define FT_EVENT_RXCHAR 1 +#define FT_EVENT_MODEM_STATUS 2 +#define FT_EVENT_LINE_STATUS 4 + +// +// Timeouts +// + +#define FT_DEFAULT_RX_TIMEOUT 300 +#define FT_DEFAULT_TX_TIMEOUT 300 + +// +// Device types +// + +typedef ULONG FT_DEVICE; + +enum { + FT_DEVICE_BM, + FT_DEVICE_AM, + FT_DEVICE_100AX, + FT_DEVICE_UNKNOWN, + FT_DEVICE_2232C, + FT_DEVICE_232R, + FT_DEVICE_2232H, + FT_DEVICE_4232H, + FT_DEVICE_232H, + FT_DEVICE_X_SERIES, + FT_DEVICE_4222H_0, + FT_DEVICE_4222H_1_2, + FT_DEVICE_4222H_3, + FT_DEVICE_4222_PROG, +}; + +// +// Bit Modes +// + +#define FT_BITMODE_RESET 0x00 +#define FT_BITMODE_ASYNC_BITBANG 0x01 +#define FT_BITMODE_MPSSE 0x02 +#define FT_BITMODE_SYNC_BITBANG 0x04 +#define FT_BITMODE_MCU_HOST 0x08 +#define FT_BITMODE_FAST_SERIAL 0x10 +#define FT_BITMODE_CBUS_BITBANG 0x20 +#define FT_BITMODE_SYNC_FIFO 0x40 + +// +// FT232R CBUS Options EEPROM values +// + +#define FT_232R_CBUS_TXDEN 0x00 // Tx Data Enable +#define FT_232R_CBUS_PWRON 0x01 // Power On +#define FT_232R_CBUS_RXLED 0x02 // Rx LED +#define FT_232R_CBUS_TXLED 0x03 // Tx LED +#define FT_232R_CBUS_TXRXLED 0x04 // Tx and Rx LED +#define FT_232R_CBUS_SLEEP 0x05 // Sleep +#define FT_232R_CBUS_CLK48 0x06 // 48MHz clock +#define FT_232R_CBUS_CLK24 0x07 // 24MHz clock +#define FT_232R_CBUS_CLK12 0x08 // 12MHz clock +#define FT_232R_CBUS_CLK6 0x09 // 6MHz clock +#define FT_232R_CBUS_IOMODE 0x0A // IO Mode for CBUS bit-bang +#define FT_232R_CBUS_BITBANG_WR 0x0B // Bit-bang write strobe +#define FT_232R_CBUS_BITBANG_RD 0x0C // Bit-bang read strobe + +// +// FT232H CBUS Options EEPROM values +// + +#define FT_232H_CBUS_TRISTATE 0x00 // Tristate +#define FT_232H_CBUS_TXLED 0x01 // Tx LED +#define FT_232H_CBUS_RXLED 0x02 // Rx LED +#define FT_232H_CBUS_TXRXLED 0x03 // Tx and Rx LED +#define FT_232H_CBUS_PWREN 0x04 // Power Enable +#define FT_232H_CBUS_SLEEP 0x05 // Sleep +#define FT_232H_CBUS_DRIVE_0 0x06 // Drive pin to logic 0 +#define FT_232H_CBUS_DRIVE_1 0x07 // Drive pin to logic 1 +#define FT_232H_CBUS_IOMODE 0x08 // IO Mode for CBUS bit-bang +#define FT_232H_CBUS_TXDEN 0x09 // Tx Data Enable +#define FT_232H_CBUS_CLK30 0x0A // 30MHz clock +#define FT_232H_CBUS_CLK15 0x0B // 15MHz clock +#define FT_232H_CBUS_CLK7_5 0x0C // 7.5MHz clock + +// +// FT X Series CBUS Options EEPROM values +// + +#define FT_X_SERIES_CBUS_TRISTATE 0x00 // Tristate +#define FT_X_SERIES_CBUS_TXLED 0x01 // Tx LED +#define FT_X_SERIES_CBUS_RXLED 0x02 // Rx LED +#define FT_X_SERIES_CBUS_TXRXLED 0x03 // Tx and Rx LED +#define FT_X_SERIES_CBUS_PWREN 0x04 // Power Enable +#define FT_X_SERIES_CBUS_SLEEP 0x05 // Sleep +#define FT_X_SERIES_CBUS_DRIVE_0 0x06 // Drive pin to logic 0 +#define FT_X_SERIES_CBUS_DRIVE_1 0x07 // Drive pin to logic 1 +#define FT_X_SERIES_CBUS_IOMODE 0x08 // IO Mode for CBUS bit-bang +#define FT_X_SERIES_CBUS_TXDEN 0x09 // Tx Data Enable +#define FT_X_SERIES_CBUS_CLK24 0x0A // 24MHz clock +#define FT_X_SERIES_CBUS_CLK12 0x0B // 12MHz clock +#define FT_X_SERIES_CBUS_CLK6 0x0C // 6MHz clock +#define FT_X_SERIES_CBUS_BCD_CHARGER 0x0D // Battery charger detected +#define FT_X_SERIES_CBUS_BCD_CHARGER_N 0x0E // Battery charger detected inverted +#define FT_X_SERIES_CBUS_I2C_TXE 0x0F // I2C Tx empty +#define FT_X_SERIES_CBUS_I2C_RXF 0x10 // I2C Rx full +#define FT_X_SERIES_CBUS_VBUS_SENSE 0x11 // Detect VBUS +#define FT_X_SERIES_CBUS_BITBANG_WR 0x12 // Bit-bang write strobe +#define FT_X_SERIES_CBUS_BITBANG_RD 0x13 // Bit-bang read strobe +#define FT_X_SERIES_CBUS_TIMESTAMP 0x14 // Toggle output when a USB SOF token is received +#define FT_X_SERIES_CBUS_KEEP_AWAKE 0x15 // + + +// Driver types +#define FT_DRIVER_TYPE_D2XX 0 +#define FT_DRIVER_TYPE_VCP 1 + + + +#ifdef __cplusplus +extern "C" { +#endif + + +#ifdef FTD2XX_STATIC + FTD2XX_API + FT_STATUS WINAPI FT_Initialise( + void + ); + + FTD2XX_API + void WINAPI FT_Finalise( + void + ); +#endif // FTD2XX_STATIC + + FTD2XX_API + FT_STATUS WINAPI FT_Open( + int deviceNumber, + FT_HANDLE *pHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_OpenEx( + PVOID pArg1, + DWORD Flags, + FT_HANDLE *pHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_ListDevices( + PVOID pArg1, + PVOID pArg2, + DWORD Flags + ); + + FTD2XX_API + FT_STATUS WINAPI FT_Close( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_Read( + FT_HANDLE ftHandle, + LPVOID lpBuffer, + DWORD dwBytesToRead, + LPDWORD lpBytesReturned + ); + + FTD2XX_API + FT_STATUS WINAPI FT_Write( + FT_HANDLE ftHandle, + LPVOID lpBuffer, + DWORD dwBytesToWrite, + LPDWORD lpBytesWritten + ); + + FTD2XX_API + FT_STATUS WINAPI FT_IoCtl( + FT_HANDLE ftHandle, + DWORD dwIoControlCode, + LPVOID lpInBuf, + DWORD nInBufSize, + LPVOID lpOutBuf, + DWORD nOutBufSize, + LPDWORD lpBytesReturned, + LPOVERLAPPED lpOverlapped + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetBaudRate( + FT_HANDLE ftHandle, + ULONG BaudRate + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetDivisor( + FT_HANDLE ftHandle, + USHORT Divisor + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetDataCharacteristics( + FT_HANDLE ftHandle, + UCHAR WordLength, + UCHAR StopBits, + UCHAR Parity + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetFlowControl( + FT_HANDLE ftHandle, + USHORT FlowControl, + UCHAR XonChar, + UCHAR XoffChar + ); + + FTD2XX_API + FT_STATUS WINAPI FT_ResetDevice( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetDtr( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_ClrDtr( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetRts( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_ClrRts( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetModemStatus( + FT_HANDLE ftHandle, + ULONG *pModemStatus + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetChars( + FT_HANDLE ftHandle, + UCHAR EventChar, + UCHAR EventCharEnabled, + UCHAR ErrorChar, + UCHAR ErrorCharEnabled + ); + + FTD2XX_API + FT_STATUS WINAPI FT_Purge( + FT_HANDLE ftHandle, + ULONG Mask + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetTimeouts( + FT_HANDLE ftHandle, + ULONG ReadTimeout, + ULONG WriteTimeout + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetQueueStatus( + FT_HANDLE ftHandle, + DWORD *dwRxBytes + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetEventNotification( + FT_HANDLE ftHandle, + DWORD Mask, + PVOID Param + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetStatus( + FT_HANDLE ftHandle, + DWORD *dwRxBytes, + DWORD *dwTxBytes, + DWORD *dwEventDWord + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetBreakOn( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetBreakOff( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetWaitMask( + FT_HANDLE ftHandle, + DWORD Mask + ); + + FTD2XX_API + FT_STATUS WINAPI FT_WaitOnMask( + FT_HANDLE ftHandle, + DWORD *Mask + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetEventStatus( + FT_HANDLE ftHandle, + DWORD *dwEventDWord + ); + + FTD2XX_API + FT_STATUS WINAPI FT_ReadEE( + FT_HANDLE ftHandle, + DWORD dwWordOffset, + LPWORD lpwValue + ); + + FTD2XX_API + FT_STATUS WINAPI FT_WriteEE( + FT_HANDLE ftHandle, + DWORD dwWordOffset, + WORD wValue + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EraseEE( + FT_HANDLE ftHandle + ); + + // + // structure to hold program data for FT_EE_Program, FT_EE_ProgramEx, FT_EE_Read + // and FT_EE_ReadEx functions + // + typedef struct ft_program_data { + + DWORD Signature1; // Header - must be 0x00000000 + DWORD Signature2; // Header - must be 0xffffffff + DWORD Version; // Header - FT_PROGRAM_DATA version + // 0 = original + // 1 = FT2232 extensions + // 2 = FT232R extensions + // 3 = FT2232H extensions + // 4 = FT4232H extensions + // 5 = FT232H extensions + + WORD VendorId; // 0x0403 + WORD ProductId; // 0x6001 + char *Manufacturer; // "FTDI" + char *ManufacturerId; // "FT" + char *Description; // "USB HS Serial Converter" + char *SerialNumber; // "FT000001" if fixed, or NULL + WORD MaxPower; // 0 < MaxPower <= 500 + WORD PnP; // 0 = disabled, 1 = enabled + WORD SelfPowered; // 0 = bus powered, 1 = self powered + WORD RemoteWakeup; // 0 = not capable, 1 = capable + // + // Rev4 (FT232B) extensions + // + UCHAR Rev4; // non-zero if Rev4 chip, zero otherwise + UCHAR IsoIn; // non-zero if in endpoint is isochronous + UCHAR IsoOut; // non-zero if out endpoint is isochronous + UCHAR PullDownEnable; // non-zero if pull down enabled + UCHAR SerNumEnable; // non-zero if serial number to be used + UCHAR USBVersionEnable; // non-zero if chip uses USBVersion + WORD USBVersion; // BCD (0x0200 => USB2) + // + // Rev 5 (FT2232) extensions + // + UCHAR Rev5; // non-zero if Rev5 chip, zero otherwise + UCHAR IsoInA; // non-zero if in endpoint is isochronous + UCHAR IsoInB; // non-zero if in endpoint is isochronous + UCHAR IsoOutA; // non-zero if out endpoint is isochronous + UCHAR IsoOutB; // non-zero if out endpoint is isochronous + UCHAR PullDownEnable5; // non-zero if pull down enabled + UCHAR SerNumEnable5; // non-zero if serial number to be used + UCHAR USBVersionEnable5; // non-zero if chip uses USBVersion + WORD USBVersion5; // BCD (0x0200 => USB2) + UCHAR AIsHighCurrent; // non-zero if interface is high current + UCHAR BIsHighCurrent; // non-zero if interface is high current + UCHAR IFAIsFifo; // non-zero if interface is 245 FIFO + UCHAR IFAIsFifoTar; // non-zero if interface is 245 FIFO CPU target + UCHAR IFAIsFastSer; // non-zero if interface is Fast serial + UCHAR AIsVCP; // non-zero if interface is to use VCP drivers + UCHAR IFBIsFifo; // non-zero if interface is 245 FIFO + UCHAR IFBIsFifoTar; // non-zero if interface is 245 FIFO CPU target + UCHAR IFBIsFastSer; // non-zero if interface is Fast serial + UCHAR BIsVCP; // non-zero if interface is to use VCP drivers + // + // Rev 6 (FT232R) extensions + // + UCHAR UseExtOsc; // Use External Oscillator + UCHAR HighDriveIOs; // High Drive I/Os + UCHAR EndpointSize; // Endpoint size + UCHAR PullDownEnableR; // non-zero if pull down enabled + UCHAR SerNumEnableR; // non-zero if serial number to be used + UCHAR InvertTXD; // non-zero if invert TXD + UCHAR InvertRXD; // non-zero if invert RXD + UCHAR InvertRTS; // non-zero if invert RTS + UCHAR InvertCTS; // non-zero if invert CTS + UCHAR InvertDTR; // non-zero if invert DTR + UCHAR InvertDSR; // non-zero if invert DSR + UCHAR InvertDCD; // non-zero if invert DCD + UCHAR InvertRI; // non-zero if invert RI + UCHAR Cbus0; // Cbus Mux control + UCHAR Cbus1; // Cbus Mux control + UCHAR Cbus2; // Cbus Mux control + UCHAR Cbus3; // Cbus Mux control + UCHAR Cbus4; // Cbus Mux control + UCHAR RIsD2XX; // non-zero if using D2XX driver + // + // Rev 7 (FT2232H) Extensions + // + UCHAR PullDownEnable7; // non-zero if pull down enabled + UCHAR SerNumEnable7; // non-zero if serial number to be used + UCHAR ALSlowSlew; // non-zero if AL pins have slow slew + UCHAR ALSchmittInput; // non-zero if AL pins are Schmitt input + UCHAR ALDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR AHSlowSlew; // non-zero if AH pins have slow slew + UCHAR AHSchmittInput; // non-zero if AH pins are Schmitt input + UCHAR AHDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR BLSlowSlew; // non-zero if BL pins have slow slew + UCHAR BLSchmittInput; // non-zero if BL pins are Schmitt input + UCHAR BLDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR BHSlowSlew; // non-zero if BH pins have slow slew + UCHAR BHSchmittInput; // non-zero if BH pins are Schmitt input + UCHAR BHDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR IFAIsFifo7; // non-zero if interface is 245 FIFO + UCHAR IFAIsFifoTar7; // non-zero if interface is 245 FIFO CPU target + UCHAR IFAIsFastSer7; // non-zero if interface is Fast serial + UCHAR AIsVCP7; // non-zero if interface is to use VCP drivers + UCHAR IFBIsFifo7; // non-zero if interface is 245 FIFO + UCHAR IFBIsFifoTar7; // non-zero if interface is 245 FIFO CPU target + UCHAR IFBIsFastSer7; // non-zero if interface is Fast serial + UCHAR BIsVCP7; // non-zero if interface is to use VCP drivers + UCHAR PowerSaveEnable; // non-zero if using BCBUS7 to save power for self-powered designs + // + // Rev 8 (FT4232H) Extensions + // + UCHAR PullDownEnable8; // non-zero if pull down enabled + UCHAR SerNumEnable8; // non-zero if serial number to be used + UCHAR ASlowSlew; // non-zero if A pins have slow slew + UCHAR ASchmittInput; // non-zero if A pins are Schmitt input + UCHAR ADriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR BSlowSlew; // non-zero if B pins have slow slew + UCHAR BSchmittInput; // non-zero if B pins are Schmitt input + UCHAR BDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR CSlowSlew; // non-zero if C pins have slow slew + UCHAR CSchmittInput; // non-zero if C pins are Schmitt input + UCHAR CDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR DSlowSlew; // non-zero if D pins have slow slew + UCHAR DSchmittInput; // non-zero if D pins are Schmitt input + UCHAR DDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR ARIIsTXDEN; // non-zero if port A uses RI as RS485 TXDEN + UCHAR BRIIsTXDEN; // non-zero if port B uses RI as RS485 TXDEN + UCHAR CRIIsTXDEN; // non-zero if port C uses RI as RS485 TXDEN + UCHAR DRIIsTXDEN; // non-zero if port D uses RI as RS485 TXDEN + UCHAR AIsVCP8; // non-zero if interface is to use VCP drivers + UCHAR BIsVCP8; // non-zero if interface is to use VCP drivers + UCHAR CIsVCP8; // non-zero if interface is to use VCP drivers + UCHAR DIsVCP8; // non-zero if interface is to use VCP drivers + // + // Rev 9 (FT232H) Extensions + // + UCHAR PullDownEnableH; // non-zero if pull down enabled + UCHAR SerNumEnableH; // non-zero if serial number to be used + UCHAR ACSlowSlewH; // non-zero if AC pins have slow slew + UCHAR ACSchmittInputH; // non-zero if AC pins are Schmitt input + UCHAR ACDriveCurrentH; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR ADSlowSlewH; // non-zero if AD pins have slow slew + UCHAR ADSchmittInputH; // non-zero if AD pins are Schmitt input + UCHAR ADDriveCurrentH; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR Cbus0H; // Cbus Mux control + UCHAR Cbus1H; // Cbus Mux control + UCHAR Cbus2H; // Cbus Mux control + UCHAR Cbus3H; // Cbus Mux control + UCHAR Cbus4H; // Cbus Mux control + UCHAR Cbus5H; // Cbus Mux control + UCHAR Cbus6H; // Cbus Mux control + UCHAR Cbus7H; // Cbus Mux control + UCHAR Cbus8H; // Cbus Mux control + UCHAR Cbus9H; // Cbus Mux control + UCHAR IsFifoH; // non-zero if interface is 245 FIFO + UCHAR IsFifoTarH; // non-zero if interface is 245 FIFO CPU target + UCHAR IsFastSerH; // non-zero if interface is Fast serial + UCHAR IsFT1248H; // non-zero if interface is FT1248 + UCHAR FT1248CpolH; // FT1248 clock polarity - clock idle high (1) or clock idle low (0) + UCHAR FT1248LsbH; // FT1248 data is LSB (1) or MSB (0) + UCHAR FT1248FlowControlH; // FT1248 flow control enable + UCHAR IsVCPH; // non-zero if interface is to use VCP drivers + UCHAR PowerSaveEnableH; // non-zero if using ACBUS7 to save power for self-powered designs + + } FT_PROGRAM_DATA, *PFT_PROGRAM_DATA; + + FTD2XX_API + FT_STATUS WINAPI FT_EE_Program( + FT_HANDLE ftHandle, + PFT_PROGRAM_DATA pData + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EE_ProgramEx( + FT_HANDLE ftHandle, + PFT_PROGRAM_DATA pData, + char *Manufacturer, + char *ManufacturerId, + char *Description, + char *SerialNumber + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EE_Read( + FT_HANDLE ftHandle, + PFT_PROGRAM_DATA pData + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EE_ReadEx( + FT_HANDLE ftHandle, + PFT_PROGRAM_DATA pData, + char *Manufacturer, + char *ManufacturerId, + char *Description, + char *SerialNumber + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EE_UASize( + FT_HANDLE ftHandle, + LPDWORD lpdwSize + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EE_UAWrite( + FT_HANDLE ftHandle, + PUCHAR pucData, + DWORD dwDataLen + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EE_UARead( + FT_HANDLE ftHandle, + PUCHAR pucData, + DWORD dwDataLen, + LPDWORD lpdwBytesRead + ); + + + typedef struct ft_eeprom_header { + FT_DEVICE deviceType; // FTxxxx device type to be programmed + // Device descriptor options + WORD VendorId; // 0x0403 + WORD ProductId; // 0x6001 + UCHAR SerNumEnable; // non-zero if serial number to be used + // Config descriptor options + WORD MaxPower; // 0 < MaxPower <= 500 + UCHAR SelfPowered; // 0 = bus powered, 1 = self powered + UCHAR RemoteWakeup; // 0 = not capable, 1 = capable + // Hardware options + UCHAR PullDownEnable; // non-zero if pull down in suspend enabled + } FT_EEPROM_HEADER, *PFT_EEPROM_HEADER; + + + // FT232B EEPROM structure for use with FT_EEPROM_Read and FT_EEPROM_Program + typedef struct ft_eeprom_232b { + // Common header + FT_EEPROM_HEADER common; // common elements for all device EEPROMs + } FT_EEPROM_232B, *PFT_EEPROM_232B; + + + // FT2232 EEPROM structure for use with FT_EEPROM_Read and FT_EEPROM_Program + typedef struct ft_eeprom_2232 { + // Common header + FT_EEPROM_HEADER common; // common elements for all device EEPROMs + // Drive options + UCHAR AIsHighCurrent; // non-zero if interface is high current + UCHAR BIsHighCurrent; // non-zero if interface is high current + // Hardware options + UCHAR AIsFifo; // non-zero if interface is 245 FIFO + UCHAR AIsFifoTar; // non-zero if interface is 245 FIFO CPU target + UCHAR AIsFastSer; // non-zero if interface is Fast serial + UCHAR BIsFifo; // non-zero if interface is 245 FIFO + UCHAR BIsFifoTar; // non-zero if interface is 245 FIFO CPU target + UCHAR BIsFastSer; // non-zero if interface is Fast serial + // Driver option + UCHAR ADriverType; // + UCHAR BDriverType; // + } FT_EEPROM_2232, *PFT_EEPROM_2232; + + + // FT232R EEPROM structure for use with FT_EEPROM_Read and FT_EEPROM_Program + typedef struct ft_eeprom_232r { + // Common header + FT_EEPROM_HEADER common; // common elements for all device EEPROMs + // Drive options + UCHAR IsHighCurrent; // non-zero if interface is high current + // Hardware options + UCHAR UseExtOsc; // Use External Oscillator + UCHAR InvertTXD; // non-zero if invert TXD + UCHAR InvertRXD; // non-zero if invert RXD + UCHAR InvertRTS; // non-zero if invert RTS + UCHAR InvertCTS; // non-zero if invert CTS + UCHAR InvertDTR; // non-zero if invert DTR + UCHAR InvertDSR; // non-zero if invert DSR + UCHAR InvertDCD; // non-zero if invert DCD + UCHAR InvertRI; // non-zero if invert RI + UCHAR Cbus0; // Cbus Mux control + UCHAR Cbus1; // Cbus Mux control + UCHAR Cbus2; // Cbus Mux control + UCHAR Cbus3; // Cbus Mux control + UCHAR Cbus4; // Cbus Mux control + // Driver option + UCHAR DriverType; // + } FT_EEPROM_232R, *PFT_EEPROM_232R; + + + // FT2232H EEPROM structure for use with FT_EEPROM_Read and FT_EEPROM_Program + typedef struct ft_eeprom_2232h { + // Common header + FT_EEPROM_HEADER common; // common elements for all device EEPROMs + // Drive options + UCHAR ALSlowSlew; // non-zero if AL pins have slow slew + UCHAR ALSchmittInput; // non-zero if AL pins are Schmitt input + UCHAR ALDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR AHSlowSlew; // non-zero if AH pins have slow slew + UCHAR AHSchmittInput; // non-zero if AH pins are Schmitt input + UCHAR AHDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR BLSlowSlew; // non-zero if BL pins have slow slew + UCHAR BLSchmittInput; // non-zero if BL pins are Schmitt input + UCHAR BLDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR BHSlowSlew; // non-zero if BH pins have slow slew + UCHAR BHSchmittInput; // non-zero if BH pins are Schmitt input + UCHAR BHDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + // Hardware options + UCHAR AIsFifo; // non-zero if interface is 245 FIFO + UCHAR AIsFifoTar; // non-zero if interface is 245 FIFO CPU target + UCHAR AIsFastSer; // non-zero if interface is Fast serial + UCHAR BIsFifo; // non-zero if interface is 245 FIFO + UCHAR BIsFifoTar; // non-zero if interface is 245 FIFO CPU target + UCHAR BIsFastSer; // non-zero if interface is Fast serial + UCHAR PowerSaveEnable; // non-zero if using BCBUS7 to save power for self-powered designs + // Driver option + UCHAR ADriverType; // + UCHAR BDriverType; // + } FT_EEPROM_2232H, *PFT_EEPROM_2232H; + + + // FT4232H EEPROM structure for use with FT_EEPROM_Read and FT_EEPROM_Program + typedef struct ft_eeprom_4232h { + // Common header + FT_EEPROM_HEADER common; // common elements for all device EEPROMs + // Drive options + UCHAR ASlowSlew; // non-zero if A pins have slow slew + UCHAR ASchmittInput; // non-zero if A pins are Schmitt input + UCHAR ADriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR BSlowSlew; // non-zero if B pins have slow slew + UCHAR BSchmittInput; // non-zero if B pins are Schmitt input + UCHAR BDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR CSlowSlew; // non-zero if C pins have slow slew + UCHAR CSchmittInput; // non-zero if C pins are Schmitt input + UCHAR CDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR DSlowSlew; // non-zero if D pins have slow slew + UCHAR DSchmittInput; // non-zero if D pins are Schmitt input + UCHAR DDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + // Hardware options + UCHAR ARIIsTXDEN; // non-zero if port A uses RI as RS485 TXDEN + UCHAR BRIIsTXDEN; // non-zero if port B uses RI as RS485 TXDEN + UCHAR CRIIsTXDEN; // non-zero if port C uses RI as RS485 TXDEN + UCHAR DRIIsTXDEN; // non-zero if port D uses RI as RS485 TXDEN + // Driver option + UCHAR ADriverType; // + UCHAR BDriverType; // + UCHAR CDriverType; // + UCHAR DDriverType; // + } FT_EEPROM_4232H, *PFT_EEPROM_4232H; + + + // FT232H EEPROM structure for use with FT_EEPROM_Read and FT_EEPROM_Program + typedef struct ft_eeprom_232h { + // Common header + FT_EEPROM_HEADER common; // common elements for all device EEPROMs + // Drive options + UCHAR ACSlowSlew; // non-zero if AC bus pins have slow slew + UCHAR ACSchmittInput; // non-zero if AC bus pins are Schmitt input + UCHAR ACDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR ADSlowSlew; // non-zero if AD bus pins have slow slew + UCHAR ADSchmittInput; // non-zero if AD bus pins are Schmitt input + UCHAR ADDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + // CBUS options + UCHAR Cbus0; // Cbus Mux control + UCHAR Cbus1; // Cbus Mux control + UCHAR Cbus2; // Cbus Mux control + UCHAR Cbus3; // Cbus Mux control + UCHAR Cbus4; // Cbus Mux control + UCHAR Cbus5; // Cbus Mux control + UCHAR Cbus6; // Cbus Mux control + UCHAR Cbus7; // Cbus Mux control + UCHAR Cbus8; // Cbus Mux control + UCHAR Cbus9; // Cbus Mux control + // FT1248 options + UCHAR FT1248Cpol; // FT1248 clock polarity - clock idle high (1) or clock idle low (0) + UCHAR FT1248Lsb; // FT1248 data is LSB (1) or MSB (0) + UCHAR FT1248FlowControl; // FT1248 flow control enable + // Hardware options + UCHAR IsFifo; // non-zero if interface is 245 FIFO + UCHAR IsFifoTar; // non-zero if interface is 245 FIFO CPU target + UCHAR IsFastSer; // non-zero if interface is Fast serial + UCHAR IsFT1248 ; // non-zero if interface is FT1248 + UCHAR PowerSaveEnable; // + // Driver option + UCHAR DriverType; // + } FT_EEPROM_232H, *PFT_EEPROM_232H; + + + // FT X Series EEPROM structure for use with FT_EEPROM_Read and FT_EEPROM_Program + typedef struct ft_eeprom_x_series { + // Common header + FT_EEPROM_HEADER common; // common elements for all device EEPROMs + // Drive options + UCHAR ACSlowSlew; // non-zero if AC bus pins have slow slew + UCHAR ACSchmittInput; // non-zero if AC bus pins are Schmitt input + UCHAR ACDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + UCHAR ADSlowSlew; // non-zero if AD bus pins have slow slew + UCHAR ADSchmittInput; // non-zero if AD bus pins are Schmitt input + UCHAR ADDriveCurrent; // valid values are 4mA, 8mA, 12mA, 16mA + // CBUS options + UCHAR Cbus0; // Cbus Mux control + UCHAR Cbus1; // Cbus Mux control + UCHAR Cbus2; // Cbus Mux control + UCHAR Cbus3; // Cbus Mux control + UCHAR Cbus4; // Cbus Mux control + UCHAR Cbus5; // Cbus Mux control + UCHAR Cbus6; // Cbus Mux control + // UART signal options + UCHAR InvertTXD; // non-zero if invert TXD + UCHAR InvertRXD; // non-zero if invert RXD + UCHAR InvertRTS; // non-zero if invert RTS + UCHAR InvertCTS; // non-zero if invert CTS + UCHAR InvertDTR; // non-zero if invert DTR + UCHAR InvertDSR; // non-zero if invert DSR + UCHAR InvertDCD; // non-zero if invert DCD + UCHAR InvertRI; // non-zero if invert RI + // Battery Charge Detect options + UCHAR BCDEnable; // Enable Battery Charger Detection + UCHAR BCDForceCbusPWREN; // asserts the power enable signal on CBUS when charging port detected + UCHAR BCDDisableSleep; // forces the device never to go into sleep mode + // I2C options + WORD I2CSlaveAddress; // I2C slave device address + DWORD I2CDeviceId; // I2C device ID + UCHAR I2CDisableSchmitt; // Disable I2C Schmitt trigger + // FT1248 options + UCHAR FT1248Cpol; // FT1248 clock polarity - clock idle high (1) or clock idle low (0) + UCHAR FT1248Lsb; // FT1248 data is LSB (1) or MSB (0) + UCHAR FT1248FlowControl; // FT1248 flow control enable + // Hardware options + UCHAR RS485EchoSuppress; // + UCHAR PowerSaveEnable; // + // Driver option + UCHAR DriverType; // + } FT_EEPROM_X_SERIES, *PFT_EEPROM_X_SERIES; + + + FTD2XX_API + FT_STATUS WINAPI FT_EEPROM_Read( + FT_HANDLE ftHandle, + void *eepromData, + DWORD eepromDataSize, + char *Manufacturer, + char *ManufacturerId, + char *Description, + char *SerialNumber + ); + + + FTD2XX_API + FT_STATUS WINAPI FT_EEPROM_Program( + FT_HANDLE ftHandle, + void *eepromData, + DWORD eepromDataSize, + char *Manufacturer, + char *ManufacturerId, + char *Description, + char *SerialNumber + ); + + + FTD2XX_API + FT_STATUS WINAPI FT_SetLatencyTimer( + FT_HANDLE ftHandle, + UCHAR ucLatency + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetLatencyTimer( + FT_HANDLE ftHandle, + PUCHAR pucLatency + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetBitMode( + FT_HANDLE ftHandle, + UCHAR ucMask, + UCHAR ucEnable + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetBitMode( + FT_HANDLE ftHandle, + PUCHAR pucMode + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetUSBParameters( + FT_HANDLE ftHandle, + ULONG ulInTransferSize, + ULONG ulOutTransferSize + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetDeadmanTimeout( + FT_HANDLE ftHandle, + ULONG ulDeadmanTimeout + ); + +#ifndef _WIN32 + // Extra functions for non-Windows platforms to compensate + // for lack of .INF file to specify Vendor and Product IDs. + + FTD2XX_API + FT_STATUS FT_SetVIDPID( + DWORD dwVID, + DWORD dwPID + ); + + FTD2XX_API + FT_STATUS FT_GetVIDPID( + DWORD * pdwVID, + DWORD * pdwPID + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetDeviceLocId( + FT_HANDLE ftHandle, + LPDWORD lpdwLocId + ); +#endif // _WIN32 + + FTD2XX_API + FT_STATUS WINAPI FT_GetDeviceInfo( + FT_HANDLE ftHandle, + FT_DEVICE *lpftDevice, + LPDWORD lpdwID, + PCHAR SerialNumber, + PCHAR Description, + LPVOID Dummy + ); + + FTD2XX_API + FT_STATUS WINAPI FT_StopInTask( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_RestartInTask( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_SetResetPipeRetryCount( + FT_HANDLE ftHandle, + DWORD dwCount + ); + + FTD2XX_API + FT_STATUS WINAPI FT_ResetPort( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_CyclePort( + FT_HANDLE ftHandle + ); + + + // + // Win32-type functions + // + + FTD2XX_API + FT_HANDLE WINAPI FT_W32_CreateFile( + LPCTSTR lpszName, + DWORD dwAccess, + DWORD dwShareMode, + LPSECURITY_ATTRIBUTES lpSecurityAttributes, + DWORD dwCreate, + DWORD dwAttrsAndFlags, + HANDLE hTemplate + ); + + FTD2XX_API + BOOL WINAPI FT_W32_CloseHandle( + FT_HANDLE ftHandle + ); + + FTD2XX_API + BOOL WINAPI FT_W32_ReadFile( + FT_HANDLE ftHandle, + LPVOID lpBuffer, + DWORD nBufferSize, + LPDWORD lpBytesReturned, + LPOVERLAPPED lpOverlapped + ); + + FTD2XX_API + BOOL WINAPI FT_W32_WriteFile( + FT_HANDLE ftHandle, + LPVOID lpBuffer, + DWORD nBufferSize, + LPDWORD lpBytesWritten, + LPOVERLAPPED lpOverlapped + ); + + FTD2XX_API + DWORD WINAPI FT_W32_GetLastError( + FT_HANDLE ftHandle + ); + + FTD2XX_API + BOOL WINAPI FT_W32_GetOverlappedResult( + FT_HANDLE ftHandle, + LPOVERLAPPED lpOverlapped, + LPDWORD lpdwBytesTransferred, + BOOL bWait + ); + + FTD2XX_API + BOOL WINAPI FT_W32_CancelIo( + FT_HANDLE ftHandle + ); + + + // + // Win32 COMM API type functions + // + typedef struct _FTCOMSTAT { + DWORD fCtsHold : 1; + DWORD fDsrHold : 1; + DWORD fRlsdHold : 1; + DWORD fXoffHold : 1; + DWORD fXoffSent : 1; + DWORD fEof : 1; + DWORD fTxim : 1; + DWORD fReserved : 25; + DWORD cbInQue; + DWORD cbOutQue; + } FTCOMSTAT, *LPFTCOMSTAT; + + typedef struct _FTDCB { + DWORD DCBlength; /* sizeof(FTDCB) */ + DWORD BaudRate; /* Baudrate at which running */ + DWORD fBinary: 1; /* Binary Mode (skip EOF check) */ + DWORD fParity: 1; /* Enable parity checking */ + DWORD fOutxCtsFlow:1; /* CTS handshaking on output */ + DWORD fOutxDsrFlow:1; /* DSR handshaking on output */ + DWORD fDtrControl:2; /* DTR Flow control */ + DWORD fDsrSensitivity:1; /* DSR Sensitivity */ + DWORD fTXContinueOnXoff: 1; /* Continue TX when Xoff sent */ + DWORD fOutX: 1; /* Enable output X-ON/X-OFF */ + DWORD fInX: 1; /* Enable input X-ON/X-OFF */ + DWORD fErrorChar: 1; /* Enable Err Replacement */ + DWORD fNull: 1; /* Enable Null stripping */ + DWORD fRtsControl:2; /* Rts Flow control */ + DWORD fAbortOnError:1; /* Abort all reads and writes on Error */ + DWORD fDummy2:17; /* Reserved */ + WORD wReserved; /* Not currently used */ + WORD XonLim; /* Transmit X-ON threshold */ + WORD XoffLim; /* Transmit X-OFF threshold */ + BYTE ByteSize; /* Number of bits/byte, 4-8 */ + BYTE Parity; /* 0-4=None,Odd,Even,Mark,Space */ + BYTE StopBits; /* FT_STOP_BITS_1 or FT_STOP_BITS_2 */ + char XonChar; /* Tx and Rx X-ON character */ + char XoffChar; /* Tx and Rx X-OFF character */ + char ErrorChar; /* Error replacement char */ + char EofChar; /* End of Input character */ + char EvtChar; /* Received Event character */ + WORD wReserved1; /* Fill for now. */ + } FTDCB, *LPFTDCB; + + typedef struct _FTTIMEOUTS { + DWORD ReadIntervalTimeout; /* Maximum time between read chars. */ + DWORD ReadTotalTimeoutMultiplier; /* Multiplier of characters. */ + DWORD ReadTotalTimeoutConstant; /* Constant in milliseconds. */ + DWORD WriteTotalTimeoutMultiplier; /* Multiplier of characters. */ + DWORD WriteTotalTimeoutConstant; /* Constant in milliseconds. */ + } FTTIMEOUTS,*LPFTTIMEOUTS; + + + FTD2XX_API + BOOL WINAPI FT_W32_ClearCommBreak( + FT_HANDLE ftHandle + ); + + FTD2XX_API + BOOL WINAPI FT_W32_ClearCommError( + FT_HANDLE ftHandle, + LPDWORD lpdwErrors, + LPFTCOMSTAT lpftComstat + ); + + FTD2XX_API + BOOL WINAPI FT_W32_EscapeCommFunction( + FT_HANDLE ftHandle, + DWORD dwFunc + ); + + FTD2XX_API + BOOL WINAPI FT_W32_GetCommModemStatus( + FT_HANDLE ftHandle, + LPDWORD lpdwModemStatus + ); + + FTD2XX_API + BOOL WINAPI FT_W32_GetCommState( + FT_HANDLE ftHandle, + LPFTDCB lpftDcb + ); + + FTD2XX_API + BOOL WINAPI FT_W32_GetCommTimeouts( + FT_HANDLE ftHandle, + FTTIMEOUTS *pTimeouts + ); + + FTD2XX_API + BOOL WINAPI FT_W32_PurgeComm( + FT_HANDLE ftHandle, + DWORD dwMask + ); + + FTD2XX_API + BOOL WINAPI FT_W32_SetCommBreak( + FT_HANDLE ftHandle + ); + + FTD2XX_API + BOOL WINAPI FT_W32_SetCommMask( + FT_HANDLE ftHandle, + ULONG ulEventMask + ); + + FTD2XX_API + BOOL WINAPI FT_W32_GetCommMask( + FT_HANDLE ftHandle, + LPDWORD lpdwEventMask + ); + + FTD2XX_API + BOOL WINAPI FT_W32_SetCommState( + FT_HANDLE ftHandle, + LPFTDCB lpftDcb + ); + + FTD2XX_API + BOOL WINAPI FT_W32_SetCommTimeouts( + FT_HANDLE ftHandle, + FTTIMEOUTS *pTimeouts + ); + + FTD2XX_API + BOOL WINAPI FT_W32_SetupComm( + FT_HANDLE ftHandle, + DWORD dwReadBufferSize, + DWORD dwWriteBufferSize + ); + + FTD2XX_API + BOOL WINAPI FT_W32_WaitCommEvent( + FT_HANDLE ftHandle, + PULONG pulEvent, + LPOVERLAPPED lpOverlapped + ); + + + // + // Device information + // + + typedef struct _ft_device_list_info_node { + ULONG Flags; + ULONG Type; + ULONG ID; + DWORD LocId; + char SerialNumber[16]; + char Description[64]; + FT_HANDLE ftHandle; + } FT_DEVICE_LIST_INFO_NODE; + + // Device information flags + enum { + FT_FLAGS_OPENED = 1, + FT_FLAGS_HISPEED = 2 + }; + + + FTD2XX_API + FT_STATUS WINAPI FT_CreateDeviceInfoList( + LPDWORD lpdwNumDevs + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetDeviceInfoList( + FT_DEVICE_LIST_INFO_NODE *pDest, + LPDWORD lpdwNumDevs + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetDeviceInfoDetail( + DWORD dwIndex, + LPDWORD lpdwFlags, + LPDWORD lpdwType, + LPDWORD lpdwID, + LPDWORD lpdwLocId, + LPVOID lpSerialNumber, + LPVOID lpDescription, + FT_HANDLE *pftHandle + ); + + + // + // Version information + // + + FTD2XX_API + FT_STATUS WINAPI FT_GetDriverVersion( + FT_HANDLE ftHandle, + LPDWORD lpdwVersion + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetLibraryVersion( + LPDWORD lpdwVersion + ); + + + FTD2XX_API + FT_STATUS WINAPI FT_Rescan( + void + ); + + FTD2XX_API + FT_STATUS WINAPI FT_Reload( + WORD wVid, + WORD wPid + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetComPortNumber( + FT_HANDLE ftHandle, + LPLONG lpdwComPortNumber + ); + + + // + // FT232H additional EEPROM functions + // + + FTD2XX_API + FT_STATUS WINAPI FT_EE_ReadConfig( + FT_HANDLE ftHandle, + UCHAR ucAddress, + PUCHAR pucValue + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EE_WriteConfig( + FT_HANDLE ftHandle, + UCHAR ucAddress, + UCHAR ucValue + ); + + FTD2XX_API + FT_STATUS WINAPI FT_EE_ReadECC( + FT_HANDLE ftHandle, + UCHAR ucOption, + LPWORD lpwValue + ); + + FTD2XX_API + FT_STATUS WINAPI FT_GetQueueStatusEx( + FT_HANDLE ftHandle, + DWORD *dwRxBytes + ); + + FTD2XX_API + FT_STATUS WINAPI FT_ComPortIdle( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_ComPortCancelIdle( + FT_HANDLE ftHandle + ); + + FTD2XX_API + FT_STATUS WINAPI FT_VendorCmdGet( + FT_HANDLE ftHandle, + UCHAR Request, + UCHAR *Buf, + USHORT Len + ); + + FTD2XX_API + FT_STATUS WINAPI FT_VendorCmdSet( + FT_HANDLE ftHandle, + UCHAR Request, + UCHAR *Buf, + USHORT Len + ); + + FTD2XX_API + FT_STATUS WINAPI FT_VendorCmdGetEx( + FT_HANDLE ftHandle, + USHORT wValue, + UCHAR *Buf, + USHORT Len + ); + + FTD2XX_API + FT_STATUS WINAPI FT_VendorCmdSetEx( + FT_HANDLE ftHandle, + USHORT wValue, + UCHAR *Buf, + USHORT Len + ); + +#ifdef __cplusplus +} +#endif + + +#endif /* FTD2XX_H */ + diff --git a/imbe/aux_sub.cc b/imbe/aux_sub.cc new file mode 100644 index 0000000..b5bfec9 --- /dev/null +++ b/imbe/aux_sub.cc @@ -0,0 +1,184 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ +#include "typedef.h" +#include "basic_op.h" +#include "imbe.h" +#include "aux_sub.h" +#include "tbls.h" + +//----------------------------------------------------------------------------- +// PURPOSE: +// Return pointer to bit allocation array +// according to the number of harmonics +// +// INPUT: +// num_harms - The number of harmonics +// +// OUTPUT: +// None +// +// RETURN: +// Pointer to bits allocation array +// +//----------------------------------------------------------------------------- +const UWord16 *get_bit_allocation_arr(Word16 num_harms) +{ + UWord16 offset_in_word; + Word16 index; + + if(num_harms == NUM_HARMS_MIN) + return &bit_allocation_tbl[0]; + else + { + index = num_harms - NUM_HARMS_MIN - 1; + offset_in_word = bit_allocation_offset_tbl[index >> 2] + ((3 + (index >> 2)) * (index & 0x3)); + return &bit_allocation_tbl[offset_in_word]; + } +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Unpack bit allocation table's item +// +// INPUT: +// num_harms - The number of harmonics +// ptr - Pointer to buffer to place bit allocation data +// +// OUTPUT: +// Unpacked bit allocation table +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void get_bit_allocation(Word16 num_harms, Word16 *ptr) +{ + const UWord16 *bat_ptr; + UWord16 tmp; + Word16 i; + + bat_ptr = get_bit_allocation_arr(num_harms); + + for(i = 0; i < num_harms - 1; i += 4) + { + tmp = *bat_ptr++; + ptr[3] = tmp & 0xF; tmp >>= 4; + ptr[2] = tmp & 0xF; tmp >>= 4; + ptr[1] = tmp & 0xF; tmp >>= 4; + ptr[0] = tmp & 0xF; + ptr += 4; + } +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Set the elements of a 16 bit input vector to zero. +// +// INPUT: +// vec - Pointer to vector +// n - size of vec +// +// OUTPUT: +// None +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void v_zap(Word16 *vec, Word16 n) +{ + while(n--) + *vec++ = 0; +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Copy the contents of one 16 bit input vector to another +// +// INPUT: +// vec1 - Pointer to the destination vector +// vec2 - Pointer to the source vector +// n - size of data should be copied +// +// OUTPUT: +// Copy of the source vector +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void v_equ(Word16 *vec1, Word16 *vec2, Word16 n) +{ + while(n--) + *vec1++ = *vec2++; +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Compute the sum of square magnitude of a 16 bit input vector +// with saturation and truncation. Output is a 32 bit number. +// +// INPUT: +// vec - Pointer to the vector +// n - size of input vectors +// +// OUTPUT: +// none +// +// RETURN: +// 32 bit long signed integer result +// +//----------------------------------------------------------------------------- +Word32 L_v_magsq(Word16 *vec, Word16 n) +{ + Word32 L_magsq = 0; + + while(n--) + { + L_magsq = L_mac(L_magsq, *vec, *vec); + vec++; + } + return L_magsq; +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Copy the contents of one 16 bit input vector to another with shift +// +// INPUT: +// vec1 - Pointer to the destination vector +// vec2 - Pointer to the source vector +// scale - right shift factor +// n - size of data should be copied +// +// OUTPUT: +// Copy of the source vector +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void v_equ_shr(Word16 *vec1, Word16 *vec2, Word16 scale, Word16 n) +{ + while(n--) + *vec1++ = shr(*vec2++,scale); +} + diff --git a/imbe/aux_sub.h b/imbe/aux_sub.h new file mode 100644 index 0000000..ada0cd2 --- /dev/null +++ b/imbe/aux_sub.h @@ -0,0 +1,133 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _AUX_SUB +#define _AUX_SUB + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Return pointer to bit allocation array +// according to the number of harmonics +// +// INPUT: +// num_harms - The number of harmonics +// +// OUTPUT: +// None +// +// RETURN: +// Pointer to bits allocation array +// +//----------------------------------------------------------------------------- +const UWord16 *get_bit_allocation_arr(Word16 num_harms); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Unpack bit allocation table's item +// +// INPUT: +// num_harms - The number of harmonics +// ptr - Pointer to buffer to place bit allocation data +// +// OUTPUT: +// Unpacked bit allocation table +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void get_bit_allocation(Word16 num_harms, Word16 *ptr); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Set the elements of a 16 bit input vector to zero. +// +// INPUT: +// vec - Pointer to vector +// n - size of vec +// +// OUTPUT: +// None +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void v_zap(Word16 *vec, Word16 n); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Copy the contents of one 16 bit input vector to another +// +// INPUT: +// vec1 - Pointer to the destination vector +// vec2 - Pointer to the source vector +// n - size of data should be copied +// +// OUTPUT: +// Copy of the source vector +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void v_equ(Word16 *vec1, Word16 *vec2, Word16 n); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Compute the sum of square magnitude of a 16 bit input vector +// with saturation and truncation. Output is a 32 bit number. +// +// INPUT: +// vec - Pointer to the vector +// n - size of input vectors +// +// OUTPUT: +// none +// +// RETURN: +// 32 bit long signed integer result +// +//----------------------------------------------------------------------------- +Word32 L_v_magsq(Word16 *vec, Word16 n); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Copy the contents of one 16 bit input vector to another with shift +// +// INPUT: +// vec1 - Pointer to the destination vector +// vec2 - Pointer to the source vector +// scale - right shift factor +// n - size of data should be copied +// +// OUTPUT: +// Copy of the source vector +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void v_equ_shr(Word16 *vec1, Word16 *vec2, Word16 scale, Word16 n); + +#endif diff --git a/imbe/basic_op.h b/imbe/basic_op.h new file mode 100644 index 0000000..9132ba1 --- /dev/null +++ b/imbe/basic_op.h @@ -0,0 +1,85 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ +/*___________________________________________________________________________ + | | + | Constants and Globals | + | | + | $Id $ + |___________________________________________________________________________| +*/ +extern Flag Overflow; +extern Flag Carry; + +#define MAX_32 (Word32)0x7fffffffL +#define MIN_32 (Word32)0x80000000L + +#define MAX_16 (Word16)0x7fff +#define MIN_16 (Word16)0x8000 + +/*___________________________________________________________________________ + | | + | Prototypes for basic arithmetic operators | + |___________________________________________________________________________| +*/ + +Word16 add (Word16 var1, Word16 var2); /* Short add, 1 */ +Word16 sub (Word16 var1, Word16 var2); /* Short sub, 1 */ +Word16 abs_s (Word16 var1); /* Short abs, 1 */ +Word16 shl (Word16 var1, Word16 var2); /* Short shift left, 1 */ +Word16 shr (Word16 var1, Word16 var2); /* Short shift right, 1 */ +Word16 mult (Word16 var1, Word16 var2); /* Short mult, 1 */ +Word32 L_mult (Word16 var1, Word16 var2); /* Long mult, 1 */ +Word16 negate (Word16 var1); /* Short negate, 1 */ +Word16 extract_h (Word32 L_var1); /* Extract high, 1 */ +Word16 extract_l (Word32 L_var1); /* Extract low, 1 */ +Word16 round (Word32 L_var1); /* Round, 1 */ +Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2); /* Mac, 1 */ +Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2); /* Msu, 1 */ +Word32 L_macNs (Word32 L_var3, Word16 var1, Word16 var2); /* Mac without + sat, 1 */ +Word32 L_msuNs (Word32 L_var3, Word16 var1, Word16 var2); /* Msu without + sat, 1 */ +Word32 L_add (Word32 L_var1, Word32 L_var2); /* Long add, 2 */ +Word32 L_sub (Word32 L_var1, Word32 L_var2); /* Long sub, 2 */ +Word32 L_add_c (Word32 L_var1, Word32 L_var2); /* Long add with c, 2 */ +Word32 L_sub_c (Word32 L_var1, Word32 L_var2); /* Long sub with c, 2 */ +Word32 L_negate (Word32 L_var1); /* Long negate, 2 */ +Word16 mult_r (Word16 var1, Word16 var2); /* Mult with round, 2 */ +Word32 L_shl (Word32 L_var1, Word16 var2); /* Long shift left, 2 */ +Word32 L_shr (Word32 L_var1, Word16 var2); /* Long shift right, 2*/ +Word16 shr_r (Word16 var1, Word16 var2); /* Shift right with + round, 2 */ +Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2); /* Mac with + rounding,2 */ +Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2); /* Msu with + rounding,2 */ +Word32 L_deposit_h (Word16 var1); /* 16 bit var1 -> MSB, 2 */ +Word32 L_deposit_l (Word16 var1); /* 16 bit var1 -> LSB, 2 */ + +Word32 L_shr_r (Word32 L_var1, Word16 var2); /* Long shift right with + round, 3 */ +Word32 L_abs (Word32 L_var1); /* Long abs, 3 */ +Word32 L_sat (Word32 L_var1); /* Long saturation, 4 */ +Word16 norm_s (Word16 var1); /* Short norm, 15 */ +Word16 div_s (Word16 var1, Word16 var2); /* Short division, 18 */ +Word16 norm_l (Word32 L_var1); /* Long norm, 30 */ + + diff --git a/imbe/basicop2.cc b/imbe/basicop2.cc new file mode 100644 index 0000000..25a795e --- /dev/null +++ b/imbe/basicop2.cc @@ -0,0 +1,2157 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ +/*___________________________________________________________________________ + | | + | Basic arithmetic operators. | + | | + | $Id $ + |___________________________________________________________________________| +*/ + +/*___________________________________________________________________________ + | | + | Include-Files | + |___________________________________________________________________________| +*/ + +#include +#include +#include "typedef.h" +#include "basic_op.h" + +#if (WMOPS) +#include "count.h" +extern BASIC_OP multiCounter[MAXCOUNTERS]; +extern int currCounter; + +#endif + +/*___________________________________________________________________________ + | | + | Local Functions | + |___________________________________________________________________________| +*/ +Word16 saturate (Word32 L_var1); + +/*___________________________________________________________________________ + | | + | Constants and Globals | + |___________________________________________________________________________| +*/ +Flag Overflow = 0; +Flag Carry = 0; + +/*___________________________________________________________________________ + | | + | Functions | + |___________________________________________________________________________| +*/ + +/*___________________________________________________________________________ + | | + | Function Name : saturate | + | | + | Purpose : | + | | + | Limit the 32 bit input to the range of a 16 bit word. | + | | + | Inputs : | + | | + | L_var1 | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var1 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 +saturate (Word32 L_var1) +{ + Word16 var_out; + + if (L_var1 > 0X00007fffL) + { + Overflow = 1; + var_out = MAX_16; + } + else if (L_var1 < (Word32) 0xffff8000L) + { + Overflow = 1; + var_out = MIN_16; + } + else + { + var_out = extract_l (L_var1); +#if (WMOPS) + multiCounter[currCounter].extract_l--; +#endif + } + + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : add | + | | + | Purpose : | + | | + | Performs the addition (var1+var2) with overflow control and saturation;| + | the 16 bit result is set at +32767 when overflow occurs or at -32768 | + | when underflow occurs. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 add (Word16 var1, Word16 var2) +{ + Word16 var_out; + Word32 L_sum; + + L_sum = (Word32) var1 + var2; + var_out = saturate (L_sum); +#if (WMOPS) + multiCounter[currCounter].add++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : sub | + | | + | Purpose : | + | | + | Performs the subtraction (var1+var2) with overflow control and satu- | + | ration; the 16 bit result is set at +32767 when overflow occurs or at | + | -32768 when underflow occurs. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 sub (Word16 var1, Word16 var2) +{ + Word16 var_out; + Word32 L_diff; + + L_diff = (Word32) var1 - var2; + var_out = saturate (L_diff); +#if (WMOPS) + multiCounter[currCounter].sub++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : abs_s | + | | + | Purpose : | + | | + | Absolute value of var1; abs_s(-32768) = 32767. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0x0000 0000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 abs_s (Word16 var1) +{ + Word16 var_out; + + if (var1 == (Word16) 0X8000) + { + var_out = MAX_16; + } + else + { + if (var1 < 0) + { + var_out = -var1; + } + else + { + var_out = var1; + } + } +#if (WMOPS) + multiCounter[currCounter].abs_s++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : shl | + | | + | Purpose : | + | | + | Arithmetically shift the 16 bit input var1 left var2 positions.Zero fill| + | the var2 LSB of the result. If var2 is negative, arithmetically shift | + | var1 right by -var2 with sign extension. Saturate the result in case of | + | underflows or overflows. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 shl (Word16 var1, Word16 var2) +{ + Word16 var_out; + Word32 result; + + if (var2 < 0) + { + if (var2 < -16) + var2 = -16; + var_out = shr (var1, -var2); +#if (WMOPS) + multiCounter[currCounter].shr--; +#endif + } + else + { + result = (Word32) var1 *((Word32) 1 << var2); + + if ((var2 > 15 && var1 != 0) || (result != (Word32) ((Word16) result))) + { + Overflow = 1; + var_out = (var1 > 0) ? MAX_16 : MIN_16; + } + else + { + var_out = extract_l (result); +#if (WMOPS) + multiCounter[currCounter].extract_l--; +#endif + } + } +#if (WMOPS) + multiCounter[currCounter].shl++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : shr | + | | + | Purpose : | + | | + | Arithmetically shift the 16 bit input var1 right var2 positions with | + | sign extension. If var2 is negative, arithmetically shift var1 left by | + | -var2 with sign extension. Saturate the result in case of underflows or | + | overflows. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 shr (Word16 var1, Word16 var2) +{ + Word16 var_out; + + if (var2 < 0) + { + if (var2 < -16) + var2 = -16; + var_out = shl (var1, -var2); +#if (WMOPS) + multiCounter[currCounter].shl--; +#endif + } + else + { + if (var2 >= 15) + { + var_out = (var1 < 0) ? -1 : 0; + } + else + { + if (var1 < 0) + { + var_out = ~((~var1) >> var2); + } + else + { + var_out = var1 >> var2; + } + } + } + +#if (WMOPS) + multiCounter[currCounter].shr++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : mult | + | | + | Purpose : | + | | + | Performs the multiplication of var1 by var2 and gives a 16 bit result | + | which is scaled i.e.: | + | mult(var1,var2) = extract_l(L_shr((var1 times var2),15)) and | + | mult(-32768,-32768) = 32767. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 mult (Word16 var1, Word16 var2) +{ + Word16 var_out; + Word32 L_product; + + L_product = (Word32) var1 *(Word32) var2; + + L_product = (L_product & (Word32) 0xffff8000L) >> 15; + + if (L_product & (Word32) 0x00010000L) + L_product = L_product | (Word32) 0xffff0000L; + + var_out = saturate (L_product); +#if (WMOPS) + multiCounter[currCounter].mult++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_mult | + | | + | Purpose : | + | | + | L_mult is the 32 bit result of the multiplication of var1 times var2 | + | with one shift left i.e.: | + | L_mult(var1,var2) = L_shl((var1 times var2),1) and | + | L_mult(-32768,-32768) = 2147483647. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_mult (Word16 var1, Word16 var2) +{ + Word32 L_var_out; + + L_var_out = (Word32) var1 *(Word32) var2; + + if (L_var_out != (Word32) 0x40000000L) + { + L_var_out *= 2; + } + else + { + Overflow = 1; + L_var_out = MAX_32; + } + +#if (WMOPS) + multiCounter[currCounter].L_mult++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : negate | + | | + | Purpose : | + | | + | Negate var1 with saturation, saturate in the case where input is -32768:| + | negate(var1) = sub(0,var1). | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 negate (Word16 var1) +{ + Word16 var_out; + + var_out = (var1 == MIN_16) ? MAX_16 : -var1; +#if (WMOPS) + multiCounter[currCounter].negate++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : extract_h | + | | + | Purpose : | + | | + | Return the 16 MSB of L_var1. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | L_var1 | + | 32 bit long signed integer (Word32 ) whose value falls in the | + | range : 0x8000 0000 <= L_var1 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 extract_h (Word32 L_var1) +{ + Word16 var_out; + + var_out = (Word16) (L_var1 >> 16); +#if (WMOPS) + multiCounter[currCounter].extract_h++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : extract_l | + | | + | Purpose : | + | | + | Return the 16 LSB of L_var1. | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | L_var1 | + | 32 bit long signed integer (Word32 ) whose value falls in the | + | range : 0x8000 0000 <= L_var1 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 extract_l (Word32 L_var1) +{ + Word16 var_out; + + var_out = (Word16) L_var1; +#if (WMOPS) + multiCounter[currCounter].extract_l++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : round | + | | + | Purpose : | + | | + | Round the lower 16 bits of the 32 bit input number into the MS 16 bits | + | with saturation. Shift the resulting bits right by 16 and return the 16 | + | bit number: | + | round(L_var1) = extract_h(L_add(L_var1,32768)) | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | L_var1 | + | 32 bit long signed integer (Word32 ) whose value falls in the | + | range : 0x8000 0000 <= L_var1 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 round (Word32 L_var1) +{ + Word16 var_out; + Word32 L_rounded; + + L_rounded = L_add (L_var1, (Word32) 0x00008000L); +#if (WMOPS) + multiCounter[currCounter].L_add--; +#endif + var_out = extract_h (L_rounded); +#if (WMOPS) + multiCounter[currCounter].extract_h--; + multiCounter[currCounter].round++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_mac | + | | + | Purpose : | + | | + | Multiply var1 by var2 and shift the result left by 1. Add the 32 bit | + | result to L_var3 with saturation, return a 32 bit result: | + | L_mac(L_var3,var1,var2) = L_add(L_var3,L_mult(var1,var2)). | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | L_var3 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_mac (Word32 L_var3, Word16 var1, Word16 var2) +{ + Word32 L_var_out; + Word32 L_product; + + L_product = L_mult (var1, var2); +#if (WMOPS) + multiCounter[currCounter].L_mult--; +#endif + L_var_out = L_add (L_var3, L_product); +#if (WMOPS) + multiCounter[currCounter].L_add--; + multiCounter[currCounter].L_mac++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_msu | + | | + | Purpose : | + | | + | Multiply var1 by var2 and shift the result left by 1. Subtract the 32 | + | bit result to L_var3 with saturation, return a 32 bit result: | + | L_msu(L_var3,var1,var2) = L_sub(L_var3,L_mult(var1,var2)). | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | L_var3 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_msu (Word32 L_var3, Word16 var1, Word16 var2) +{ + Word32 L_var_out; + Word32 L_product; + + L_product = L_mult (var1, var2); +#if (WMOPS) + multiCounter[currCounter].L_mult--; +#endif + L_var_out = L_sub (L_var3, L_product); +#if (WMOPS) + multiCounter[currCounter].L_sub--; + multiCounter[currCounter].L_msu++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_macNs | + | | + | Purpose : | + | | + | Multiply var1 by var2 and shift the result left by 1. Add the 32 bit | + | result to L_var3 without saturation, return a 32 bit result. Generate | + | carry and overflow values : | + | L_macNs(L_var3,var1,var2) = L_add_c(L_var3,L_mult(var1,var2)). | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | L_var3 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + | | + | Caution : | + | | + | In some cases the Carry flag has to be cleared or set before using | + | operators which take into account its value. | + |___________________________________________________________________________| +*/ + +Word32 L_macNs (Word32 L_var3, Word16 var1, Word16 var2) +{ + Word32 L_var_out; + + L_var_out = L_mult (var1, var2); +#if (WMOPS) + multiCounter[currCounter].L_mult--; +#endif + L_var_out = L_add_c (L_var3, L_var_out); +#if (WMOPS) + multiCounter[currCounter].L_add_c--; + multiCounter[currCounter].L_macNs++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_msuNs | + | | + | Purpose : | + | | + | Multiply var1 by var2 and shift the result left by 1. Subtract the 32 | + | bit result from L_var3 without saturation, return a 32 bit result. Ge- | + | nerate carry and overflow values : | + | L_msuNs(L_var3,var1,var2) = L_sub_c(L_var3,L_mult(var1,var2)). | + | | + | Complexity weight : 1 | + | | + | Inputs : | + | | + | L_var3 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + | | + | Caution : | + | | + | In some cases the Carry flag has to be cleared or set before using | + | operators which take into account its value. | + |___________________________________________________________________________| +*/ + +Word32 L_msuNs (Word32 L_var3, Word16 var1, Word16 var2) +{ + Word32 L_var_out; + + L_var_out = L_mult (var1, var2); +#if (WMOPS) + multiCounter[currCounter].L_mult--; +#endif + L_var_out = L_sub_c (L_var3, L_var_out); +#if (WMOPS) + multiCounter[currCounter].L_sub_c--; + multiCounter[currCounter].L_msuNs++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_add | + | | + | Purpose : | + | | + | 32 bits addition of the two 32 bits variables (L_var1+L_var2) with | + | overflow control and saturation; the result is set at +2147483647 when | + | overflow occurs or at -2147483648 when underflow occurs. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var1 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | L_var2 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_add (Word32 L_var1, Word32 L_var2) +{ + Word32 L_var_out; + + L_var_out = L_var1 + L_var2; + + if (((L_var1 ^ L_var2) & MIN_32) == 0) + { + if ((L_var_out ^ L_var1) & MIN_32) + { + L_var_out = (L_var1 < 0) ? MIN_32 : MAX_32; + Overflow = 1; + } + } +#if (WMOPS) + multiCounter[currCounter].L_add++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_sub | + | | + | Purpose : | + | | + | 32 bits subtraction of the two 32 bits variables (L_var1-L_var2) with | + | overflow control and saturation; the result is set at +2147483647 when | + | overflow occurs or at -2147483648 when underflow occurs. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var1 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | L_var2 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_sub (Word32 L_var1, Word32 L_var2) +{ + Word32 L_var_out; + + L_var_out = L_var1 - L_var2; + + if (((L_var1 ^ L_var2) & MIN_32) != 0) + { + if ((L_var_out ^ L_var1) & MIN_32) + { + L_var_out = (L_var1 < 0L) ? MIN_32 : MAX_32; + Overflow = 1; + } + } +#if (WMOPS) + multiCounter[currCounter].L_sub++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_add_c | + | | + | Purpose : | + | | + | Performs 32 bits addition of the two 32 bits variables (L_var1+L_var2+C)| + | with carry. No saturation. Generate carry and Overflow values. The car- | + | ry and overflow values are binary variables which can be tested and as- | + | signed values. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var1 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | L_var2 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + | | + | Caution : | + | | + | In some cases the Carry flag has to be cleared or set before using | + | operators which take into account its value. | + |___________________________________________________________________________| +*/ +Word32 L_add_c (Word32 L_var1, Word32 L_var2) +{ + Word32 L_var_out; + Word32 L_test; + Flag carry_int = 0; + + L_var_out = L_var1 + L_var2 + Carry; + + L_test = L_var1 + L_var2; + + if ((L_var1 > 0) && (L_var2 > 0) && (L_test < 0)) + { + Overflow = 1; + carry_int = 0; + } + else + { + if ((L_var1 < 0) && (L_var2 < 0)) + { + if (L_test >= 0) + { + Overflow = 1; + carry_int = 1; + } + else + { + Overflow = 0; + carry_int = 1; + } + } + else + { + if (((L_var1 ^ L_var2) < 0) && (L_test >= 0)) + { + Overflow = 0; + carry_int = 1; + } + else + { + Overflow = 0; + carry_int = 0; + } + } + } + + if (Carry) + { + if (L_test == MAX_32) + { + Overflow = 1; + Carry = carry_int; + } + else + { + if (L_test == (Word32) 0xFFFFFFFFL) + { + Carry = 1; + } + else + { + Carry = carry_int; + } + } + } + else + { + Carry = carry_int; + } + +#if (WMOPS) + multiCounter[currCounter].L_add_c++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_sub_c | + | | + | Purpose : | + | | + | Performs 32 bits subtraction of the two 32 bits variables with carry | + | (borrow) : L_var1-L_var2-C. No saturation. Generate carry and Overflow | + | values. The carry and overflow values are binary variables which can | + | be tested and assigned values. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var1 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | L_var2 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + | | + | Caution : | + | | + | In some cases the Carry flag has to be cleared or set before using | + | operators which take into account its value. | + |___________________________________________________________________________| +*/ + +Word32 L_sub_c (Word32 L_var1, Word32 L_var2) +{ + Word32 L_var_out; + Word32 L_test; + Flag carry_int = 0; + + if (Carry) + { + Carry = 0; + if (L_var2 != MIN_32) + { + L_var_out = L_add_c (L_var1, -L_var2); +#if (WMOPS) + multiCounter[currCounter].L_add_c--; +#endif + } + else + { + L_var_out = L_var1 - L_var2; + if (L_var1 > 0L) + { + Overflow = 1; + Carry = 0; + } + } + } + else + { + L_var_out = L_var1 - L_var2 - (Word32) 0X00000001L; + L_test = L_var1 - L_var2; + + if ((L_test < 0) && (L_var1 > 0) && (L_var2 < 0)) + { + Overflow = 1; + carry_int = 0; + } + else if ((L_test > 0) && (L_var1 < 0) && (L_var2 > 0)) + { + Overflow = 1; + carry_int = 1; + } + else if ((L_test > 0) && ((L_var1 ^ L_var2) > 0)) + { + Overflow = 0; + carry_int = 1; + } + if (L_test == MIN_32) + { + Overflow = 1; + Carry = carry_int; + } + else + { + Carry = carry_int; + } + } + +#if (WMOPS) + multiCounter[currCounter].L_sub_c++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_negate | + | | + | Purpose : | + | | + | Negate the 32 bit variable L_var1 with saturation; saturate in the case | + | where input is -2147483648 (0x8000 0000). | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var1 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_negate (Word32 L_var1) +{ + Word32 L_var_out; + + L_var_out = (L_var1 == MIN_32) ? MAX_32 : -L_var1; +#if (WMOPS) + multiCounter[currCounter].L_negate++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : mult_r | + | | + | Purpose : | + | | + | Same as mult with rounding, i.e.: | + | mult_r(var1,var2) = extract_l(L_shr(((var1 * var2) + 16384),15)) and | + | mult_r(-32768,-32768) = 32767. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 mult_r (Word16 var1, Word16 var2) +{ + Word16 var_out; + Word32 L_product_arr; + + L_product_arr = (Word32) var1 *(Word32) var2; /* product */ + L_product_arr += (Word32) 0x00004000L; /* round */ + L_product_arr &= (Word32) 0xffff8000L; + L_product_arr >>= 15; /* shift */ + + if (L_product_arr & (Word32) 0x00010000L) /* sign extend when necessary */ + { + L_product_arr |= (Word32) 0xffff0000L; + } + var_out = saturate (L_product_arr); +#if (WMOPS) + multiCounter[currCounter].mult_r++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_shl | + | | + | Purpose : | + | | + | Arithmetically shift the 32 bit input L_var1 left var2 positions. Zero | + | fill the var2 LSB of the result. If var2 is negative, arithmetically | + | shift L_var1 right by -var2 with sign extension. Saturate the result in | + | case of underflows or overflows. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var1 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_shl (Word32 L_var1, Word16 var2) +{ + Word32 L_var_out=0; + + if (var2 <= 0) + { + if (var2 < -32) + var2 = -32; + L_var_out = L_shr (L_var1, -var2); +#if (WMOPS) + multiCounter[currCounter].L_shr--; +#endif + } + else + { + for (; var2 > 0; var2--) + { + if (L_var1 > (Word32) 0X3fffffffL) + { + Overflow = 1; + L_var_out = MAX_32; + break; + } + else + { + if (L_var1 < (Word32) 0xc0000000L) + { + Overflow = 1; + L_var_out = MIN_32; + break; + } + } + L_var1 *= 2; + L_var_out = L_var1; + } + } +#if (WMOPS) + multiCounter[currCounter].L_shl++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_shr | + | | + | Purpose : | + | | + | Arithmetically shift the 32 bit input L_var1 right var2 positions with | + | sign extension. If var2 is negative, arithmetically shift L_var1 left | + | by -var2 and zero fill the -var2 LSB of the result. Saturate the result | + | in case of underflows or overflows. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var1 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_shr (Word32 L_var1, Word16 var2) +{ + Word32 L_var_out; + + if (var2 < 0) + { + if (var2 < -32) + var2 = -32; + L_var_out = L_shl (L_var1, -var2); +#if (WMOPS) + multiCounter[currCounter].L_shl--; +#endif + } + else + { + if (var2 >= 31) + { + L_var_out = (L_var1 < 0L) ? -1 : 0; + } + else + { + if (L_var1 < 0) + { + L_var_out = ~((~L_var1) >> var2); + } + else + { + L_var_out = L_var1 >> var2; + } + } + } +#if (WMOPS) + multiCounter[currCounter].L_shr++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : shr_r | + | | + | Purpose : | + | | + | Same as shr(var1,var2) but with rounding. Saturate the result in case of| + | underflows or overflows : | + | - If var2 is greater than zero : | + | if (sub(shl(shr(var1,var2),1),shr(var1,sub(var2,1)))) | + | is equal to zero | + | then | + | shr_r(var1,var2) = shr(var1,var2) | + | else | + | shr_r(var1,var2) = add(shr(var1,var2),1) | + | - If var2 is less than or equal to zero : | + | shr_r(var1,var2) = shr(var1,var2). | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 shr_r (Word16 var1, Word16 var2) +{ + Word16 var_out; + + if (var2 > 15) + { + var_out = 0; + } + else + { + var_out = shr (var1, var2); +#if (WMOPS) + multiCounter[currCounter].shr--; +#endif + + if (var2 > 0) + { + if ((var1 & ((Word16) 1 << (var2 - 1))) != 0) + { + var_out++; + } + } + } +#if (WMOPS) + multiCounter[currCounter].shr_r++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : mac_r | + | | + | Purpose : | + | | + | Multiply var1 by var2 and shift the result left by 1. Add the 32 bit | + | result to L_var3 with saturation. Round the LS 16 bits of the result | + | into the MS 16 bits with saturation and shift the result right by 16. | + | Return a 16 bit result. | + | mac_r(L_var3,var1,var2) = round(L_mac(L_var3,var1,var2)) | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var3 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0x0000 8000 <= L_var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 mac_r (Word32 L_var3, Word16 var1, Word16 var2) +{ + Word16 var_out; + + L_var3 = L_mac (L_var3, var1, var2); +#if (WMOPS) + multiCounter[currCounter].L_mac--; +#endif + L_var3 = L_add (L_var3, (Word32) 0x00008000L); +#if (WMOPS) + multiCounter[currCounter].L_add--; +#endif + var_out = extract_h (L_var3); +#if (WMOPS) + multiCounter[currCounter].extract_h--; + multiCounter[currCounter].mac_r++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : msu_r | + | | + | Purpose : | + | | + | Multiply var1 by var2 and shift the result left by 1. Subtract the 32 | + | bit result to L_var3 with saturation. Round the LS 16 bits of the res- | + | ult into the MS 16 bits with saturation and shift the result right by | + | 16. Return a 16 bit result. | + | msu_r(L_var3,var1,var2) = round(L_msu(L_var3,var1,var2)) | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | L_var3 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= L_var3 <= 0x7fff ffff. | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0x0000 8000 <= L_var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word16 msu_r (Word32 L_var3, Word16 var1, Word16 var2) +{ + Word16 var_out; + + L_var3 = L_msu (L_var3, var1, var2); +#if (WMOPS) + multiCounter[currCounter].L_msu--; +#endif + L_var3 = L_add (L_var3, (Word32) 0x00008000L); +#if (WMOPS) + multiCounter[currCounter].L_add--; +#endif + var_out = extract_h (L_var3); +#if (WMOPS) + multiCounter[currCounter].extract_h--; + multiCounter[currCounter].msu_r++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_deposit_h | + | | + | Purpose : | + | | + | Deposit the 16 bit var1 into the 16 MS bits of the 32 bit output. The | + | 16 LS bits of the output are zeroed. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= var_out <= 0x7fff 0000. | + |___________________________________________________________________________| +*/ + +Word32 L_deposit_h (Word16 var1) +{ + Word32 L_var_out; + + L_var_out = (Word32) var1 << 16; +#if (WMOPS) + multiCounter[currCounter].L_deposit_h++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_deposit_l | + | | + | Purpose : | + | | + | Deposit the 16 bit var1 into the 16 LS bits of the 32 bit output. The | + | 16 MS bits of the output are sign extended. | + | | + | Complexity weight : 2 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0xFFFF 8000 <= var_out <= 0x0000 7fff. | + |___________________________________________________________________________| +*/ + +Word32 L_deposit_l (Word16 var1) +{ + Word32 L_var_out; + + L_var_out = (Word32) var1; +#if (WMOPS) + multiCounter[currCounter].L_deposit_l++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_shr_r | + | | + | Purpose : | + | | + | Same as L_shr(L_var1,var2) but with rounding. Saturate the result in | + | case of underflows or overflows : | + | - If var2 is greater than zero : | + | if (L_sub(L_shl(L_shr(L_var1,var2),1),L_shr(L_var1,sub(var2,1))))| + | is equal to zero | + | then | + | L_shr_r(L_var1,var2) = L_shr(L_var1,var2) | + | else | + | L_shr_r(L_var1,var2) = L_add(L_shr(L_var1,var2),1) | + | - If var2 is less than or equal to zero : | + | L_shr_r(L_var1,var2) = L_shr(L_var1,var2). | + | | + | Complexity weight : 3 | + | | + | Inputs : | + | | + | L_var1 | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= var1 <= 0x7fff ffff. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_shr_r (Word32 L_var1, Word16 var2) +{ + Word32 L_var_out; + + if (var2 > 31) + { + L_var_out = 0; + } + else + { + L_var_out = L_shr (L_var1, var2); +#if (WMOPS) + multiCounter[currCounter].L_shr--; +#endif + if (var2 > 0) + { + if ((L_var1 & ((Word32) 1 << (var2 - 1))) != 0) + { + L_var_out++; + } + } + } +#if (WMOPS) + multiCounter[currCounter].L_shr_r++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_abs | + | | + | Purpose : | + | | + | Absolute value of L_var1; Saturate in case where the input is | + | -214783648 | + | | + | Complexity weight : 3 | + | | + | Inputs : | + | | + | L_var1 | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= var1 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x0000 0000 <= var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_abs (Word32 L_var1) +{ + Word32 L_var_out; + + if (L_var1 == MIN_32) + { + L_var_out = MAX_32; + } + else + { + if (L_var1 < 0) + { + L_var_out = -L_var1; + } + else + { + L_var_out = L_var1; + } + } + +#if (WMOPS) + multiCounter[currCounter].L_abs++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : L_sat | + | | + | Purpose : | + | | + | 32 bit L_var1 is set to 2147483647 if an overflow occured or to | + | -2147483648 if an underflow occured on the most recent L_add_c, | + | L_sub_c, L_macNs or L_msuNs operations. The carry and overflow values | + | are binary values which can be tested and assigned values. | + | | + | Complexity weight : 4 | + | | + | Inputs : | + | | + | L_var1 | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= var1 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | L_var_out | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= var_out <= 0x7fff ffff. | + |___________________________________________________________________________| +*/ + +Word32 L_sat (Word32 L_var1) +{ + Word32 L_var_out; + + L_var_out = L_var1; + + if (Overflow) + { + + if (Carry) + { + L_var_out = MIN_32; + } + else + { + L_var_out = MAX_32; + } + + Carry = 0; + Overflow = 0; + } +#if (WMOPS) + multiCounter[currCounter].L_sat++; +#endif + return (L_var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : norm_s | + | | + | Purpose : | + | | + | Produces the number of left shift needed to normalize the 16 bit varia- | + | ble var1 for positive values on the interval with minimum of 16384 and | + | maximum of 32767, and for negative values on the interval with minimum | + | of -32768 and maximum of -16384; in order to normalize the result, the | + | following operation must be done : | + | norm_var1 = shl(var1,norm_s(var1)). | + | | + | Complexity weight : 15 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0xffff 8000 <= var1 <= 0x0000 7fff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0x0000 0000 <= var_out <= 0x0000 000f. | + |___________________________________________________________________________| +*/ + +Word16 norm_s (Word16 var1) +{ + Word16 var_out; + + if (var1 == 0) + { + var_out = 0; + } + else + { + if (var1 == (Word16) 0xffff) + { + var_out = 15; + } + else + { + if (var1 < 0) + { + var1 = ~var1; + } + for (var_out = 0; var1 < 0x4000; var_out++) + { + var1 <<= 1; + } + } + } + +#if (WMOPS) + multiCounter[currCounter].norm_s++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : div_s | + | | + | Purpose : | + | | + | Produces a result which is the fractional integer division of var1 by | + | var2; var1 and var2 must be positive and var2 must be greater or equal | + | to var1; the result is positive (leading bit equal to 0) and truncated | + | to 16 bits. | + | If var1 = var2 then div(var1,var2) = 32767. | + | | + | Complexity weight : 18 | + | | + | Inputs : | + | | + | var1 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0x0000 0000 <= var1 <= var2 and var2 != 0. | + | | + | var2 | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : var1 <= var2 <= 0x0000 7fff and var2 != 0. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0x0000 0000 <= var_out <= 0x0000 7fff. | + | It's a Q15 value (point between b15 and b14). | + |___________________________________________________________________________| +*/ + +Word16 div_s (Word16 var1, Word16 var2) +{ + Word16 var_out = 0; + Word16 iteration; + Word32 L_num; + Word32 L_denom; + + if ((var1 > var2) || (var1 < 0) || (var2 < 0)) + { + printf ("Division Error var1=%d var2=%d\n", var1, var2); + abort(); /* exit (0); */ + } + if (var2 == 0) + { + printf ("Division by 0, Fatal error \n"); + abort(); /* exit (0); */ + } + if (var1 == 0) + { + var_out = 0; + } + else + { + if (var1 == var2) + { + var_out = MAX_16; + } + else + { + L_num = L_deposit_l (var1); +#if (WMOPS) + multiCounter[currCounter].L_deposit_l--; +#endif + L_denom = L_deposit_l (var2); +#if (WMOPS) + multiCounter[currCounter].L_deposit_l--; +#endif + + for (iteration = 0; iteration < 15; iteration++) + { + var_out <<= 1; + L_num <<= 1; + + if (L_num >= L_denom) + { + L_num = L_sub (L_num, L_denom); +#if (WMOPS) + multiCounter[currCounter].L_sub--; +#endif + var_out = add (var_out, 1); +#if (WMOPS) + multiCounter[currCounter].add--; +#endif + } + } + } + } + +#if (WMOPS) + multiCounter[currCounter].div_s++; +#endif + return (var_out); +} + +/*___________________________________________________________________________ + | | + | Function Name : norm_l | + | | + | Purpose : | + | | + | Produces the number of left shifts needed to normalize the 32 bit varia-| + | ble L_var1 for positive values on the interval with minimum of | + | 1073741824 and maximum of 2147483647, and for negative values on the in-| + | terval with minimum of -2147483648 and maximum of -1073741824; in order | + | to normalize the result, the following operation must be done : | + | norm_L_var1 = L_shl(L_var1,norm_l(L_var1)). | + | | + | Complexity weight : 30 | + | | + | Inputs : | + | | + | L_var1 | + | 32 bit long signed integer (Word32) whose value falls in the | + | range : 0x8000 0000 <= var1 <= 0x7fff ffff. | + | | + | Outputs : | + | | + | none | + | | + | Return Value : | + | | + | var_out | + | 16 bit short signed integer (Word16) whose value falls in the | + | range : 0x0000 0000 <= var_out <= 0x0000 001f. | + |___________________________________________________________________________| +*/ + +Word16 norm_l (Word32 L_var1) +{ + Word16 var_out; + + if (L_var1 == 0) + { + var_out = 0; + } + else + { + if (L_var1 == (Word32) 0xffffffffL) + { + var_out = 31; + } + else + { + if (L_var1 < 0) + { + L_var1 = ~L_var1; + } + for (var_out = 0; L_var1 < (Word32) 0x40000000L; var_out++) + { + L_var1 <<= 1; + } + } + } + +#if (WMOPS) + multiCounter[currCounter].norm_l++; +#endif + return (var_out); +} + diff --git a/imbe/ch_decode.cc b/imbe/ch_decode.cc new file mode 100644 index 0000000..da0b6cc --- /dev/null +++ b/imbe/ch_decode.cc @@ -0,0 +1,185 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "basic_op.h" +#include "ch_decode.h" +#include "aux_sub.h" + + +void decode_frame_vector(IMBE_PARAM *imbe_param, Word16 *frame_vector) +{ + Word16 bit_stream[BIT_STREAM_LEN]; + Word16 i, vec_num, tmp, tmp1, tmp2, bit_thr, shift; + Word16 *b_ptr, *ba_ptr, index0; + Word32 L_tmp; + + imbe_param->b_vec[0] = (shr(frame_vector[0], 4) & 0xFC) | (shr(frame_vector[7], 1) & 0x3); + + if (imbe_param->b_vec[0] < 0 || imbe_param->b_vec[0] > 207) + return; // If we return here IMBE parameters from previous frame will be used (frame repeating) + + tmp = ((imbe_param->b_vec[0] & 0xFF) << 1) + 0x4F; // Convert b_vec[0] to unsigned Q15.1 format and add 39.5 + + //imbe_param->ff = 4./((double)imbe_param->b_vec[0] + 39.5); + + // Calculate fundamental frequency with higher precession + shift = norm_s(tmp); + tmp1 = tmp << shift; + + tmp2 = div_s(0x4000, tmp1); + imbe_param->fund_freq = L_shr(L_deposit_h(tmp2), 11 - shift); + + L_tmp = L_sub(0x40000000, L_mult(tmp1, tmp2)); + tmp2 = div_s(extract_l(L_shr(L_tmp, 2)), tmp1); + L_tmp = L_shr(L_deposit_l(tmp2), 11 - shift - 2); + imbe_param->fund_freq = L_add(imbe_param->fund_freq, L_tmp); + + //printf("%X %X \n", imbe_param->fund_freq, (Word32)(imbe_param->ff * (double)((UWord32)1<<31))); + + tmp = (tmp + 0x2) >> 3; // Calculate (b0 + 39.5 + 1)/4 + imbe_param->num_harms = ((UWord32)CNST_0_9254_Q0_16 * tmp) >> 16; + + if(imbe_param->num_harms <= 36) + imbe_param->num_bands = extract_h((UWord32)(imbe_param->num_harms + 2) * CNST_0_33_Q0_16); // fix((L+2)/3) + else + imbe_param->num_bands = NUM_BANDS_MAX; + + // Convert input vector (from b_3 to b_L+1) to bit stream + bit_stream[0] = (frame_vector[0] & 0x4)?1:0; + bit_stream[1] = (frame_vector[0] & 0x2)?1:0; + bit_stream[2] = (frame_vector[0] & 0x1)?1:0; + + bit_stream[BIT_STREAM_LEN - 3] = (frame_vector[7] & 0x40)?1:0; + bit_stream[BIT_STREAM_LEN - 2] = (frame_vector[7] & 0x20)?1:0; + bit_stream[BIT_STREAM_LEN - 1] = (frame_vector[7] & 0x10)?1:0; + + + index0 = 3 + 3 * 12 - 1; + for(vec_num = 3; vec_num >= 1; vec_num--) + { + tmp = frame_vector[vec_num]; + for(i = 0; i < 12; i++) + { + bit_stream[index0] = (tmp & 0x1)?1:0; + tmp >>= 1; + index0--; + } + } + + index0 = 3 + 3 * 12 + 3 * 11 - 1; + for(vec_num = 6; vec_num >= 4; vec_num--) + { + tmp = frame_vector[vec_num]; + for(i = 0; i < 11; i++) + { + bit_stream[index0] = (tmp & 0x1)?1:0; + tmp >>= 1; + index0--; + } + } + + // Rebuild b1 + index0 = 3 + 3 * 12; + tmp = 0; + for(i = 0; i < imbe_param->num_bands; i++) + tmp = (tmp << 1) | bit_stream[index0++]; + + imbe_param->b_vec[1] = tmp; + + // Rebuild b2 + tmp = 0; + tmp |= bit_stream[index0++] << 1; + tmp |= bit_stream[index0++]; + imbe_param->b_vec[2] = (frame_vector[0] & 0x38) | (tmp << 1) | (shr(frame_vector[7], 3) & 0x01); + + // Shift the rest of sequence + tmp = imbe_param->num_bands + 2; // shift + for(; index0 < BIT_STREAM_LEN; index0++) + bit_stream[index0 - tmp] = bit_stream[index0]; + + // Priority ReScanning + b_ptr = &imbe_param->b_vec[3]; + ba_ptr = imbe_param->bit_alloc; + for(i = 0; i < B_NUM; i++) + ba_ptr[i] = b_ptr[i] = 0; + + + // Unpack bit allocation table's item + get_bit_allocation(imbe_param->num_harms, imbe_param->bit_alloc); + + index0 = 0; + bit_thr = (imbe_param->num_harms == 0xb)?9:ba_ptr[0]; + + while(index0 < BIT_STREAM_LEN - imbe_param->num_bands - 2) + { + for(i = 0; i < imbe_param->num_harms - 1; i++) + if(bit_thr && bit_thr <= ba_ptr[i]) + b_ptr[i] = (b_ptr[i] << 1) | bit_stream[index0++]; + bit_thr--; + } + + // Synchronization Bit Decoding + imbe_param->b_vec[imbe_param->num_harms + 2] = frame_vector[7] & 1; +} + + +void v_uv_decode(IMBE_PARAM *imbe_param) +{ + Word16 num_harms; + Word16 num_bands; + Word16 vu_vec, *p_v_uv_dsn, mask, i, uv_cnt; + + num_harms = imbe_param->num_harms; + num_bands = imbe_param->num_bands; + vu_vec = imbe_param->b_vec[1]; + + p_v_uv_dsn = imbe_param->v_uv_dsn; + + mask = 1 << (num_bands - 1); + + v_zap(p_v_uv_dsn, NUM_HARMS_MAX); + + i = 0; uv_cnt = 0; + while(num_harms--) + { + if(vu_vec & mask) + *p_v_uv_dsn++ = 1; + else + { + *p_v_uv_dsn++ = 0; + uv_cnt++; + } + + if(++i == 3) + { + if(num_bands > 1) + { + num_bands--; + mask >>= 1; + } + i = 0; + } + } + imbe_param->l_uv = uv_cnt; +} diff --git a/imbe/ch_decode.h b/imbe/ch_decode.h new file mode 100644 index 0000000..027ab11 --- /dev/null +++ b/imbe/ch_decode.h @@ -0,0 +1,32 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#ifndef _CH_DECODE +#define _CH_DECODE + +#include "typedef.h" + +#define BIT_STREAM_LEN (3 + 3*12 + 3*11 + 3) + +void decode_frame_vector(IMBE_PARAM *imbe_param, Word16 *frame_vector); +void v_uv_decode(IMBE_PARAM *imbe_param); + +#endif diff --git a/imbe/ch_encode.cc b/imbe/ch_encode.cc new file mode 100644 index 0000000..6d12083 --- /dev/null +++ b/imbe/ch_encode.cc @@ -0,0 +1,110 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "basic_op.h" +#include "ch_encode.h" +#include "aux_sub.h" + + +void encode_frame_vector(IMBE_PARAM *imbe_param, Word16 *frame_vector) +{ + Word16 bit_stream[EN_BIT_STREAM_LEN], index0, bit_thr, bit_mask, i; + Word16 vec_num, num_harms, num_bands, tmp; + Word16 *ba_ptr, *b_ptr; + + num_harms = imbe_param->num_harms; + num_bands = imbe_param->num_bands; + + v_zap(frame_vector, 8); + + // Unpack bit allocation table's item + get_bit_allocation(num_harms, imbe_param->bit_alloc); + + // Priority Scanning + index0 = 0; + ba_ptr = imbe_param->bit_alloc; + bit_thr = (num_harms == 0xb)?9:ba_ptr[0]; + bit_mask = shl(1, bit_thr - 1); + + while(index0 < EN_BIT_STREAM_LEN - (num_bands - 3)) + { + b_ptr = &imbe_param->b_vec[3]; + for(i = 0; i < num_harms - 1; i++) + if(bit_thr && bit_thr <= ba_ptr[i]) + bit_stream[index0++] = (b_ptr[i] & bit_mask)?1:0; + + bit_thr--; + bit_mask = shr(bit_mask, 1); + } + + frame_vector[0] = shl(imbe_param->b_vec[0] & 0xFC, 4) | (imbe_param->b_vec[2] & 0x38); + + index0 = 0; + frame_vector[0] |= (bit_stream[index0++])?4:0; + frame_vector[0] |= (bit_stream[index0++])?2:0; + frame_vector[0] |= (bit_stream[index0++])?1:0; + + for(vec_num = 1; vec_num <= 3; vec_num++) + { + tmp = 0; + for(i = 0; i < 12; i++) + { + tmp <<= 1; + tmp |= bit_stream[index0++]; + } + frame_vector[vec_num] = tmp; + } + + index0 -= num_bands + 2; + + bit_mask = shl(1, num_bands - 1); + for(i = 0; i < num_bands; i++) + { + bit_stream[index0++] = (imbe_param->b_vec[1] & bit_mask)?1:0; + bit_mask >>= 1; + } + + bit_stream[index0++] = (imbe_param->b_vec[2] & 0x04)?1:0; + bit_stream[index0++] = (imbe_param->b_vec[2] & 0x02)?1:0; + + index0 -= num_bands + 2; + + for(vec_num = 4; vec_num <= 6; vec_num++) + { + tmp = 0; + for(i = 0; i < 11; i++) + { + tmp <<= 1; + tmp |= bit_stream[index0++]; + } + frame_vector[vec_num] = tmp; + } + + frame_vector[7] = shl(imbe_param->b_vec[0] & 0x03, 1) | shl(imbe_param->b_vec[2] & 0x01, 3); + frame_vector[7] |= (bit_stream[index0++])?0x40:0; + frame_vector[7] |= (bit_stream[index0++])?0x20:0; + frame_vector[7] |= (bit_stream[index0++])?0x10:0; + frame_vector[7] |= (imbe_param->b_vec[num_harms + 2])?0x01:0; +} diff --git a/imbe/ch_encode.h b/imbe/ch_encode.h new file mode 100644 index 0000000..0a9b8de --- /dev/null +++ b/imbe/ch_encode.h @@ -0,0 +1,32 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _CH_ENCODE +#define _CH_ENCODE + +#define EN_BIT_STREAM_LEN (3 + 3*12 + 6 + 2*11 + 3) + + +void encode_frame_vector(IMBE_PARAM *imbe_param, Word16 *frame_vector); + + +#endif diff --git a/imbe/dc_rmv.cc b/imbe/dc_rmv.cc new file mode 100644 index 0000000..946174c --- /dev/null +++ b/imbe/dc_rmv.cc @@ -0,0 +1,66 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "aux_sub.h" +#include "basic_op.h" +#include "math_sub.h" +#include "dc_rmv.h" + + +#define CNST_0_99_Q1_15 0x7EB8 + + +//----------------------------------------------------------------------------- +// PURPOSE: +// High-pass filter to remove DC +// +// +// INPUT: +// *sigin - pointer to input signal buffer +// *sigout - pointer to output signal buffer +// *mem - pointer to filter's memory element +// len - number of input signal samples +// +// OUTPUT: +// None +// +// RETURN: +// Saved filter state in mem +// +//----------------------------------------------------------------------------- +void dc_rmv(Word16 *sigin, Word16 *sigout, Word32 *mem, Word16 len) +{ + Word32 L_tmp, L_mem; + + L_mem = *mem; + while(len--) + { + L_tmp = L_deposit_h(*sigin++); + L_mem = L_add(L_mem, L_tmp); + *sigout++ = round(L_mem); + L_mem = L_mpy_ls(L_mem, CNST_0_99_Q1_15); + L_mem = L_sub(L_mem, L_tmp); + } + *mem = L_mem; +} diff --git a/imbe/dc_rmv.h b/imbe/dc_rmv.h new file mode 100644 index 0000000..d36393b --- /dev/null +++ b/imbe/dc_rmv.h @@ -0,0 +1,46 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _DC_RMV +#define _DC_RMV + +//----------------------------------------------------------------------------- +// PURPOSE: +// High-pass filter to remove DC +// +// +// INPUT: +// *sigin - pointer to input signal buffer +// *sigout - pointer to output signal buffer +// *mem - pointer to filter's memory element +// len - number of input signal samples +// +// OUTPUT: +// None +// +// RETURN: +// Saved filter state in mem +// +//----------------------------------------------------------------------------- +void dc_rmv(Word16 *sigin, Word16 *sigout, Word32 *mem, Word16 len); + +#endif diff --git a/imbe/decode.cc b/imbe/decode.cc new file mode 100644 index 0000000..5481697 --- /dev/null +++ b/imbe/decode.cc @@ -0,0 +1,112 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "ch_decode.h" +#include "sa_decode.h" +#include "sa_enh.h" +#include "v_synt.h" +#include "uv_synt.h" +#include "basic_op.h" +#include "aux_sub.h" +#include "encode.h" +#include "dsp_sub.h" +#include "imbe_vocoder_impl.h" + +#include + +const uint8_t BIT_MASK_TABLE8[] = { 0x80U, 0x40U, 0x20U, 0x10U, 0x08U, 0x04U, 0x02U, 0x01U }; +#define READ_BIT(p,i) (p[(i)>>3] & BIT_MASK_TABLE8[(i)&7]) + + +void imbe_vocoder_impl::decode_init(IMBE_PARAM *imbe_param) +{ + v_synt_init(); + uv_synt_init(); + sa_decode_init(); + + // Make previous frame for the first frame + memset((char *)imbe_param, 0, sizeof(IMBE_PARAM)); + imbe_param->fund_freq = 0x0cf6474a; + imbe_param->num_harms = 9; + imbe_param->num_bands = 3; + +} + + +void imbe_vocoder_impl::decode(IMBE_PARAM *imbe_param, Word16 *frame_vector, Word16 *snd) +{ + Word16 snd_tmp[FRAME]; + Word16 j; + + decode_frame_vector(imbe_param, frame_vector); + v_uv_decode(imbe_param); + sa_decode(imbe_param); + sa_enh(imbe_param); + v_synt(imbe_param, snd); + uv_synt(imbe_param, snd_tmp); + + for(j = 0; j < FRAME; j++) + snd[j] = add(snd[j], snd_tmp[j]); +} + +void imbe_vocoder_impl::decode_4400(int16_t *snd, uint8_t *imbe) +{ + int16_t frame[8U] = {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000}; + unsigned int offset = 0U; + + int16_t mask = 0x0800; + for (unsigned int i = 0U; i < 12U; i++, mask >>= 1, offset++) + frame[0U] |= READ_BIT(imbe, offset) != 0x00U ? mask : 0x0000; + + mask = 0x0800; + for (unsigned int i = 0U; i < 12U; i++, mask >>= 1, offset++) + frame[1U] |= READ_BIT(imbe, offset) != 0x00U ? mask : 0x0000; + + mask = 0x0800; + for (unsigned int i = 0U; i < 12U; i++, mask >>= 1, offset++) + frame[2U] |= READ_BIT(imbe, offset) != 0x00U ? mask : 0x0000; + + mask = 0x0800; + for (unsigned int i = 0U; i < 12U; i++, mask >>= 1, offset++) + frame[3U] |= READ_BIT(imbe, offset) != 0x00U ? mask : 0x0000; + + mask = 0x0400; + for (unsigned int i = 0U; i < 11U; i++, mask >>= 1, offset++) + frame[4U] |= READ_BIT(imbe, offset) != 0x00U ? mask : 0x0000; + + mask = 0x0400; + for (unsigned int i = 0U; i < 11U; i++, mask >>= 1, offset++) + frame[5U] |= READ_BIT(imbe, offset) != 0x00U ? mask : 0x0000; + + mask = 0x0400; + for (unsigned int i = 0U; i < 11U; i++, mask >>= 1, offset++) + frame[6U] |= READ_BIT(imbe, offset) != 0x00U ? mask : 0x0000; + + mask = 0x0040; + for (unsigned int i = 0U; i < 7U; i++, mask >>= 1, offset++) + frame[7U] |= READ_BIT(imbe, offset) != 0x00U ? mask : 0x0000; + + imbe_decode(frame, snd); +} + diff --git a/imbe/decode.h b/imbe/decode.h new file mode 100644 index 0000000..962be53 --- /dev/null +++ b/imbe/decode.h @@ -0,0 +1,31 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _DECODE +#define _DECODE +#if 0 +void decode_init(IMBE_PARAM *imbe_param); +void decode(IMBE_PARAM *imbe_param, Word16 *frame_vector, Word16 *snd); +void decode_4400(int16_t *pcm, uint8_t *imbe); +#endif +#endif + diff --git a/imbe/dsp_sub.cc b/imbe/dsp_sub.cc new file mode 100644 index 0000000..2a02051 --- /dev/null +++ b/imbe/dsp_sub.cc @@ -0,0 +1,278 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "basic_op.h" +#include "imbe.h" +#include "tbls.h" +#include "dsp_sub.h" +#include "math_sub.h" +#include "encode.h" +#include "imbe_vocoder_impl.h" + +//----------------------------------------------------------------------------- +// PURPOSE: +// Perform inverse DCT +// +// +// INPUT: +// in - pointer to input data +// m_lim - input data's size +// i_lim - result's size +// out - pointer to save result +// +// OUTPUT: +// None +// +// RETURN: +// Saved in out result of conversion +// +//----------------------------------------------------------------------------- +void imbe_vocoder_impl::idct(Word16 *in, Word16 m_lim, Word16 i_lim, Word16 *out) +{ + UWord16 angl_step, angl_intl, angl_intl_2; + UWord16 angl_acc; + Word32 sum; + Word16 i, m; + + if(m_lim == 1) + { + angl_intl = CNST_0_5_Q1_15; + angl_intl_2 = CNST_1_0_Q1_15; + } + else + { + angl_intl = div_s ((Word16) CNST_0_5_Q5_11, m_lim << 11); // calculate 0.5/m_lim + angl_intl_2 = shl(angl_intl, 1); + } + + angl_step = angl_intl; + for(i = 0; i < i_lim; i++) + { + sum = 0; + angl_acc = angl_step; + for(m = 1; m < m_lim; m++) + { + sum = L_add(sum, L_shr( L_mult(in[m], cos_fxp(angl_acc)), 7)); + angl_acc += angl_step; + } + sum = L_add(sum, L_shr( L_deposit_h(in[0]), 8)); + out[i] = extract_l(L_shr_r (sum, 8)); + angl_step += angl_intl_2; + } +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Perform DCT +// +// +// INPUT: +// in - pointer to input data +// m_lim - input data's size +// i_lim - result's size +// out - pointer to save result +// +// OUTPUT: +// None +// +// RETURN: +// Saved in out result of conversion +// +//----------------------------------------------------------------------------- +void imbe_vocoder_impl::dct(Word16 *in, Word16 m_lim, Word16 i_lim, Word16 *out) +{ + UWord16 angl_step, angl_intl, angl_intl_2, angl_begin; + UWord16 angl_acc; + Word32 sum; + Word16 i, m; + + if(m_lim == 1) + { + angl_intl = CNST_0_5_Q1_15; + angl_intl_2 = CNST_1_0_Q1_15; + } + else + { + angl_intl = div_s ((Word16) CNST_0_5_Q5_11, m_lim << 11); // calculate 0.5/m_lim + angl_intl_2 = shl(angl_intl, 1); + } + + // Calculate first coefficient + sum = 0; + for(m = 0; m < m_lim; m++) + sum = L_add(sum, L_deposit_l(in[m])); + out[0] = extract_l(L_mpy_ls(sum, angl_intl_2)); + + // Calculate the others coefficients + angl_begin = angl_intl; + angl_step = angl_intl_2; + for(i = 1; i < i_lim; i++) + { + sum = 0; + angl_acc = angl_begin; + for(m = 0; m < m_lim; m++) + { + sum = L_add(sum, L_deposit_l(mult(in[m], cos_fxp(angl_acc)))); + angl_acc += angl_step; + } + out[i] = extract_l(L_mpy_ls(sum, angl_intl_2)); + + angl_step += angl_intl_2; + angl_begin += angl_intl; + } +} + + + + +void imbe_vocoder_impl::fft_init(void) +{ + Word16 i, fft_len2, shift, step, theta; + + fft_len2 = shr(FFTLENGTH, 1); + shift = norm_s(fft_len2); + step = shl(2, shift); + theta = 0; + + for(i = 0; i <= fft_len2; i++) + { + wr_array[i] = cos_fxp(theta); + wi_array[i] = sin_fxp(theta); + if(i >= (fft_len2 - 1)) + theta = ONE_Q15; + else + theta = add(theta, step); + } +} + + +// Subroutine FFT: Fast Fourier Transform +// *************************************************************** +// * Replaces data by its DFT, if isign is 1, or replaces data * +// * by inverse DFT times nn if isign is -1. data is a complex * +// * array of length nn, input as a real array of length 2*nn. * +// * nn MUST be an integer power of two. This is not checked * +// * The real part of the number should be in the zeroeth * +// * of data , and the imaginary part should be in the next * +// * element. Hence all the real parts should have even indeces * +// * and the imaginary parts, odd indeces. * +// * * +// * Data is passed in an array starting in position 0, but the * +// * code is copied from Fortran so uses an internal pointer * +// * which accesses position 0 as position 1, etc. * +// * * +// * This code uses e+jwt sign convention, so isign should be * +// * reversed for e-jwt. * +// *************************************************************** +// +// Q values: +// datam1 - Q14 +// isign - Q15 + +#define SWAP(a,b) temp1 = (a);(a) = (b); (b) = temp1 + +void imbe_vocoder_impl::fft(Word16 *datam1, Word16 nn, Word16 isign) +{ + Word16 n, mmax, m, j, istep, i; + Word16 wr, wi, temp1; + Word32 L_tempr, L_tempi; + Word16 *data; + Word32 L_temp1, L_temp2; + Word16 index, index_step; + + // Use pointer indexed from 1 instead of 0 + data = &datam1[-1]; + + n = shl(nn,1); + j = 1; + for( i = 1; i < n; i+=2 ) + { + if ( j > i) + { + SWAP(data[j],data[i]); + SWAP(data[j+1],data[i+1]); + } + m = nn; + while ( m >= 2 && j > m ) + { + j = sub(j,m); + m = shr(m,1); + } + j = add(j,m); + } + mmax = 2; + + // initialize index step + index_step = nn; + + while ( n > mmax) + { + istep = shl(mmax,1); // istep = 2 * mmax + + index = 0; + index_step = shr(index_step,1); + + wr = ONE_Q15; + wi = 0; + for ( m = 1; m < mmax; m+=2) + { + for ( i = m; i <= n; i += istep) + { + j = i + mmax; + + // tempr = wr * data[j] - wi * data[j+1] + L_temp1 = L_shr(L_mult(wr,data[j]),1); + L_temp2 = L_shr(L_mult(wi,data[j+1]),1); + L_tempr = L_sub(L_temp1,L_temp2); + + // tempi = wr * data[j+1] + wi * data[j] + L_temp1 = L_shr(L_mult(wr,data[j+1]),1); + L_temp2 = L_shr(L_mult(wi,data[j]),1); + L_tempi = L_add(L_temp1,L_temp2); + + + // data[j] = data[i] - tempr + L_temp1 = L_shr(L_deposit_h(data[i]),1); + data[j] = round(L_sub(L_temp1,L_tempr)); + + // data[i] += tempr + data[i] = round(L_add(L_temp1,L_tempr)); + + // data[j+1] = data[i+1] - tempi + L_temp1 = L_shr(L_deposit_h(data[i+1]),1); + data[j+1] = round(L_sub(L_temp1,L_tempi)); + + // data[i+1] += tempi + data[i+1] = round(L_add(L_temp1,L_tempi)); + } + index = add(index,index_step); + wr = wr_array[index]; + if (isign < 0) + wi = negate(wi_array[index]); + else + wi = wi_array[index]; + } + mmax = istep; + } +} + + diff --git a/imbe/dsp_sub.h b/imbe/dsp_sub.h new file mode 100644 index 0000000..53590e6 --- /dev/null +++ b/imbe/dsp_sub.h @@ -0,0 +1,81 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _DSP_SUB +#define _DSP_SUB + + +#define CNST_0_5_Q1_15 0x4000 +#define CNST_0_5_Q5_11 0x0400 +#define CNST_1_0_Q1_15 0x7FFF + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Perform inverse DCT +// +// +// INPUT: +// in - pointer to input data +// m_lim - input data's size +// i_lim - result's size +// out - pointer to save result +// +// OUTPUT: +// None +// +// RETURN: +// Saved in out result of conversion +// +//----------------------------------------------------------------------------- +void idct(Word16 *in, Word16 m_lim, Word16 i_lim, Word16 *out); + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Perform DCT +// +// +// INPUT: +// in - pointer to input data +// m_lim - input data's size +// i_lim - result's size +// out - pointer to save result +// +// OUTPUT: +// None +// +// RETURN: +// Saved in out result of conversion +// +//----------------------------------------------------------------------------- +void dct(Word16 *in, Word16 m_lim, Word16 i_lim, Word16 *out); + +#define FFTLENGTH 256 + + +void fft_init(void); +void fft(Word16 *datam1, Word16 nn, Word16 isign); + +void c_fft(Word16 * farray_ptr); + +#endif diff --git a/imbe/encode.cc b/imbe/encode.cc new file mode 100644 index 0000000..ef54ded --- /dev/null +++ b/imbe/encode.cc @@ -0,0 +1,142 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "basic_op.h" +#include "dsp_sub.h" +#include "aux_sub.h" +#include "tbls.h" +#include "encode.h" +#include "dc_rmv.h" +#include "pe_lpf.h" +#include "pitch_est.h" +#include "pitch_ref.h" +#include "v_uv_det.h" +#include "sa_encode.h" +#include "ch_encode.h" +#include "imbe_vocoder_impl.h" + +const uint8_t BIT_MASK_TABLE8[] = { 0x80U, 0x40U, 0x20U, 0x10U, 0x08U, 0x04U, 0x02U, 0x01U }; +#define WRITE_BIT(p,i,b) p[(i)>>3] = (b) ? (p[(i)>>3] | BIT_MASK_TABLE8[(i)&7]) : (p[(i)>>3] & ~BIT_MASK_TABLE8[(i)&7]) + + +void imbe_vocoder_impl::encode_init(void) +{ + v_zap(pitch_est_buf, PITCH_EST_BUF_SIZE); + v_zap(pitch_ref_buf, PITCH_EST_BUF_SIZE); + v_zap(pe_lpf_mem, PE_LPF_ORD); + pitch_est_init(); + fft_init(); + dc_rmv_mem = 0; + sa_encode_init(); + pitch_ref_init(); +} + + +void imbe_vocoder_impl::encode(IMBE_PARAM *imbe_param, Word16 *frame_vector, Word16 *snd) +{ + Word16 i; + Word16 *wr_ptr, *sig_ptr; + + for(i = 0; i < PITCH_EST_BUF_SIZE - FRAME; i++) + { + pitch_est_buf[i] = pitch_est_buf[i + FRAME]; + pitch_ref_buf[i] = pitch_ref_buf[i + FRAME]; + } + + dc_rmv(snd, &pitch_ref_buf[PITCH_EST_BUF_SIZE - FRAME], &dc_rmv_mem, FRAME); + pe_lpf(&pitch_ref_buf[PITCH_EST_BUF_SIZE - FRAME], &pitch_est_buf[PITCH_EST_BUF_SIZE - FRAME], pe_lpf_mem, FRAME); + + pitch_est(imbe_param, pitch_est_buf); + + // + // Speech windowing and FFT calculation + // + wr_ptr = (Word16 *)wr; + sig_ptr = &pitch_ref_buf[40]; + for(i = 146; i < 256; i++) + { + fft_buf[i].re = mult(*sig_ptr++, *wr_ptr++); + fft_buf[i].im = 0; + } + fft_buf[0].re = *sig_ptr++; + fft_buf[0].im = 0; + wr_ptr--; + for(i = 1; i < 111; i++) + { + fft_buf[i].re = mult(*sig_ptr++, *wr_ptr--); + fft_buf[i].im = 0; + } + for(i = 111; i < 146; i++) + fft_buf[i].re = fft_buf[i].im = 0; + + fft((Word16 *)&fft_buf, FFTLENGTH, 1); + + pitch_ref(imbe_param, fft_buf); + v_uv_det(imbe_param, fft_buf); + sa_encode(imbe_param); + encode_frame_vector(imbe_param, frame_vector); +} + +void imbe_vocoder_impl::encode_4400(int16_t *pcm, uint8_t *imbe) +{ + int16_t frame_vector[8]; + memset(imbe, 0, 11); + + imbe_encode(frame_vector, pcm); + uint32_t offset = 0U; + int16_t mask = 0x0800; + + for (uint32_t i = 0U; i < 12U; i++, mask >>= 1, offset++) + WRITE_BIT(imbe, offset, (frame_vector[0U] & mask) != 0); + + mask = 0x0800; + for (uint32_t i = 0U; i < 12U; i++, mask >>= 1, offset++) + WRITE_BIT(imbe, offset, (frame_vector[1U] & mask) != 0); + + mask = 0x0800; + for (uint32_t i = 0U; i < 12U; i++, mask >>= 1, offset++) + WRITE_BIT(imbe, offset, (frame_vector[2U] & mask) != 0); + + mask = 0x0800; + for (uint32_t i = 0U; i < 12U; i++, mask >>= 1, offset++) + WRITE_BIT(imbe, offset, (frame_vector[3U] & mask) != 0); + + mask = 0x0400; + for (uint32_t i = 0U; i < 11U; i++, mask >>= 1, offset++) + WRITE_BIT(imbe, offset, (frame_vector[4U] & mask) != 0); + + mask = 0x0400; + for (uint32_t i = 0U; i < 11U; i++, mask >>= 1, offset++) + WRITE_BIT(imbe, offset, (frame_vector[5U] & mask) != 0); + + mask = 0x0400; + for (uint32_t i = 0U; i < 11U; i++, mask >>= 1, offset++) + WRITE_BIT(imbe, offset, (frame_vector[6U] & mask) != 0); + + mask = 0x0040; + for (uint32_t i = 0U; i < 7U; i++, mask >>= 1, offset++) + WRITE_BIT(imbe, offset, (frame_vector[7U] & mask) != 0); +} + diff --git a/imbe/encode.h b/imbe/encode.h new file mode 100644 index 0000000..685c6a6 --- /dev/null +++ b/imbe/encode.h @@ -0,0 +1,33 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _ENCODE +#define _ENCODE + +#define PITCH_EST_BUF_SIZE 621 +#if 0 +void encode_init(void); +void encode(IMBE_PARAM *imbe_param, Word16 *frame_vector, Word16 *snd); +void encode_4400(int16_t *pcm, uint8_t *imbe); +#endif + +#endif diff --git a/imbe/globals.h b/imbe/globals.h new file mode 100644 index 0000000..2010e7f --- /dev/null +++ b/imbe/globals.h @@ -0,0 +1,62 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _GLOBALS +#define _GLOBALS + + +//#define PI (double)3.1415926535897932384626433832795 + +#define CNST_0_9254_Q0_16 60647 // 0.9254 in unsigned Q0.16 format +#define CNST_0_33_Q0_16 0x5556 // 0.(3) = 1/3 in unsigned Q0.16 format + + +#define CNST_ONE_Q8_24 0x01000000 +#define CNST_0_7_Q1_15 0x599A +#define CNST_0_4_Q1_15 0x3333 +#define CNST_0_03_Q1_15 0x03D7 +#define CNST_0_05_Q1_15 0x0666 + +#define CNST_1_125_Q8_8 0x0120 +#define CNST_0_5_Q8_8 0x0080 +#define CNST_0_125_Q8_8 0x0020 +#define CNST_0_25_Q8_8 0x0040 + +#define CNST_0_8717_Q1_15 0x6F94 +#define CNST_0_0031_Q1_15 0x0064 +#define CNST_0_48_Q4_12 0x07AE +#define CNST_1_00_Q4_12 0x1000 +#define CNST_0_85_Q4_12 0x0D9B +#define CNST_0_4_Q4_12 0x0666 +#define CNST_0_05_Q4_12 0x00CD +#define CNST_0_5882_Q1_15 0x4B4B +#define CNST_0_2857_Q1_15 0x2492 + + +#define HI_BYTE(a) ((a >> 8) & 0xFF) +#define LO_BYTE(a) (a & 0xFF); + + + + + +#endif diff --git a/imbe/imbe.h b/imbe/imbe.h new file mode 100644 index 0000000..e7f5f3a --- /dev/null +++ b/imbe/imbe.h @@ -0,0 +1,69 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _IMBE +#define _IMBE + +#include "typedef.h" + +#define FRAME 160 // Number samples in frame +#define NUM_HARMS_MAX 56 // Maximum number of harmonics +#define NUM_HARMS_MIN 9 // Minimum number of harmonics +#define NUM_BANDS_MAX 12 // Maximum number of bands +#define MAX_BLOCK_LEN 10 // Maximum length of block used during spectral amplitude encoding +#define NUM_PRED_RES_BLKS 6 // Number of Prediction Residual Blocks +#define PE_LPF_ORD 21 // Order of Pitch estimation LPF +#define PITCH_EST_FRAME 301 // Pitch estimation frame size + + +#define B_NUM (NUM_HARMS_MAX - 1) + + +typedef struct +{ + Word16 e_p; + Word16 pitch; // Q14.2 + Word16 ref_pitch; // Q8.8 + Word32 fund_freq; + Word16 num_harms; + Word16 num_bands; + Word16 v_uv_dsn[NUM_HARMS_MAX]; + Word16 b_vec[NUM_HARMS_MAX + 3]; + Word16 bit_alloc[B_NUM + 4]; + Word16 sa[NUM_HARMS_MAX]; + Word16 l_uv; + Word16 div_one_by_num_harm; + Word16 div_one_by_num_harm_sh; +} IMBE_PARAM; + +typedef struct +{ + Word16 re; + Word16 im; +} Cmplx16; + +#if 0 +void decode_init(IMBE_PARAM *imbe_param); +void decode(IMBE_PARAM *imbe_param, Word16 *frame_vector, Word16 *snd); +#endif + +#endif diff --git a/imbe/imbe_vocoder.cc b/imbe/imbe_vocoder.cc new file mode 100644 index 0000000..c932160 --- /dev/null +++ b/imbe/imbe_vocoder.cc @@ -0,0 +1,37 @@ +#include "imbe_vocoder_impl.h" +#include "imbe_vocoder.h" + +imbe_vocoder::imbe_vocoder() +{ + Impl = new imbe_vocoder_impl(); +} + +imbe_vocoder::~imbe_vocoder() +{ + delete Impl; +} + +void imbe_vocoder::imbe_encode(int16_t *frame_vector, int16_t *snd) +{ + Impl->imbe_encode(frame_vector, snd); +} + +void imbe_vocoder::imbe_decode(int16_t *frame_vector, int16_t *snd) +{ + Impl->imbe_decode(frame_vector, snd); +} + +void imbe_vocoder::encode_4400(int16_t *snd, uint8_t *imbe) +{ + Impl->encode_4400(snd, imbe); +} + +void imbe_vocoder::decode_4400(int16_t *snd, uint8_t *imbe) +{ + Impl->decode_4400(snd, imbe); +} + +const IMBE_PARAM* imbe_vocoder::param(void) +{ + return Impl->param(); +} diff --git a/imbe/imbe_vocoder.h b/imbe/imbe_vocoder.h new file mode 100644 index 0000000..908c572 --- /dev/null +++ b/imbe/imbe_vocoder.h @@ -0,0 +1,33 @@ +/* + * * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * * Version 1.0 (c) Copyright 2009 + * */ +/* -*- c++ -*- */ +#ifndef INCLUDED_IMBE_VOCODER_H +#define INCLUDED_IMBE_VOCODER_H + +#include +#include "imbe.h" + +class imbe_vocoder_impl; +class imbe_vocoder +{ +public: + imbe_vocoder(void); // constructor + ~imbe_vocoder(); // destructor + // imbe_encode compresses 160 samples (in unsigned int format) + // outputs u[] vectors as frame_vector[] + void imbe_encode(int16_t *frame_vector, int16_t *snd); + + // imbe_decode decodes IMBE codewords (frame_vector), + // outputs the resulting 160 audio samples (snd) + void imbe_decode(int16_t *frame_vector, int16_t *snd); + void encode_4400(int16_t *snd, uint8_t *imbe); + void decode_4400(int16_t *snd, uint8_t *imbe); + const IMBE_PARAM* param(void); + +private: + imbe_vocoder_impl *Impl; +}; +#endif /* INCLUDED_IMBE_VOCODER_H */ diff --git a/imbe/imbe_vocoder_impl.cc b/imbe/imbe_vocoder_impl.cc new file mode 100644 index 0000000..479388a --- /dev/null +++ b/imbe/imbe_vocoder_impl.cc @@ -0,0 +1,42 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + */ + +#include + +#include "imbe_vocoder_impl.h" + +imbe_vocoder_impl::imbe_vocoder_impl (void) : + prev_pitch(0), + prev_prev_pitch(0), + prev_e_p(0), + prev_prev_e_p(0), + seed(1), + num_harms_prev1(0), + num_harms_prev2(0), + num_harms_prev3(0), + fund_freq_prev(0), + th_max(0), + dc_rmv_mem(0) +{ + memset(wr_array, 0, sizeof(wr_array)); + memset(wi_array, 0, sizeof(wi_array)); + memset(pitch_est_buf, 0, sizeof(pitch_est_buf)); + memset(pitch_ref_buf, 0, sizeof(pitch_ref_buf)); + memset(pe_lpf_mem, 0, sizeof(pe_lpf_mem)); + memset(fft_buf, 0, sizeof(fft_buf)); + memset(sa_prev1, 0, sizeof(sa_prev1)); + memset(sa_prev2, 0, sizeof(sa_prev2)); + memset(uv_mem, 0, sizeof(uv_mem)); + memset(ph_mem, 0, sizeof(ph_mem)); + memset(vu_dsn_prev, 0, sizeof(vu_dsn_prev)); + memset(sa_prev3, 0, sizeof(sa_prev3)); + memset(v_uv_dsn, 0, sizeof(v_uv_dsn)); + + memset(&my_imbe_param, 0, sizeof(IMBE_PARAM)); + + decode_init(&my_imbe_param); + encode_init(); +} diff --git a/imbe/imbe_vocoder_impl.h b/imbe/imbe_vocoder_impl.h new file mode 100644 index 0000000..04d0e3a --- /dev/null +++ b/imbe/imbe_vocoder_impl.h @@ -0,0 +1,92 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + */ +/* -*- c++ -*- */ +#ifndef INCLUDED_IMBE_VOCODER_IMPL_H +#define INCLUDED_IMBE_VOCODER_IMPL_H + +#include +#include + +#include "imbe.h" +#include "dsp_sub.h" +#include "basic_op.h" +#include "math_sub.h" +#include "encode.h" +#include "decode.h" + +class imbe_vocoder_impl +{ +public: + imbe_vocoder_impl(void); // constructor + ~imbe_vocoder_impl() {} // destructor + // imbe_encode compresses 160 samples (in unsigned int format) + // outputs u[] vectors as frame_vector[] + void imbe_encode(int16_t *frame_vector, int16_t *snd) { + encode(&my_imbe_param, frame_vector, snd); + } + // imbe_decode decodes IMBE codewords (frame_vector), + // outputs the resulting 160 audio samples (snd) + void imbe_decode(int16_t *frame_vector, int16_t *snd) { + decode(&my_imbe_param, frame_vector, snd); + } + void encode_4400(int16_t *snd, uint8_t *imbe); + void decode_4400(int16_t *snd, uint8_t *imbe); + const IMBE_PARAM* param(void) {return &my_imbe_param;} +private: + IMBE_PARAM my_imbe_param; + + /* data items originally static (moved from individual c++ sources) */ + Word16 prev_pitch, prev_prev_pitch, prev_e_p, prev_prev_e_p; + UWord32 seed ; + Word16 num_harms_prev1; + Word32 sa_prev1[NUM_HARMS_MAX + 2]; + Word16 num_harms_prev2; + Word32 sa_prev2[NUM_HARMS_MAX + 2]; + Word16 uv_mem[105]; + UWord32 ph_mem[NUM_HARMS_MAX]; + Word16 num_harms_prev3; + Word32 fund_freq_prev; + Word16 vu_dsn_prev[NUM_HARMS_MAX]; + Word16 sa_prev3[NUM_HARMS_MAX]; + Word32 th_max; + Word16 v_uv_dsn[NUM_BANDS_MAX]; + Word16 wr_array[FFTLENGTH / 2 + 1]; + Word16 wi_array[FFTLENGTH / 2 + 1]; + Word16 pitch_est_buf[PITCH_EST_BUF_SIZE]; + Word16 pitch_ref_buf[PITCH_EST_BUF_SIZE]; + Word32 dc_rmv_mem; + Cmplx16 fft_buf[FFTLENGTH]; + Word16 pe_lpf_mem[PE_LPF_ORD]; + + /* member functions */ + void idct(Word16 *in, Word16 m_lim, Word16 i_lim, Word16 *out); + void dct(Word16 *in, Word16 m_lim, Word16 i_lim, Word16 *out); + void fft_init(void); + void fft(Word16 *datam1, Word16 nn, Word16 isign); + void encode(IMBE_PARAM *imbe_param, Word16 *frame_vector, Word16 *snd); + void parse(int argc, char **argv); + void pitch_est_init(void); + Word32 autocorr(Word16 *sigin, Word16 shift, Word16 scale_shift); + void e_p(Word16 *sigin, Word16 *res_buf); + void pitch_est(IMBE_PARAM *imbe_param, Word16 *frames_buf); + void sa_decode_init(void); + void sa_decode(IMBE_PARAM *imbe_param); + void sa_encode_init(void); + void sa_encode(IMBE_PARAM *imbe_param); + void uv_synt_init(void); + void uv_synt(IMBE_PARAM *imbe_param, Word16 *snd); + void v_synt_init(void); + void v_synt(IMBE_PARAM *imbe_param, Word16 *snd); + void pitch_ref_init(void); + Word16 voiced_sa_calc(Word32 num, Word16 den); + Word16 unvoiced_sa_calc(Word32 num, Word16 den); + void v_uv_det(IMBE_PARAM *imbe_param, Cmplx16 *fft_buf); + void decode_init(IMBE_PARAM *imbe_param); + void decode(IMBE_PARAM *imbe_param, Word16 *frame_vector, Word16 *snd); + void encode_init(void); +}; + +#endif /* INCLUDED_IMBE_VOCODER_IMPL_H */ diff --git a/imbe/math_sub.cc b/imbe/math_sub.cc new file mode 100644 index 0000000..6bbc2f8 --- /dev/null +++ b/imbe/math_sub.cc @@ -0,0 +1,355 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "basic_op.h" +#include "math_sub.h" + +//----------------------------------------------------------------------------- +// Table for routine Pow2() table[] = 2^(-1...0) +//----------------------------------------------------------------------------- +static const Word16 pow2_table[33] = +{ + 16384, 16743, 17109, 17484, 17867, 18258, 18658, 19066, 19484, 19911, + 20347, 20792, 21247, 21713, 22188, 22674, 23170, 23678, 24196, 24726, + 25268, 25821, 26386, 26964, 27554, 28158, 28774, 29405, 30048, 30706, + 31379, 32066, 32767 +}; + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes pow(2.0, x) +// +// INPUT: +// x - In signed Q10.22 format +// +// OUTPUT: +// None +// +// RETURN: +// Result in signed Q14.2 format +// +//----------------------------------------------------------------------------- +Word16 Pow2(Word32 x) +{ + Word16 exp, i, a, tmp; + Word32 L_x; + Word16 exponent, fraction; + + exponent = extract_h(L_shr(x, 6)); + if(exponent < 0) + exponent = add(exponent, 1); + fraction = extract_l(L_shr(L_sub(x, L_shl(L_deposit_l(exponent),6 + 16)), 7)); + + if(x < 0) + fraction = negate(fraction); + + L_x = L_mult(fraction, 32); // L_x = fraction<<6 + i = extract_h(L_x); // Extract b10-b16 of fraction + L_x = L_shr(L_x, 1); + a = extract_l(L_x); // Extract b0-b9 of fraction + a = a & (Word16)0x7fff; + + L_x = L_deposit_h (pow2_table[i]); // table[i] << 16 + tmp = sub(pow2_table[i], pow2_table[i + 1]); // table[i] - table[i+1] + L_x = L_msu(L_x, tmp, a); // L_x -= tmp*a*2 + + if(x < 0) + { + L_x = L_deposit_h(div_s(0x4000, extract_h(L_x))); // calculate 1/fraction + exponent = sub(exponent, 1); + } + + exp = sub(12, exponent); + L_x = L_shr_r(L_x, exp); + + return extract_h(L_x); +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Multiply a 32 bit number (L_var2) and a 16 bit +// number (var1) returning a 32 bit result. L_var2 +// is truncated to 31 bits prior to executing the +// multiply. +// +// INPUT: +// L_var2 - A Word32 input variable +// var1 - A Word16 input variable +// +// OUTPUT: +// None +// +// RETURN: +// A Word32 value +// +//----------------------------------------------------------------------------- +Word32 L_mpy_ls(Word32 L_var2, Word16 var1) +{ + Word32 L_varOut; + Word16 swtemp; + + swtemp = shr(extract_l(L_var2), 1); + swtemp = (Word16)32767 & (Word16) swtemp; + + L_varOut = L_mult(var1, swtemp); + L_varOut = L_shr(L_varOut, 15); + L_varOut = L_mac(L_varOut, var1, extract_h(L_var2)); + return (L_varOut); +} + +//----------------------------------------------------------------------------- +// Table for routine cos_fxp() +//----------------------------------------------------------------------------- +static const Word16 cos_table[129] = +{ + 32767, 32766, 32758, 32746, 32729, 32706, 32679, 32647, 32610, + 32568, 32522, 32470, 32413, 32352, 32286, 32214, 32138, 32058, + 31972, 31881, 31786, 31686, 31581, 31471, 31357, 31238, 31114, + 30986, 30853, 30715, 30572, 30425, 30274, 30118, 29957, 29792, + 29622, 29448, 29269, 29086, 28899, 28707, 28511, 28311, 28106, + 27897, 27684, 27467, 27246, 27020, 26791, 26557, 26320, 26078, + 25833, 25583, 25330, 25073, 24812, 24548, 24279, 24008, 23732, + 23453, 23170, 22884, 22595, 22302, 22006, 21706, 21403, 21097, + 20788, 20475, 20160, 19841, 19520, 19195, 18868, 18538, 18205, + 17869, 17531, 17190, 16846, 16500, 16151, 15800, 15447, 15091, + 14733, 14373, 14010, 13646, 13279, 12910, 12540, 12167, 11793, + 11417, 11039, 10660, 10279, 9896, 9512, 9127, 8740, 8351, + 7962, 7571, 7180, 6787, 6393, 5998, 5602, 5205, 4808, + 4410, 4011, 3612, 3212, 2811, 2411, 2009, 1608, 1206, + 804, 402, 0 +}; + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes the cosine of x whose value is expressed in radians/PI. +// +// INPUT: +// x - argument in Q1.15 +// +// OUTPUT: +// None +// +// RETURN: +// Result in Q1.15 +// +//----------------------------------------------------------------------------- +Word16 cos_fxp(Word16 x) +{ + Word16 tx, ty; + Word16 sign; + Word16 index1,index2; + Word16 m; + Word16 temp; + + sign = 0; + if(x < 0) + tx = negate(x); + else + tx = x; + + // if angle > pi/2, cos(angle) = -cos(pi-angle) + if(tx > X05_Q15) + { + tx = sub(ONE_Q15,tx); + sign = -1; + } + // convert input to be within range 0-128 + index1 = shr(tx,7); + index2 = add(index1,1); + + if (index1 == 128) + return (Word16)0; + + m = sub(tx,shl(index1,7)); + // convert decimal part to Q15 + m = shl(m,8); + + temp = sub(cos_table[index2],cos_table[index1]); + temp = mult(m,temp); + ty = add(cos_table[index1],temp); + + if(sign) + return negate(ty); + else + return ty; +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes the sinus of x whose value is expressed in radians/PI. +// +// INPUT: +// x - argument in Q1.15 +// +// OUTPUT: +// None +// +// RETURN: +// Result in Q1.15 +// +//----------------------------------------------------------------------------- +Word16 sin_fxp(Word16 x) +{ + Word16 tx, ty; + Word16 sign; + + sign = 0; + if(x < 0) + { + tx = negate(x); + sign = 1; + } + else + tx = x; + + if(tx > X05_Q15) + tx = sub(tx, X05_Q15); + else + tx = sub(X05_Q15,tx); + + ty = cos_fxp(tx); + + if(sign) + return negate(ty); + else + return ty; +} + + +//----------------------------------------------------------------------------- +// Table for routine sqrt_l_exp() +// table[] = sqrt((i+16)*2^-6) * 2^15, i.e. sqrt(x) scaled Q15 +//----------------------------------------------------------------------------- +static const Word16 sqrt_table[49] = +{ + 16384, 16888, 17378, 17854, 18318, 18770, 19212, 19644, 20066, 20480, + 20886, 21283, 21674, 22058, 22435, 22806, 23170, 23530, 23884, 24232, + 24576, 24915, 25249, 25580, 25905, 26227, 26545, 26859, 27170, 27477, + 27780, 28081, 28378, 28672, 28963, 29251, 29537, 29819, 30099, 30377, + 30652, 30924, 31194, 31462, 31727, 31991, 32252, 32511, 32767 +}; + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes sqrt(L_x), where L_x is positive. +// +// INPUT: +// L_x - argument in Q1.31 +// *exp - pointer to save denormalization exponent +// OUTPUT: +// Right shift to be applied to result, Q16.0 +// +// RETURN: +// Result in Q1.31 +// Right shift should be applied to it! +// +//----------------------------------------------------------------------------- +Word32 sqrt_l_exp(Word32 L_x, Word16 *exp) +{ + Word16 e, i, a, tmp; + Word32 L_y; + + if(L_x <= (Word32)0) + { + *exp = 0; + return (Word32)0; + } + + e = norm_l(L_x) & 0xFFFE; // get next lower EVEN norm. exp + L_x = L_shl(L_x, e); // L_x is normalized to [0.25..1) + *exp = e >> 1; // return 2*exponent (or Q1) + + L_x = L_shr(L_x, 9); + i = extract_h(L_x); // Extract b25-b31, 16 <= i <= 63 because of normalization + L_x = L_shr(L_x, 1); + a = extract_l(L_x); // Extract b10-b24 + a = a & (Word16)0x7fff; + + i = sub(i, 16); // 0 <= i <= 47 + + L_y = L_deposit_h(sqrt_table[i]); // table[i] << 16 + tmp = sub(sqrt_table[i], sqrt_table[i + 1]); // table[i] - table[i+1]) + L_y = L_msu(L_y, tmp, a); // L_y -= tmp*a*2 + + return L_y; +} + +//----------------------------------------------------------------------------- +// Table for routine Log2() +//----------------------------------------------------------------------------- +static const Word16 log_table[33] = +{ + 0, 1455, 2866, 4236, 5568, 6863, 8124, 9352, 10549, 11716, + 12855, 13967, 15054, 16117, 17156, 18172, 19167, 20142, 21097, 22033, + 22951, 23852, 24735, 25603, 26455, 27291, 28113, 28922, 29716, 30497, + 31266, 32023, 32767 +}; + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes log2 of x +// +// INPUT: +// x - argument in Q14.2 +// +// OUTPUT: +// None +// +// RETURN: +// Result in Q10.22 +// +//----------------------------------------------------------------------------- +Word32 Log2(Word16 x) +{ + Word16 exp, i, a, tmp; + Word32 L_y; + + if(x <= (Word16)0) + return 0; + + exp = norm_s(x); + x = shl(x, exp); + + i = shr(x, 9); // Extract b15-b9 + a = shl(x & 0x1FF, 6); // Extract b8-b0 + i = sub (i, 32); + + L_y = L_deposit_h(log_table[i]); // table[i] << 16 + tmp = sub(log_table[i], log_table[i + 1]); // table[i] - table[i+1] + L_y = L_msu(L_y, tmp, a); // L_y -= tmp*a*2 + + L_y = L_shr(L_y, 9); + + exp = sub(12, exp); + L_y = L_add(L_y, L_deposit_h(shl(exp, 6))); + + return L_y; +} + + + + + + + + + diff --git a/imbe/math_sub.h b/imbe/math_sub.h new file mode 100644 index 0000000..baf75fe --- /dev/null +++ b/imbe/math_sub.h @@ -0,0 +1,130 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _MATH_SUB +#define _MATH_SUB + +#define X05_Q15 16384 // (0.5*(1<<15)) +#define ONE_Q15 32767 // ((1<<15)-1) + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes the cosine of x whose value is expressed in radians/PI. +// +// INPUT: +// x - argument in Q1.15 +// +// OUTPUT: +// None +// +// RETURN: +// Result in Q1.15 +// +//----------------------------------------------------------------------------- +Word16 cos_fxp(Word16 x); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes the sinus of x whose value is expressed in radians/PI. +// +// INPUT: +// x - argument in Q1.15 +// +// OUTPUT: +// None +// +// RETURN: +// Result in Q1.15 +// +//----------------------------------------------------------------------------- +Word16 sin_fxp(Word16 x); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Multiply a 32 bit number (L_var2) and a 16 bit +// number (var1) returning a 32 bit result. L_var2 +// is truncated to 31 bits prior to executing the +// multiply. +// +// INPUT: +// L_var2 - A Word32 input variable +// var1 - A Word16 input variable +// +// OUTPUT: +// None +// +// RETURN: +// A Word32 value +// +//----------------------------------------------------------------------------- +Word32 L_mpy_ls(Word32 L_var2, Word16 var1); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes pow(2.0, x) +// +// INPUT: +// x - In signed Q10.22 format +// +// OUTPUT: +// None +// +// RETURN: +// Result in signed Q14.2 format +// +//----------------------------------------------------------------------------- +Word16 Pow2 (Word32 x); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes sqrt(L_x), where L_x is positive. +// +// INPUT: +// L_x - argument in Q1.31 +// *exp - pointer to save denormalization exponent +// OUTPUT: +// Right shift to be applied to result, Q16.0 +// +// RETURN: +// Result in Q1.31 +// Right shift should be applied to it! +// +//----------------------------------------------------------------------------- +Word32 sqrt_l_exp (Word32 L_x, Word16 *exp); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Computes log2 of x +// +// INPUT: +// x - argument in Q14.2 +// +// OUTPUT: +// None +// +// RETURN: +// Result in Q10.22 +// +//----------------------------------------------------------------------------- +Word32 Log2(Word16 x); + +#endif diff --git a/imbe/pe_lpf.cc b/imbe/pe_lpf.cc new file mode 100644 index 0000000..b16547b --- /dev/null +++ b/imbe/pe_lpf.cc @@ -0,0 +1,74 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "aux_sub.h" +#include "basic_op.h" +#include "math_sub.h" +#include "pe_lpf.h" + + + +static const Word16 lpf_coef[PE_LPF_ORD] = +{ + -94, -92, 185, 543, 288, -883, -1834, -495, 3891, 9141, 11512, + 9141, 3891, -495, -1834, -883, 288, 543, 185, -92, -94 +}; + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Low-pass filter for pitch estimator +// +// +// INPUT: +// *sigin - pointer to input signal buffer +// *sigout - pointer to output signal buffer +// *mem - pointer to filter's memory element +// len - number of input signal samples +// +// OUTPUT: +// None +// +// RETURN: +// Saved filter state in mem +// +//----------------------------------------------------------------------------- +void pe_lpf(Word16 *sigin, Word16 *sigout, Word16 *mem, Word16 len) +{ + Word16 i; + Word32 L_sum; + + while(len--) + { + for(i = 0; i < PE_LPF_ORD - 1; i++) + mem[i] = mem[i + 1]; + mem[PE_LPF_ORD - 1] = *sigin++; + + L_sum = 0; + for(i = 0; i < PE_LPF_ORD; i++) + L_sum = L_mac(L_sum, mem[i], lpf_coef[i]); + + *sigout++ = round(L_sum); + } +} diff --git a/imbe/pe_lpf.h b/imbe/pe_lpf.h new file mode 100644 index 0000000..54fd017 --- /dev/null +++ b/imbe/pe_lpf.h @@ -0,0 +1,47 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#ifndef _PE_LPF +#define _PE_LPF + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Low-pass filter for pitch estimator +// +// +// INPUT: +// *sigin - pointer to input signal buffer +// *sigout - pointer to output signal buffer +// *mem - pointer to filter's memory element +// len - number of input signal samples +// +// OUTPUT: +// None +// +// RETURN: +// Saved filter state in mem +// +//----------------------------------------------------------------------------- +void pe_lpf(Word16 *sigin, Word16 *sigout, Word16 *mem, Word16 len); + + +#endif diff --git a/imbe/pitch_est.cc b/imbe/pitch_est.cc new file mode 100644 index 0000000..dba94d5 --- /dev/null +++ b/imbe/pitch_est.cc @@ -0,0 +1,350 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "basic_op.h" +#include "aux_sub.h" +#include "math_sub.h" +#include "tbls.h" +#include "pitch_est.h" +#include "encode.h" +#include "dsp_sub.h" +#include "imbe_vocoder_impl.h" + + + +static const UWord16 min_max_tbl[203] = +{ + 0x0008, 0x0009, 0x000a, 0x000c, 0x000d, 0x000e, 0x000f, 0x0010, 0x0012, 0x0013, + 0x0014, 0x0115, 0x0216, 0x0218, 0x0319, 0x041a, 0x051b, 0x061c, 0x061e, 0x071f, + 0x0820, 0x0921, 0x0a22, 0x0a24, 0x0b25, 0x0c26, 0x0d27, 0x0e28, 0x0e2a, 0x0f2b, + 0x102c, 0x112d, 0x122e, 0x1230, 0x1331, 0x1432, 0x1533, 0x1634, 0x1636, 0x1737, + 0x1838, 0x1939, 0x1a3a, 0x1a3c, 0x1b3d, 0x1c3e, 0x1d3f, 0x1e40, 0x1e42, 0x1f43, + 0x2044, 0x2145, 0x2246, 0x2248, 0x2349, 0x244a, 0x254b, 0x264c, 0x264e, 0x274f, + 0x2850, 0x2951, 0x2a52, 0x2a54, 0x2b55, 0x2c56, 0x2d57, 0x2e58, 0x2e5a, 0x2f5b, + 0x305c, 0x315d, 0x325e, 0x3260, 0x3361, 0x3462, 0x3563, 0x3664, 0x3666, 0x3767, + 0x3868, 0x3969, 0x3a6a, 0x3a6c, 0x3b6d, 0x3c6e, 0x3d6f, 0x3e70, 0x3e72, 0x3f73, + 0x4074, 0x4175, 0x4276, 0x4278, 0x4379, 0x447a, 0x457b, 0x467c, 0x467e, 0x477f, + 0x4880, 0x4981, 0x4a82, 0x4a84, 0x4b85, 0x4c86, 0x4d87, 0x4e88, 0x4e8a, 0x4f8b, + 0x508c, 0x518d, 0x528e, 0x5290, 0x5391, 0x5492, 0x5593, 0x5694, 0x5696, 0x5797, + 0x5898, 0x5999, 0x5a9a, 0x5a9c, 0x5b9d, 0x5c9e, 0x5d9f, 0x5ea0, 0x5ea2, 0x5fa3, + 0x60a4, 0x61a5, 0x62a6, 0x62a8, 0x63a9, 0x64aa, 0x65ab, 0x66ac, 0x66ae, 0x67af, + 0x68b0, 0x69b1, 0x6ab2, 0x6ab4, 0x6bb5, 0x6cb6, 0x6db7, 0x6eb8, 0x6eba, 0x6fbb, + 0x70bc, 0x71bd, 0x72be, 0x72c0, 0x73c1, 0x74c2, 0x75c3, 0x76c4, 0x76c6, 0x77c7, + 0x78c8, 0x79c9, 0x7aca, 0x7aca, 0x7bca, 0x7cca, 0x7dca, 0x7eca, 0x7eca, 0x7fca, + 0x80ca, 0x81ca, 0x82ca, 0x82ca, 0x83ca, 0x84ca, 0x85ca, 0x86ca, 0x86ca, 0x87ca, + 0x88ca, 0x89ca, 0x8aca, 0x8aca, 0x8bca, 0x8cca, 0x8dca, 0x8eca, 0x8eca, 0x8fca, + 0x90ca, 0x91ca, 0x92ca, 0x92ca, 0x93ca, 0x94ca, 0x95ca, 0x96ca, 0x96ca, 0x97ca, + 0x98ca, 0x99ca, 0x9aca +}; + + + + + +void imbe_vocoder_impl::pitch_est_init(void) +{ + prev_pitch = prev_prev_pitch = 158; // 100 + prev_e_p = prev_prev_e_p = 0; +} + + + +Word32 imbe_vocoder_impl::autocorr(Word16 *sigin, Word16 shift, Word16 scale_shift) +{ + Word32 L_sum; + Word16 i; + + L_sum = 0; + for(i = 0; i < PITCH_EST_FRAME - shift; i++) + L_sum = L_add(L_sum, L_shr(L_mult(sigin[i], sigin[i + shift]), scale_shift) ); + + return L_sum; +} + + + +void imbe_vocoder_impl::e_p(Word16 *sigin, Word16 *res_buf) +{ + Word16 i, j, den_part_acc, tmp; + Word32 L_sum, L_num, L_den, L_e0, L_tmp; + Word16 sig_wndwed[PITCH_EST_FRAME]; + Word32 corr[259]; + Word16 index_beg, index_step; + Word16 scale_shift; + + + // Windowing input signal s * wi^2 + for(i = 0 ; i < PITCH_EST_FRAME; i++) + sig_wndwed[i] = mult_r(sigin[i], wi[i]); + + L_sum = 0; + for(i = 0 ; i < PITCH_EST_FRAME; i++) + L_sum = L_add(L_sum, L_mpy_ls( L_mult(sigin[i], sigin[i]), wi[i]) ); // sum(s^2 * wi^2) + + // Check for the overflow + if(L_sum == MAX_32) + { + // Recalculate with scaling + L_sum = 0; + for(i = 0 ; i < PITCH_EST_FRAME; i++) + L_sum = L_add(L_sum, L_mpy_ls( L_shr(L_mult(sigin[i], sigin[i]), 5), wi[i])); + scale_shift = 5; + } + else + scale_shift = 0; + + L_e0 = 0; + for(i = 0 ; i < PITCH_EST_FRAME; i++) + L_e0 = L_add(L_e0, L_shr( L_mult(sig_wndwed[i], sig_wndwed[i]), scale_shift)); // sum(s^2 * wi^4) + + // Calculate correlation for time shift in range 21...150 with step 0.5 + // For integer shifts + for(tmp = 21, i = 0; tmp <= 150; tmp++, i += 2) + corr[i] = autocorr(sig_wndwed, tmp, scale_shift); + // For intermediate shifts + for(i = 1; i < 258; i += 2) + corr[i] = L_shr( L_add(corr[i - 1], corr[i + 1]), 1); + + + // variable to calculate 1 - P * sum(wi ^4) in denominator + den_part_acc = CNST_0_8717_Q1_15; + + index_step = 42; // Note: 42 = 21 in Q15.1 format, so index_step will be used also as p in Q15.1 format + index_beg = 0; + L_e0 = L_shr(L_e0, 7); // divide by 64 to compensate wi scaling + // p = 21...122 by step 0.5 + for(i = 0; i < 203; i++) + { + + // Calculate sum( corr ( n * p) ) + L_tmp = 0; + j = index_beg; + while(j <= 258) + { + L_tmp = L_add(L_tmp, corr[j]); + j += index_step; + } + + L_tmp = L_shr(L_tmp, 6); // compensate wi scaling + L_tmp = L_add(L_tmp, L_e0); // For n = 0 + L_tmp = L_tmp * index_step; + L_num = L_sub(L_sum, L_tmp); + + index_beg++; + index_step++; + + L_den = L_mpy_ls(L_sum, den_part_acc); + + if(L_num < L_den && L_den != 0) + { + //res_buf[i] = (Word16)((double)L_num/(double)L_den * 4096.); // Q4.12 + + if(L_num <= 0) + res_buf[i] = 0; + else + { + tmp = norm_l(L_den); + tmp = div_s(extract_h(L_shl(L_num, tmp)), extract_h(L_shl(L_den, tmp))); + res_buf[i] = shr(tmp, 3); // convert to Q4.12 + } + } + else if(L_num >= L_den) + { + res_buf[i] = CNST_1_00_Q4_12; + //res_buf[i] = (Word16)((double)L_num/(double)L_den * 4096.); // Q4.12 + } + else + res_buf[i] = CNST_1_00_Q4_12; + + den_part_acc = sub(den_part_acc, CNST_0_0031_Q1_15); + } +} + + + + +void imbe_vocoder_impl::pitch_est(IMBE_PARAM *imbe_param, Word16 *frames_buf) +{ + Word16 e_p_arr0[203], e_p_arr1[203], e_p_arr2[203], e1p1_e2p2_est_save[203]; + Word16 min_index, max_index, p, i, p_index; + UWord16 tmp=0, p_fp; + UWord32 UL_tmp; + Word16 e_p_cur, pb, pf, ceb, s_tmp; + Word16 cef_est, cef, p0_est, p0, p1, p2, p1_max_index, p2_max_index, e1p1_e2p2_est, e1p1_e2p2; + Word16 e_p_arr2_min[203]; + + // Calculate E(p) function for current and two future frames + e_p(&frames_buf[0], e_p_arr0); + + // Look-Back Pitch Tracking + min_index = HI_BYTE(min_max_tbl[prev_pitch]); + max_index = LO_BYTE(min_max_tbl[prev_pitch]); + + p = pb = min_index; + e_p_cur = e_p_arr0[min_index]; + while(++p <= max_index) + if(e_p_arr0[p] < e_p_cur) + { + e_p_cur = e_p_arr0[p]; + pb = p; + } + ceb = add(e_p_cur, add(prev_e_p, prev_prev_e_p)); + + + if(ceb <= CNST_0_48_Q4_12) + { + prev_prev_pitch = prev_pitch; + prev_pitch = pb; + prev_prev_e_p = prev_e_p; + prev_e_p = e_p_arr0[pb]; + + imbe_param->pitch = pb + 42; // Result in Q15.1 format + imbe_param->e_p = prev_e_p; + return; + } + + + // Look-Ahead Pitch Tracking + e_p(&frames_buf[FRAME], e_p_arr1); + e_p(&frames_buf[2 * FRAME], e_p_arr2); + + p0_est = p0 = 0; + cef_est = e_p_arr0[p0] + e_p_arr1[p0] + e_p_arr2[p0]; + e1p1_e2p2 = 1; + + p1 = 0; + while(p1 < 203) + { + p2 = HI_BYTE(min_max_tbl[p1]); + p2_max_index = LO_BYTE(min_max_tbl[p1]); + s_tmp = e_p_arr2[p1]; + while(p2 <= p2_max_index) + { + if(e_p_arr2[p2] < s_tmp) + s_tmp = e_p_arr2[p2]; + p2++; + } + e_p_arr2_min[p1] = s_tmp; + p1++; + } + while(p0 < 203) + { + e1p1_e2p2_est = e_p_arr1[p0] + e_p_arr2_min[p0]; + p1 = HI_BYTE(min_max_tbl[p0]); + p1_max_index = LO_BYTE(min_max_tbl[p0]); + while(p1 <= p1_max_index) + { + if(add(e_p_arr1[p1], e_p_arr2_min[p1]) < e1p1_e2p2_est) + e1p1_e2p2_est = add(e_p_arr1[p1], e_p_arr2_min[p1]); + p1++; + } + e1p1_e2p2_est_save[p0] = e1p1_e2p2_est; + cef = add(e_p_arr0[p0], e1p1_e2p2_est); + if(cef < cef_est) + { + cef_est = cef; + p0_est = p0; + } + p0++; + } + + pf = p0_est; + // Sub-multiples analysis + if(pf >= 42) // Check if Sub-multiples are possible + { + if(pf < 84) + i = 1; + else if(pf < 126) + i = 2; + else if(pf < 168) + i = 3; + else + i = 4; + + p_fp = (pf + 42) << 8; // Convert pitch estimation from array index to unsigned Q7.19 format + + while(i--) + { + switch(i) + { + case 0: + tmp = p_fp >> 1; // P_est/2 + break; + + case 1: + UL_tmp = (UWord32)p_fp * 0x5555; // P_est/3 + tmp = UL_tmp >> 16; + break; + + case 2: + tmp = p_fp >> 2; // P_est/4 + break; + + case 3: + UL_tmp = (UWord32)p_fp * 0x3333; // P_est/5 + tmp = UL_tmp >> 16; + break; + } + + p_index = ((tmp + 0x0080) >> 8) - 42; // Convert fixed-point pitch value to integer array index with rounding + + cef = add(e_p_arr0[p_index], e1p1_e2p2_est_save[p_index]); + + if(cef <= CNST_0_85_Q4_12 && mult_r(cef, CNST_0_5882_Q1_15) <= cef_est) // 1/1.7 = 0.5882 + { + pf = p_index; + break; + } + + if(cef <= CNST_0_4_Q4_12 && mult_r(cef, CNST_0_2857_Q1_15) <= cef_est) // 1/3.5 = 0.2857 + { + pf = p_index; + break; + } + + if(cef <= CNST_0_05_Q4_12) + { + pf = p_index; + break; + } + } + } + + cef = add(e_p_arr0[pf], e1p1_e2p2_est_save[pf]); + + if(ceb <= cef) + p = pb; + else + p = pf; + + prev_prev_pitch = prev_pitch; + prev_pitch = p; + prev_prev_e_p = prev_e_p; + prev_e_p = e_p_arr0[p]; + + + imbe_param->pitch = p + 42; // Result in Q15.1 format + imbe_param->e_p = prev_e_p; +} diff --git a/imbe/pitch_est.h b/imbe/pitch_est.h new file mode 100644 index 0000000..b6b052d --- /dev/null +++ b/imbe/pitch_est.h @@ -0,0 +1,29 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _PITCH_EST +#define _PITCH_EST + +void pitch_est_init(void); +void pitch_est(IMBE_PARAM *imbe_param, Word16 *frames_buf); + +#endif diff --git a/imbe/pitch_ref.cc b/imbe/pitch_ref.cc new file mode 100644 index 0000000..85c5a13 --- /dev/null +++ b/imbe/pitch_ref.cc @@ -0,0 +1,167 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "basic_op.h" +#include "aux_sub.h" +#include "math_sub.h" +#include "dsp_sub.h" +#include "tbls.h" +#include "pitch_ref.h" + +#include +#include +#include + + +#define PITCH_REF_FRAME 221 +#define MIN_INDEX 50 + + + + +void pitch_ref(IMBE_PARAM *imbe_param, Cmplx16 *fft_buf) +{ + Word16 i, j, index_a_save, pitch_est, tmp, shift, index_wr, up_lim; + Cmplx16 sp_rec[FFTLENGTH/2]; + Word32 fund_freq, fund_freq_2, fund_freq_acc_a, fund_freq_acc_b, fund_freq_acc, L_tmp, amp_re_acc, amp_im_acc, L_sum, L_diff_min; + Word16 ha, hb, index_a, index_b, index_tbl[20], it_ind, re_tmp, im_tmp, pitch_cand=0; + Word32 fund_freq_cand=0; + + + pitch_est = shl(imbe_param->pitch, 7); // Convert to Q8.8 + pitch_est = sub(pitch_est, CNST_1_125_Q8_8); // Sub 1.125 = 9/8 + + L_diff_min = MAX_32; + for(i = 0; i < 19; i++) + { + shift = norm_s(pitch_est); + tmp = shl(pitch_est, shift); + tmp = div_s(0x4000, tmp); + fund_freq = L_shl(tmp, shift + 11); + + fund_freq_acc = fund_freq; + fund_freq_2 = L_shr(fund_freq, 1); + fund_freq_acc_a = L_sub(fund_freq, fund_freq_2); + fund_freq_acc_b = L_add(fund_freq, fund_freq_2); + + // Calculate upper limit for spectrum reconstruction + up_lim = extract_h(L_shr((UWord32)CNST_0_9254_Q0_16 * pitch_est, 1)); // 0.9254/fund_freq + up_lim = sub(up_lim, CNST_0_5_Q8_8); // sub 0.5 + up_lim = up_lim & 0xFF00; // extract fixed part + up_lim = mult(up_lim, extract_h(fund_freq)); + up_lim = shr(up_lim, 1); + + index_b = 0; + while(index_b <= up_lim) + { + ha = extract_h(fund_freq_acc_a); + hb = extract_h(fund_freq_acc_b); + index_a = (ha >> 8) + ((ha & 0xFF)?1:0); + index_b = (hb >> 8) + ((hb & 0xFF)?1:0); + + if(index_b >= MIN_INDEX) + { + L_tmp = L_shl(L_deposit_h(index_a), 8); + L_tmp = L_sub(L_tmp, fund_freq_acc); + L_tmp = L_add(L_tmp, 0x00020000); // for rounding purpose + L_tmp = L_shr(L_tmp, 2); + + index_a_save = index_a; + it_ind = 0; + + amp_re_acc = amp_im_acc = 0; + while(index_a < index_b) + { + index_wr = extract_h(L_tmp); + if(index_wr < 0 && (L_tmp & 0xFFFF)) // truncating for negative number + index_wr = add(index_wr, 1); + index_wr = add(index_wr, 160); + index_tbl[it_ind++] = index_wr; + if(index_wr >= 0 && index_wr <= 320) + { + amp_re_acc = L_mac(amp_re_acc, fft_buf[index_a].re, wr_sp[index_wr]); + amp_im_acc = L_mac(amp_im_acc, fft_buf[index_a].im, wr_sp[index_wr]); + } + + index_a++; + L_tmp = L_add(L_tmp, 0x400000); + } + + it_ind = 0; + index_a = index_a_save; + while(index_a < index_b) + { + index_wr = index_tbl[it_ind++]; + if(index_wr < 0 || index_wr > 320) + { + sp_rec[index_a].im = sp_rec[index_a].re = 0; + } + else + { + sp_rec[index_a].im = mult(mult(extract_h(amp_im_acc), wr_sp[index_wr]), 0x6666); + sp_rec[index_a].re = mult(mult(extract_h(amp_re_acc), wr_sp[index_wr]), 0x6666); + } + + index_a++; + } + } + + fund_freq_acc_a = L_add(fund_freq_acc_a, fund_freq); + fund_freq_acc_b = L_add(fund_freq_acc_b, fund_freq); + fund_freq_acc = L_add(fund_freq_acc, fund_freq); + } + + L_sum = 0; + for(j = MIN_INDEX; j <= up_lim; j++) + { + re_tmp = sub(fft_buf[j].re, sp_rec[j].re); + im_tmp = sub(fft_buf[j].im, sp_rec[j].im); + L_sum = L_mac(L_sum, re_tmp, re_tmp); + L_sum = L_mac(L_sum, im_tmp, im_tmp); + } + + if(L_sum < L_diff_min) + { + L_diff_min = L_sum; + pitch_cand = pitch_est; + fund_freq_cand = fund_freq; + } + + pitch_est = add(pitch_est, CNST_0_125_Q8_8); // Add 0.125 = 1/8 + } + + imbe_param->ref_pitch = pitch_cand; + imbe_param->fund_freq = fund_freq_cand; +} + + + + + + + + + + diff --git a/imbe/pitch_ref.h b/imbe/pitch_ref.h new file mode 100644 index 0000000..3a72b7f --- /dev/null +++ b/imbe/pitch_ref.h @@ -0,0 +1,28 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _PITCH_REF +#define _PITCH_REF + +void pitch_ref(IMBE_PARAM *imbe_param, Cmplx16 *fft_buf); + +#endif diff --git a/imbe/qnt_sub.cc b/imbe/qnt_sub.cc new file mode 100644 index 0000000..bd0cbe8 --- /dev/null +++ b/imbe/qnt_sub.cc @@ -0,0 +1,144 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#include "typedef.h" +#include "basic_op.h" +#include "qnt_sub.h" + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Dequantize by quantizer step size +// +// +// INPUT: +// qval - quantized value +// step_size - step size used to quantize in unsigned Q0.16 format +// bit_num - the number of bits +// +// OUTPUT: +// None +// +// RETURN: +// Quantized Value in signed (bit_num).16 format +// +//----------------------------------------------------------------------------- +Word32 deqnt_by_step(Word16 qval, UWord16 step_size, Word16 bit_num) +{ + Word32 res; + + if(bit_num == 0) + return (Word32)0; + + res = (Word32)step_size * (qval - (1 << (bit_num - 1))); + res = L_add(res, ((Word32)step_size * CNST_0_5_Q0_16) >> 16); + + return res; +} + + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Quantize by quantizer step size +// +// +// INPUT: +// val - value to be quantized in Q5.10 format +// step_size - step size used to quantize in unsigned Q0.16 format +// bit_num - the number of bits +// +// OUTPUT: +// None +// +// RETURN: +// Quantized Value in integer +// +//----------------------------------------------------------------------------- +Word16 qnt_by_step(Word16 val, UWord16 step_size, Word16 bit_num) +{ + Word16 index, min_val, max_val; + Word16 q_index, shift, tmp; + + shift = norm_s(step_size); + + tmp = div_s(0x4000, shl(step_size, shift)); // Remark: To get result in Qxx.16 format it is necessary left shift tmp by (shift + 3) + q_index = shr_r(mult(val, tmp), sub(9, shift)); // q_index here is rounded to the nearest integer + + max_val = 1 << (bit_num - 1); + min_val = negate(max_val); + + if(q_index < min_val) + index = 0; + else if(q_index >= max_val) + index = (1 << bit_num) - 1; + else + index = max_val + q_index; + + return index; +} + +//----------------------------------------------------------------------------- +// PURPOSE: +// Quantize by table +// +// +// INPUT: +// val - value to be quantized +// q_tbl - pointer to table +// q_tbl_size - size of table +// +// OUTPUT: +// None +// +// RETURN: +// Quantized Value in integer +// +//----------------------------------------------------------------------------- +Word16 tbl_quant(Word16 val, Word16 *q_tbl, Word16 q_tbl_size) +{ + Word16 min_index, max_index, index; + + min_index = 0; + max_index = q_tbl_size - 1; + + if(val >= q_tbl[max_index]) + return max_index; + + if(val <= q_tbl[min_index]) + return min_index; + + while(max_index - min_index != 1) + { + index = min_index + ((max_index - min_index) >> 1); + + if(q_tbl[index] > val) + max_index = index; + else + min_index = index; + } + + if(q_tbl[max_index] - val <= val - q_tbl[min_index]) + return max_index; + else + return min_index; +} diff --git a/imbe/qnt_sub.h b/imbe/qnt_sub.h new file mode 100644 index 0000000..ee3ac1c --- /dev/null +++ b/imbe/qnt_sub.h @@ -0,0 +1,86 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#ifndef _QNT_SUB +#define _QNT_SUB + + +#define CNST_0_5_Q0_16 0x8000 + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Dequantize by quantizer step size +// +// +// INPUT: +// qval - quantized value +// step_size - step size used to quantize in unsigned Q0.16 format +// bit_num - the number of bits +// +// OUTPUT: +// None +// +// RETURN: +// Quantized Value in signed (bit_num).16 format +// +//----------------------------------------------------------------------------- +Word32 deqnt_by_step(Word16 qval, UWord16 step_size, Word16 bit_num); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Quantize by quantizer step size +// +// +// INPUT: +// val - value to be quantized +// step_size - step size used to quantize in unsigned Q0.16 format +// bit_num - the number of bits +// +// OUTPUT: +// None +// +// RETURN: +// Quantized Value in integer +// +//----------------------------------------------------------------------------- +Word16 qnt_by_step(Word16 val, UWord16 step_size, Word16 bit_num); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Quantize by table +// +// +// INPUT: +// val - value to be quantized +// q_tbl - pointer to table +// q_tbl_size - size of table +// +// OUTPUT: +// None +// +// RETURN: +// Quantized Value in integer +// +//----------------------------------------------------------------------------- +Word16 tbl_quant(Word16 val, Word16 *q_tbl, Word16 q_tbl_size); + +#endif diff --git a/imbe/rand_gen.cc b/imbe/rand_gen.cc new file mode 100644 index 0000000..b818d64 --- /dev/null +++ b/imbe/rand_gen.cc @@ -0,0 +1,61 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + + +#include "typedef.h" +#include "basic_op.h" + +static UWord32 seed = 1; + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Generate pseudo-random numbers in range -1...1 +// +// +// INPUT: +// None +// +// OUTPUT: +// None +// +// RETURN: +// Pseudo-random number in signed Q1.16 format +// +//----------------------------------------------------------------------------- +Word16 rand_gen(void) +{ + UWord32 hi, lo; + + lo = 16807 * (seed & 0xFFFF); + hi = 16807 * (seed >> 16); + + lo += (Word32)(hi & 0x7FFF) << 16; + lo += (hi >> 15); + + if(lo > 0x7FFFFFFF) + lo -= 0x7FFFFFFF; + + seed = lo; + + return (Word16)lo; +} diff --git a/imbe/rand_gen.h b/imbe/rand_gen.h new file mode 100644 index 0000000..f67d15e --- /dev/null +++ b/imbe/rand_gen.h @@ -0,0 +1,44 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _RAND_GEN +#define _RAND_GEN + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Generate pseudo-random numbers in range -1...1 +// +// +// INPUT: +// None +// +// OUTPUT: +// None +// +// RETURN: +// Pseudo-random number in signed Q1.16 format +// +//----------------------------------------------------------------------------- +Word16 rand_gen(void); + +#endif diff --git a/imbe/sa_decode.cc b/imbe/sa_decode.cc new file mode 100644 index 0000000..94d8f46 --- /dev/null +++ b/imbe/sa_decode.cc @@ -0,0 +1,200 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + + +#include "typedef.h" +#include "globals.h" +#include "basic_op.h" +#include "imbe.h" +#include "tbls.h" +#include "qnt_sub.h" +#include "sa_decode.h" +#include "aux_sub.h" +#include "dsp_sub.h" +#include "math_sub.h" +#include "encode.h" +#include "imbe_vocoder_impl.h" + + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Initialization of Spectral Amplitude Decoder +// +// +// INPUT: +// None +// +// OUTPUT: +// None +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +void imbe_vocoder_impl::sa_decode_init(void) +{ + num_harms_prev1 = 30; + v_zap((Word16 *)sa_prev1, 2 * (NUM_HARMS_MAX + 2)); +} + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Perform Spectral Amplitude Decoding +// +// +// INPUT: +// IMBE_PARAM *imbe_param - pointer to IMBE_PARAM structure with +// valid num_harms and b_vec items +// +// OUTPUT: +// None +// +// RETURN: +// Decoded Spectral Amplitudes +// +//----------------------------------------------------------------------------- +void imbe_vocoder_impl::sa_decode(IMBE_PARAM *imbe_param) +{ + Word16 gain_vec[6], gain_r[6]; + UWord16 index, index_1, num_harms; + Word16 *gss_ptr, *ba_ptr, i, j, *t_vec_ptr, *b_vec_ptr; + Word16 t_vec[NUM_HARMS_MAX], c_vec[MAX_BLOCK_LEN]; + UWord32 lmprbl_item; + Word16 bl_len, step_size, num_bits, tmp, ro_coef, si_coef, tmp1; + UWord32 k_coef, k_acc; + Word32 sum, tmp_word32, sa_tmp[NUM_HARMS_MAX]; + Word16 *sa; + + num_harms = imbe_param->num_harms; + index = num_harms - NUM_HARMS_MIN; + ba_ptr = imbe_param->bit_alloc; + b_vec_ptr = &imbe_param->b_vec[2]; + sa = imbe_param->sa; + + // Decoding the Gain Vector. gain_vec has signed Q5.11 format + gss_ptr = (Word16 *)&gain_step_size_tbl[index * 5]; + gain_vec[0] = gain_qnt_tbl[*b_vec_ptr++]; + + for(i = 1; i < 6; i++) + gain_vec[i] = extract_l(L_shr(deqnt_by_step(*b_vec_ptr++, *gss_ptr++, *ba_ptr++), 5)); + idct(gain_vec, NUM_PRED_RES_BLKS, NUM_PRED_RES_BLKS, gain_r); + + lmprbl_item = lmprbl_tbl[index]; + v_zap(t_vec, NUM_HARMS_MAX); + + // Decoding the Higher Order DCT Coefficients + t_vec_ptr = t_vec; + for(i = 0; i < NUM_PRED_RES_BLKS; i++) + { + bl_len = (lmprbl_item >> 28) & 0xF; lmprbl_item <<= 4; + v_zap(c_vec, MAX_BLOCK_LEN); + c_vec[0] = gain_r[i]; + for(j = 1; j < bl_len; j++) + { + num_bits = *ba_ptr++; + if(num_bits) + { + step_size = extract_h(((Word32)hi_ord_std_tbl[j - 1] * hi_ord_step_size_tbl[num_bits - 1]) << 1); + c_vec[j] = extract_l(L_shr(deqnt_by_step(*b_vec_ptr, step_size, num_bits), 5)); + } + else + c_vec[j] = 0; + + b_vec_ptr++; + } + idct(c_vec, bl_len, bl_len, t_vec_ptr); + t_vec_ptr += bl_len; + } + + // Calculate num_harms_prev/num_harms. Result save in unsigned format Q8.24 + if(num_harms == num_harms_prev1) + k_coef = (Word32)CNST_ONE_Q8_24; + else if(num_harms > num_harms_prev1) + k_coef = (Word32)div_s(num_harms_prev1 << 9, num_harms << 9) << 9; + else + { + // imbe_param->num_harms < num_harms_prev1 + k_coef = 0; + tmp = num_harms_prev1; + while(tmp > num_harms) + { + tmp -= num_harms; + k_coef += (Word32)CNST_ONE_Q8_24; + } + k_coef += (Word32)div_s(tmp << 9, num_harms << 9) << 9; + } + + if(num_harms <= 15) + ro_coef = CNST_0_4_Q1_15; + else if(num_harms <= 24) + ro_coef = num_harms * CNST_0_03_Q1_15 - CNST_0_05_Q1_15; + else + ro_coef = CNST_0_7_Q1_15; + + k_acc = k_coef; + sum = 0; + + for(i = num_harms_prev1 + 1; i < NUM_HARMS_MAX + 2; i++) + sa_prev1[i] = sa_prev1[num_harms_prev1]; + + for(i = 0; i < num_harms; i++) + { + index = (UWord16)(k_acc >> 24); // Get integer part + si_coef = (Word16)((k_acc - ((UWord32)index << 24)) >> 9); // Get fractional part + + if(si_coef == 0) + { + tmp_word32 = L_mpy_ls(sa_prev1[index], ro_coef); // sa_prev1 here is in Q10.22 format + sa_tmp[i] = L_add(L_shr(L_deposit_h(t_vec[i]), 5), tmp_word32); // Convert t_vec to Q10.22 and add ... + sum = L_add(sum, sa_prev1[index]); // sum in Q10.22 format + } + else + { + index_1 = index + 1; + tmp_word32 = L_mpy_ls(sa_prev1[index], sub(0x7FFF, si_coef)); + sum = L_add(sum, tmp_word32); + sa_tmp[i] = L_add(L_shr(L_deposit_h(t_vec[i]), 5), L_mpy_ls(tmp_word32, ro_coef)); + + tmp_word32 = L_mpy_ls(sa_prev1[index_1], si_coef); + sum = L_add(sum, tmp_word32); + sa_tmp[i] = L_add(sa_tmp[i], L_mpy_ls(tmp_word32, ro_coef)); + } + + k_acc += k_coef; + } + + imbe_param->div_one_by_num_harm_sh = tmp = norm_s(num_harms); + imbe_param->div_one_by_num_harm = tmp1 = div_s(0x4000, num_harms << tmp); // calculate 1/num_harms with scaling for better pricision + // save result to use late + + sum = L_shr(L_mpy_ls(L_mpy_ls(sum, ro_coef), tmp1), (14 - tmp)); + + for(i = 1; i <= num_harms; i++) + { + sa_prev1[i] = L_sub(sa_tmp[i - 1], sum); + sa[i - 1] = Pow2(sa_prev1[i]); + } + + num_harms_prev1 = num_harms; +} diff --git a/imbe/sa_decode.h b/imbe/sa_decode.h new file mode 100644 index 0000000..88d1e33 --- /dev/null +++ b/imbe/sa_decode.h @@ -0,0 +1,64 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _SA_DECODE +#define _SA_DECODE + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Initialization of Spectral Amplitude Decoder +// +// +// INPUT: +// None +// +// OUTPUT: +// None +// +// RETURN: +// None +// +//----------------------------------------------------------------------------- +#if 0 +void sa_decode_init(void); + +//----------------------------------------------------------------------------- +// PURPOSE: +// Perform Spectral Amplitude Decoding +// +// +// INPUT: +// IMBE_PARAM *imbe_param - pointer to IMBE_PARAM structure with +// valid num_harms and b_vec items +// +// OUTPUT: +// None +// +// RETURN: +// Decoded Spectral Amplitudes +// +//----------------------------------------------------------------------------- +void sa_decode(IMBE_PARAM *imbe_param); +#endif + +#endif diff --git a/imbe/sa_encode.cc b/imbe/sa_encode.cc new file mode 100644 index 0000000..0525fae --- /dev/null +++ b/imbe/sa_encode.cc @@ -0,0 +1,296 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "globals.h" +#include "basic_op.h" +#include "imbe.h" +#include "tbls.h" +#include "qnt_sub.h" +#include "sa_encode.h" +#include "aux_sub.h" +#include "dsp_sub.h" +#include "math_sub.h" + +#include +#include +#include "encode.h" +#include "imbe_vocoder_impl.h" + + +void imbe_vocoder_impl::sa_encode_init(void) +{ + Word16 i; + num_harms_prev2 = 30; + for(i = 0; i < NUM_HARMS_MAX + 2; i++) + sa_prev2[i] = 0; +} + +void imbe_vocoder_impl::sa_encode(IMBE_PARAM *imbe_param) +{ + Word16 gain_vec[6], gain_r[6]; + UWord16 index, i, j, num_harms; + Word16 *ba_ptr, *t_vec_ptr, *b_vec_ptr, *gss_ptr, *sa_ptr; + Word16 t_vec[NUM_HARMS_MAX], c_vec[MAX_BLOCK_LEN]; + UWord32 lmprbl_item; + Word16 bl_len, step_size, num_bits, tmp, ro_coef, si_coef, tmp1; + UWord32 k_coef, k_acc; + Word32 sum, tmp_word32, vec32_tmp[NUM_HARMS_MAX], *vec32_ptr; + + num_harms = imbe_param->num_harms; + + // Calculate num_harms_prev2/num_harms. Result save in unsigned format Q8.24 + if(num_harms == num_harms_prev2) + k_coef = (Word32)CNST_ONE_Q8_24; + else if(num_harms > num_harms_prev2) + k_coef = (Word32)div_s(num_harms_prev2 << 9, num_harms << 9) << 9; + else + { + // imbe_param->num_harms < num_harms_prev2 + k_coef = 0; + tmp = num_harms_prev2; + while(tmp > num_harms) + { + tmp -= num_harms; + k_coef += (Word32)CNST_ONE_Q8_24; + } + k_coef += (Word32)div_s(tmp << 9, num_harms << 9) << 9; + } + + // Calculate prediction coefficient + if(num_harms <= 15) + ro_coef = CNST_0_4_Q1_15; + else if(num_harms <= 24) + ro_coef = num_harms * CNST_0_03_Q1_15 - CNST_0_05_Q1_15; + else + ro_coef = CNST_0_7_Q1_15; + + for(i = num_harms_prev2 + 1; i < NUM_HARMS_MAX + 2; i++) + sa_prev2[i] = sa_prev2[num_harms_prev2]; + + k_acc = k_coef; + sum = 0; + sa_ptr = imbe_param->sa; + vec32_ptr = vec32_tmp; + for(i = 0; i < num_harms; i++) + { + index = (UWord16)(k_acc >> 24); // Get integer part + si_coef = (Word16)((k_acc - ((UWord32)index << 24)) >> 9); // Get fractional part + + + if(si_coef == 0) + { + tmp_word32 = L_mpy_ls(sa_prev2[index], ro_coef); // sa_prev2 here is in Q10.22 format + *vec32_ptr++ = L_sub(Log2(*sa_ptr++), tmp_word32); + sum = L_add(sum, sa_prev2[index]); // sum in Q10.22 format + } + else + { + tmp_word32 = L_mpy_ls(sa_prev2[index], sub(0x7FFF, si_coef)); + sum = L_add(sum, tmp_word32); + *vec32_ptr = L_sub(Log2(*sa_ptr++), L_mpy_ls(tmp_word32, ro_coef)); + + tmp_word32 = L_mpy_ls(sa_prev2[index + 1], si_coef); + sum = L_add(sum, tmp_word32); + *vec32_ptr = L_sub(*vec32_ptr, L_mpy_ls(tmp_word32, ro_coef)); + + vec32_ptr++; + } + + k_acc += k_coef; + } + + imbe_param->div_one_by_num_harm_sh = tmp = norm_s(num_harms); + imbe_param->div_one_by_num_harm = tmp1 = div_s(0x4000, num_harms << tmp); // calculate 1/num_harms with scaling for better pricision + // save result to use late + sum = L_shr(L_mpy_ls(L_mpy_ls(sum, ro_coef), tmp1), (14 - tmp)); + + for(i = 0; i < num_harms; i++) + t_vec[i] = extract_h(L_shl(L_add(vec32_tmp[i], sum), 5)); // t_vec has Q5.11 format + ////////////////////////////////////////////// + // + // Encode T vector + // + ////////////////////////////////////////////// + index = num_harms - NUM_HARMS_MIN; + + // Unpack bit allocation table's item + get_bit_allocation(num_harms, imbe_param->bit_alloc); + lmprbl_item = lmprbl_tbl[index]; + + // Encoding the Higher Order DCT Coefficients + t_vec_ptr = t_vec; + b_vec_ptr = &imbe_param->b_vec[8]; + ba_ptr = &imbe_param->bit_alloc[5]; + for(i = 0; i < NUM_PRED_RES_BLKS; i++) + { + bl_len = (lmprbl_item >> 28) & 0xF; lmprbl_item <<= 4; + + dct(t_vec_ptr, bl_len, bl_len, c_vec); + gain_vec[i] = c_vec[0]; +/* + for(j = 0; j < bl_len; j++) + printf("%g ", (double)t_vec_ptr[j]/2048.); + printf("\n"); + for(j = 0; j < bl_len; j++) + printf("%g ", (double)c_vec[j]/2048.); + printf("\n"); + printf("\n"); +*/ + for(j = 1; j < bl_len; j++) + { + num_bits = *ba_ptr++; + if(num_bits) + { + step_size = extract_h(((Word32)hi_ord_std_tbl[j - 1] * hi_ord_step_size_tbl[num_bits - 1]) << 1); + *b_vec_ptr = qnt_by_step(c_vec[j], step_size, num_bits); + } + else + *b_vec_ptr = 0; + + b_vec_ptr++; + } + t_vec_ptr += bl_len; + } + + // Encoding the Gain Vector + dct(gain_vec, NUM_PRED_RES_BLKS, NUM_PRED_RES_BLKS, gain_r); + + b_vec_ptr = &imbe_param->b_vec[2]; + ba_ptr = &imbe_param->bit_alloc[0]; + gss_ptr = (Word16 *)&gain_step_size_tbl[index * 5]; + + *b_vec_ptr++ = tbl_quant(gain_r[0], (Word16 *)&gain_qnt_tbl[0], GAIN_QNT_TBL_SIZE); + for(j = 1; j < 6; j++) + *b_vec_ptr++ = qnt_by_step(gain_r[j], *gss_ptr++, *ba_ptr++); + +/* + for(j = 0; j < NUM_PRED_RES_BLKS; j++) + printf("%g ", (double)gain_vec[j]/2048.); + printf("\n"); + for(j = 0; j < NUM_PRED_RES_BLKS; j++) + printf("%g ", (double)gain_r[j]/2048.); + printf("\n"); + printf("\n"); +*/ + + + + ////////////////////////////////////////////// + // + // Decode T vector + // + ////////////////////////////////////////////// + ba_ptr = imbe_param->bit_alloc; + b_vec_ptr = &imbe_param->b_vec[2]; + + // Decoding the Gain Vector. gain_vec has signed Q5.11 format + gss_ptr = (Word16 *)&gain_step_size_tbl[index * 5]; + gain_vec[0] = gain_qnt_tbl[*b_vec_ptr++]; + + for(i = 1; i < 6; i++) + gain_vec[i] = extract_l(L_shr(deqnt_by_step(*b_vec_ptr++, *gss_ptr++, *ba_ptr++), 5)); +/* + printf("gain deqnt\n"); + for(j = 0; j < 6; j++) + printf("%g ", (double)gain_vec[j]/2048.); + printf("\n"); +*/ + idct(gain_vec, NUM_PRED_RES_BLKS, NUM_PRED_RES_BLKS, gain_r); + + v_zap(t_vec, NUM_HARMS_MAX); + lmprbl_item = lmprbl_tbl[index]; + + // Decoding the Higher Order DCT Coefficients + t_vec_ptr = t_vec; + for(i = 0; i < NUM_PRED_RES_BLKS; i++) + { + bl_len = (lmprbl_item >> 28) & 0xF; lmprbl_item <<= 4; + v_zap(c_vec, MAX_BLOCK_LEN); + c_vec[0] = gain_r[i]; + for(j = 1; j < bl_len; j++) + { + num_bits = *ba_ptr++; + if(num_bits) + { + step_size = extract_h(((Word32)hi_ord_std_tbl[j - 1] * hi_ord_step_size_tbl[num_bits - 1]) << 1); + c_vec[j] = extract_l(L_shr(deqnt_by_step(*b_vec_ptr, step_size, num_bits), 5)); + } + else + c_vec[j] = 0; + + b_vec_ptr++; + } +/* + printf("\n"); + for(j = 0; j < bl_len; j++) + printf("%g ", (double)c_vec[j]/2048.); + printf("\n"); +*/ + idct(c_vec, bl_len, bl_len, t_vec_ptr); + t_vec_ptr += bl_len; + } +/* + printf("\n====t_vec_rec ===\n"); + for(j = 0; j < num_harms; j++) + printf("%g ", (double)t_vec[j]/2048.); + printf("\n"); +*/ + ////////////////////////////////////////////// + // + // Reconstruct Spectral Amplitudes + // + ////////////////////////////////////////////// + k_acc = k_coef; + vec32_ptr = vec32_tmp; + + for(i = num_harms_prev2 + 1; i < NUM_HARMS_MAX + 2; i++) + sa_prev2[i] = sa_prev2[num_harms_prev2]; + + for(i = 0; i < num_harms; i++) + { + index = (UWord16)(k_acc >> 24); // Get integer part + si_coef = (Word16)((k_acc - ((UWord32)index << 24)) >> 9); // Get fractional part + + if(si_coef == 0) + { + tmp_word32 = L_mpy_ls(sa_prev2[index], ro_coef); // sa_prev2 here is in Q10.22 format + *vec32_ptr++ = L_add(L_shr(L_deposit_h(t_vec[i]), 5), tmp_word32); // Convert t_vec to Q10.22 and add ... + } + else + { + tmp_word32 = L_mpy_ls(sa_prev2[index], sub(0x7FFF, si_coef)); + *vec32_ptr = L_add(L_shr(L_deposit_h(t_vec[i]), 5), L_mpy_ls(tmp_word32, ro_coef)); + + tmp_word32 = L_mpy_ls(sa_prev2[index + 1], si_coef); + *vec32_ptr = L_add(*vec32_ptr, L_mpy_ls(tmp_word32, ro_coef)); + + vec32_ptr++; + } + + k_acc += k_coef; + } + + for(i = 1; i <= num_harms; i++) + sa_prev2[i] = L_sub(vec32_tmp[i - 1], sum); + + num_harms_prev2 = num_harms; +} diff --git a/imbe/sa_encode.h b/imbe/sa_encode.h new file mode 100644 index 0000000..06e4145 --- /dev/null +++ b/imbe/sa_encode.h @@ -0,0 +1,30 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _SA_ENCODE +#define _SA_ENCODE + + +void sa_encode_init(void); +void sa_encode(IMBE_PARAM *imbe_param); + +#endif diff --git a/imbe/sa_enh.cc b/imbe/sa_enh.cc new file mode 100644 index 0000000..c6586eb --- /dev/null +++ b/imbe/sa_enh.cc @@ -0,0 +1,202 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "basic_op.h" +#include "imbe.h" +#include "qnt_sub.h" +#include "aux_sub.h" +#include "math_sub.h" +#include "sa_enh.h" + + + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Perform Spectral Amplitude Enhancement +// +// +// INPUT: +// IMBE_PARAM *imbe_param - pointer to IMBE_PARAM structure with +// valid num_harms, sa and fund_freq items +// +// OUTPUT: +// None +// +// RETURN: +// Enhanced Spectral Amplitudes +// +//----------------------------------------------------------------------------- +void sa_enh(IMBE_PARAM *imbe_param) +{ + Word16 *sa, num_harm, sa_tmp[NUM_HARMS_MAX], nm; + Word16 cos_w[NUM_HARMS_MAX], i, tmp; + Word32 L_tmp, Rm0, Rm1; + Word32 w0, cos_acc; + Word32 L_den, L_num, L_Rm0_2, L_Rm1_2, L_sum_Rm02_Rm12, L_sum_mod; + Word16 Rm0Rm1, nm1, nm2, tot_nm; + Word16 Rm0_s, Rm1_s; + + + sa = imbe_param->sa; + num_harm = imbe_param->num_harms; + + v_equ(sa_tmp, sa, num_harm); + + Rm0 = L_v_magsq(sa, num_harm); + + if(Rm0 == 0) + return; + + nm = norm_l (Rm0); + if(Rm0 == MAX_32) + { + nm = 1; + v_equ_shr(sa_tmp, sa, nm, num_harm); + Rm0 = L_v_magsq(sa_tmp, num_harm); + } + else + { + if(nm > 2) + { + nm = -(nm >> 1); + v_equ_shr(sa_tmp, sa, nm, num_harm); + Rm0 = L_v_magsq(sa_tmp, num_harm); + } + } + + w0 = imbe_param->fund_freq; + + cos_acc = 0; Rm1 = 0; + for(i = 0; i < num_harm; i++) + { + cos_acc = L_add(cos_acc, w0); + + cos_w[i] = cos_fxp(extract_h(cos_acc)); + Rm1 = L_add(Rm1, L_mpy_ls(L_mult(sa_tmp[i], sa_tmp[i]), cos_w[i])); + } + + Rm0_s = extract_h(Rm0); + Rm1_s = extract_h(Rm1); + + L_Rm0_2 = L_mult(Rm0_s, Rm0_s); + L_Rm1_2 = L_mult(Rm1_s, Rm1_s); + L_den = L_sub(L_Rm0_2, L_Rm1_2); + L_den = L_mult(extract_h(L_den), Rm0_s); + nm1 = norm_l(L_den); + L_den = L_shl(L_den, nm1); + + nm2 = norm_l(w0); + L_den = L_mpy_ls(L_den, extract_h(L_shl(w0, nm2))); // Calculate w0 * Rm0 * (Rm0^2 - Rm1^2) + nm1 += nm2; // total denominator shift + + if (L_den < 1) return; // fix bug infinite loop due to invalid input + + L_sum_Rm02_Rm12 = L_add(L_shr(L_Rm0_2, 2), L_shr(L_Rm1_2, 2)); + Rm0Rm1 = shr(mult_r(Rm0_s, Rm1_s), 1); + + for(i = 0; i < num_harm; i++) + { + if((((i + 1) << 3) > num_harm) && (sa_tmp[i] != 0x0000)) + { + L_num = L_sub(L_sum_Rm02_Rm12, L_mult(Rm0Rm1, cos_w[i])); + tot_nm = norm_l(L_num); + L_num = L_shl(L_num, tot_nm); + while(L_num >= L_den) + { + L_num = L_shr(L_num, 1); + tot_nm -= 1; + } + + tmp = div_s(extract_h(L_num), extract_h(L_den)); + tot_nm -= nm1; + + L_tmp = L_mult(sa_tmp[i], sa_tmp[i]); + nm2 = norm_l(L_tmp); + L_tmp = L_shl(L_tmp, nm2); + L_tmp = L_mult(extract_h(L_tmp), tmp); + tot_nm += nm2; + tot_nm -= 2; + + if(tot_nm <= 0) + { + L_tmp = L_shr(L_tmp, add(8, tot_nm)); + L_tmp = sqrt_l_exp(L_tmp, &tot_nm); + L_tmp = L_shr(L_tmp, tot_nm); + L_tmp = sqrt_l_exp(L_tmp, &tot_nm); + L_tmp = L_shr(L_tmp, tot_nm); + L_tmp = L_mult(extract_h(L_tmp), CNST_0_9898_Q1_15); + tmp = extract_h(L_shl(L_tmp, 1)); + } + else + { + if(tot_nm <= 8) + { + L_tmp = L_shr(L_tmp, tot_nm); + L_tmp = sqrt_l_exp(L_tmp, &tot_nm); + L_tmp = L_shr(L_tmp, tot_nm); + L_tmp = sqrt_l_exp(L_tmp, &tot_nm); + L_tmp = L_shr(L_tmp, tot_nm + 1); + tmp = mult(extract_h(L_tmp), CNST_0_9898_Q1_15); + } + else + { + nm1 = tot_nm & 0xFFFE; + L_tmp = L_shr(L_tmp, tot_nm - nm1); + L_tmp = sqrt_l_exp(L_tmp, &tot_nm); + L_tmp = L_shr(L_tmp, tot_nm); + tot_nm = nm1 >> 1; + + nm1 = tot_nm & 0xFFFE; + L_tmp = L_shr(L_tmp, tot_nm - nm1); + L_tmp = sqrt_l_exp(L_tmp, &tot_nm); + L_tmp = L_shr(L_tmp, tot_nm); + L_tmp = L_mult(extract_h(L_tmp), CNST_0_9898_Q1_15); + tot_nm = nm1 >> 1; + tmp = extract_h(L_shr(L_tmp, tot_nm + 1)); + } + } + + if(tmp > CNST_1_2_Q2_14) + sa[i] = extract_h(L_shl(L_mult(sa[i], CNST_1_2_Q2_14), 1)); + else if(tmp < CNST_0_5_Q2_14) + sa[i] = shr(sa[i], 1); + else + sa[i] = extract_h(L_shl(L_mult(sa[i], tmp), 1)); + } + } + + // Compute the correct scale factor + v_equ_shr(sa_tmp, sa, nm, num_harm); + L_sum_mod = L_v_magsq(sa_tmp, num_harm); + if(L_sum_mod > Rm0) + { + tmp = div_s(extract_h(Rm0), extract_h(L_sum_mod)); + L_tmp = sqrt_l_exp(L_deposit_h(tmp), &tot_nm); + tmp = shr(extract_h(L_tmp), tot_nm); + for(i = 0; i < num_harm; i++) + sa[i] = mult_r(sa[i], tmp); + } +} + + + diff --git a/imbe/sa_enh.h b/imbe/sa_enh.h new file mode 100644 index 0000000..6b3f277 --- /dev/null +++ b/imbe/sa_enh.h @@ -0,0 +1,50 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _SA_ENH +#define _SA_ENH + +#define CNST_0_9898_Q1_15 0x7EB3 +#define CNST_0_5_Q2_14 0x2000 +#define CNST_1_2_Q2_14 0x4CCC + + +//----------------------------------------------------------------------------- +// PURPOSE: +// Perform Spectral Amplitude Enhancement +// +// +// INPUT: +// IMBE_PARAM *imbe_param - pointer to IMBE_PARAM structure with +// valid num_harms, sa and fund_freq items +// +// OUTPUT: +// None +// +// RETURN: +// Enhanced Spectral Amplitudes +// +//----------------------------------------------------------------------------- +void sa_enh(IMBE_PARAM *imbe_param); + + +#endif diff --git a/imbe/tbls.cc b/imbe/tbls.cc new file mode 100644 index 0000000..1819c8f --- /dev/null +++ b/imbe/tbls.cc @@ -0,0 +1,368 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ +#include "typedef.h" +#include "tbls.h" + + +//----------------------------------------------------------------------------- +// +// Bit allocation and ancillary tables +// +//----------------------------------------------------------------------------- +const UWord16 bit_allocation_tbl[] = +{ + 0xA999, 0x9987, + 0x9988, 0x8976, 0x5000, + 0x8887, 0x7976, 0x5400, + 0x8777, 0x7876, 0x5430, + 0x7776, 0x6776, 0x5433, + 0x7666, 0x6775, 0x4434, 0x3000, + 0x7666, 0x5675, 0x4433, 0x3300, + 0x6665, 0x5665, 0x4433, 0x3320, + 0x6655, 0x5555, 0x4443, 0x3232, + 0x6555, 0x5545, 0x5433, 0x3322, 0x2000, + 0x6554, 0x4545, 0x4433, 0x3323, 0x2100, + 0x6554, 0x4545, 0x4433, 0x2321, 0x3210, + 0x5554, 0x4445, 0x4433, 0x2232, 0x1321, + 0x5544, 0x4444, 0x4432, 0x3223, 0x2122, 0x1000, + 0x5444, 0x4434, 0x4343, 0x2322, 0x2212, 0x2100, + 0x5444, 0x4433, 0x4333, 0x3232, 0x1221, 0x2210, + 0x5444, 0x3433, 0x4333, 0x3232, 0x1221, 0x2111, + 0x5443, 0x3433, 0x4333, 0x2232, 0x1221, 0x1221, 0x1000, + 0x5443, 0x3432, 0x4323, 0x2232, 0x2122, 0x1122, 0x1100, + 0x4443, 0x3432, 0x4323, 0x2223, 0x2112, 0x2112, 0x1110, + 0x4443, 0x3332, 0x4322, 0x3222, 0x3211, 0x2111, 0x2111, + 0x4443, 0x3332, 0x2332, 0x2322, 0x1321, 0x1211, 0x1211, 0x1000, + 0x4433, 0x3332, 0x2332, 0x2322, 0x1221, 0x1211, 0x1211, 0x1100, + 0x4433, 0x3332, 0x2332, 0x2322, 0x1221, 0x1211, 0x1121, 0x1100, + 0x4333, 0x3332, 0x2332, 0x2321, 0x1221, 0x1121, 0x1112, 0x1111, + 0x4333, 0x3322, 0x2322, 0x2322, 0x1122, 0x1112, 0x1111, 0x2111, 0x0000, + 0x4333, 0x3322, 0x2322, 0x2232, 0x1112, 0x2111, 0x2111, 0x0211, 0x1000, + 0x4333, 0x3322, 0x2132, 0x2213, 0x2111, 0x2211, 0x1211, 0x1021, 0x1100, + 0x4333, 0x2322, 0x2132, 0x2223, 0x2111, 0x2111, 0x1211, 0x1021, 0x1110, + 0x4333, 0x2322, 0x2132, 0x2213, 0x2111, 0x2111, 0x1211, 0x1102, 0x1111, 0x0000, + 0x4333, 0x2322, 0x2132, 0x2213, 0x2111, 0x2211, 0x1021, 0x1110, 0x2111, 0x0000, + 0x4333, 0x2322, 0x2132, 0x2113, 0x2111, 0x1221, 0x1102, 0x1111, 0x0211, 0x1000, + 0x4332, 0x2322, 0x1132, 0x2211, 0x3211, 0x1122, 0x1110, 0x2111, 0x1021, 0x1100, + 0x4332, 0x2322, 0x2113, 0x2221, 0x1221, 0x1112, 0x2111, 0x0211, 0x1002, 0x1110, 0x0000, + 0x4332, 0x2322, 0x2113, 0x2221, 0x1221, 0x1112, 0x1111, 0x0211, 0x1002, 0x1111, 0x0000, + 0x4332, 0x2322, 0x1113, 0x2221, 0x1221, 0x1112, 0x1111, 0x0211, 0x1100, 0x2111, 0x1000, + 0x4332, 0x2322, 0x1113, 0x2211, 0x1221, 0x1112, 0x2111, 0x0021, 0x1110, 0x0211, 0x1100, + 0x3332, 0x2322, 0x1113, 0x2211, 0x1221, 0x1111, 0x2211, 0x1002, 0x1111, 0x0021, 0x1110, 0x0000, + 0x3332, 0x2322, 0x1113, 0x2211, 0x1122, 0x1111, 0x1221, 0x1100, 0x2111, 0x1002, 0x1110, 0x0000, + 0x3332, 0x2322, 0x1111, 0x3221, 0x1112, 0x2111, 0x1122, 0x1110, 0x0211, 0x1000, 0x2111, 0x0000, + 0x3332, 0x2322, 0x1111, 0x3221, 0x1112, 0x2111, 0x1022, 0x1110, 0x0211, 0x1000, 0x2111, 0x1000, + 0x3332, 0x2322, 0x1111, 0x3221, 0x1112, 0x2111, 0x1022, 0x1110, 0x0211, 0x1100, 0x0211, 0x1000, 0x0000, + 0x3332, 0x2322, 0x1111, 0x3211, 0x1112, 0x2111, 0x1022, 0x1110, 0x0021, 0x1110, 0x0021, 0x1110, 0x0000, + 0x3322, 0x2321, 0x1111, 0x3221, 0x1112, 0x2111, 0x1102, 0x2111, 0x0002, 0x1111, 0x0002, 0x1111, 0x0000, + 0x3322, 0x2321, 0x1111, 0x3221, 0x1111, 0x2211, 0x1110, 0x2211, 0x1000, 0x2111, 0x1000, 0x2111, 0x0000, + 0x3322, 0x2322, 0x1111, 0x0322, 0x1111, 0x0221, 0x1111, 0x0221, 0x1100, 0x0211, 0x1100, 0x0211, 0x1000, 0x0000, + 0x3322, 0x2322, 0x1111, 0x0322, 0x1111, 0x0221, 0x1111, 0x0221, 0x1100, 0x0211, 0x1000, 0x0211, 0x1100, 0x0000, + 0x3322, 0x2322, 0x1111, 0x0322, 0x1111, 0x0221, 0x1111, 0x0221, 0x1100, 0x0211, 0x1100, 0x0021, 0x1100, 0x0000 +}; + +const UWord16 bit_allocation_offset_tbl[] = +{ + 0x0002, 0x000E, 0x001E, 0x0032, 0x004A, 0x0066, 0x0086, 0x00AA, 0x00D2, 0x00FE, 0x012E, 0x0162 +}; + +//----------------------------------------------------------------------------- +// +// Log Magnitude Prediction Residual Block Length +// +//----------------------------------------------------------------------------- +const UWord32 lmprbl_tbl[] = +{ + 0x11122200, + 0x11222200, + 0x12222200, + 0x22222200, + 0x22222300, + 0x22223300, + 0x22233300, + 0x22333300, + 0x23333300, + 0x33333300, + 0x33333400, + 0x33334400, + 0x33344400, + 0x33444400, + 0x34444400, + 0x44444400, + 0x44444500, + 0x44445500, + 0x44455500, + 0x44555500, + 0x45555500, + 0x55555500, + 0x55555600, + 0x55556600, + 0x55566600, + 0x55666600, + 0x56666600, + 0x66666600, + 0x66666700, + 0x66667700, + 0x66677700, + 0x66777700, + 0x67777700, + 0x77777700, + 0x77777800, + 0x77778800, + 0x77788800, + 0x77888800, + 0x78888800, + 0x88888800, + 0x88888900, + 0x88889900, + 0x88899900, + 0x88999900, + 0x89999900, + 0x99999900, + 0x99999A00, + 0x9999AA00 +}; + + + +//----------------------------------------------------------------------------- +// +// Gain Quantizer Levels in signed Q5.11 format +// +//----------------------------------------------------------------------------- +const Word16 gain_qnt_tbl[] = +{ + -5821, -5518, -5239, -4880, -4549, -4292, -4057, -3760, -3370, -2903, + -2583, -2305, -1962, -1601, -1138, -711, -302, 57, 433, 795, + 1132, 1510, 1909, 2333, 2705, 3038, 3376, 3689, 3979, 4339, + 4754, 5129, 5435, 5695, 5991, 6300, 6596, 6969, 7342, 7751, + 8101, 8511, 8835, 9102, 9375, 9698, 10055, 10415, 10762, 11084, + 11403, 11752, 12123, 12468, 12863, 13239, 13615, 13997, 14382, 14770, + 15301, 15849, 16640, 17809 +}; + + +//----------------------------------------------------------------------------- +// +// Gain Ste Size in unsigned Q0.16 format +// +//----------------------------------------------------------------------------- +const UWord16 gain_step_size_tbl[] = +{ + 203, 263, 220, 190, 173, + 406, 263, 440, 380, 346, + 813, 527, 440, 760, 692, + 813, 1054, 881, 760, 692, + 1625, 1054, 881, 1425, 1298, + 1625, 1976, 1652, 1425, 1298, + 1625, 1976, 1652, 1425, 2422, + 3047, 1976, 1652, 2661, 2422, + 3047, 1976, 3083, 2661, 2422, + 3047, 3688, 3083, 2661, 2422, + 3047, 3688, 3083, 3801, 3460, + 3047, 3688, 3083, 3801, 3460, + 5689, 3688, 3083, 3801, 3460, + 5689, 3688, 4404, 3801, 3460, + 5689, 5269, 4404, 3801, 3460, + 5689, 5269, 4404, 3801, 3460, + 5689, 5269, 4404, 3801, 5623, + 5689, 5269, 4404, 6177, 5623, + 5689, 5269, 4404, 6177, 5623, + 8126, 5269, 4404, 6177, 5623, + 8126, 5269, 4404, 6177, 5623, + 8126, 5269, 4404, 6177, 5623, + 8126, 5269, 7157, 6177, 5623, + 8126, 5269, 7157, 6177, 5623, + 8126, 8562, 7157, 6177, 5623, + 8126, 8562, 7157, 6177, 5623, + 8126, 8562, 7157, 6177, 5623, + 8126, 8562, 7157, 6177, 5623, + 8126, 8562, 7157, 6177, 7353, + 8126, 8562, 7157, 6177, 7353, + 8126, 8562, 7157, 6177, 7353, + 8126, 8562, 7157, 6177, 7353, + 8126, 8562, 7157, 8077, 7353, + 8126, 8562, 7157, 8077, 7353, + 8126, 8562, 7157, 8077, 7353, + 8126, 8562, 7157, 8077, 7353, + 8126, 8562, 7157, 8077, 7353, + 13206, 8562, 7157, 8077, 7353, + 13206, 8562, 7157, 8077, 7353, + 13206, 8562, 7157, 8077, 7353, + 13206, 8562, 7157, 8077, 7353, + 13206, 8562, 7157, 8077, 7353, + 13206, 8562, 7157, 8077, 7353, + 13206, 8562, 9359, 8077, 7353, + 13206, 8562, 9359, 8077, 7353, + 13206, 8562, 9359, 8077, 7353, + 13206, 8562, 9359, 8077, 7353, + 13206, 8562, 9359, 8077, 7353 +}; + + +//----------------------------------------------------------------------------- +// +// Standard Deviation of Higher Order DCT Coefficients in unsigned Q0.16 format +// +//----------------------------------------------------------------------------- +const UWord16 hi_ord_std_tbl[] = +{ + 20120, 15794, 13566, 12452, 11731, 11338, 10813, 11141, 11141 +}; + +//----------------------------------------------------------------------------- +// +// Quantizer Step for Higher Order DCT Coefficients in unsigned Q1.15 format +// +//----------------------------------------------------------------------------- +const UWord16 hi_ord_step_size_tbl[] = +{ + 39322, 27853, 21299, 13107, 9175, 4915, 2621, 1311, 655, 328 +}; + +//----------------------------------------------------------------------------- +// +// Speech Synthesis Window +// +//----------------------------------------------------------------------------- +const Word16 ws[49] = +{ + 655, 1310, 1966, 2621, 3276, 3932, 4587, 5242, 5898, 6553, + 7208, 7864, 8519, 9175, 9830, 10485, 11141, 11796, 12451, 13107, + 13762, 14417, 15073, 15728, 16384, 17039, 17694, 18350, 19005, 19660, + 20316, 20971, 21626, 22282, 22937, 23592, 24248, 24903, 25559, 26214, + 26869, 27525, 28180, 28835, 29491, 30146, 30801, 31457, 32112 +}; + +/* +const Word16 ws_ws[49] = +{ + + 17052, 17746, 18467, 19212, 19980, 20770, 21580, 22407, 23246, 24094, + 24945, 25793, 26631, 27453, 28248, 29008, 29724, 30385, 30983, 31507, + 31950, 32302, 32559, 32715, 32767, 32715, 32559, 32302, 31950, 31507, + 30983, 30385, 29724, 29008, 28248, 27453, 26631, 25793, 24945, 24094, + 23246, 22407, 21580, 20770, 19980, 19212, 18467, 17746, 17052 +}; +*/ + +//----------------------------------------------------------------------------- +// +// Squared Pitch Estimation Window 64*wi^2 +// +//----------------------------------------------------------------------------- +const Word16 wi[301] = +{ + 15, 18, 21, 25, 29, 34, 40, 46, 52, 59, + 67, 76, 86, 96, 108, 120, 133, 148, 164, 180, + 199, 218, 239, 261, 285, 311, 338, 367, 398, 431, + 465, 502, 541, 582, 625, 671, 719, 769, 822, 878, + 936, 997, 1061, 1128, 1198, 1271, 1347, 1426, 1508, 1594, + 1683, 1775, 1871, 1970, 2073, 2179, 2289, 2403, 2520, 2641, + 2766, 2894, 3026, 3162, 3301, 3445, 3592, 3742, 3897, 4055, + 4216, 4382, 4551, 4723, 4899, 5078, 5261, 5447, 5636, 5828, + 6023, 6221, 6423, 6626, 6833, 7042, 7253, 7467, 7683, 7900, + 8120, 8341, 8564, 8788, 9014, 9241, 9468, 9696, 9925, 10154, + 10383, 10613, 10842, 11070, 11298, 11525, 11752, 11977, 12200, 12422, + 12642, 12860, 13076, 13289, 13500, 13708, 13912, 14114, 14312, 14506, + 14696, 14882, 15064, 15242, 15414, 15582, 15745, 15903, 16055, 16202, + 16343, 16478, 16608, 16731, 16848, 16958, 17062, 17159, 17250, 17333, + 17410, 17480, 17542, 17597, 17646, 17686, 17720, 17746, 17764, 17776, + 17779, 17776, 17764, 17746, 17720, 17686, 17646, 17597, 17542, 17480, + 17410, 17333, 17250, 17159, 17062, 16958, 16848, 16731, 16608, 16478, + 16343, 16202, 16055, 15903, 15745, 15582, 15414, 15242, 15064, 14882, + 14696, 14506, 14312, 14114, 13912, 13708, 13500, 13289, 13076, 12860, + 12642, 12422, 12200, 11977, 11752, 11525, 11298, 11070, 10842, 10613, + 10383, 10154, 9925, 9696, 9468, 9241, 9014, 8788, 8564, 8341, + 8120, 7900, 7683, 7467, 7253, 7042, 6833, 6626, 6423, 6221, + 6023, 5828, 5636, 5447, 5261, 5078, 4899, 4723, 4551, 4382, + 4216, 4055, 3897, 3742, 3592, 3445, 3301, 3162, 3026, 2894, + 2766, 2641, 2520, 2403, 2289, 2179, 2073, 1970, 1871, 1775, + 1683, 1594, 1508, 1426, 1347, 1271, 1198, 1128, 1061, 997, + 936, 878, 822, 769, 719, 671, 625, 582, 541, 502, + 465, 431, 398, 367, 338, 311, 285, 261, 239, 218, + 199, 180, 164, 148, 133, 120, 108, 96, 86, 76, + 67, 59, 52, 46, 40, 34, 29, 25, 21, 18, + 15 +}; + +//----------------------------------------------------------------------------- +// +// Pitch Refinement Window +// +//----------------------------------------------------------------------------- +const Word16 wr[] = +{ + 487, 570, 658, 753, 854, 962, 1076, 1197, 1325, 1460, + 1602, 1752, 1909, 2074, 2246, 2426, 2614, 2810, 3014, 3227, + 3447, 3675, 3912, 4157, 4410, 4671, 4941, 5219, 5505, 5799, + 6101, 6411, 6729, 7054, 7388, 7728, 8077, 8432, 8795, 9164, + 9541, 9923, 10312, 10707, 11108, 11515, 11927, 12344, 12766, 13192, + 13622, 14056, 14494, 14935, 15379, 15825, 16273, 16724, 17175, 17628, + 18081, 18534, 18988, 19440, 19892, 20342, 20790, 21237, 21680, 22120, + 22557, 22990, 23419, 23842, 24261, 24673, 25080, 25480, 25874, 26259, + 26638, 27008, 27370, 27722, 28066, 28400, 28724, 29037, 29340, 29632, + 29912, 30181, 30438, 30683, 30915, 31135, 31341, 31535, 31715, 31881, + 32033, 32172, 32296, 32406, 32502, 32583, 32649, 32701, 32738, 32760, +}; + +//----------------------------------------------------------------------------- +// +// Real Part Spectrum of Pitch Refinement Window * 256 +// +//----------------------------------------------------------------------------- +const Word16 wr_sp[] = +{ + 16, 43, 71, 102, 135, 170, 207, 247, 289, 333, + 380, 430, 483, 538, 596, 657, 721, 787, 857, 930, + 1006, 1085, 1168, 1254, 1343, 1435, 1531, 1630, 1733, 1840, + 1950, 2063, 2181, 2302, 2426, 2555, 2687, 2823, 2962, 3106, + 3253, 3404, 3559, 3718, 3881, 4047, 4218, 4392, 4570, 4751, + 4937, 5126, 5319, 5516, 5716, 5920, 6128, 6339, 6554, 6772, + 6994, 7219, 7447, 7679, 7914, 8152, 8393, 8637, 8884, 9134, + 9387, 9642, 9900, 10160, 10423, 10688, 10956, 11225, 11497, 11770, + 12045, 12322, 12601, 12881, 13162, 13444, 13728, 14012, 14298, 14584, + 14871, 15158, 15445, 15733, 16020, 16308, 16595, 16882, 17168, 17454, + 17738, 18022, 18305, 18586, 18866, 19145, 19421, 19696, 19969, 20240, + 20508, 20774, 21037, 21298, 21556, 21811, 22062, 22310, 22555, 22796, + 23033, 23267, 23496, 23722, 23943, 24159, 24372, 24579, 24782, 24980, + 25172, 25360, 25542, 25719, 25891, 26057, 26217, 26372, 26520, 26663, + 26800, 26930, 27055, 27173, 27285, 27390, 27489, 27581, 27667, 27746, + 27818, 27884, 27942, 27994, 28039, 28078, 28109, 28133, 28151, 28161, + 28165, 28161, 28151, 28133, 28109, 28078, 28039, 27994, 27942, 27884, + 27818, 27746, 27667, 27581, 27489, 27390, 27285, 27173, 27055, 26930, + 26800, 26663, 26520, 26372, 26217, 26057, 25891, 25719, 25542, 25360, + 25172, 24980, 24782, 24579, 24372, 24159, 23943, 23722, 23496, 23267, + 23033, 22796, 22555, 22310, 22062, 21811, 21556, 21298, 21037, 20774, + 20508, 20240, 19969, 19696, 19421, 19145, 18866, 18586, 18305, 18022, + 17738, 17454, 17168, 16882, 16595, 16308, 16020, 15733, 15445, 15158, + 14871, 14584, 14298, 14012, 13728, 13444, 13162, 12881, 12601, 12322, + 12045, 11770, 11497, 11225, 10956, 10688, 10423, 10160, 9900, 9642, + 9387, 9134, 8884, 8637, 8393, 8152, 7914, 7679, 7447, 7219, + 6994, 6772, 6554, 6339, 6128, 5920, 5716, 5516, 5319, 5126, + 4937, 4751, 4570, 4392, 4218, 4047, 3881, 3718, 3559, 3404, + 3253, 3106, 2962, 2823, 2687, 2555, 2426, 2302, 2181, 2063, + 1950, 1840, 1733, 1630, 1531, 1435, 1343, 1254, 1168, 1085, + 1006, 930, 857, 787, 721, 657, 596, 538, 483, 430, + 380, 333, 289, 247, 207, 170, 135, 102, 71, 43, + 16 +}; + diff --git a/imbe/tbls.h b/imbe/tbls.h new file mode 100644 index 0000000..fd0ade4 --- /dev/null +++ b/imbe/tbls.h @@ -0,0 +1,99 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#ifndef _TBLS +#define _TBLS + + +//----------------------------------------------------------------------------- +// +// Bit allocation and ancillary tables +// +//----------------------------------------------------------------------------- +extern const UWord16 bit_allocation_tbl[]; +extern const UWord16 bit_allocation_offset_tbl[]; + +//----------------------------------------------------------------------------- +// +// Log Magnitude Prediction Residual Block Length +// +//----------------------------------------------------------------------------- +extern const UWord32 lmprbl_tbl[]; + +//----------------------------------------------------------------------------- +// +// Gain Quantizer Levels in Q5.11 format +// +//----------------------------------------------------------------------------- +extern const Word16 gain_qnt_tbl[]; +#define GAIN_QNT_TBL_SIZE 64 + +//----------------------------------------------------------------------------- +// +// Gain Ste Size in unsigned Q0.16 format +// +//----------------------------------------------------------------------------- +extern const UWord16 gain_step_size_tbl[]; + +//----------------------------------------------------------------------------- +// +// Standard Deviation of Higher Order DCT Coefficients in unsigned Q0.16 format +// +//----------------------------------------------------------------------------- +extern const UWord16 hi_ord_std_tbl[]; + +//----------------------------------------------------------------------------- +// +// Quantizer Step for Higher Order DCT Coefficients in unsigned Q1.15 format +// +//----------------------------------------------------------------------------- +extern const UWord16 hi_ord_step_size_tbl[]; + +//----------------------------------------------------------------------------- +// +// Speech Synthesis Window +// +//----------------------------------------------------------------------------- +extern const Word16 ws[]; + +//----------------------------------------------------------------------------- +// +// Squared Pitch Estimation Window 64*wi^2 +// +//----------------------------------------------------------------------------- +extern const Word16 wi[]; + +//----------------------------------------------------------------------------- +// +// Pitch Refinement Window +// +//----------------------------------------------------------------------------- +extern const Word16 wr[]; + +//----------------------------------------------------------------------------- +// +// Real Part Spectrum of Pitch Refinement Window * 256 +// +//----------------------------------------------------------------------------- +extern const Word16 wr_sp[]; + +#endif + diff --git a/imbe/typedef.h b/imbe/typedef.h new file mode 100644 index 0000000..fcf3b4c --- /dev/null +++ b/imbe/typedef.h @@ -0,0 +1,74 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ +/* +******************************************************************************** +* +* GSM AMR speech codec Version 7.4.0 January 31, 2000 +* +******************************************************************************** +* +* File : typedef.c +* Purpose : Basic types. +* +******************************************************************************** +*/ +#ifndef typedef_h +#define typedef_h "$Id $" + +#undef ORIGINAL_TYPEDEF_H /* define to get "original" ETSI version + of typedef.h */ + +#ifdef ORIGINAL_TYPEDEF_H +/* + * this is the original code from the ETSI file typedef.h + */ + +#if defined(__BORLANDC__) || defined(__WATCOMC__) || defined(_MSC_VER) || defined(__ZTC__) +typedef signed char Word8; +typedef short Word16; +typedef long Word32; +typedef int Flag; + +#elif defined(__sun) +typedef signed char Word8; +typedef short Word16; +typedef long Word32; +typedef int Flag; + +#elif defined(__unix__) || defined(__unix) +typedef signed char Word8; +typedef short Word16; +typedef int Word32; +typedef int Flag; + +#endif +#else /* not original typedef.h */ + +/* + * use (improved) type definition file typdefs.h and add a "Flag" type + */ +#include "typedefs.h" +typedef int Flag; + +#endif + +#endif + diff --git a/imbe/typedefs.h b/imbe/typedefs.h new file mode 100644 index 0000000..45fe1a0 --- /dev/null +++ b/imbe/typedefs.h @@ -0,0 +1,201 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ +/* +******************************************************************************** +* +* GSM AMR speech codec Version 7.4.0 January 31, 2000 +* +******************************************************************************** +* +* File : typedefs.h +* Description : Definition of platform independent data +* types and constants +* +* +* The following platform independent data types and corresponding +* preprocessor (#define) constants are defined: +* +* defined type meaning corresponding constants +* ---------------------------------------------------------- +* Char character (none) +* Bool boolean true, false +* Word8 8-bit signed minWord8, maxWord8 +* UWord8 8-bit unsigned minUWord8, maxUWord8 +* Word16 16-bit signed minWord16, maxWord16 +* UWord16 16-bit unsigned minUWord16, maxUWord16 +* Word32 32-bit signed minWord32, maxWord32 +* UWord32 32-bit unsigned minUWord32, maxUWord32 +* Float floating point minFloat, maxFloat +* +* +* The following compile switches are #defined: +* +* PLATFORM string indicating platform progam is compiled on +* possible values: "OSF", "PC", "SUN" +* +* OSF only defined if the current platform is an Alpha +* PC only defined if the current platform is a PC +* SUN only defined if the current platform is a Sun +* +* LSBFIRST is defined if the byte order on this platform is +* "least significant byte first" -> defined on DEC Alpha +* and PC, undefined on Sun +* +******************************************************************************** +*/ +#ifndef typedefs_h +#define typedefs_h "$Id $" + +/* +******************************************************************************** +* INCLUDE FILES +******************************************************************************** +*/ +#include +#include + +#define __MSDOS__ + +/* +******************************************************************************** +* DEFINITION OF CONSTANTS +******************************************************************************** +*/ +/* + ********* define char type + */ +typedef char Char; + +/* + ********* define 8 bit signed/unsigned types & constants + */ +#if SCHAR_MAX == 127 +typedef signed char Word8; +#define minWord8 SCHAR_MIN +#define maxWord8 SCHAR_MAX + +typedef unsigned char UWord8; +#define minUWord8 0 +#define maxUWord8 UCHAR_MAX +#else +#error cannot find 8-bit type +#endif + + +/* + ********* define 16 bit signed/unsigned types & constants + */ +#if INT_MAX == 32767 +typedef int Word16; +#define minWord16 INT_MIN +#define maxWord16 INT_MAX +typedef unsigned int UWord16; +#define minUWord16 0 +#define maxUWord16 UINT_MAX +#elif SHRT_MAX == 32767 +typedef short Word16; +#define minWord16 SHRT_MIN +#define maxWord16 SHRT_MAX +typedef unsigned short UWord16; +#define minUWord16 0 +#define maxUWord16 USHRT_MAX +#else +#error cannot find 16-bit type +#endif + + +/* + ********* define 32 bit signed/unsigned types & constants + */ +#if INT_MAX == 2147483647 +typedef int Word32; +#define minWord32 INT_MIN +#define maxWord32 INT_MAX +typedef unsigned int UWord32; +#define minUWord32 0 +#define maxUWord32 UINT_MAX +#elif LONG_MAX == 2147483647 +typedef long Word32; +#define minWord32 LONG_MIN +#define maxWord32 LONG_MAX +typedef unsigned long UWord32; +#define minUWord32 0 +#define maxUWord32 ULONG_MAX +#else +#error cannot find 32-bit type +#endif + +/* + ********* define floating point type & constants + */ +/* use "#if 0" below if Float should be double; + use "#if 1" below if Float should be float + */ +#if 0 +typedef float Float; +#define maxFloat FLT_MAX +#define minFloat FLT_MIN +#else +typedef double Float; +#define maxFloat DBL_MAX +#define minFloat DBL_MIN +#endif + +/* + ********* define complex type + */ +typedef struct { + Float r; /* real part */ + Float i; /* imaginary part */ +} CPX; + +/* + ********* define boolean type + */ +typedef int Bool; +#define false 0 +#define true 1 + +/* + ********* Check current platform + */ +#if defined(__MSDOS__) +#define PC +#define PLATFORM "PC" +#define LSBFIRST +#elif defined(__osf__) +#define OSF +#define PLATFORM "OSF" +#define LSBFIRST +#elif defined(__sun__) || defined(__sun) +#define SUN +#define PLATFORM "SUN" +#undef LSBFIRST +#elif defined(linux) && defined(i386) +#define PC +#define PLATFORM "PC" +#define LSBFIRST +#else +#error "can't determine architecture; adapt typedefs.h to your platform" +#endif + +#endif + diff --git a/imbe/uv_synt.cc b/imbe/uv_synt.cc new file mode 100644 index 0000000..2c319d9 --- /dev/null +++ b/imbe/uv_synt.cc @@ -0,0 +1,147 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#include "typedef.h" +#include "basic_op.h" +#include "imbe.h" +#include "aux_sub.h" +#include "dsp_sub.h" +#include "math_sub.h" +#include "uv_synt.h" +#include "rand_gen.h" +#include "tbls.h" +#include "encode.h" +#include "imbe_vocoder_impl.h" + + + + +void imbe_vocoder_impl::uv_synt_init(void) +{ + fft_init(); + v_zap(uv_mem, 105); +} + + + + + + +void imbe_vocoder_impl::uv_synt(IMBE_PARAM *imbe_param, Word16 *snd) +{ + Cmplx16 Uw[FFTLENGTH]; + Word16 i, index_a, index_b, index_aux, ha, hb, *v_uv_dsn_ptr, *sa_ptr, sa; + Word32 fund_freq, fund_freq_2, fund_freq_acc_a, fund_freq_acc_b; + + sa_ptr = imbe_param->sa; + v_uv_dsn_ptr = imbe_param->v_uv_dsn; + fund_freq = imbe_param->fund_freq; + fund_freq_2 = L_shr(fund_freq, 1); + + v_zap((Word16 *)&Uw, 2 * FFTLENGTH); + + fund_freq_acc_a = L_sub(fund_freq, fund_freq_2); + fund_freq_acc_b = L_add(fund_freq, fund_freq_2); + + for(i = 0; i < imbe_param->num_harms; i++) + { + ha = extract_h(fund_freq_acc_a); + hb = extract_h(fund_freq_acc_b); + index_a = (ha >> 8) + ((ha & 0xFF)?1:0); + index_b = (hb >> 8) + ((hb & 0xFF)?1:0); + + index_aux = 256 - index_a; + + sa = shl(*sa_ptr, 3); + + if(*v_uv_dsn_ptr++) + { + while(index_a < index_b) + { + Uw[index_a].re = Uw[index_a].im = 0; + Uw[index_aux].re = Uw[index_aux].im = 0; + index_a++; + index_aux--; + } + } + else + { + while(index_a < index_b) + { + Uw[index_a].re = mult(sa, rand_gen()); + Uw[index_a].im = mult(sa, rand_gen()); + //Uw[index_a].re = sa; + //Uw[index_a].im = sa; + + Uw[index_aux].re = Uw[index_a].re; + Uw[index_aux].im = negate(Uw[index_a].im); + index_a++; + index_aux--; + } + } + + fund_freq_acc_a = L_add(fund_freq_acc_a, fund_freq); + fund_freq_acc_b = L_add(fund_freq_acc_b, fund_freq); + sa_ptr++; + } + +/* + j = 128; + for(i = 0; i < 128; i++) + Uw_tmp[j++] = Uw[i]; + + j = 128; + for(i = 0; i < 128; i++) + Uw_tmp[i] = Uw[j++]; + + for(i = 0; i < 256; i++) + Uw[i] = Uw_tmp[i]; +*/ + + + fft((Word16 *)&Uw, FFTLENGTH, -1); + + for(i = 0; i < 105; i++) + snd[i] = uv_mem[i]; + + index_aux = 73; + for(i = 105; i < FRAME; i++) + snd[i] = shl(Uw[index_aux++].re, 3); + + + // Weighted Overlap Add Algorithm + index_aux = 24; + index_a = 0; + index_b = 48; + for(i = 56; i < 105; i++) + { + snd[i] = extract_h(L_add(L_mult(snd[i], ws[index_b]), L_mult(shl(Uw[index_aux].re, 3), ws[index_a]))); + + index_aux++; + index_a++; + index_b--; + } + + index_aux = 128; + for(i = 0; i < 105; i++) + uv_mem[i] = shl(Uw[index_aux++].re, 3); +} + diff --git a/imbe/uv_synt.h b/imbe/uv_synt.h new file mode 100644 index 0000000..ef04cb7 --- /dev/null +++ b/imbe/uv_synt.h @@ -0,0 +1,29 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + +#ifndef _UV_SYNT +#define _UV_SYNT + +void uv_synt_init(void); +void uv_synt(IMBE_PARAM *imbe_param, Word16 *snd); +void fft(Word16 *datam1, Word16 nn, Word16 isign); + +#endif diff --git a/imbe/v_synt.cc b/imbe/v_synt.cc new file mode 100644 index 0000000..13b63a2 --- /dev/null +++ b/imbe/v_synt.cc @@ -0,0 +1,248 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#include "typedef.h" +#include "basic_op.h" +#include "imbe.h" +#include "aux_sub.h" +#include "dsp_sub.h" +#include "math_sub.h" +#include "v_synt.h" +#include "rand_gen.h" +#include "tbls.h" +#include "encode.h" +#include "imbe_vocoder_impl.h" + + + + + + +#define CNST_0_1_Q1_15 0x0CCD + + + +void imbe_vocoder_impl::v_synt_init(void) +{ + Word16 i; + + for(i = 0; i < NUM_HARMS_MAX; i++) + { + ph_mem[i] = L_deposit_h(rand_gen()); + vu_dsn_prev[i] = 0; + } + + num_harms_prev3 = 0; + fund_freq_prev = 0; +} + + +void imbe_vocoder_impl::v_synt(IMBE_PARAM *imbe_param, Word16 *snd) +{ + Word32 L_tmp, L_tmp1, fund_freq, L_snd[FRAME], L_ph_acc, L_ph_step; + Word32 L_ph_acc_aux, L_ph_step_prev, L_amp_acc, L_amp_step, L_ph_step_aux; + Word16 num_harms, i, j, *vu_dsn, *sa, *s_ptr, *s_ptr_aux, num_harms_max, num_harms_max_4; + UWord32 ph_mem_prev[NUM_HARMS_MAX], dph[NUM_HARMS_MAX]; + Word16 num_harms_inv, num_harms_sh, num_uv; + Word16 freq_flag; + + + fund_freq = imbe_param->fund_freq; + num_harms = imbe_param->num_harms; + vu_dsn = imbe_param->v_uv_dsn; + sa = imbe_param->sa; + num_harms_inv = imbe_param->div_one_by_num_harm; + num_harms_sh = imbe_param->div_one_by_num_harm_sh; + num_uv = imbe_param->l_uv; + + for(i = 0; i < FRAME; i++) + L_snd[i] = 0; + + // Update phases (calculated phase value correspond to bound of frame) + L_tmp = (((fund_freq_prev + fund_freq) >> 7) * FRAME/2) << 7; // It is performed integer multiplication by mod 1 + + L_ph_acc = 0; + for(i = 0; i < NUM_HARMS_MAX; i++) + { + ph_mem_prev[i] = ph_mem[i]; + L_ph_acc += L_tmp; + ph_mem[i] += L_ph_acc; + dph[i] = 0; + } + + num_harms_max = (num_harms >= num_harms_prev3)?num_harms:num_harms_prev3; + num_harms_max_4 = num_harms_max >> 2; + + if(L_abs(L_sub(fund_freq, fund_freq_prev)) >= L_mpy_ls(fund_freq, CNST_0_1_Q1_15)) + freq_flag = 1; + else + freq_flag = 0; + + L_ph_step = L_ph_step_prev = 0; + for(i = 0; i < num_harms_max; i++) + { + L_ph_step += fund_freq; + L_ph_step_prev += fund_freq_prev; + + + if(i > num_harms_max_4) + { + if(num_uv == num_harms) + { + dph[i] = L_deposit_h(rand_gen()); + } + else + { + L_tmp = L_mult(rand_gen(), num_harms_inv); + dph[i] = L_shr(L_tmp, 15 - num_harms_sh) * num_uv; + } + ph_mem[i] += dph[i]; + } + + if(vu_dsn[i] == 0 && vu_dsn_prev[i] == 0) + continue; + + if(vu_dsn[i] == 1 && vu_dsn_prev[i] == 0) // unvoiced => voiced + { + s_ptr = (Word16 *)ws; + L_ph_acc = ph_mem[i] - (((L_ph_step >> 7) * 104) << 7); + for(j = 56; j <= 104; j++) + { + L_tmp = L_mult(*s_ptr++, sa[i]); + L_tmp = L_mpy_ls(L_tmp, cos_fxp(extract_h(L_ph_acc))); + L_tmp = L_shr(L_tmp, 1); + L_snd[j] = L_add(L_snd[j], L_tmp); + L_ph_acc += L_ph_step; + } + + for(j = 105; j <= 159; j++) + { + L_tmp = L_mult(sa[i], cos_fxp(extract_h(L_ph_acc))); + L_tmp = L_shr(L_tmp, 1); + L_snd[j] = L_add(L_snd[j], L_tmp); + L_ph_acc += L_ph_step; + } + continue; + } + + + if(vu_dsn[i] == 0 && vu_dsn_prev[i] == 1) // voiced => unvoiced + { + s_ptr = (Word16 *)&ws[48]; + L_ph_acc = ph_mem_prev[i]; + + for(j = 0; j <= 55; j++) + { + L_tmp = L_mult(sa_prev3[i], cos_fxp(extract_h(L_ph_acc))); + L_tmp = L_shr(L_tmp, 1); + L_snd[j] = L_add(L_snd[j], L_tmp); + L_ph_acc += L_ph_step_prev; + } + + for(j = 56; j <= 104; j++) + { + L_tmp = L_mult(*s_ptr--, sa_prev3[i]); + L_tmp = L_mpy_ls(L_tmp, cos_fxp(extract_h(L_ph_acc))); + L_tmp = L_shr(L_tmp, 1); + L_snd[j] = L_add(L_snd[j], L_tmp); + L_ph_acc += L_ph_step_prev; + } + continue; + } + + if(i >=7 || freq_flag) + { + s_ptr_aux = (Word16 *)&ws[48]; + L_ph_acc_aux = ph_mem_prev[i]; + + s_ptr = (Word16 *)ws; + L_ph_acc = ph_mem[i] - (((L_ph_step >> 7) * 104) << 7); + + for(j = 0; j <= 55; j++) + { + L_tmp = L_mult(sa_prev3[i], cos_fxp(extract_h(L_ph_acc_aux))); + L_tmp = L_shr(L_tmp, 1); + L_snd[j] = L_add(L_snd[j], L_tmp); + L_ph_acc_aux += L_ph_step_prev; + } + + for(j = 56; j <= 104; j++) + { + L_tmp = L_mult(*s_ptr_aux--, sa_prev3[i]); + L_tmp = L_mpy_ls(L_tmp, cos_fxp(extract_h(L_ph_acc_aux))); + L_tmp = L_shr(L_tmp, 1); + L_snd[j] = L_add(L_snd[j], L_tmp); + + L_tmp = L_mult(*s_ptr++, sa[i]); + L_tmp = L_mpy_ls(L_tmp, cos_fxp(extract_h(L_ph_acc))); + L_tmp = L_shr(L_tmp, 1); + L_snd[j] = L_add(L_snd[j], L_tmp); + + L_ph_acc_aux += L_ph_step_prev; + L_ph_acc += L_ph_step; + } + + for(j = 105; j <= 159; j++) + { + L_tmp = L_mult(sa[i], cos_fxp(extract_h(L_ph_acc))); + L_tmp = L_shr(L_tmp, 1); + L_snd[j] = L_add(L_snd[j], L_tmp); + L_ph_acc += L_ph_step; + } + continue; + } + + L_amp_step = L_mpy_ls(L_shr(L_deposit_h(sub(sa[i], sa_prev3[i])), 4 + 1), CNST_0_1_Q1_15); // (sa[i] - sa_prev3[i]) / 160, 1/160 = 0.1/16 + L_amp_acc = L_shr(L_deposit_h(sa_prev3[i]), 1); + + + L_ph_step_aux = L_mpy_ls(L_shr(fund_freq - fund_freq_prev, 4 + 1), CNST_0_1_Q1_15); // (fund_freq - fund_freq_prev)/(2*160) + L_ph_step_aux = ((L_ph_step_aux >> 7) * (i + 1)) << 7; + + L_ph_acc = ph_mem_prev[i]; + + L_tmp1 = L_mpy_ls(L_shr(dph[i], 4), CNST_0_1_Q1_15); // dph[i] / 160 + + for(j = 0; j < 160; j++) + { + L_ph_acc_aux = ((L_ph_step_aux >> 9) * j) << 9; + L_ph_acc_aux = ((L_ph_acc_aux >> 9) * j) << 9; + + L_tmp = L_mpy_ls(L_amp_acc, cos_fxp(extract_h(L_ph_acc + L_ph_acc_aux))); + L_snd[j] = L_add(L_snd[j], L_tmp); + + L_amp_acc = L_add(L_amp_acc, L_amp_step); + L_ph_acc += L_ph_step_prev; + L_ph_acc += L_tmp1; + } + } + + for(i = 0; i < FRAME; i++) + *snd++ = extract_h(L_snd[i]); + + v_zap(vu_dsn_prev, NUM_HARMS_MAX); + v_equ(vu_dsn_prev, imbe_param->v_uv_dsn, num_harms); + v_equ(sa_prev3, imbe_param->sa, num_harms); + + num_harms_prev3 = num_harms; + fund_freq_prev = fund_freq; +} diff --git a/imbe/v_synt.h b/imbe/v_synt.h new file mode 100644 index 0000000..2139fb2 --- /dev/null +++ b/imbe/v_synt.h @@ -0,0 +1,30 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _V_SYNT +#define _V_SYNT + +void v_synt_init(void); +void v_synt(IMBE_PARAM *imbe_param, Word16 *snd); + + +#endif diff --git a/imbe/v_uv_det.cc b/imbe/v_uv_det.cc new file mode 100644 index 0000000..bf721cf --- /dev/null +++ b/imbe/v_uv_det.cc @@ -0,0 +1,373 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#include "typedef.h" +#include "globals.h" +#include "imbe.h" +#include "basic_op.h" +#include "aux_sub.h" +#include "math_sub.h" +#include "dsp_sub.h" +#include "tbls.h" +#include "v_uv_det.h" + +#include +#include +#include +#include "encode.h" +#include "imbe_vocoder_impl.h" + + +#define CNST_0_5625_Q1_15 0x4800 +#define CNST_0_45_Q1_15 0x3999 +#define CNST_0_1741_Q1_15 0x164A +#define CNST_0_1393_Q1_15 0x11D5 +#define CNST_0_99_Q1_15 0x7EB8 +#define CNST_0_01_Q1_15 0x0148 +#define CNST_0_0025_Q1_15 0x0051 +#define CNST_0_25_Q1_15 0x2000 +#define CNST_PI_4_Q1_15 0x6488 +#define CNST_0_55_Q4_12 0x08CD + + + + + + + +extern FILE *fp_in, *fp_out; +extern int frame_cnt; + + +void imbe_vocoder_impl::pitch_ref_init(void) +{ + v_zap(v_uv_dsn, NUM_BANDS_MAX); + th_max = 0; +} + +Word16 imbe_vocoder_impl::voiced_sa_calc(Word32 num, Word16 den) +{ + Word16 tmp; + Word32 L_tmp; + + L_tmp = L_mpy_ls(num, den); + L_tmp = sqrt_l_exp(L_tmp, &tmp); + L_tmp = L_shr(L_tmp, tmp - 3); + + //L_tmp =0; + //return (Word16)(2*256.0*sqrt(2*(double)num/(double)den)); + return extract_h(L_tmp); +} + +Word16 imbe_vocoder_impl::unvoiced_sa_calc(Word32 num, Word16 den) +{ + Word16 shift, tmp; + Word32 L_tmp; + + shift = norm_s(den); + tmp = div_s(0x4000, shl(den, shift)); + L_tmp = L_shl(L_mpy_ls(num, tmp), shift + 2); + L_tmp = sqrt_l_exp(L_tmp, &tmp); + L_tmp = L_shr(L_tmp, tmp - 2 + 6); + L_tmp = L_mpy_ls(L_tmp, 0x4A76); + + //L_tmp =0; + //return (Word16)(2*0.1454 * sqrt(2*256*(double)num/(double)den)); + return extract_h(L_tmp); +} + +//============================================================================= +// +// Voiced/Unvoiced Determination & Spectral Amplitudes Estimation +// +//============================================================================= +void imbe_vocoder_impl::v_uv_det(IMBE_PARAM *imbe_param, Cmplx16 *fft_buf) +{ + Word16 i, j, index_a_save, tmp, index_wr; + Word32 fund_freq, fund_freq_2, fund_freq_acc_a, fund_freq_acc_b, fund_freq_acc, fund_fr_acc, L_tmp, amp_re_acc, amp_im_acc; + Word16 ha, hb, index_a, index_b, index_tbl[30], it_ind, re_tmp, im_tmp, re_tmp2, im_tmp2, sc_coef; + Word32 Sw_sum, M_num[NUM_HARMS_MAX], M_num_sum, M_den_sum, D_num, D_den, th_lf, th_hf, th0, fund_fr_step, M_fcn_num, M_fcn_den; + Word16 sp_rec_re, sp_rec_im, M_fcn; + Word16 band_cnt, num_harms_cnt, uv_harms_cnt, Dk; + Word16 num_harms, num_bands, dsn_thr=0; + Word16 thr[NUM_BANDS_MAX], M_den[NUM_HARMS_MAX], b1_vec; + + + fund_freq = imbe_param->fund_freq; + + tmp = shr( add( shr(imbe_param->ref_pitch, 1), CNST_0_25_Q8_8), 8); // fix(pitch_cand / 2 + 0.5) + num_harms = extract_h((UWord32)CNST_0_9254_Q0_16 * tmp); // fix(0.9254 * fix(pitch_cand / 2 + 0.5)) + if(num_harms < NUM_HARMS_MIN) + num_harms = NUM_HARMS_MIN; + else if(num_harms > NUM_HARMS_MAX) + num_harms = NUM_HARMS_MAX; + + if(num_harms <= 36) + num_bands = extract_h((UWord32)(num_harms + 2) * CNST_0_33_Q0_16); // fix((L+2)/3) + else + num_bands = NUM_BANDS_MAX; + + imbe_param->num_harms = num_harms; + imbe_param->num_bands = num_bands; + + //========================================================================= + // + // M(th) function calculation + // + //========================================================================= + for(j = 0, th_lf = 0; j < 64; j++) + { + th_lf = L_mac(th_lf, fft_buf[j].re, fft_buf[j].re); + th_lf = L_mac(th_lf, fft_buf[j].im, fft_buf[j].im); + } + for(j = 64, th_hf = 0; j < 128; j++) + { + th_hf = L_mac(th_hf, fft_buf[j].re, fft_buf[j].re); + th_hf = L_mac(th_hf, fft_buf[j].im, fft_buf[j].im); + } + th0 = L_add(th_lf, th_hf); + + if(th0 > th_max) + th_max = L_shr(L_add(th_max, th0), 1); + else + th_max = L_add(L_mpy_ls(th_max, CNST_0_99_Q1_15), L_mpy_ls(th0, CNST_0_01_Q1_15)); + + M_fcn_num = L_add(th0, L_mpy_ls(th_max, CNST_0_0025_Q1_15)); + M_fcn_den = L_add(th0, L_mpy_ls(th_max, CNST_0_01_Q1_15)); + if(M_fcn_den == 0) + M_fcn = CNST_0_25_Q1_15; + else + { + tmp = norm_l(M_fcn_den); + M_fcn_den = L_shl(M_fcn_den, tmp); + M_fcn_num = L_shl(M_fcn_num, tmp); + + M_fcn = div_s(extract_h(M_fcn_num), extract_h(M_fcn_den)); + + if(th_lf < (L_tmp= L_add(L_shl(th_hf, 2), th_hf))) // compare th_lf < 5*th_hf + { + tmp = norm_l(L_tmp); + M_fcn_den = L_shl(L_tmp, tmp); + th_lf = L_shl(th_lf, tmp); + + tmp = div_s(extract_h(th_lf), extract_h(M_fcn_den)); + L_tmp = sqrt_l_exp(L_deposit_h(tmp), &tmp); + if(tmp) + L_tmp = L_shr(L_tmp, tmp); + M_fcn = mult(M_fcn, extract_h(L_tmp)); + } + } + // ======================================================================== + fund_fr_step = L_shl(L_mpy_ls(fund_freq, CNST_PI_4_Q1_15), 2); // mult by PI + + uv_harms_cnt = 0; + b1_vec = 0; + band_cnt = 0; + num_harms_cnt = 0; + Sw_sum = 0; + D_num = D_den = 0; + + fund_fr_acc = 0; + fund_freq_acc = fund_freq; + fund_freq_2 = L_shr(fund_freq, 1); + fund_freq_acc_a = L_sub(fund_freq, fund_freq_2); + fund_freq_acc_b = L_add(fund_freq, fund_freq_2); + for(j = 0; j < num_harms; j++) + { + ha = extract_h(fund_freq_acc_a); + hb = extract_h(fund_freq_acc_b); + index_a = (ha >> 8) + ((ha & 0xFF)?1:0); + index_b = (hb >> 8) + ((hb & 0xFF)?1:0); + + L_tmp = L_shl(L_deposit_h(index_a), 8); + L_tmp = L_sub(L_tmp, fund_freq_acc); + L_tmp = L_add(L_tmp, 0x00020000); // for rounding purpose + L_tmp = L_shr(L_tmp, 2); + + index_a_save = index_a; + it_ind = 0; + + // =========== v/uv determination threshold function == + if(num_harms_cnt == 0) // calculate one time per band + { + if(imbe_param->e_p > CNST_0_55_Q4_12 && band_cnt >= 1) + dsn_thr = 0; + else if(v_uv_dsn[band_cnt] == 1) + dsn_thr = mult(M_fcn, sub(CNST_0_5625_Q1_15, mult(CNST_0_1741_Q1_15, extract_h(fund_fr_acc)))); + else + dsn_thr = mult(M_fcn, sub(CNST_0_45_Q1_15, mult(CNST_0_1393_Q1_15, extract_h(fund_fr_acc)))); + + fund_fr_acc = L_add(fund_fr_acc, fund_fr_step); + + thr[band_cnt] = dsn_thr; + } + // ==================================================== + + M_den_sum = 0; + amp_re_acc = amp_im_acc = 0; + while(index_a < index_b) + { + index_wr = extract_h(L_tmp); + if(index_wr < 0 && (L_tmp & 0xFFFF)) // truncating for negative number + index_wr = add(index_wr, 1); + index_wr = add(index_wr, 160); + index_tbl[it_ind++] = index_wr; + if(index_wr >= 0 && index_wr <= 320) + { + amp_re_acc = L_mac(amp_re_acc, fft_buf[index_a].re, wr_sp[index_wr]); + amp_im_acc = L_mac(amp_im_acc, fft_buf[index_a].im, wr_sp[index_wr]); + M_den_sum = L_add(M_den_sum, mult(wr_sp[index_wr], wr_sp[index_wr])); + } + + index_a++; + L_tmp = L_add(L_tmp, 0x400000); + } + sc_coef = div_s(0x4000, extract_l(L_shr(M_den_sum, 1))); + im_tmp2 = mult(extract_h(amp_im_acc), sc_coef); + re_tmp2 = mult(extract_h(amp_re_acc), sc_coef); + + M_num_sum = 0; + it_ind = 0; + index_a = index_a_save; + while(index_a < index_b) + { + index_wr = index_tbl[it_ind++]; + if(index_wr < 0 || index_wr > 320) + sp_rec_re = sp_rec_im = 0; + else + { + sp_rec_im = mult( im_tmp2, wr_sp[index_wr]); + sp_rec_re = mult( re_tmp2, wr_sp[index_wr]); + } + + re_tmp = sub(fft_buf[index_a].re, sp_rec_re); + im_tmp = sub(fft_buf[index_a].im, sp_rec_im); + D_num = L_mac(D_num, re_tmp, re_tmp); + D_num = L_mac(D_num, im_tmp, im_tmp); + + M_num_sum = L_mac(M_num_sum, fft_buf[index_a].re, fft_buf[index_a].re); + M_num_sum = L_mac(M_num_sum, fft_buf[index_a].im, fft_buf[index_a].im); + + index_a++; + } + + M_den[j] = sc_coef; + M_num[j] = M_num_sum; + D_den = L_add(D_den, M_num_sum); + + if(++num_harms_cnt == 3 && band_cnt < num_bands - 1) + { + b1_vec <<= 1; + + if(D_den > D_num && D_den != 0) + { + tmp = norm_l(D_den); + Dk = div_s(extract_h(L_shl(D_num, tmp)), extract_h(L_shl(D_den, tmp))); + } + else + Dk = MAX_16; + + if(Dk < dsn_thr) + { + // voiced band + v_uv_dsn[band_cnt] = 1; + b1_vec |= 1; + i = j - 2; + while(i <= j) + { + imbe_param->sa[i] = voiced_sa_calc(M_num[i], M_den[i]); + imbe_param->v_uv_dsn[i] = 1; + i++; + } + } + else + { + // unvoiced band + v_uv_dsn[band_cnt] = 0; + i = j - 2; + while(i <= j) + { + imbe_param->sa[i] = unvoiced_sa_calc(M_num[i], index_b - index_a_save); + imbe_param->v_uv_dsn[i] = 0; + uv_harms_cnt++; + i++; + } + } + + D_num = D_den = 0; + num_harms_cnt = 0; + band_cnt++; + } + + + fund_freq_acc_a = L_add(fund_freq_acc_a, fund_freq); + fund_freq_acc_b = L_add(fund_freq_acc_b, fund_freq); + fund_freq_acc = L_add(fund_freq_acc, fund_freq); + } + + if(num_harms_cnt) + { + b1_vec <<= 1; + if(D_den > D_num && D_den != 0) + { + tmp = norm_l(D_den); + Dk= div_s(extract_h(L_shl(D_num, tmp)), extract_h(L_shl(D_den, tmp))); + } + else + Dk = MAX_16; + + if(Dk < dsn_thr) + { + // voiced band + v_uv_dsn[band_cnt] = 1; + b1_vec |= 1; + + i = num_harms - num_harms_cnt; + while(i < num_harms) + { + imbe_param->sa[i] = voiced_sa_calc(M_num[i], M_den[i]); + imbe_param->v_uv_dsn[i] = 1; + i++; + } + } + else + { + // unvoiced band + v_uv_dsn[band_cnt] = 0; + i = num_harms - num_harms_cnt; + while(i < num_harms) + { + imbe_param->sa[i] = unvoiced_sa_calc(M_num[i], index_b - index_a_save); + imbe_param->v_uv_dsn[i] = 0; + uv_harms_cnt++; + i++; + } + } + } + + imbe_param->l_uv = uv_harms_cnt; + + + imbe_param->b_vec[1] = b1_vec; // Save encoded voiced/unvoiced decision + imbe_param->b_vec[0] = shr( sub(imbe_param->ref_pitch, 0x1380), 7); // Pitch encode fix(2*pitch - 39) + +} diff --git a/imbe/v_uv_det.h b/imbe/v_uv_det.h new file mode 100644 index 0000000..ebe270f --- /dev/null +++ b/imbe/v_uv_det.h @@ -0,0 +1,28 @@ +/* + * Project 25 IMBE Encoder/Decoder Fixed-Point implementation + * Developed by Pavel Yazev E-mail: pyazev@gmail.com + * Version 1.0 (c) Copyright 2009 + * + * This 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 3, or (at your option) + * any later version. + * + * The software 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 51 Franklin Street, Boston, MA + * 02110-1301, USA. + */ + + +#ifndef _V_UV_DET +#define _V_UV_DET + +void v_uv_det(IMBE_PARAM *imbe_param, Cmplx16 *fft_buf); + +#endif diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..40674d9 --- /dev/null +++ b/main.cpp @@ -0,0 +1,127 @@ +// +// main.cpp +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 13/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#include "main.h" +#include "ctimepoint.h" +#include "cambeserver.h" +#include "cudpsocket.h" +#include "cconfig.h" + +#include "syslog.h" +#include + +//////////////////////////////////////////////////////////////////////////////////////// +// global objects + + +//////////////////////////////////////////////////////////////////////////////////////// +// function declaration + + +int main(int argc, const char * argv[]) +{ +#ifdef RUN_AS_DAEMON + + // redirect cout, cerr and clog to syslog + syslog::redirect cout_redir(std::cout); + syslog::redirect cerr_redir(std::cerr); + syslog::redirect clog_redir(std::clog); + + //Fork the Parent Process + pid_t pid, sid; + pid = ::fork(); + //pid = ::vfork(); + if ( pid < 0 ) + { + exit(EXIT_FAILURE); + } + + // We got a good pid, Close the Parent Process + if (pid > 0) + { + exit(EXIT_SUCCESS); + } + + // Change File Mask + ::umask(0); + + //Create a new Signature Id for our child + sid = ::setsid(); + if (sid < 0) + { + exit(EXIT_FAILURE); + } + + // Change Directory + // If we cant find the directory we exit with failure. + if ( (::chdir("/")) < 0) + { + exit(EXIT_FAILURE); + } + + // Close Standard File Descriptors + close(STDIN_FILENO); + close(STDOUT_FILENO); + close(STDERR_FILENO); + +#endif + + // check arguments, the listen IP used to be an argument and is now in ambed.ini + if ( argc > 2 || (argc == 2 && g_Config.IsValidIp(argv[1])) ) + { + std::cout << "Usage: ambed [ambed.ini]" << std::endl; + std::cout << "example: ambed /ambed/ambed.ini" << std::endl; + std::cout << "The listen IP is now LISTEN_IP in ambed.ini" << std::endl; + return 1; + } + + // load the settings, main.h defaults without an ambed.ini + if ( argc == 2 ) + { + g_Config.Load(argv[1]); + } + + // initialize ambeserver + g_AmbeServer.SetListenIp(CIp(g_Config.GetListenIp().c_str())); + + // and let it run + std::cout << "Starting AMBEd " << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_REVISION << std::endl << std::endl; + if ( !g_AmbeServer.Start() ) + { + std::cout << "Error starting AMBEd" << std::endl; + exit(EXIT_FAILURE); + } + std::cout << "AMBEd started and listening on " << g_AmbeServer.GetListenIp() << ":" << g_Config.GetListenPort() << std::endl; + + // Log DSCP status once at startup + CUdpSocket::LogDscpStatus(); + + // run forever — shutdown is handled by process termination + // (destructors of static objects run on exit) + for (;;) + { + CTimePoint::TaskSleepFor(CONFIG_RELOAD_PERIOD * 1000); + g_Config.Reload(); + } +} diff --git a/main.h b/main.h new file mode 100644 index 0000000..7cea0c2 --- /dev/null +++ b/main.h @@ -0,0 +1,191 @@ +// +// main.h +// ambed +// +// Created by Jean-Luc Deltombe (LX3JL) on 13/04/2017. +// Copyright © 2015 Jean-Luc Deltombe (LX3JL). All rights reserved. +// +// ---------------------------------------------------------------------------- +// This file is part of ambed. +// +// xlxd 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 3 of the License, or +// (at your option) any later version. +// +// xlxd 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 Foobar. If not, see . +// ---------------------------------------------------------------------------- + +#ifndef main_h +#define main_h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////// +// defines + +// version ----------------------------------------------------- + +#define VERSION_MAJOR 1 +#define VERSION_MINOR 5 +#define VERSION_REVISION 0 + +// global ------------------------------------------------------ +//#define RUN_AS_DAEMON +//#define DEBUG_DUMPFILE + +// Network, also overridden by ambed.ini +#define LISTEN_IP "127.0.0.1" // IP to bind to +#define LISTEN_PORT 10100 // UDP port, xlxd's TRANSCODER_PORT must match + +// QoS - set DSCP/TOS on outgoing packets for network prioritization, also overridden by ambed.ini +// DSCP values: 0-63 (6 bits). Common choices for voice: +// 46 (EF) - Expedited Forwarding, highest priority voice +// 34 (AF41)- Assured Forwarding class 4, high priority +// 26 (AF31)- Assured Forwarding class 3, medium-high priority +// 0 - Best effort (default, no priority) +#define DSCP_MARKING_ENABLE 1 // 1 = enable, 0 = disable +#define DSCP_VALUE 46 // DSCP value (0-63) + +// Codecs ------------------------------------------------------- +#define CODEC_NONE 0 +#define CODEC_AMBEPLUS 1 +#define CODEC_AMBE2PLUS 2 +#define CODEC_CODEC2 3 +#define CODEC_IMBE 4 +#define NB_OF_CODECS 5 // CODEC_NONE to CODEC_IMBE + +// Frame sizes -------------------------------------------------- +#define AMBE_FRAME_SIZE 9 +#define CODEC2_FRAME_SIZE 8 +#define IMBE_FRAME_SIZE 11 + +// Transcoding gains, in dB. These are the defaults, ambed.ini overrides them at runtime. +// Every path is: decode -> _TO_PCM -> bandpass filter -> AGC -> PCM_TO_ -> encode +#define DSTAR_TO_PCM -10.0f // D-Star (AMBE+) decode +#define DMR_TO_PCM -1.5f // DMR, YSF and NXDN (AMBE2+) decode +#define M17_TO_PCM -10.75f // M17 (Codec2) decode +#define P25_TO_PCM -3.75f // P25 (IMBE) decode +#define PCM_TO_DSTAR +11.5f // D-Star (AMBE+) encode +#define PCM_TO_DMR 0.0f // DMR, YSF and NXDN (AMBE2+) encode +#define PCM_TO_M17 +5.25f // M17 (Codec2) encode +#define PCM_TO_P25 +0.75f // P25 (IMBE) encode + +// AGC, also overridden by ambed.ini. It levels each speaker: fast down, hold +// through gaps, then up, faster the further a station is below the target +#define USE_AGC 1 // 1=AGC, 0=no AGC +#define AGC_TARGET -41.0f // speech peak level the AGC aims for, in dBFS +#define AGC_CLAMPING 9.0f // most the AGC can move the gain either way in dB, 0=off +#define AGC_ATTACK 150.0f // in ms, how fast the gain comes down +#define AGC_HANG 1000.0f // in ms, how long the gain holds before it can rise +#define AGC_RECOVERY 2.0f // in dB/s for each dB below the target, how fast the gain rises +#define AGC_RECOVERY_MIN 3.0f // in dB/s, slowest rise +#define AGC_RECOVERY_MAX 20.0f // in dB/s, fastest rise +#define AGC_GATE -60.0f // in dBFS, quieter frames don't move the gain +#define AGC_CEILING -1.0f // in dBFS, the limiter keeps the loudest encoder input below this, not in ambed.ini + +// Bandpass filter on PCM, also overridden by ambed.ini +#define USE_BANDPASSFILTER 1 // 1=on, 0=off + +// Tuning ------------------------------------------------------- +#define TUNING_LOG 1 // 1 = log levels when a stream closes, 0 = off, also overridden by ambed.ini +#define CONFIG_RELOAD_PERIOD 180 // in seconds, how often ambed.ini is checked +#define TUNING_SILENCE_LEVEL -55.0f // in dBFS, decoded frames below this aren't voice + +// Software queue depth limit - prevents unbounded growth if hardware stalls +// At 50 frames/sec, 50 = 1 second of buffering +#define SOFTWARE_QUEUE_MAX_DEPTH 50 + +// Timeouts, also overridden by ambed.ini ------------------------ +#define STREAM_ACTIVITY_TIMEOUT 3 // in seconds + +// XOMBE software vocoder, also overridden by ambed.ini (needs a restart) +#define XOMBE_THREADS 0 // 0 = auto (CPU cores, 2..8), or 1..16 +#define XOMBE_PAIRS_PER_THREAD 4 // bidirectional channel pairs per thread (1..16) + +//////////////////////////////////////////////////////////////////////////////////////// +// typedefs + +typedef unsigned char uint8; +typedef unsigned short uint16; +typedef unsigned int uint32; +typedef unsigned int uint; + + +//////////////////////////////////////////////////////////////////////////////////////// +// macros + +#define MIN(a,b) (((a) < (b)) ? (a) : (b)) +#define MAX(a,b) (((a) > (b)) ? (a) : (b)) +#define MAKEWORD(low, high) ((uint16)(((uint8)(low)) | (((uint16)((uint8)(high))) << 8))) +#define MAKEDWORD(low, high) ((uint32)(((uint16)(low)) | (((uint32)((uint16)(high))) << 16))) +#define LOBYTE(w) ((uint8)(uint16)(w & 0x00FF)) +#define HIBYTE(w) ((uint8)((((uint16)(w)) >> 8) & 0xFF)) +#define LOWORD(dw) ((uint16)(uint32)(dw & 0x0000FFFF)) +#define HIWORD(dw) ((uint16)((((uint32)(dw)) >> 16) & 0xFFFF)) + +//////////////////////////////////////////////////////////////////////////////////////// +// FIR Filter coefficients computed to be the closest to the recommended filter in +// Documentation +// +// Following GNU Octave script was used +/* +pkg load signal; +fsamp = 8000; +fcuts = [300 400 3000 3400]; +mags = [0 1 0]; +devs = [0.2 1 0.2]; + +[n,Wn,beta,ftype] = kaiserord(fcuts,mags,devs,fsamp); +n = n + rem(n,2); +hh = fir1(n,Wn,ftype,kaiser(n+1,beta),'noscale'); + +freqz(hh); +[H,f] = freqz(hh,1,1024,fsamp); +plot(f,abs(H)) +disp(hh); +grid +*/ + +const float FILTER_TAPS[] { +-0.05063341f, -0.00060337f, -0.08892498f, -0.02026701f, -0.05940750f, -0.10977641f, 0.03244024f, -0.22304499f, +0.11452865f, 0.72500000f, 0.11452865f, -0.22304499f, 0.03244024f, -0.10977641f, -0.05940750f, -0.02026701f, +-0.08892498f, -0.00060337f, -0.05063341f }; +#define FILTER_TAPS_LENGTH 19 + +//////////////////////////////////////////////////////////////////////////////////////// +// global objects + +class CAmbeServer; +extern CAmbeServer g_AmbeServer; + +class CVocodecs; +extern CVocodecs g_Vocodecs; + +class CConfig; +extern CConfig g_Config; + + +//////////////////////////////////////////////////////////////////////////////////////// +#endif /* main_h */ diff --git a/makefile b/makefile new file mode 100644 index 0000000..b5ba3f8 --- /dev/null +++ b/makefile @@ -0,0 +1,63 @@ +CC?=g++ +XOMBE_DIR?=./xombe +USE_FTDI?=0 + +CFLAGS=-c -O2 -std=c++11 -pthread -I$(XOMBE_DIR)/include -I$(XOMBE_DIR)/build/include +LDFLAGS=-std=c++11 -pthread +XOMBE_LIB=$(XOMBE_DIR)/build/libxombe.a + +ALL_SOURCES=$(wildcard *.cpp) +ifeq ($(USE_FTDI),1) + CFLAGS += -DUSE_FTDI + LIBS = $(XOMBE_LIB) -lftd2xx -lm -Wl,-rpath,/usr/local/lib + SOURCES = $(ALL_SOURCES) +else + LIBS = $(XOMBE_LIB) -lm + SOURCES = $(filter-out cftdidevicedescr.cpp cusb3%.cpp, $(ALL_SOURCES)) +endif + +OBJECTS=$(SOURCES:.cpp=.o) +CODEC2_SOURCES=$(wildcard codec2/*.cpp) +CODEC2_OBJECTS=$(CODEC2_SOURCES:.cpp=.o) +IMBE_SOURCES=$(wildcard imbe/*.cc) +IMBE_OBJECTS=$(IMBE_SOURCES:.cc=.o) +EXECUTABLE=ambed + +.PHONY: all clean distclean install + +all: $(EXECUTABLE) + +$(XOMBE_LIB): + @if [ ! -f "$(XOMBE_DIR)/CMakeLists.txt" ]; then \ + echo "ERRORE: submodule xombe non trovato in $(XOMBE_DIR)."; \ + echo "Esegui: git submodule update --init --recursive"; \ + exit 1; \ + fi + mkdir -p $(XOMBE_DIR)/build + cd $(XOMBE_DIR)/build && cmake -DCMAKE_BUILD_TYPE=Release .. && $(MAKE) xombe + +$(OBJECTS): | $(XOMBE_LIB) + +$(EXECUTABLE): $(XOMBE_LIB) $(OBJECTS) $(CODEC2_OBJECTS) $(IMBE_OBJECTS) + $(CC) $(LDFLAGS) $(OBJECTS) $(CODEC2_OBJECTS) $(IMBE_OBJECTS) $(LIBS) -o $@ + +.cpp.o: + $(CC) $(CFLAGS) $< -o $@ + +codec2/%.o: codec2/%.cpp + $(CC) $(CFLAGS) $< -o $@ + +imbe/%.o: imbe/%.cc + $(CC) $(CFLAGS) $< -o $@ + +clean: + $(RM) $(EXECUTABLE) *.o codec2/*.o imbe/*.o + +distclean: clean + $(RM) -r $(XOMBE_DIR)/build + +install: + mkdir -p /ambed + cp $(EXECUTABLE) /ambed/ + cp ./run /ambed/ + test -f /ambed/ambed.ini || cp ./ambed.ini /ambed/ diff --git a/run b/run new file mode 100644 index 0000000..5122df1 --- /dev/null +++ b/run @@ -0,0 +1,6 @@ +#!/bin/bash +# start ambed server + +sudo rmmod ftdi_sio +sudo rmmod usbserial +sudo /ambed/ambed /ambed/ambed.ini & \ No newline at end of file diff --git a/syslog.h b/syslog.h new file mode 100644 index 0000000..aba8f83 --- /dev/null +++ b/syslog.h @@ -0,0 +1,96 @@ +/************************************************************************* + ** Copyright (C) 2014 Jan Pedersen + ** + ** 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 3 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, see . + *************************************************************************/ + +#ifndef __syslog +#define __syslog + +#include +#include +#include +namespace csyslog { +#include +} + +namespace syslog +{ + struct level { + enum pri { + emerg = LOG_EMERG, // A panic condition + alert = LOG_ALERT, // A condition that should be corrected + critical= LOG_CRIT, // Critical condition, e.g, hard device error + error = LOG_ERR, // Errors + warning = LOG_WARNING, // Warning messages + notice = LOG_NOTICE, // Possibly be handled specially + info = LOG_INFO, // Informational + debug = LOG_DEBUG // For debugging program + }; + }; + + class streambuf : public std::streambuf + { + std::string _buf; + int _level; + + public: + + streambuf() : _level(level::debug) { } + void level(int level) { _level = level; } + + protected: + + int sync() + { + if (_buf.size()) { + csyslog::syslog(_level, "%s", _buf.c_str()); + _buf.erase(); + } + return 0; + } + + int_type overflow(int_type c) + { + if(c == traits_type::eof()) sync(); + else _buf += static_cast(c); + return c; + } + + }; + + class ostream : public std::ostream + { + streambuf _logbuf; + public: + ostream() : std::ostream(&_logbuf) {} + ostream& operator<<(const level::pri lev) { _logbuf.level(lev); return *this; } + }; + + class redirect + { + ostream dst; + std::ostream &src; + std::streambuf * const sbuf; + + public: + redirect(std::ostream & src) : src(src), sbuf(src.rdbuf(dst.rdbuf())) { dst << (&src == &std::cout ? level::info : level::error); } + ~redirect() { src.rdbuf(sbuf); } + }; +} + +#endif + + +