PocketSphinx  0.6
pocketsphinx.c
1 /* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /* ====================================================================
3  * Copyright (c) 2008 Carnegie Mellon University. All rights
4  * reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * This work was supported in part by funding from the Defense Advanced
19  * Research Projects Agency and the National Science Foundation of the
20  * United States of America, and the CMU Sphinx Speech Consortium.
21  *
22  * THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
23  * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
26  * NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  * ====================================================================
35  *
36  */
37 
38 /* System headers. */
39 #include <stdio.h>
40 #include <assert.h>
41 
42 /* SphinxBase headers. */
43 #include <sphinxbase/err.h>
44 #include <sphinxbase/strfuncs.h>
45 #include <sphinxbase/filename.h>
46 #include <sphinxbase/pio.h>
47 
48 /* Local headers. */
49 #include "cmdln_macro.h"
50 #include "pocketsphinx_internal.h"
51 #include "ps_lattice_internal.h"
52 #include "phone_loop_search.h"
53 #include "fsg_search_internal.h"
54 #include "ngram_search.h"
55 #include "ngram_search_fwdtree.h"
56 #include "ngram_search_fwdflat.h"
57 
58 static const arg_t ps_args_def[] = {
59  POCKETSPHINX_OPTIONS,
60  CMDLN_EMPTY_OPTION
61 };
62 
63 /* I'm not sure what the portable way to do this is. */
64 static int
65 file_exists(const char *path)
66 {
67  FILE *tmp;
68 
69  tmp = fopen(path, "rb");
70  if (tmp) fclose(tmp);
71  return (tmp != NULL);
72 }
73 
74 static int
75 hmmdir_exists(const char *path)
76 {
77  FILE *tmp;
78  char *mdef = string_join(path, "/mdef", NULL);
79 
80  tmp = fopen(mdef, "rb");
81  if (tmp) fclose(tmp);
82  ckd_free(mdef);
83  return (tmp != NULL);
84 }
85 
86 static void
87 ps_add_file(ps_decoder_t *ps, const char *arg,
88  const char *hmmdir, const char *file)
89 {
90  char *tmp = string_join(hmmdir, "/", file, NULL);
91 
92  if (cmd_ln_str_r(ps->config, arg) == NULL && file_exists(tmp))
93  cmd_ln_set_str_r(ps->config, arg, tmp);
94  ckd_free(tmp);
95 }
96 
97 static void
98 ps_init_defaults(ps_decoder_t *ps)
99 {
100  char const *hmmdir, *lmfile, *dictfile;
101 
102  /* Disable memory mapping on Blackfin (FIXME: should be uClinux in general). */
103 #ifdef __ADSPBLACKFIN__
104  E_INFO("Will not use mmap() on uClinux/Blackfin.");
105  cmd_ln_set_boolean_r(ps->config, "-mmap", FALSE);
106 #endif
107 
108 #ifdef MODELDIR
109  /* Set default acoustic and language models. */
110  hmmdir = cmd_ln_str_r(ps->config, "-hmm");
111  lmfile = cmd_ln_str_r(ps->config, "-lm");
112  dictfile = cmd_ln_str_r(ps->config, "-dict");
113  if (hmmdir == NULL && hmmdir_exists(MODELDIR "/hmm/en_US/hub4wsj_sc_8k")) {
114  hmmdir = MODELDIR "/hmm/en_US/hub4wsj_sc_8k";
115  cmd_ln_set_str_r(ps->config, "-hmm", hmmdir);
116  }
117  if (lmfile == NULL && !cmd_ln_str_r(ps->config, "-fsg")
118  && !cmd_ln_str_r(ps->config, "-jsgf")
119  && file_exists(MODELDIR "/lm/en_US/hub4.5000.DMP")) {
120  lmfile = MODELDIR "/lm/en_US/hub4.5000.DMP";
121  cmd_ln_set_str_r(ps->config, "-lm", lmfile);
122  }
123  if (dictfile == NULL && file_exists(MODELDIR "/lm/en_US/cmu07a.dic")) {
124  dictfile = MODELDIR "/lm/en_US/cmu07a.dic";
125  cmd_ln_set_str_r(ps->config, "-dict", dictfile);
126  }
127 
128  /* Expand acoustic and language model filenames relative to installation path. */
129  if (hmmdir && !path_is_absolute(hmmdir) && !hmmdir_exists(hmmdir)) {
130  char *tmphmm = string_join(MODELDIR "/hmm/", hmmdir, NULL);
131  if (hmmdir_exists(tmphmm)) {
132  cmd_ln_set_str_r(ps->config, "-hmm", tmphmm);
133  } else {
134  E_ERROR("Failed to find mdef file inside the model folder specified with -hmm '%s'\n", hmmdir);
135  }
136  ckd_free(tmphmm);
137  }
138  if (lmfile && !path_is_absolute(lmfile) && !file_exists(lmfile)) {
139  char *tmplm = string_join(MODELDIR "/lm/", lmfile, NULL);
140  cmd_ln_set_str_r(ps->config, "-lm", tmplm);
141  ckd_free(tmplm);
142  }
143  if (dictfile && !path_is_absolute(dictfile) && !file_exists(dictfile)) {
144  char *tmpdict = string_join(MODELDIR "/lm/", dictfile, NULL);
145  cmd_ln_set_str_r(ps->config, "-dict", tmpdict);
146  ckd_free(tmpdict);
147  }
148 #endif
149 
150  /* Get acoustic model filenames and add them to the command-line */
151  if ((hmmdir = cmd_ln_str_r(ps->config, "-hmm")) != NULL) {
152  ps_add_file(ps, "-mdef", hmmdir, "mdef");
153  ps_add_file(ps, "-mean", hmmdir, "means");
154  ps_add_file(ps, "-var", hmmdir, "variances");
155  ps_add_file(ps, "-tmat", hmmdir, "transition_matrices");
156  ps_add_file(ps, "-mixw", hmmdir, "mixture_weights");
157  ps_add_file(ps, "-sendump", hmmdir, "sendump");
158  ps_add_file(ps, "-fdict", hmmdir, "noisedict");
159  ps_add_file(ps, "-lda", hmmdir, "feature_transform");
160  ps_add_file(ps, "-featparams", hmmdir, "feat.params");
161  ps_add_file(ps, "-senmgau", hmmdir, "senmgau");
162  }
163 }
164 
165 static void
166 ps_free_searches(ps_decoder_t *ps)
167 {
168  gnode_t *gn;
169 
170  if (ps->searches == NULL)
171  return;
172 
173  for (gn = ps->searches; gn; gn = gnode_next(gn))
174  ps_search_free(gnode_ptr(gn));
175  glist_free(ps->searches);
176  ps->searches = NULL;
177  ps->search = NULL;
178 }
179 
180 static ps_search_t *
181 ps_find_search(ps_decoder_t *ps, char const *name)
182 {
183  gnode_t *gn;
184 
185  for (gn = ps->searches; gn; gn = gnode_next(gn)) {
186  if (0 == strcmp(ps_search_name(gnode_ptr(gn)), name))
187  return (ps_search_t *)gnode_ptr(gn);
188  }
189  return NULL;
190 }
191 
192 int
193 ps_reinit(ps_decoder_t *ps, cmd_ln_t *config)
194 {
195  char const *lmfile, *lmctl = NULL;
196 
197  if (config && config != ps->config) {
198  cmd_ln_free_r(ps->config);
199  ps->config = cmd_ln_retain(config);
200  }
201 
202  err_set_debug_level(cmd_ln_int32_r(ps->config, "-debug"));
203  ps->mfclogdir = cmd_ln_str_r(ps->config, "-mfclogdir");
204  ps->rawlogdir = cmd_ln_str_r(ps->config, "-rawlogdir");
205  ps->senlogdir = cmd_ln_str_r(ps->config, "-senlogdir");
206 
207  /* Fill in some default arguments. */
208  ps_init_defaults(ps);
209 
210  /* Free old searches (do this before other reinit) */
211  ps_free_searches(ps);
212 
213  /* Free old acmod. */
214  acmod_free(ps->acmod);
215  ps->acmod = NULL;
216 
217  /* Free old dictionary (must be done after the two things above) */
218  dict_free(ps->dict);
219  ps->dict = NULL;
220 
221  /* Free d2p */
222  dict2pid_free(ps->d2p);
223  ps->d2p = NULL;
224 
225  /* Logmath computation (used in acmod and search) */
226  if (ps->lmath == NULL
227  || (logmath_get_base(ps->lmath) !=
228  (float64)cmd_ln_float32_r(ps->config, "-logbase"))) {
229  if (ps->lmath)
230  logmath_free(ps->lmath);
231  ps->lmath = logmath_init
232  ((float64)cmd_ln_float32_r(ps->config, "-logbase"), 0,
233  cmd_ln_boolean_r(ps->config, "-bestpath"));
234  }
235 
236  /* Acoustic model (this is basically everything that
237  * uttproc.c, senscr.c, and others used to do) */
238  if ((ps->acmod = acmod_init(ps->config, ps->lmath, NULL, NULL)) == NULL)
239  return -1;
240 
241  if ((ps->pl_window = cmd_ln_int32_r(ps->config, "-pl_window"))) {
242  /* Initialize an auxiliary phone loop search, which will run in
243  * "parallel" with FSG or N-Gram search. */
244  if ((ps->phone_loop = phone_loop_search_init(ps->config,
245  ps->acmod, ps->dict)) == NULL)
246  return -1;
247  ps->searches = glist_add_ptr(ps->searches, ps->phone_loop);
248  }
249 
250  /* Dictionary and triphone mappings (depends on acmod). */
251  /* FIXME: pass config, change arguments, implement LTS, etc. */
252  if ((ps->dict = dict_init(ps->config, ps->acmod->mdef)) == NULL)
253  return -1;
254 
255  /* Determine whether we are starting out in FSG or N-Gram search mode. */
256  if (cmd_ln_str_r(ps->config, "-fsg") || cmd_ln_str_r(ps->config, "-jsgf")) {
257  ps_search_t *fsgs;
258 
259  if ((ps->d2p = dict2pid_build(ps->acmod->mdef, ps->dict)) == NULL)
260  return -1;
261  if ((fsgs = fsg_search_init(ps->config, ps->acmod, ps->dict, ps->d2p)) == NULL)
262  return -1;
263  fsgs->pls = ps->phone_loop;
264  ps->searches = glist_add_ptr(ps->searches, fsgs);
265  ps->search = fsgs;
266  }
267  else if ((lmfile = cmd_ln_str_r(ps->config, "-lm"))
268  || (lmctl = cmd_ln_str_r(ps->config, "-lmctl"))) {
269  ps_search_t *ngs;
270 
271  /* Make the acmod's feature buffer growable if we are doing two-pass search. */
272  if (cmd_ln_boolean_r(ps->config, "-fwdflat")
273  && cmd_ln_boolean_r(ps->config, "-fwdtree"))
274  acmod_set_grow(ps->acmod, TRUE);
275 
276  if ((ps->d2p = dict2pid_build(ps->acmod->mdef, ps->dict)) == NULL)
277  return -1;
278  if ((ngs = ngram_search_init(ps->config, ps->acmod, ps->dict, ps->d2p)) == NULL)
279  return -1;
280  ngs->pls = ps->phone_loop;
281  ps->searches = glist_add_ptr(ps->searches, ngs);
282  ps->search = ngs;
283  }
284  /* Otherwise, we will initialize the search whenever the user
285  * decides to load an FSG or a language model. */
286  else {
287  if ((ps->d2p = dict2pid_build(ps->acmod->mdef, ps->dict)) == NULL)
288  return -1;
289  }
290 
291  /* Initialize performance timer. */
292  ps->perf.name = "decode";
293  ptmr_init(&ps->perf);
294 
295  return 0;
296 }
297 
298 ps_decoder_t *
299 ps_init(cmd_ln_t *config)
300 {
301  ps_decoder_t *ps;
302 
303  ps = ckd_calloc(1, sizeof(*ps));
304  ps->refcount = 1;
305  if (ps_reinit(ps, config) < 0) {
306  ps_free(ps);
307  return NULL;
308  }
309  return ps;
310 }
311 
312 arg_t const *
313 ps_args(void)
314 {
315  return ps_args_def;
316 }
317 
318 ps_decoder_t *
320 {
321  ++ps->refcount;
322  return ps;
323 }
324 
325 int
327 {
328  if (ps == NULL)
329  return 0;
330  if (--ps->refcount > 0)
331  return ps->refcount;
332  ps_free_searches(ps);
333  dict_free(ps->dict);
334  dict2pid_free(ps->d2p);
335  acmod_free(ps->acmod);
336  logmath_free(ps->lmath);
337  cmd_ln_free_r(ps->config);
338  ckd_free(ps->uttid);
339  ckd_free(ps);
340  return 0;
341 }
342 
343 char const *
345 {
346  return ps->uttid;
347 }
348 
349 cmd_ln_t *
351 {
352  return ps->config;
353 }
354 
355 logmath_t *
357 {
358  return ps->lmath;
359 }
360 
361 fe_t *
363 {
364  return ps->acmod->fe;
365 }
366 
367 feat_t *
369 {
370  return ps->acmod->fcb;
371 }
372 
373 ps_mllr_t *
375 {
376  return acmod_update_mllr(ps->acmod, mllr);
377 }
378 
379 ngram_model_t *
381 {
382  if (ps->search == NULL
383  || 0 != strcmp(ps_search_name(ps->search), "ngram"))
384  return NULL;
385  return ((ngram_search_t *)ps->search)->lmset;
386 }
387 
388 ngram_model_t *
389 ps_update_lmset(ps_decoder_t *ps, ngram_model_t *lmset)
390 {
391  ngram_search_t *ngs;
392  ps_search_t *search;
393 
394  /* Look for N-Gram search. */
395  search = ps_find_search(ps, "ngram");
396  if (search == NULL) {
397  /* Initialize N-Gram search. */
398  search = ngram_search_init(ps->config, ps->acmod, ps->dict, ps->d2p);
399  if (search == NULL)
400  return NULL;
401  search->pls = ps->phone_loop;
402  ps->searches = glist_add_ptr(ps->searches, search);
403  ngs = (ngram_search_t *)search;
404  }
405  else if (lmset != NULL) {
406  ngs = (ngram_search_t *)search;
407  /* Free any previous lmset if this is a new one. */
408  if (ngs->lmset != NULL && ngs->lmset != lmset)
409  ngram_model_free(ngs->lmset);
410  ngs->lmset = lmset;
411  /* Tell N-Gram search to update its view of the world. */
412  if (ps_search_reinit(search, ps->dict, ps->d2p) < 0)
413  return NULL;
414  } else {
415  /* Just activate the existing search */
416  ngs = (ngram_search_t *)search;
417  }
418  ps->search = search;
419  return ngs->lmset;
420 }
421 
422 fsg_set_t *
424 {
425  if (ps->search == NULL
426  || 0 != strcmp(ps_search_name(ps->search), "fsg"))
427  return NULL;
428  return (fsg_set_t *)ps->search;
429 }
430 
431 fsg_set_t *
433 {
434  ps_search_t *search;
435 
436  /* Look for FSG search. */
437  search = ps_find_search(ps, "fsg");
438  if (search == NULL) {
439  /* Initialize FSG search. */
440  if ((search = fsg_search_init(ps->config,
441  ps->acmod, ps->dict, ps->d2p)) == NULL) {
442  return NULL;
443  }
444  search->pls = ps->phone_loop;
445  ps->searches = glist_add_ptr(ps->searches, search);
446  }
447  else {
448  /* Tell FSG search to update its view of the world. */
449  if (ps_search_reinit(search, ps->dict, ps->d2p) < 0)
450  return NULL;
451  }
452  ps->search = search;
453  return (fsg_set_t *)search;
454 }
455 
456 int
457 ps_load_dict(ps_decoder_t *ps, char const *dictfile,
458  char const *fdictfile, char const *format)
459 {
460  cmd_ln_t *newconfig;
461  dict2pid_t *d2p;
462  dict_t *dict;
463  gnode_t *gn;
464  int rv;
465 
466  /* Create a new scratch config to load this dict (so existing one
467  * won't be affected if it fails) */
468  newconfig = cmd_ln_init(NULL, ps_args(), TRUE, NULL);
469  cmd_ln_set_boolean_r(newconfig, "-dictcase",
470  cmd_ln_boolean_r(ps->config, "-dictcase"));
471  cmd_ln_set_str_r(newconfig, "-dict", dictfile);
472  if (fdictfile)
473  cmd_ln_set_str_r(newconfig, "-fdict", fdictfile);
474  else
475  cmd_ln_set_str_r(newconfig, "-fdict",
476  cmd_ln_str_r(ps->config, "-fdict"));
477 
478  /* Try to load it. */
479  if ((dict = dict_init(newconfig, ps->acmod->mdef)) == NULL) {
480  cmd_ln_free_r(newconfig);
481  return -1;
482  }
483 
484  /* Reinit the dict2pid. */
485  if ((d2p = dict2pid_build(ps->acmod->mdef, dict)) == NULL) {
486  cmd_ln_free_r(newconfig);
487  return -1;
488  }
489 
490  /* Success! Update the existing config to reflect new dicts and
491  * drop everything into place. */
492  cmd_ln_free_r(newconfig);
493  cmd_ln_set_str_r(ps->config, "-dict", dictfile);
494  if (fdictfile)
495  cmd_ln_set_str_r(ps->config, "-fdict", fdictfile);
496  dict_free(ps->dict);
497  ps->dict = dict;
498  dict2pid_free(ps->d2p);
499  ps->d2p = d2p;
500 
501  /* And tell all searches to reconfigure themselves. */
502  for (gn = ps->searches; gn; gn = gnode_next(gn)) {
503  ps_search_t *search = gnode_ptr(gn);
504  if ((rv = ps_search_reinit(search, dict, d2p)) < 0)
505  return rv;
506  }
507 
508  return 0;
509 }
510 
511 int
512 ps_save_dict(ps_decoder_t *ps, char const *dictfile,
513  char const *format)
514 {
515  return dict_write(ps->dict, dictfile, format);
516 }
517 
518 int
520  char const *word,
521  char const *phones,
522  int update)
523 {
524  int32 wid, lmwid;
525  ngram_model_t *lmset;
526  s3cipid_t *pron;
527  char **phonestr, *tmp;
528  int np, i, rv;
529 
530  /* Parse phones into an array of phone IDs. */
531  tmp = ckd_salloc(phones);
532  np = str2words(tmp, NULL, 0);
533  phonestr = ckd_calloc(np, sizeof(*phonestr));
534  str2words(tmp, phonestr, np);
535  pron = ckd_calloc(np, sizeof(*pron));
536  for (i = 0; i < np; ++i) {
537  pron[i] = bin_mdef_ciphone_id(ps->acmod->mdef, phonestr[i]);
538  if (pron[i] == -1) {
539  E_ERROR("Unknown phone %s in phone string %s\n",
540  phonestr[i], tmp);
541  ckd_free(phonestr);
542  ckd_free(tmp);
543  ckd_free(pron);
544  return -1;
545  }
546  }
547  /* No longer needed. */
548  ckd_free(phonestr);
549  ckd_free(tmp);
550 
551  /* Add it to the dictionary. */
552  if ((wid = dict_add_word(ps->dict, word, pron, np)) == -1) {
553  ckd_free(pron);
554  return -1;
555  }
556  /* No longer needed. */
557  ckd_free(pron);
558 
559  /* Now we also have to add it to dict2pid. */
560  dict2pid_add_word(ps->d2p, wid);
561 
562  if ((lmset = ps_get_lmset(ps)) != NULL) {
563  /* Add it to the LM set (meaning, the current LM). In a perfect
564  * world, this would result in the same WID, but because of the
565  * weird way that word IDs are handled, it doesn't. */
566  if ((lmwid = ngram_model_add_word(lmset, word, 1.0))
567  == NGRAM_INVALID_WID)
568  return -1;
569  }
570 
571  /* Rebuild the widmap and search tree if requested. */
572  if (update) {
573  if ((rv = ps_search_reinit(ps->search, ps->dict, ps->d2p) < 0))
574  return rv;
575  }
576  return wid;
577 }
578 
579 int
580 ps_decode_raw(ps_decoder_t *ps, FILE *rawfh,
581  char const *uttid, long maxsamps)
582 {
583  long total, pos;
584 
585  ps_start_utt(ps, uttid);
586  /* If this file is seekable or maxsamps is specified, then decode
587  * the whole thing at once. */
588  if (maxsamps != -1 || (pos = ftell(rawfh)) >= 0) {
589  int16 *data;
590 
591  if (maxsamps == -1) {
592  long endpos;
593  fseek(rawfh, 0, SEEK_END);
594  endpos = ftell(rawfh);
595  fseek(rawfh, pos, SEEK_SET);
596  maxsamps = endpos - pos;
597  }
598  data = ckd_calloc(maxsamps, sizeof(*data));
599  total = fread(data, sizeof(*data), maxsamps, rawfh);
600  ps_process_raw(ps, data, total, FALSE, TRUE);
601  ckd_free(data);
602  }
603  else {
604  /* Otherwise decode it in a stream. */
605  total = 0;
606  while (!feof(rawfh)) {
607  int16 data[256];
608  size_t nread;
609 
610  nread = fread(data, sizeof(*data), sizeof(data)/sizeof(*data), rawfh);
611  ps_process_raw(ps, data, nread, FALSE, FALSE);
612  total += nread;
613  }
614  }
615  ps_end_utt(ps);
616  return total;
617 }
618 
619 int
620 ps_start_utt(ps_decoder_t *ps, char const *uttid)
621 {
622  int rv;
623 
624  if (ps->search == NULL) {
625  E_ERROR("No search module is selected, did you forget to "
626  "specify a language model or grammar?\n");
627  return -1;
628  }
629 
630  ptmr_reset(&ps->perf);
631  ptmr_start(&ps->perf);
632 
633  if (uttid) {
634  ckd_free(ps->uttid);
635  ps->uttid = ckd_salloc(uttid);
636  }
637  else {
638  char nuttid[16];
639  ckd_free(ps->uttid);
640  sprintf(nuttid, "%09u", ps->uttno);
641  ps->uttid = ckd_salloc(nuttid);
642  ++ps->uttno;
643  }
644  /* Remove any residual word lattice and hypothesis. */
645  ps_lattice_free(ps->search->dag);
646  ps->search->dag = NULL;
647  ps->search->last_link = NULL;
648  ps->search->post = 0;
649  ckd_free(ps->search->hyp_str);
650  ps->search->hyp_str = NULL;
651 
652  if ((rv = acmod_start_utt(ps->acmod)) < 0)
653  return rv;
654 
655  /* Start logging features and audio if requested. */
656  if (ps->mfclogdir) {
657  char *logfn = string_join(ps->mfclogdir, "/",
658  ps->uttid, ".mfc", NULL);
659  FILE *mfcfh;
660  E_INFO("Writing MFCC log file: %s\n", logfn);
661  if ((mfcfh = fopen(logfn, "wb")) == NULL) {
662  E_ERROR_SYSTEM("Failed to open MFCC log file %s", logfn);
663  ckd_free(logfn);
664  return -1;
665  }
666  ckd_free(logfn);
667  acmod_set_mfcfh(ps->acmod, mfcfh);
668  }
669  if (ps->rawlogdir) {
670  char *logfn = string_join(ps->rawlogdir, "/",
671  ps->uttid, ".raw", NULL);
672  FILE *rawfh;
673  E_INFO("Writing raw audio log file: %s\n", logfn);
674  if ((rawfh = fopen(logfn, "wb")) == NULL) {
675  E_ERROR_SYSTEM("Failed to open raw audio log file %s", logfn);
676  ckd_free(logfn);
677  return -1;
678  }
679  ckd_free(logfn);
680  acmod_set_rawfh(ps->acmod, rawfh);
681  }
682  if (ps->senlogdir) {
683  char *logfn = string_join(ps->senlogdir, "/",
684  ps->uttid, ".sen", NULL);
685  FILE *senfh;
686  E_INFO("Writing senone score log file: %s\n", logfn);
687  if ((senfh = fopen(logfn, "wb")) == NULL) {
688  E_ERROR_SYSTEM("Failed to open senone score log file %s", logfn);
689  ckd_free(logfn);
690  return -1;
691  }
692  ckd_free(logfn);
693  acmod_set_senfh(ps->acmod, senfh);
694  }
695 
696  /* Start auxiliary phone loop search. */
697  if (ps->phone_loop)
698  ps_search_start(ps->phone_loop);
699 
700  return ps_search_start(ps->search);
701 }
702 
703 static int
704 ps_search_forward(ps_decoder_t *ps)
705 {
706  int nfr;
707 
708  nfr = 0;
709  while (ps->acmod->n_feat_frame > 0) {
710  int k;
711  if (ps->phone_loop)
712  if ((k = ps_search_step(ps->phone_loop, ps->acmod->output_frame)) < 0)
713  return k;
714  if (ps->acmod->output_frame >= ps->pl_window)
715  if ((k = ps_search_step(ps->search,
716  ps->acmod->output_frame - ps->pl_window)) < 0)
717  return k;
718  acmod_advance(ps->acmod);
719  ++ps->n_frame;
720  ++nfr;
721  }
722  return nfr;
723 }
724 
725 int
727  char const *uttid)
728 {
729  int nfr, n_searchfr;
730 
731  ps_start_utt(ps, uttid);
732  n_searchfr = 0;
733  acmod_set_insenfh(ps->acmod, senfh);
734  while ((nfr = acmod_read_scores(ps->acmod)) > 0) {
735  if ((nfr = ps_search_forward(ps)) < 0) {
736  ps_end_utt(ps);
737  return nfr;
738  }
739  n_searchfr += nfr;
740  }
741  ps_end_utt(ps);
742  acmod_set_insenfh(ps->acmod, NULL);
743 
744  return n_searchfr;
745 }
746 
747 int
749  int16 const *data,
750  size_t n_samples,
751  int no_search,
752  int full_utt)
753 {
754  int n_searchfr = 0;
755 
756  if (ps->acmod->state == ACMOD_IDLE) {
757  E_ERROR("Failed to process data, utterance is not started. Use start_utt to start it\n");
758  return 0;
759  }
760 
761  if (no_search)
762  acmod_set_grow(ps->acmod, TRUE);
763 
764  while (n_samples) {
765  int nfr;
766 
767  /* Process some data into features. */
768  if ((nfr = acmod_process_raw(ps->acmod, &data,
769  &n_samples, full_utt)) < 0)
770  return nfr;
771 
772  /* Score and search as much data as possible */
773  if (no_search)
774  continue;
775  if ((nfr = ps_search_forward(ps)) < 0)
776  return nfr;
777  n_searchfr += nfr;
778  }
779 
780  return n_searchfr;
781 }
782 
783 int
785  mfcc_t **data,
786  int32 n_frames,
787  int no_search,
788  int full_utt)
789 {
790  int n_searchfr = 0;
791 
792  if (no_search)
793  acmod_set_grow(ps->acmod, TRUE);
794 
795  while (n_frames) {
796  int nfr;
797 
798  /* Process some data into features. */
799  if ((nfr = acmod_process_cep(ps->acmod, &data,
800  &n_frames, full_utt)) < 0)
801  return nfr;
802 
803  /* Score and search as much data as possible */
804  if (no_search)
805  continue;
806  if ((nfr = ps_search_forward(ps)) < 0)
807  return nfr;
808  n_searchfr += nfr;
809  }
810 
811  return n_searchfr;
812 }
813 
814 int
816 {
817  int rv, i;
818 
819  acmod_end_utt(ps->acmod);
820 
821  /* Search any remaining frames. */
822  if ((rv = ps_search_forward(ps)) < 0) {
823  ptmr_stop(&ps->perf);
824  return rv;
825  }
826  /* Finish phone loop search. */
827  if (ps->phone_loop) {
828  if ((rv = ps_search_finish(ps->phone_loop)) < 0) {
829  ptmr_stop(&ps->perf);
830  return rv;
831  }
832  }
833  /* Search any frames remaining in the lookahead window. */
834  for (i = ps->acmod->output_frame - ps->pl_window;
835  i < ps->acmod->output_frame; ++i)
836  ps_search_step(ps->search, i);
837  /* Finish main search. */
838  if ((rv = ps_search_finish(ps->search)) < 0) {
839  ptmr_stop(&ps->perf);
840  return rv;
841  }
842  ptmr_stop(&ps->perf);
843 
844  /* Log a backtrace if requested. */
845  if (cmd_ln_boolean_r(ps->config, "-backtrace")) {
846  char const *uttid, *hyp;
847  ps_seg_t *seg;
848  int32 score;
849 
850  hyp = ps_get_hyp(ps, &score, &uttid);
851  E_INFO("%s: %s (%d)\n", uttid, hyp, score);
852  E_INFO_NOFN("%-20s %-5s %-5s %-5s %-10s %-10s %-3s\n",
853  "word", "start", "end", "pprob", "ascr", "lscr", "lback");
854  for (seg = ps_seg_iter(ps, &score); seg;
855  seg = ps_seg_next(seg)) {
856  char const *word;
857  int sf, ef;
858  int32 post, lscr, ascr, lback;
859 
860  word = ps_seg_word(seg);
861  ps_seg_frames(seg, &sf, &ef);
862  post = ps_seg_prob(seg, &ascr, &lscr, &lback);
863  E_INFO_NOFN("%-20s %-5d %-5d %-1.3f %-10d %-10d %-3d\n",
864  word, sf, ef, logmath_exp(ps_get_logmath(ps), post), ascr, lscr, lback);
865  }
866  }
867  return rv;
868 }
869 
870 char const *
871 ps_get_hyp(ps_decoder_t *ps, int32 *out_best_score, char const **out_uttid)
872 {
873  char const *hyp;
874 
875  ptmr_start(&ps->perf);
876  hyp = ps_search_hyp(ps->search, out_best_score, NULL);
877  if (out_uttid)
878  *out_uttid = ps->uttid;
879  ptmr_stop(&ps->perf);
880  return hyp;
881 }
882 
883 char const *
884 ps_get_hyp_final(ps_decoder_t *ps, int32 *out_is_final)
885 {
886  char const *hyp;
887 
888  ptmr_start(&ps->perf);
889  hyp = ps_search_hyp(ps->search, NULL, out_is_final);
890  ptmr_stop(&ps->perf);
891  return hyp;
892 }
893 
894 
895 int32
896 ps_get_prob(ps_decoder_t *ps, char const **out_uttid)
897 {
898  int32 prob;
899 
900  ptmr_start(&ps->perf);
901  prob = ps_search_prob(ps->search);
902  if (out_uttid)
903  *out_uttid = ps->uttid;
904  ptmr_stop(&ps->perf);
905  return prob;
906 }
907 
908 ps_seg_t *
909 ps_seg_iter(ps_decoder_t *ps, int32 *out_best_score)
910 {
911  ps_seg_t *itor;
912 
913  ptmr_start(&ps->perf);
914  itor = ps_search_seg_iter(ps->search, out_best_score);
915  ptmr_stop(&ps->perf);
916  return itor;
917 }
918 
919 ps_seg_t *
921 {
922  return ps_search_seg_next(seg);
923 }
924 
925 char const *
927 {
928  return seg->word;
929 }
930 
931 void
932 ps_seg_frames(ps_seg_t *seg, int *out_sf, int *out_ef)
933 {
934  if (out_sf) *out_sf = seg->sf;
935  if (out_ef) *out_ef = seg->ef;
936 }
937 
938 int32
939 ps_seg_prob(ps_seg_t *seg, int32 *out_ascr, int32 *out_lscr, int32 *out_lback)
940 {
941  if (out_ascr) *out_ascr = seg->ascr;
942  if (out_lscr) *out_lscr = seg->lscr;
943  if (out_lback) *out_lback = seg->lback;
944  return seg->prob;
945 }
946 
947 void
949 {
950  ps_search_seg_free(seg);
951 }
952 
953 ps_lattice_t *
955 {
956  return ps_search_lattice(ps->search);
957 }
958 
959 ps_nbest_t *
960 ps_nbest(ps_decoder_t *ps, int sf, int ef,
961  char const *ctx1, char const *ctx2)
962 {
963  ps_lattice_t *dag;
964  ngram_model_t *lmset;
965  ps_astar_t *nbest;
966  float32 lwf;
967  int32 w1, w2;
968 
969  if (ps->search == NULL)
970  return NULL;
971  if ((dag = ps_get_lattice(ps)) == NULL)
972  return NULL;
973 
974  /* FIXME: This is all quite specific to N-Gram search. Either we
975  * should make N-best a method for each search module or it needs
976  * to be abstracted to work for N-Gram and FSG. */
977  if (0 != strcmp(ps_search_name(ps->search), "ngram")) {
978  lmset = NULL;
979  lwf = 1.0f;
980  }
981  else {
982  lmset = ((ngram_search_t *)ps->search)->lmset;
983  lwf = ((ngram_search_t *)ps->search)->bestpath_fwdtree_lw_ratio;
984  }
985 
986  w1 = ctx1 ? dict_wordid(ps_search_dict(ps->search), ctx1) : -1;
987  w2 = ctx2 ? dict_wordid(ps_search_dict(ps->search), ctx2) : -1;
988  nbest = ps_astar_start(dag, lmset, lwf, sf, ef, w1, w2);
989 
990  return (ps_nbest_t *)nbest;
991 }
992 
993 void
995 {
996  ps_astar_finish(nbest);
997 }
998 
999 ps_nbest_t *
1001 {
1002  ps_latpath_t *next;
1003 
1004  next = ps_astar_next(nbest);
1005  if (next == NULL) {
1006  ps_nbest_free(nbest);
1007  return NULL;
1008  }
1009  return nbest;
1010 }
1011 
1012 char const *
1013 ps_nbest_hyp(ps_nbest_t *nbest, int32 *out_score)
1014 {
1015  assert(nbest != NULL);
1016 
1017  if (nbest->top == NULL)
1018  return NULL;
1019  if (out_score) *out_score = nbest->top->score;
1020  return ps_astar_hyp(nbest, nbest->top);
1021 }
1022 
1023 ps_seg_t *
1024 ps_nbest_seg(ps_nbest_t *nbest, int32 *out_score)
1025 {
1026  if (nbest->top == NULL)
1027  return NULL;
1028  if (out_score) *out_score = nbest->top->score;
1029  return ps_astar_seg_iter(nbest, nbest->top, 1.0);
1030 }
1031 
1032 int
1034 {
1035  return ps->acmod->output_frame + 1;
1036 }
1037 
1038 void
1039 ps_get_utt_time(ps_decoder_t *ps, double *out_nspeech,
1040  double *out_ncpu, double *out_nwall)
1041 {
1042  int32 frate;
1043 
1044  frate = cmd_ln_int32_r(ps->config, "-frate");
1045  *out_nspeech = (double)ps->acmod->output_frame / frate;
1046  *out_ncpu = ps->perf.t_cpu;
1047  *out_nwall = ps->perf.t_elapsed;
1048 }
1049 
1050 void
1051 ps_get_all_time(ps_decoder_t *ps, double *out_nspeech,
1052  double *out_ncpu, double *out_nwall)
1053 {
1054  int32 frate;
1055 
1056  frate = cmd_ln_int32_r(ps->config, "-frate");
1057  *out_nspeech = (double)ps->n_frame / frate;
1058  *out_ncpu = ps->perf.t_tot_cpu;
1059  *out_nwall = ps->perf.t_tot_elapsed;
1060 }
1061 
1062 void
1063 ps_search_init(ps_search_t *search, ps_searchfuncs_t *vt,
1064  cmd_ln_t *config, acmod_t *acmod, dict_t *dict,
1065  dict2pid_t *d2p)
1066 {
1067  search->vt = vt;
1068  search->config = config;
1069  search->acmod = acmod;
1070  if (d2p)
1071  search->d2p = dict2pid_retain(d2p);
1072  else
1073  search->d2p = NULL;
1074  if (dict) {
1075  search->dict = dict_retain(dict);
1076  search->start_wid = dict_startwid(dict);
1077  search->finish_wid = dict_finishwid(dict);
1078  search->silence_wid = dict_silwid(dict);
1079  search->n_words = dict_size(dict);
1080  }
1081  else {
1082  search->dict = NULL;
1083  search->start_wid = search->finish_wid = search->silence_wid = -1;
1084  search->n_words = 0;
1085  }
1086 }
1087 
1088 void
1089 ps_search_base_reinit(ps_search_t *search, dict_t *dict,
1090  dict2pid_t *d2p)
1091 {
1092  dict_free(search->dict);
1093  dict2pid_free(search->d2p);
1094  /* FIXME: _retain() should just return NULL if passed NULL. */
1095  if (dict) {
1096  search->dict = dict_retain(dict);
1097  search->start_wid = dict_startwid(dict);
1098  search->finish_wid = dict_finishwid(dict);
1099  search->silence_wid = dict_silwid(dict);
1100  search->n_words = dict_size(dict);
1101  }
1102  else {
1103  search->dict = NULL;
1104  search->start_wid = search->finish_wid = search->silence_wid = -1;
1105  search->n_words = 0;
1106  }
1107  if (d2p)
1108  search->d2p = dict2pid_retain(d2p);
1109  else
1110  search->d2p = NULL;
1111 }
1112 
1113 
1114 void
1115 ps_search_deinit(ps_search_t *search)
1116 {
1117  /* FIXME: We will have refcounting on acmod, config, etc, at which
1118  * point we will free them here too. */
1119  dict_free(search->dict);
1120  dict2pid_free(search->d2p);
1121  ckd_free(search->hyp_str);
1122  ps_lattice_free(search->dag);
1123 }