/*
 * GStreamer
 * Copyright (C) 2009 Digitro
 * Author Tiago Katcipis <tiagokatcipis@gmail.com>
 * Author Paulo Pizarro  <paulo.pizarro@gmail.com>
 * Author Rogério Santos <rogerio.santos@digitro.com.br>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * Alternatively, the contents of this file may be used under the
 * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
 * which case the following provisions apply instead of the ones
 * mentioned above:
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "vad_private.h"
#include <string.h>

union pgen {
    unsigned long a;
    void *v;
    unsigned long *l;
    unsigned char *b;
    unsigned short *w;
    short *s;
};

struct _cqueue_s {
    union pgen base;
    union pgen tail;
    union pgen head;
    int size;
};

typedef struct _cqueue_s cqueue_t;

struct _vad_s {
    short vad_buffer[VAD_BUFFER_SIZE];
    cqueue_t cqueue;
    int vad_state;
    unsigned long vad_samples;
    unsigned long vad_power;
    long vad_zcr;
};

VADFilter* vad_new()
{
    VADFilter* vad = malloc(sizeof(VADFilter));
    memset(vad, 0, sizeof(vad));
    vad->cqueue.base.s = vad->vad_buffer;
    vad->cqueue.tail.a = vad->cqueue.head.a = 0;
    vad->cqueue.size = VAD_BUFFER_SIZE;
    return vad;
}

int vad_update(struct _vad_s *p, short *data, int len)
{
    unsigned long tail;
    int frame_type;
    short sample;
    int i;

    for (i = 0; i < len; i++) {
        p->vad_power = VAD_POWER_ALPHA * ((data[i] * data[i] >> 14) & 0xFFFF) + \
                       (0xFFFF - VAD_POWER_ALPHA) * (p->vad_power >> 16) + \
                        ((0xFFFF - VAD_POWER_ALPHA) * (p->vad_power & 0xFFFF) >> 16);
        /* Update VAD buffer */
        p->cqueue.base.s[p->cqueue.head.a] = data[i];
        p->cqueue.head.a = ++p->cqueue.head.a & (p->cqueue.size - 1); 
        if (p->cqueue.head.a == p->cqueue.tail.a)
            p->cqueue.tail.a = ++p->cqueue.tail.a & (p->cqueue.size - 1); 
    }

    tail = p->cqueue.tail.a;
    p->vad_zcr = 0;
    for (;;) {
        sample = p->cqueue.base.s[tail];
        tail = (tail + 1) & (p->cqueue.size - 1);
        if (tail == p->cqueue.head.a) break;
        p->vad_zcr += ((sample & 0x8000) != (p->cqueue.base.s[tail] & 0x8000)) ? 1 : -1;
    }

    frame_type = (p->vad_power > VAD_POWER_THRESHOLD && p->vad_zcr < VAD_ZCR_THRESHOLD) ? VAD_VOICE : VAD_SILENCE;

    if (p->vad_state != frame_type) {
        /* Voice to silence transition */
        if (p->vad_state == VAD_VOICE) {
            p->vad_samples += len;
            if (p->vad_samples >= VAD_HYSTERESIS) {
                p->vad_state = frame_type;
                p->vad_samples = 0;
            }
        }
        else {
            p->vad_state = frame_type;
            p->vad_samples = 0;
        }
    }
    else {
        p->vad_samples = 0;
    }

    return p->vad_state;
}
