//
// SPTK-3.9のpitchコマンドを以下の点で改造したもの。
//   - SWIPE法によるF0抽出に特化させた。
//   - 入力をwavファイルからにした。
//
// [コンパイル方法]
//   SPTK をソースからビルドする
//   libsndfile をインストールする
//   SPTKの bin/pitch/Makefile を参考にして Makefile を作る
//   また Makefile で sndfile.h がインクルードできるようにする
//   また Makefile で libsndfile.a がリンクされるようにする
//   make
//   strip getF0swipe.exe
//
// [実行例]
//   getF0swipe.exe -t 0 -p 441 -H 800 -L 100 -o 1 temp.wav > result.txt
//

/* ----------------------------------------------------------------- */
/*             The Speech Signal Processing Toolkit (SPTK)           */
/*             developed by SPTK Working Group                       */
/*             http://sp-tk.sourceforge.net/                         */
/* ----------------------------------------------------------------- */
/*                                                                   */
/*  Copyright (c) 1984-2007  Tokyo Institute of Technology           */
/*                           Interdisciplinary Graduate School of    */
/*                           Science and Engineering                 */
/*                                                                   */
/*                1996-2015  Nagoya Institute of Technology          */
/*                           Department of Computer Science          */
/*                                                                   */
/* All rights reserved.                                              */
/*                                                                   */
/* Redistribution and use in source and binary forms, with or        */
/* without modification, are permitted provided that the following   */
/* conditions are met:                                               */
/*                                                                   */
/* - Redistributions of source code must retain the above copyright  */
/*   notice, this list of conditions and the following disclaimer.   */
/* - Redistributions in binary form must reproduce the above         */
/*   copyright notice, this list of conditions and the following     */
/*   disclaimer in the documentation and/or other materials provided */
/*   with the distribution.                                          */
/* - Neither the name of the SPTK working group nor the names of its */
/*   contributors may be used to endorse or promote products derived */
/*   from this software without specific prior written permission.   */
/*                                                                   */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND            */
/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,       */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF          */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE          */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */
/* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          */
/* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED   */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,   */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY    */
/* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/* POSSIBILITY OF SUCH DAMAGE.                                       */
/* ----------------------------------------------------------------- */

/************************************************************************
*                                                                       *
*    Pitch Extraction                                                   *
*                                                                       *
*                                      1998.7  M.Tamura                 *
*                                      2000.3  T.Tanaka                 *
*                                      2011.10 A.Tamamori               *
*                                      2011.11 T.Sawada                 *
*                                                                       *
*       usage:                                                          *
*               pitch [ options ] [ infile ] > stdout                   *
*       options:                                                        *
*               -a  a     :  algorithm used for pitch      [0]          *
*                            estimation                                 *
*                              0 (RAPT)                                 *
*                              1 (SWIPE')                               *
*               -s  s     :  sampling frequency (Hz)       [16]         *
*               -p  p     :  frame shift                   [80]         *
*               -T  T     :  voiced/unvoiced threshold     [0.0]        *
*                            (used only for RAPT algorithm)             *
*               -t  t     :  voiced/unvoiced threshold     [0.3]        *
*                            (used only for SWIPE' algorithm)           *
*               -L  L     :  minimum fundamental frequency [60]         *
*                            to search for (Hz)                         *
*               -H  H     :  maximum fundamental frequency [240]        *
*                            to search for (Hz)                         *
*               -o  o     :  output format                 [0]          *
*                              0 (pitch)                                *
*                              1 (f0)                                   *
*                              2 (log(f0))                              *
*       infile:                                                         *
*               data sequence                                           *
*                       x(0), x(1), ..., x(n-1), ...                    *
*       stdout:                                                         *
*               pitch, f0, or log(f0)                                   *
*                                                                       *
************************************************************************/

static char *rcs_id = "$Id: pitch.c,v 1.47 2015/12/14 01:14:21 uratec Exp $";


/*  Standard C Libraries  */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#ifdef HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#ifndef HAVE_STRRCHR
#define strrchr rindex
#endif
#endif


#if defined(WIN32)
#include "SPTK.h"
#else
#include <SPTK.h>
#endif

//koko
#include "swipe/vector.h"
#include <sndfile.h>

/*  Default Values  */
#define LOW    60.0
#define HIGH   240.0
#define FRAME_SHIFT 80
#define OTYPE 0
#define STR_LEN 255
#define THRESH_RAPT 0.0
#define THRESH_SWIPE 0.3
#define NOISEMASK 50.0
#define SEED 1
#define RND_MAX 32767
#define FSP 10.0
#define ALPHA 0.00275
#define BETA_1 9600.0
#define BETA_2 168.0
#define BETA_3 96000.0

/*  Command Name  */
char *cmnd;

typedef struct _float_list {
   float f;
   struct _float_list *next;
} float_list;

vector readWav(char *);

void usage(int status)
{
   fprintf(stderr, "\n");
   fprintf(stderr, " %s - pitch extraction using SWIPE algorithm\n", cmnd);
   fprintf(stderr, "\n");
   fprintf(stderr, "  usage:\n");
   fprintf(stderr, "       %s [ options ] infile > stdout\n", cmnd);
   fprintf(stderr, "  options:\n");
   fprintf(stderr, "       -p p  : frame shift                     [%d]\n",
           FRAME_SHIFT);
   fprintf(stderr, "       -t t  : voiced/unvoiced threshold       [%g]\n",
           THRESH_SWIPE);
   fprintf(stderr, "               (used only for SWIPE' algorithm)\n");
   fprintf(stderr, "       -L L  : minimum fundamental             [%g]\n",
           LOW);
   fprintf(stderr, "               frequency to search for (Hz)\n");
   fprintf(stderr, "       -H H  : maximum fundamental             [%g]\n",
           HIGH);
   fprintf(stderr, "               frequency to search for (Hz)\n");
   fprintf(stderr, "       -o o  : output format                   [%d]\n",
           OTYPE);
   fprintf(stderr, "                 0 (pitch)\n");
   fprintf(stderr, "                 1 (f0)\n");
   fprintf(stderr, "                 2 (log(f0))\n");
   fprintf(stderr, "       -h    : print this message\n");
   fprintf(stderr, "  infile:\n");
   fprintf(stderr, "       waveform (%s)             \n", FORMAT);
   fprintf(stderr, "  stdout:\n");
   fprintf(stderr, "       pitch, f0 or log(f0) (%s)\n", FORMAT);
#ifdef PACKAGE_VERSION
   fprintf(stderr, "\n");
   fprintf(stderr, " SPTK: version %s\n", PACKAGE_VERSION);
   fprintf(stderr, " CVS Info: %s", rcs_id);
#endif
   fprintf(stderr, "\n");
   exit(status);
}


int main(int argc, char **argv)
{
   int frame_shift = FRAME_SHIFT, otype = OTYPE;
   double thresh_swipe = THRESH_SWIPE, L = LOW, H = HIGH;
   char *fname = NULL;
   void swipe(vector x,
              int frame_shift, double min, double max, double threshold,
              int otype);

   if ((cmnd = strrchr(argv[0], '/')) == NULL)
      cmnd = argv[0];
   else
      cmnd++;
   while (--argc)
      if (**++argv == '-') {
         switch (*(*argv + 1)) {
         case 'p':
            frame_shift = atoi(*++argv);
            --argc;
            break;
         case 't':
            thresh_swipe = atof(*++argv);
            --argc;
            break;
         case 'L':
            L = atof(*++argv);
            --argc;
            break;
         case 'H':
            H = atof(*++argv);
            --argc;
            break;
         case 'o':
            otype = atoi(*++argv);
            --argc;
            break;
         case 'h':
            usage(0);
         default:
            fprintf(stderr, "%s : Invalid option '%c'!\n", cmnd, *(*argv + 1));
            usage(1);
         }
      } else {
         fname = *argv;
      }

   if (fname == NULL){
     fprintf(stderr, "%s : Invalid option '%c'!\n", cmnd, *(*argv + 1));
     usage(1);
   }

   vector inx;
   inx = readWav(fname);
   swipe(inx, frame_shift, L, H, thresh_swipe, otype);
   return (0);
}

//------------------------------------------------------------------------
vector readWav(char *filename){
  SNDFILE *fp;
  SF_INFO info;
  int N;
  vector result;

  memset((void *)&info, 0, sizeof(SF_INFO));
  if ((fp = sf_open(filename, SFM_READ, &info)) == NULL){
    fprintf(stderr, "error: can not open (%s)\n", filename);
    exit(EXIT_FAILURE);
  }

  result = makev(info.frames);
  if (info.channels == 1){
    sf_read_double(fp, result.v, info.frames);
  } else {
    N = info.frames * info.channels;
    double *x = (double*) malloc(sizeof(double) * N);
    sf_read_double(fp, x, N);    // 全チャンネルの瞬時値をxに読む
    int i = 0;
    for (int seq = 0; seq < N; seq++){
      result.v[seq] = 0.0;
      for (int c = 0; c < info.channels; c++) result.v[seq] += x[i++];
      result.v[seq] /= info.channels;
    }
  }

  result.samplerate = info.samplerate;

  sf_close(fp);
  return result;
}

