/*
    Tucnak - VHF contest log
    Copyright (C) 2014-2015  Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#include "header.h"

#include "fifo.h"
#include "language2.h"
#include "sndpipe.h"




int sndpipe_open(struct dsp *dsp, int rec){
    
    dbg("sndpipe_open(%s)\n", rec?"record":"playback");
    
    zg_free0(dsp->name);
    dsp->name = g_strdup("sndpipe");
    
	dsp->samples = dsp->frames * dsp->channels;
	dsp->bytes = dsp->samples * sizeof(short);

	if (!dsp->pipe_opened){
		if (z_pipe(dsp->pipe) < 0){
			log_addf(VTEXT(T_CANT_OPEN_SOUND_PIPE));
			goto err;
		}
		dsp->pipe_opened = 1;
	}

	z_sock_nonblock(dsp->pipe[0], 1);

	
    //log_addf("sndpipe opened, rate=%d, bufsize=%df %ds %db", dsp->speed, dsp->frames, dsp->samples, dsp->bytes); 
    dbg("sndpipe opened, rate=%d, bufsize=%df %ds %db\n", dsp->speed, dsp->frames, dsp->samples, dsp->bytes); 
    goto x;
    
err:;
    sndpipe_close(dsp);

x:;
    return 0;
} 

int sndpipe_close(struct dsp *dsp){
    dbg("sndpipe_close()\n");
    dsp->reset(dsp);
	z_pipe_close(dsp->pipe[0]);
	z_pipe_close(dsp->pipe[1]);
	dsp->pipe_opened = 0;
	dsp->pipe_opened_for_play = 0;
	return 0;
}


int sndpipe_write(struct dsp *dsp, void *data, int frames){
	int ret;
	int bytes = (frames * dsp->bytes) / dsp->frames;

	ret = z_pipe_write(dsp->pipe[1], data, bytes);
	if (ret > 0) ret = (ret * dsp->frames) / dsp->bytes;
	return ret;
}


int sndpipe_read(struct dsp *dsp, void *data, int frames){
	int ret;
	int bytes = (frames * dsp->bytes) / dsp->frames;

	ret = z_pipe_read(dsp->pipe[0], data, bytes);
	if (ret < 0){
		if (z_sock_wouldblock(z_sock_errno)) return -EWOULDBLOCK;
	}
	if (ret > 0) ret = (ret * dsp->frames) / dsp->bytes;
	return ret;
}


int sndpipe_reset(struct dsp *dsp){
	return 0;
}


int sndpipe_sync(struct dsp *dsp){
	return 0;
}

#ifdef HAVE_SNDFILE
int sndpipe_set_format(struct dsp *dsp, SF_INFO *sfinfo, int ret){
	dsp->speed = sfinfo->samplerate;
	dsp->channels = sfinfo->channels;
	dsp->frames = 0;
    return 0;
}    
#endif

int sndpipe_set_sdr_format(struct dsp *dsp, int frames, int speed, int rec){
	
	dsp->speed = speed;
	dsp->channels = 2;
	dsp->frames = frames;

	if (dsp->speed != 0) dsp->period_time = frames * 1000 / dsp->speed;

    return 0;

}    


