1#!/usr/local/bin/python3.8
2'''
3  Demo receive program for FreeDV API 700D mode.
4
5  cd ~/codec2/build_linux
6  cat ../raw/ve9qrp_10s.raw | ./demo/freedv_700d_tx | ../demo/freedv_700d_rx.py | aplay -f S16_LE
7
8  Credits: Thanks DJ2LS, xssfox, VK5QI
9'''
10
11import ctypes
12from ctypes import *
13import sys
14import pathlib
15import platform
16
17if platform.system() == 'Darwin':
18    libname = pathlib.Path().absolute() / "src/libcodec2.dylib"
19else:
20    libname = pathlib.Path().absolute() / "src/libcodec2.so"
21
22# See: https://docs.python.org/3/library/ctypes.html
23
24c_lib = ctypes.CDLL(libname)
25
26c_lib.freedv_open.argype = [c_int]
27c_lib.freedv_open.restype = c_void_p
28
29c_lib.freedv_get_n_max_speech_samples.argtype = [c_void_p]
30c_lib.freedv_get_n_max_speech_samples.restype = c_int
31
32c_lib.freedv_nin.argtype = [c_void_p]
33c_lib.freedv_nin.restype = c_int
34
35c_lib.freedv_rx.argtype = [c_void_p, c_char_p, c_char_p]
36c_lib.freedv_rx.restype = c_int
37
38FREEDV_MODE_700D = 7 # from freedv_api.h
39freedv = cast(c_lib.freedv_open(FREEDV_MODE_700D), c_void_p)
40
41n_max_speech_samples = c_lib.freedv_get_n_max_speech_samples(freedv)
42speech_out = create_string_buffer(2*n_max_speech_samples)
43
44while True:
45    nin = c_lib.freedv_nin(freedv)
46    demod_in = sys.stdin.buffer.read(nin*2)
47    if len(demod_in) == 0: quit()
48    nout = c_lib.freedv_rx(freedv, speech_out, demod_in)
49    sys.stdout.buffer.write(speech_out[:nout*2])
50