/*
    Tucnak - VHF contest log
    Copyright (C) 2014-2016  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 "sndf.h"

#ifdef HAVE_SNDFILE


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

    
	dsp->sndfile = sf_open (rec? dsp->rec_filename : dsp->play_filename, rec ? SFM_READ : SFM_WRITE, dsp->sfinfo);
    if (!dsp->sndfile){
		char *sferr = z_1250_to_8859_2(g_strdup(sf_strerror(NULL)));
        log_addf(VTEXT(T_CANT_OPEN_FILE_S_S), dsp->name, sferr);
        g_free(sferr);
        goto err;
    }

	if (rec) { // set parameters from file
		dsp->speed = dsp->sfinfo->samplerate;
		dsp->period_time = dsp->frames * 1000 / dsp->speed;
	}

	

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

x:;
    return 0;
} 

int sndfile_close(struct dsp *dsp){
    
    dsp->reset(dsp);
	if (dsp->sndfile) sf_close(dsp->sndfile);
	dsp->sndfile = NULL;
	return 0;
}


int sndfile_write(struct dsp *dsp, void *data, int frames){
	int ret = sf_writef_short(dsp->sndfile, (short*)data, frames);
	return ret;
}


int sndfile_read(struct dsp *dsp, void *data, int frames){
	int ret = sf_readf_short(dsp->sndfile, (short*)data, frames);
	return ret;
}


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


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


int sndfile_set_format(struct dsp *dsp, SF_INFO *sfinfo, int ret){
    g_free(dsp->sfinfo);
    dsp->sfinfo = g_new0(SF_INFO, 1);
    memcpy(dsp->sfinfo, sfinfo, sizeof(SF_INFO));
    return 0;
}    

int sndfile_set_sdr_format(struct dsp *dsp, int frames, int speed, int rec){
    g_free(dsp->sfinfo);
    dsp->sfinfo = g_new0(SF_INFO, 1);
	dsp->sfinfo->format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
	dsp->sfinfo->samplerate = speed;
	dsp->sfinfo->channels = 2;
	
	dsp->speed = speed;
	dsp->channels = 2;
	dsp->frames = frames;
	dsp->samples = dsp->frames * dsp->sfinfo->channels;
	dsp->bytes = dsp->samples * sizeof(short);

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

    return 0;

}    


#endif
