full duplex

This commit is contained in:
Sébastien Bourdeauducq 2024-12-26 17:45:59 +08:00
parent 312ab52eca
commit 75f0393c7c

View File

@ -17,6 +17,7 @@ static std::atomic<float> frequency = 440.0f;
#define SND_SIG 1 #define SND_SIG 1
#define SND_BITS 16 #define SND_BITS 16
#define SND_PCHAN 2 #define SND_PCHAN 2
#define SND_RCHAN 1
#define SND_RATE 44100 #define SND_RATE 44100
#define SND_BUFLEN 4096 #define SND_BUFLEN 4096
@ -25,7 +26,7 @@ static void dsp_thread()
struct sio_hdl *hdl; struct sio_hdl *hdl;
struct sio_par par; struct sio_par par;
hdl = sio_open(SIO_DEVANY, SIO_PLAY, 1); hdl = sio_open(SIO_DEVANY, SIO_PLAY|SIO_REC, 1);
if(hdl == nullptr) { if(hdl == nullptr) {
std::cerr << "failed to open sound device" << std::endl; std::cerr << "failed to open sound device" << std::endl;
return; return;
@ -34,6 +35,7 @@ static void dsp_thread()
par.sig = SND_SIG; par.sig = SND_SIG;
par.bits = SND_BITS; par.bits = SND_BITS;
par.pchan = SND_PCHAN; par.pchan = SND_PCHAN;
par.pchan = SND_RCHAN;
par.rate = SND_RATE; par.rate = SND_RATE;
par.le = SIO_LE_NATIVE; par.le = SIO_LE_NATIVE;
par.xrun = SIO_ERROR; par.xrun = SIO_ERROR;
@ -60,14 +62,15 @@ static void dsp_thread()
size_t buf_out_idx = SND_BUFLEN*SND_PCHAN; size_t buf_out_idx = SND_BUFLEN*SND_PCHAN;
nfds_t nfds = sio_nfds(hdl); nfds_t nfds = sio_nfds(hdl);
struct pollfd pfd[nfds]; struct pollfd pfd[nfds];
while(!shutdown_threads) { while(!shutdown_threads) {
sio_pollfd(hdl, pfd, POLLOUT); sio_pollfd(hdl, pfd, POLLOUT|POLLIN);
poll(pfd, nfds, INFTIM); poll(pfd, nfds, INFTIM);
int revents = sio_revents(hdl, pfd); int revents = sio_revents(hdl, pfd);
if(revents & POLLOUT) { if(revents & POLLOUT) {
uint32_t ftw = frequency*(float)UINT32_MAX/SND_RATE;
if(buf_out_idx == SND_BUFLEN*SND_PCHAN) { if(buf_out_idx == SND_BUFLEN*SND_PCHAN) {
uint32_t ftw = frequency*(float)UINT32_MAX/SND_RATE;
for(int i=0;i<SND_BUFLEN;i++) { for(int i=0;i<SND_BUFLEN;i++) {
buf_out[2*i] = buf_out[2*i+1] = (INT16_MAX-1)*sin(phase*2.0f*(float)M_PI/(float)UINT32_MAX); buf_out[2*i] = buf_out[2*i+1] = (INT16_MAX-1)*sin(phase*2.0f*(float)M_PI/(float)UINT32_MAX);
phase += ftw; phase += ftw;
@ -76,12 +79,14 @@ static void dsp_thread()
} }
size_t written = sio_write(hdl, &buf_out[buf_out_idx], sizeof(buf_out) - buf_out_idx*sizeof(buf_out[0])); size_t written = sio_write(hdl, &buf_out[buf_out_idx], sizeof(buf_out) - buf_out_idx*sizeof(buf_out[0]));
buf_out_idx += written/sizeof(buf_out[0]); buf_out_idx += written/sizeof(buf_out[0]);
if(!written) { }
std::cerr << "failed to write to sound device" << std::endl;
sio_stop(hdl); if(revents & POLLIN) {
sio_close(hdl); int16_t buf_in[SND_BUFLEN*SND_RCHAN];
return; sio_read(hdl, buf_in, sizeof(buf_in));
} for(int i=0;i<10;i++)
std::cout << buf_in[i] << " ";
std::cout << std::endl;
} }
} }