/**************************************************************************
 * Copyright (C) 2017-2017  Unisound
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 **************************************************************************
 *
 * Description : uni_vui_interface.c
 * Author      : yzs.unisound.com
 * Date        : 2018.06.19
 *
 **************************************************************************/
#include <autoconf.h>
#include <stdio.h>
#include <types.h>

#include <driver/uni_timer.h>
#include <driver/uni_delay.h>
#include <driver/uni_cache.h>
#include <driver/uni_pmu_ctrl.h>

#include <lvp_context.h>
#include <lvp_buffer.h>
#include <lvp_pmu.h>
#include <lvp_app_core.h>

#include <kws/ofa_consts.h>
#include <kws/ual_ofa.h>
#include <osal/osal.h>

#include "lvp_audio_in.h"
#include "lvp_system_init.h"

#include "uni_vui_interface.h"

#include "asrfix.h"
#include "grammar.h"
#include "databuf.h"

#define LOG_TAG          "[UNI_VUI]"

#define KWS_DECODER_BUF_SIZE    (1024 * 30)
#define KWS_FRAMES_FBANK_SZIE   (40)
#define KWS_TIMEOUT_DEF         (1000 * 10)
#define STANDBY_TIMEOUT_DEF     (1000 * 10)

typedef enum {
  VUI_RECOGN_INIT = 0,
  VUI_RECOGN_INITED,
  VUI_RECOGN_STOP,
  VUI_RECOGN_RUNNING,
} VuiRecognStatus;

typedef struct {
  VuiRecognStatus status;
  int             session_id;
  VuiRecognModel  model;
  VuiRecognCB     result_cb;
  HANDLE          kws;
  DataBufHandle   databuf;
  unsigned int    time_ms;
  int             timeout;
  int             standby;
  int             standby_cnt;
  int             standby_flg;
  int             standby_timeout;
} Vui;

static Vui g_vui = {VUI_RECOGN_INIT, 0, UNI_LP_WAKEUP, NULL, NULL, NULL, 0, KWS_TIMEOUT_DEF, 0, 0, STANDBY_TIMEOUT_DEF};

char g_decoder_pool[KWS_DECODER_BUF_SIZE] __attribute__ ((aligned(4))) = {0};
static KWSRecognizeCallbackData g_callback_data = {0};

DRAM0_STAGE2_SRAM_ATTR static int _LvpKwsRun(LVP_CONTEXT *context) {
  LVP_CONTEXT_HEADER *ctx_header = context->ctx_header;
  static int padding_flag = -1;
  int i = 0;
  int ctx_number   = CONFIG_LVP_LOGFBANK_FRAME_NUM_PER_CHANNEL / CONFIG_LVP_PCM_FRAME_NUM_PER_CONTEXT;
  unsigned int fbank_len = ctx_header->logfbank_buffer_size / \
                           ctx_header->logfbank_frame_num_per_channel * \
                           ctx_header->pcm_frame_num_per_context;
  if (context->ctx_index + 1 < ctx_number + 2) {
    if (0 == padding_flag) {
      padding_flag = 1;
    }
  } else {
    padding_flag = 0;
  }
  char *fbank_buffer = (char *)LvpGetLogfankBuffer(context, context->ctx_index);
  uni_dcache_invalid_range((unsigned int*)fbank_buffer, fbank_len);
  if (g_vui.status == VUI_RECOGN_RUNNING) {
    if (1 == padding_flag) {
      for (i = 0; i < 6; i++) {
        DataBufferWriteForcely(g_vui.databuf, fbank_buffer, fbank_len);
      }
      padding_flag = -1;
      // printf("padding 6 frames\n");
    }
    DataBufferWriteForcely(g_vui.databuf, fbank_buffer, fbank_len);
  }
#ifdef CONFIG_UNI_UART_RECORD
  APP_EVENT plc_event = {
      .event_id = AUDIO_IN_RECORD_DONE_EVENT_ID,
      .ctx_index = context->ctx_index
  };
  LvpTriggerAppEvent(&plc_event);
#endif

  LvpAudioInUpdateReadIndex(1);
  return 0;
}

DRAM0_STAGE2_SRAM_ATTR static int _LvpAudioInCallback(int ctx_index, void *priv) {
  if (ctx_index > 0) {
    LVP_CONTEXT *context;
    unsigned int ctx_size;
    LvpGetContext(ctx_index - 1, &context, &ctx_size);
    context->ctx_index = ctx_index - 1;
    //context->kws         = 0; // 挪到 ctc.c 中清0
    context->vad         = 0;
    context->G_vad         = 0;

#ifdef CONFIG_ENABLE_NOISE_JUDGEMENT
    LvpAuidoInQueryEnvNoise(context);
#endif

#if (defined CONFIG_LVP_STANDBY_ENABLE) && (!defined CONFIG_UNI_UART_RECORD)
    if (g_vui.standby) {
      unsigned int frame_length = context->ctx_header->frame_length;
      unsigned int frame_num_per_ctx = context->ctx_header->pcm_frame_num_per_context;
      g_vui.standby_cnt ++;
      if (g_vui.standby_cnt * frame_length * frame_num_per_ctx >= g_vui.standby_timeout &&
          !LvpPmuSuspendIsLocked()) {
        g_vui.standby_cnt = 0;
        g_vui.standby_flg = 1;
        // LvpPmuSuspend(LRT_AUDIO_IN);
      }
    }
#endif
    /* input KWS recognize */
    _LvpKwsRun(context);
  }

  return 0;
}

__attribute__((unused)) static void ShowResourceInfo(void* kws) {
  /* 获取KWS引擎版本 */
  const char* version __attribute__((unused)) = UalOFAGetVersion(kws);
  printf(LOG_TAG"kws version is %s\n", version);

  /* 打印所有声学模型、语法的信息 */
  UalOFAPrintResourceInfo(kws);

  /* 获取当前的工作语种 */
  const char* default_lang __attribute__((unused)) =
    UalOFAGetOptionString(kws, KWS_CURRENT_LANGUAGE_ID);

  /* 获取当前使用的声学模型ID */
  int default_am_id __attribute__((unused)) = UalOFAGetActiveAmId(kws);

  /* 获取当前使用的语法domain */
  const char* default_grammar_domain __attribute__((unused)) =
    UalOFAGetActiveGrammarDomain(kws);

  printf(LOG_TAG"Default Info:\n");
  printf(LOG_TAG"AmID: %d\n", default_am_id);
  printf(LOG_TAG"Language: %s\n", default_lang);
  printf(LOG_TAG"GrammarDomain: %s\n", default_grammar_domain);
}

int VuiRecognInit(VuiRecognCB cb) {
  if (VUI_RECOGN_INIT != g_vui.status) {
    printf(LOG_TAG"VUI was inited.\n");
    return -1;
  }

  /* Open log */
  OsalLogInit();
  OsalLogSetLevel(LOG_ERROR);

  /* init KWS*/
  g_vui.kws = UalOFAInitializeFromBuffer(global_kws_lp_acoutstic_model, global_kws_lp_grammar);
  if (NULL == g_vui.kws) {
    printf(LOG_TAG"UalOFAInitializeFromBuffer failed\n");
    return -1;
  }
  UalOFASetOptionInt(g_vui.kws, KWS_BEAM_ID, 7);
  //ShowResourceInfo(g_vui.kws);

  /* audio ring buffer */
  g_vui.databuf = DataBufferCreate(KWS_FRAMES_FBANK_SZIE * sizeof(short) * 6 * 16);
  if (!g_vui.databuf) {
    printf(LOG_TAG"DataBufferCreate Failed\n");
    UalOFARelease(g_vui.kws);
    return -1;
  }
  /* open ADC */
  LvpInitBuffer();
  UNI_WAKEUP_SOURCE start_mode = uni_pmu_get_wakeup_source();
  if (start_mode == UNI_WAKEUP_SOURCE_COLD || start_mode == UNI_WAKEUP_SOURCE_WDT) {
    printf(LOG_TAG"LvpAudioInInit...\n");
    if (0 != LvpAudioInInit(_LvpAudioInCallback)) {
      printf(LOG_TAG"LvpAudioInInit Failed\n");
      DataBufferDestroy(g_vui.databuf);
      UalOFARelease(g_vui.kws);
      return -1;
    }
  } else {
    // printf(LOG_TAG"LvpAudioInResume...\n");
    // LvpAudioInResume();
  }
  g_vui.standby_flg = 0;
  g_vui.result_cb = cb;
  g_vui.model = UNI_LP_WAKEUP;
  g_vui.time_ms = 0;
  g_vui.timeout = KWS_TIMEOUT_DEF;
  g_vui.status = VUI_RECOGN_INITED;
  g_callback_data.need_input = 0;
  g_callback_data.recog_status = 0;

  printf(LOG_TAG"_KWSModeInit finished!\n");
  return 0;
}

int VuiRecognDone(void) {
  if (VUI_RECOGN_INIT == g_vui.status) {
    printf(LOG_TAG"VUI was not inited.\n");
    return -1;
  }
  while(0 != UalOFAStop(g_vui.kws)) {
    printf(LOG_TAG"Ofa stop processing, retry.\n");
    uni_udelay(100);
  }
  UalOFARelease(g_vui.kws);
  OsalLogRelease();
  DataBufferDestroy(g_vui.databuf);
  g_vui.result_cb = NULL;
  g_vui.model = UNI_LP_WAKEUP;
  g_vui.time_ms = 0;
  g_vui.status = VUI_RECOGN_INIT;
  return 0;
}

int VuiRecognStart(VuiRecognModel model, unsigned int timeout_ms) {
  const char *p_domain = NULL;
  const int am_id = 37;   // 100k-->21; 270k-->35; 300k-->38
  char tmp_buf[KWS_FRAMES_FBANK_SZIE * sizeof(short)];

  if (VUI_RECOGN_RUNNING == g_vui.status) {
    printf(LOG_TAG"VUI is running already.\n");
    return -1;
  } else if (VUI_RECOGN_INIT == g_vui.status) {
    printf(LOG_TAG"VUI is not inited.\n");
    return -1;
  } else if (VUI_RECOGN_STOP == g_vui.status) {
    /* read out cache buffer for kws quick restart */
    while (KWS_FRAMES_FBANK_SZIE * sizeof(short) ==  
           DataBufferRead(tmp_buf, KWS_FRAMES_FBANK_SZIE * sizeof(short),
           g_vui.databuf)) {
    }
  }
  /* start engine */
  //UalOFAReset(g_vui.kws);
  if (UNI_LP_WAKEUP == model) {
    p_domain = "wakeup";
  } else {
    p_domain = "ivm";
  }
  g_vui.model = model;
  if (ASR_RECOGNIZER_OK != UalOFAStart(g_vui.kws, p_domain, am_id,
        g_decoder_pool, KWS_DECODER_BUF_SIZE)) {
    printf(LOG_TAG"UalOFAStart failed\n");
    return -1;
  }
  g_vui.session_id++;
  g_callback_data.need_input = 1;
  g_callback_data.recog_status = 0;
  g_vui.time_ms = uni_get_time_ms();
  g_vui.timeout = timeout_ms;
  g_vui.status = VUI_RECOGN_RUNNING;
  printf(LOG_TAG"VUI working mode : %s\n", p_domain);

  return 0;
}

int VuiRecognStop(void) {
  if (VUI_RECOGN_RUNNING != g_vui.status) {
    //printf(LOG_TAG"VUI is not running.\n");
    return -1;
  }
  //printf("stop free databuf is %d\n", DataBufferGetFreeSize(g_vui.databuf));
  int ret = UalOFAStop(g_vui.kws);
  while(0 != ret) {
    printf(LOG_TAG"ual ofa stop fail [%d], retry.\n", ret);
    uni_udelay(100);
    ret = UalOFAStop(g_vui.kws);
  }
  g_callback_data.need_input = 0;
  g_callback_data.recog_status = 0;
  g_vui.time_ms = 0;
  g_vui.status = VUI_RECOGN_STOP;
  return 0;
}

int VuiRecognGetSessionId(void) {
  return g_vui.session_id;
}

VuiRecognModel VuiRecognGetmodel(void) {
  return g_vui.model;
}

int VuiReloadStandby(int standby, int offset_ms) {
  g_vui.standby_cnt = 0;
  g_vui.standby = standby;
  g_vui.standby_timeout = offset_ms;
  return 0;
}

#define IS_NUMBER(c)       (c >= '0' && c <= '9')
#define IS_ENGLISH_CHAR(c) ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
#define IS_SPACE(c)        (c == ' ')
#define IS_CHINESE(c)      (!IS_NUMBER(c) && !IS_ENGLISH_CHAR(c) && !IS_SPACE(c))

/* 适用于UTF-8编码格式 */
static void _filter(unsigned char *wake_word) {
  int idx = 0;
  unsigned char c;
  unsigned char *p = wake_word;
  while ((c = *p) != '\0') {
    /* 去除中文与中文之间的空格 */
    if (!(IS_SPACE(c) && (IS_CHINESE(*(p - 1)) && IS_CHINESE(*(p + 1))))) {
      wake_word[idx++] = c;
    }
    p++;
  }
  wake_word[idx] = '\0';
}

static int _ParseWakeupResult(char* result, char* wake_word, float* score) {
  int i = 0;
  char *p = result;
  char ss[16] = {0};
  char c = 0;
  if (NULL == result || NULL == wake_word || NULL == score) {
    return -1;
  }
  /* lasr result string format: "%d <s> %s </s> \n%f\n" */
  /* skip <s> */
  p = strstr(result, "<s>");
  if (NULL == p) {
    printf(LOG_TAG"result: %s\n", result);
    return -1;
  }
  p += 3;   // skip <s>
  /* remove space in wake_word[0] */
  while ((*p == ' ') || (*p == '\t')) {
    p++;
  }
  /* get context with not TAB */
  while (((c = *p++) != '<') && (i < 63)) {       // p point to /
    if (c != '\t') {
      wake_word[i++] = c;
    }
  }
  if (i <= 0) {
    printf(LOG_TAG"wake_word: %s\n", p);
    return -1;
  }
  wake_word[i] = '\0';
  while ((i > 0) && (wake_word[i - 1] == ' ')) {
    wake_word[i - 1] = '\0';
    i--;
  }

  /* support english, must remove space between chinese word, en not */
  _filter((unsigned char*)wake_word);

  /* get score */
  p += 3;   // skip </s>
  while ((' ' == *p) || ('\n' == *p) || ('\t' == *p)) {
    p++;
  }
  if ('\0' == *p) {
    printf(LOG_TAG"result: %s", wake_word);
    return -1;
  }
  /* skip timestamp if there it is */
  i = 0;
  while ('\0' != *p) {
    if ((' ' == *p) || ('\n' == *p) || ('\t' == *p)) {
      break;
    }
    ss[i++] = *p++;
    if (i >= (sizeof(ss) - 1)) {
      break;
    }
  }
  ss[i] = '\0';
  *score = atof(ss);
  return 0;
}

static inline float _f16tof32(unsigned short f16) {
  unsigned int f32 = (unsigned int)f16;
  f32 = ((f32 & 0x7fff) << 13) + 0x38000000;
  f32 |= ((f16 & 0x8000) << 16);
  return *(float *)&f32;
}

static inline int _convert_fbank_buf(char *fbank16, char *fbank32, int len) {
  int i = 0;
  unsigned short *fp16 = (unsigned short *)fbank16;
  float *fp32 = (float *)fbank32;
  for (i = 0; i < len; i++) {
    *fp32 = _f16tof32(*fp16);
    fp32++;
    fp16++;
  }
  return 0;
}

void VuiRecognProcessTick(void) {
  static char result_buffer[256] __attribute__ ((aligned(4))) = {0};
  static char fbank_buf16[40 * 2] __attribute__ ((aligned(4))) = {0};
  static char fbank_buf32[40 * 4] __attribute__ ((aligned(4))) = {0};
  char recog_word[64] = {0};
  float score = 0.0;
  int ret  = -1;

  if (g_vui.standby_flg == 1) {
    g_vui.standby_flg = 0;
    printf("LvpPmuSuspend\n");
    LvpAudioInSuspend();               // 关audio中断
    while (gx_snpu_get_state() == 1);  // 等待snpu运行结束
    LvpPmuSuspend(LRT_AUDIO_IN);
  }

  if (VUI_RECOGN_RUNNING != g_vui.status) {
    return;
  }
  if (DataBufferGetDataSize(g_vui.databuf) < KWS_FRAMES_FBANK_SZIE * sizeof(short)) {
    return;
  }
  if (g_callback_data.need_input) {
    DataBufferRead(fbank_buf16, KWS_FRAMES_FBANK_SZIE * sizeof(short), g_vui.databuf);
    _convert_fbank_buf(fbank_buf16, fbank_buf32, KWS_FRAMES_FBANK_SZIE);
    ret = UalOFARecognizeAsyncFeat(g_vui.kws, (float *)fbank_buf32,
        KWS_FRAMES_FBANK_SZIE, &g_callback_data);
  } else {
    ret = UalOFARecognizeAsyncFeat(g_vui.kws, NULL, 0, &g_callback_data);
  }
  if (ret != ASR_RECOGNIZER_OK) {
    printf(LOG_TAG"UalOFARecognizeAsync error %d\n", ret);
    return;
  }

  if (g_callback_data.recog_status == 2) {
    const char* result_const = UalOFAGetResult(g_vui.kws);
    OsalStrncpy(result_buffer, result_const, sizeof(result_buffer)-1);
    int parse_ret = _ParseWakeupResult(result_buffer, recog_word, &score);
    if (OsalStrcmp(result_buffer, "#NULL") != 0 && parse_ret == 0) {
      if (g_vui.result_cb) {
        g_vui.result_cb(recog_word, score, false);
      }
    } else {
      printf(LOG_TAG"#NULL\n");
    }
  } else {
    if (UNI_LP_LASR == g_vui.model) {
      unsigned int time = uni_get_time_ms();
      int diff_time = 0;
      if (time > g_vui.time_ms) {
        diff_time = time - g_vui.time_ms;
      } else {
        diff_time = time + (0xffffffffUL - g_vui.time_ms);
      }
      if (diff_time > g_vui.timeout) {
        g_vui.result_cb(NULL, 0.0, true);
      }
    }
  }
}

