#include <t_services.h>
#include "kernel_id.h"
#include "player.h"
#include "lpc23xx.h"

#define	FM_SAMPRATE	48000

static int loop;
static int abort;

/*
 * FM tuner is connected to TI Codec's line input terminal.
 * Here, we simplay read stereo audio data from codec and
 * send it to pcmsender_task() through DTQ_PCM.
 */
void tuner_listener()
{
    pcm_data *pcm;
    Player_Status *pst;
    int rate;

    pst = get_player();
    rate = FM_SAMPRATE;
    (pst->pdevfuncs[pst->o_device]->init_output)();
    if (pst->o_device == O_USB) {
        (pst->pdevfuncs[O_USB]->rate_set)(rate);
        (pst->pdevfuncs[O_CODEC]->rate_set)(rate);
        codec_input_reset();
    } else {
        (pst->pdevfuncs[O_CODEC]->rate_set)(rate);
    }
    pst->cur_rate = rate;

    loop = 0;
    i2s_flush();

    dly_tsk(20);
    for (abort = 0; abort == 0; loop++) {
        syscall(get_mpf(MPF_PCM, (VP)&pcm));
        pcm->rate = rate;
        pcm->samples = PCM_BSIZE;
        codec_ring_read(pcm->raw_buffer, PCM_BSIZE);
#ifdef DEBUG
        rel_mpf(MPF_PCM, (VP)pcm);
#else
        syscall(snd_dtq(DTQ_PCM, (VP_INT)pcm));
#endif
    }
    snd_dtq(DTQ_PCM, (VP_INT)NULL);

    i2s_stop();
}

void fm_command(int argc, char **argv)
{
    if (argc > 1) {
        if (strncmp(argv[1], "start", 5) == 0)
            act_tsk(TUNER_TASK);
        else if (strncmp(argv[1], "stop", 4) == 0)
            abort = 1;
    }
    cons_printf("abort = %d, loop = %d\n", abort, loop);
}

/*
 * Start FM tuner function.
 * If USB speaker is selected as output device, then we need to
 * activate tuner_listener() task.
 * If codec is selected as output device, we simplay bypass the
 * codec line input to codec output -- loop back in a codec.
 */
void start_tuner_mode()
{
    Player_Status *pst;

    pst = get_player();
    if (pst->o_device == O_USB) {
        act_tsk(TUNER_TASK);
    } else {
        /* Output to codec.
         * Use bypass method. No CPU power required!!
         */
        codec_bypass(1);
    }
}

void finish_tuner_mode()
{
    /* Set abort flag. tuner_listener() task will soon terminate. */
    abort = 1;
    /* XXX: SHOULD USE FLAG WAIT */
    dly_tsk(200);
    /* Reset codec bypass mode */
    codec_bypass(0);
}
