Exemplo n.º 1
0
SWIGINTERN Decoder *new_Decoder__SWIG_1(Config *c){
		Decoder *d = ps_init(c);
		return d;
	}
Exemplo n.º 2
0
int
main(int argc, char *argv[])
{
    ps_decoder_t *ps;
    cmd_ln_t *config;
    acmod_t *acmod;
    ps_search_t *ngs, *pls;
    clock_t c;
    int32 score;
    int i;

    TEST_ASSERT(config =
            cmd_ln_init(NULL, ps_args(), TRUE,
                "-hmm", MODELDIR "/en-us/en-us",
                "-lm", MODELDIR "/en-us/en-us.lm.dmp",
                "-dict", MODELDIR "/en-us/cmudict-en-us.dict",
                "-fwdtree", "yes",
                "-fwdflat", "no",
                "-bestpath", "no",
                "-pl_window", "6",
                "-input_endian", "little",
                "-samprate", "16000", NULL));
    TEST_ASSERT(ps = ps_init(config));

    ngs = ps->search;
    pls = ps->phone_loop;
    acmod = ps->acmod;

    setbuf(stdout, NULL);
    c = clock();
    for (i = 0; i < 5; ++i) {
        FILE *rawfh;
        int16 buf[2048];
        size_t nread;
        int16 const *bptr;
        int nfr, n_searchfr;

        TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb"));
        TEST_EQUAL(0, acmod_start_utt(acmod));
        ps_search_start(ngs);
        ps_search_start(pls);
        n_searchfr = 0;
        while (!feof(rawfh)) {
            nread = fread(buf, sizeof(*buf), 2048, rawfh);
            bptr = buf;
            while ((nfr = acmod_process_raw(acmod, &bptr, &nread, FALSE)) > 0) {
                while (acmod->n_feat_frame > 0) {
                    ps_search_step(pls, n_searchfr);
                    if (n_searchfr >= 6)
                        ps_search_step(ngs, n_searchfr - 6);
                    acmod_advance(acmod);
                    ++n_searchfr;
                }
            }
        }
        for (nfr = n_searchfr - 6; nfr < n_searchfr; ++nfr) {
            ps_search_step(ngs, nfr);
        }
        ps_search_finish(pls);
        ps_search_finish(ngs);
        printf("%s\n", ps_search_hyp(ngs, &score, NULL));

        TEST_ASSERT(acmod_end_utt(acmod) >= 0);
        fclose(rawfh);
    }
    printf("%s\n", ps_search_hyp(ngs, &score, NULL));
    TEST_EQUAL(0, strcmp("go forward ten meters", ps_search_hyp(ngs, &score, NULL)));
    c = clock() - c;
    printf("5 * fwdtree search in %.2f sec\n",
           (double)c / CLOCKS_PER_SEC);
    ps_free(ps);
    cmd_ln_free_r(config);

    return 0;
}
Exemplo n.º 3
0
int
main(int argc, char *argv[])
{
	ps_decoder_t *ps;
	cmd_ln_t *config;
	acmod_t *acmod;
	ngram_search_t *ngs;
	clock_t c;

	TEST_ASSERT(config =
		    cmd_ln_init(NULL, ps_args(), TRUE,
				"-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
				"-lm", MODELDIR "/lm/en_US/wsj0vp.5000.DMP",
				"-dict", MODELDIR "/lm/en_US/cmu07a.dic",
				"-fwdtree", "no",
				"-fwdflat", "yes",
				"-bestpath", "no",
				"-input_endian", "little",
				"-samprate", "16000", NULL));
	TEST_ASSERT(ps = ps_init(config));

	ngs = (ngram_search_t *)ps->search;
	acmod = ps->acmod;

	setbuf(stdout, NULL);
	c = clock();
	{
		FILE *rawfh;
		int16 buf[2048];
		size_t nread;
		int16 const *bptr;
		int nfr;

		TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb"));
		TEST_EQUAL(0, acmod_start_utt(acmod));
		ngram_fwdflat_start(ngs);
		while (!feof(rawfh)) {
			nread = fread(buf, sizeof(*buf), 2048, rawfh);
			bptr = buf;
			while ((nfr = acmod_process_raw(acmod, &bptr, &nread, FALSE)) > 0) {
				while (acmod->n_feat_frame > 0) {
					ngram_fwdflat_search(ngs,acmod->output_frame);
					acmod_advance(acmod);
				}
			}
		}
		ngram_fwdflat_finish(ngs);
		printf("%s\n",
		       ngram_search_bp_hyp(ngs, ngram_search_find_exit(ngs, -1, NULL)));

		TEST_ASSERT(acmod_end_utt(acmod) >= 0);
		fclose(rawfh);
	}
	TEST_EQUAL(0, strcmp("go forward and users",
			     ngram_search_bp_hyp(ngs, ngram_search_find_exit(ngs, -1, NULL))));
	c = clock() - c;
	printf("2 * fwdflat search in %.2f sec\n",
	       (double)c / CLOCKS_PER_SEC);
	ps_free(ps);

	return 0;
}
Exemplo n.º 4
0
// *************************************************************************************************
// @fn          init_application
// @brief       Initialize the microcontroller.
// @param       none
// @return      none
// *************************************************************************************************
void init_application(void)
{
	volatile unsigned char *ptr;
	  
	// ---------------------------------------------------------------------
	// Enable watchdog
	
	// Watchdog triggers after 16 seconds when not cleared
#ifdef USE_WATCHDOG		
	WDTCTL = WDTPW + WDTIS__512K + WDTSSEL__ACLK;
#else
	WDTCTL = WDTPW + WDTHOLD;
#endif
	
	// ---------------------------------------------------------------------
	// Configure PMM
	SetVCore(3);
	
	// Set global high power request enable
	PMMCTL0_H  = 0xA5;
	PMMCTL0_L |= PMMHPMRE;
	PMMCTL0_H  = 0x00;	

	// ---------------------------------------------------------------------
	// Enable 32kHz ACLK	
	P5SEL |= 0x03;                            // Select XIN, XOUT on P5.0 and P5.1
	UCSCTL6 &= ~XT1OFF;        				  // XT1 On, Highest drive strength
	UCSCTL6 |= XCAP_3;                        // Internal load cap

	UCSCTL3 = SELA__XT1CLK;                   // Select XT1 as FLL reference
	UCSCTL4 = SELA__XT1CLK | SELS__DCOCLKDIV | SELM__DCOCLKDIV;      
	
	// ---------------------------------------------------------------------
	// Configure CPU clock for 12MHz
	_BIS_SR(SCG0);                  // Disable the FLL control loop
	UCSCTL0 = 0x0000;          // Set lowest possible DCOx, MODx
	UCSCTL1 = DCORSEL_5;       // Select suitable range
	UCSCTL2 = FLLD_1 + 0x16E;  // Set DCO Multiplier
	_BIC_SR(SCG0);                  // Enable the FLL control loop

    // Worst-case settling time for the DCO when the DCO range bits have been
    // changed is n x 32 x 32 x f_MCLK / f_FLL_reference. See UCS chapter in 5xx
    // UG for optimization.
    // 32 x 32 x 8 MHz / 32,768 Hz = 250000 = MCLK cycles for DCO to settle
	uint8_t i;
	for (i=0; i<10; i++)
    __delay_cycles(25000);
  
	// Loop until XT1 & DCO stabilizes, use do-while to insure that 
	// body is executed at least once
	do
	{
        UCSCTL7 &= ~(XT2OFFG + XT1LFOFFG + XT1HFOFFG + DCOFFG);
		SFRIFG1 &= ~OFIFG;                      // Clear fault flags
	} while ((SFRIFG1 & OFIFG));	

	
	// ---------------------------------------------------------------------
	// Configure port mapping
	
	// Disable all interrupts
	__disable_interrupt();
	// Get write-access to port mapping registers:
	PMAPPWD = 0x02D52;
	// Allow reconfiguration during runtime:
	PMAPCTL = PMAPRECFG;

	// P2.7 = TA0CCR1A or TA1CCR0A output (buzzer output)
	ptr  = &P2MAP0;
	*(ptr+7) = PM_TA1CCR0A;
	P2OUT &= ~BIT7;
	P2DIR |= BIT7;

	// P1.5 = SPI MISO input
	ptr  = &P1MAP0;
	*(ptr+5) = PM_UCA0SOMI;
	// P1.6 = SPI MOSI output
	*(ptr+6) = PM_UCA0SIMO;
	// P1.7 = SPI CLK output
	*(ptr+7) = PM_UCA0CLK;

	// Disable write-access to port mapping registers:
	PMAPPWD = 0;
	// Re-enable all interrupts
	__enable_interrupt();
	
	// ---------------------------------------------------------------------
	// Configure ports

	// ---------------------------------------------------------------------
	// Reset radio core
	radio_reset();
	radio_powerdown();	
	
	#ifdef FEATURE_PROVIDE_ACCEL
	// ---------------------------------------------------------------------
	// Init acceleration sensor
	as_init();
	#else
	as_disconnect();
	#endif
	
	// ---------------------------------------------------------------------
	// Init LCD
	lcd_init();
  
	// ---------------------------------------------------------------------
	// Init buttons
	init_buttons();

	// ---------------------------------------------------------------------
	// Configure Timer0 for use by the clock and delay functions
	Timer0_Init();
	
	// ---------------------------------------------------------------------
	// Init pressure sensor
	ps_init();
}
Exemplo n.º 5
0
  ReturnType Recognizer::init(const Config& config) {
    parseStringList(HMM_FOLDERS, &acoustic_models, &default_acoustic_model);
#ifdef LM_FILES
    parseStringList(LM_FILES, &language_models, &default_language_model);
#endif /* LM_FILES */
#ifdef DICT_FILES
    parseStringList(DICT_FILES, &dictionaries, &default_dictionary);
#endif /* DICT_FILES */

    const arg_t cont_args_def[] = {
      POCKETSPHINX_OPTIONS,
      { "-argfile",
	ARG_STRING,
	NULL,
	"Argument file giving extra arguments." },
      { "-adcdev",
	ARG_STRING,
	NULL,
	"Name of audio device to use for input." },
      { "-infile",
	ARG_STRING,
	NULL,
	"Audio file to transcribe." },
      { "-time",
	ARG_BOOLEAN,
	"no",
	"Print word times in file transcription." },
      CMDLN_EMPTY_OPTION
    };

    std::map<std::string, std::string> parameters;
    for (int i=0 ; i< config.size() ; ++i)
      parameters[config[i].key] = config[i].value;
    
    if ((parameters.find("-hmm") == parameters.end()) || (acoustic_models.find(parameters["-hmm"]) == acoustic_models.end()))
      parameters["-hmm"] = default_acoustic_model;
    if (parameters.find("-bestpath") == parameters.end())
      parameters["-bestpath"] = "no";
    if (parameters.find("-remove_noise") == parameters.end())
      parameters["-remove_noise"] = "no";

    int argc = 2 * parameters.size();
    char ** argv = new char*[argc];
    int index = 0;
    for (StringsMapIterator i = parameters.begin() ; i != parameters.end(); ++i) {
      if (isValidParameter(i->first, i->second)) {
	if (i->first == "-lm") is_fsg = false;
	argv[index++] = (char*) i->first.c_str();
	argv[index++] = (char*) i->second.c_str();
      }
    }

    cmd_ln_t * cmd_line = cmd_ln_parse_r(NULL, cont_args_def, argc, argv, FALSE);
    if (cmd_line == NULL) {
      delete [] argv;
      return RUNTIME_ERROR;
    }
    decoder = ps_init(cmd_line);
    delete [] argv;
    if (decoder == NULL) {
      return RUNTIME_ERROR;
    }
    logmath = logmath_init(1.0001, 0, 0);
    if (logmath == NULL) {
      return RUNTIME_ERROR;
    }
    return SUCCESS;
  }
Exemplo n.º 6
0
/*! function to load a grammar to the asr interface */
static switch_status_t pocketsphinx_asr_load_grammar(switch_asr_handle_t *ah, const char *grammar, const char *name)
{
	char *jsgf, *dic, *model, *rate = NULL;
	pocketsphinx_t *ps = (pocketsphinx_t *) ah->private_info;
	switch_status_t status = SWITCH_STATUS_FALSE;

	if (switch_test_flag(ps, PSFLAG_READY)) {
		ps_end_utt(ps->ps);
		switch_clear_flag(ps, PSFLAG_READY);
	}

	if (switch_is_file_path(grammar)) {
		char *dot = strrchr(grammar, '.');
		if (dot && !strcmp(dot, ".gram")) {
			jsgf = strdup(grammar);
		} else {
			jsgf = switch_mprintf("%s.gram", grammar);
		}
	} else {
		jsgf = switch_mprintf("%s%s%s.gram", SWITCH_GLOBAL_dirs.grammar_dir, SWITCH_PATH_SEPARATOR, grammar);
	}

	if (ah->rate == 8000) {
		model = switch_mprintf("%s%smodel%s%s", SWITCH_GLOBAL_dirs.grammar_dir, SWITCH_PATH_SEPARATOR, SWITCH_PATH_SEPARATOR, globals.model8k);
	} else {
		model = switch_mprintf("%s%smodel%s%s", SWITCH_GLOBAL_dirs.grammar_dir, SWITCH_PATH_SEPARATOR, SWITCH_PATH_SEPARATOR, globals.model16k);
	}

	dic = switch_mprintf("%s%s%s", SWITCH_GLOBAL_dirs.grammar_dir, SWITCH_PATH_SEPARATOR, globals.dictionary);

	if (switch_file_exists(dic, ah->memory_pool) != SWITCH_STATUS_SUCCESS) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't open dictionary %s.\n", dic);
		goto end;
	}

	if (switch_file_exists(model, ah->memory_pool) != SWITCH_STATUS_SUCCESS) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Can't open speech model %s.\n", model);
		goto end;
	}

	if (switch_file_exists(jsgf, ah->memory_pool) != SWITCH_STATUS_SUCCESS) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Can't open grammar file %s.\n", jsgf);
		goto end;
	}

	rate = switch_mprintf("%d", ah->rate);

	switch_assert(jsgf && dic && model);

	ps->config = cmd_ln_init(ps->config, ps_args(), FALSE,
							 "-samprate", rate,
							 "-hmm", model, "-jsgf", jsgf, "-lw", globals.language_weight, "-dict", dic, "-frate", "50", "-silprob", "0.005", NULL);

	if (ps->config == NULL) {
		status = SWITCH_STATUS_GENERR;
		goto end;
	}

	switch_mutex_lock(ps->flag_mutex);
	if (switch_test_flag(ps, PSFLAG_ALLOCATED)) {
		ps_reinit(ps->ps, ps->config);
	} else {
		if (!(ps->ps = ps_init(ps->config))) {
			switch_mutex_unlock(ps->flag_mutex);
			goto end;
		}
		switch_set_flag(ps, PSFLAG_ALLOCATED);
	}
	switch_mutex_unlock(ps->flag_mutex);

	ps_start_utt(ps->ps, NULL);
	switch_set_flag(ps, PSFLAG_READY);
	switch_safe_free(ps->grammar);
	ps->grammar = strdup(grammar);

	status = SWITCH_STATUS_SUCCESS;

  end:

	switch_safe_free(rate);
	switch_safe_free(jsgf);
	switch_safe_free(dic);
	switch_safe_free(model);

	return status;
}
SWIGINTERN struct ps_decoder_s *new_ps_decoder_s__SWIG_1(Config *c){
		Decoder *d = ps_init(c);
		return d;
	}
Exemplo n.º 8
0
Arquivo: csv.c Projeto: adh/dfsch
dfsch_object_t* dfsch_csv_read_line(dfsch_object_t* port,
                                    dfsch_csv_params_t* params){
  char ch;
  dfsch_object_t* ret = NULL;
  dfsch_list_collector_t* lc = NULL; 
  partial_string_t ps;

  if (!params){
    params = &default_params;
  }


  DFSCH_UNWIND {
    dfsch_port_batch_read_start(port);

  start:
    ch = dfsch_port_batch_read(port);
    if (ch != -1) {
      lc = dfsch_make_list_collector();
    } else {
      goto out;
    }
    ps_init(&ps);
    goto field_dispatch;
    
  field:
    ch = dfsch_port_batch_read(port);
  field_dispatch:
    if (ch == params->quote){
      goto quoted;
    } else if (ch == params->delim){
      dfsch_list_collect(lc, dfsch_make_string_buf(ps.buf, ps.ptr));
      ps_init(&ps);
    } else if (ch == -1 || ch == '\n'){
      dfsch_list_collect(lc, dfsch_make_string_buf(ps.buf, ps.ptr));
      goto out;
    } else if (ch == params->escape){
      ch = dfsch_port_batch_read(port);
      if (ch == -1){
        dfsch_error("Unexpected end of file", port);
      }
      ps_append(&ps, ch);
    } else {
      ps_append(&ps, ch);
    }
    goto field;

  quoted:
    ch = dfsch_port_batch_read(port);
    if (ch == params->quote){
      ch = dfsch_port_batch_read(port);
      if (ch != params->quote){
        goto field_dispatch;
      } else {
        ps_append(&ps, ch);
      }
    } else if (ch == params->escape){
      ch = dfsch_port_batch_read(port);
      if (ch == -1){
        dfsch_error("Unexpected end of file", port);
      }
      ps_append(&ps, ch);
    } else {
      if (ch == -1){
        dfsch_error("Unexpected end of file", port);
      }
      ps_append(&ps, ch);
    }
    goto quoted;
    
  out:
    if (lc){
      ret = dfsch_list_2_vector(dfsch_collected_list(lc));
    } else {
      ret = NULL;
    }
  } DFSCH_PROTECT {
    dfsch_port_batch_read_end(port);
  } DFSCH_PROTECT_END;

  return ret;
}
Exemplo n.º 9
0
int
main(int argc, char *argv[])
{
	int			pctlfd;
	int			pstatusfd;
	char			procname[PROCSIZE];
	char			*command;
	char			*rdb_commands = NULL;
	pid_t			cpid;
	pstatus_t		pstatus;
	sysset_t		sysset;
	int			c;
	int			error = 0;
	long			oper;
	struct iovec		piov[2];
	extern FILE		*yyin;

	command = argv[0];

	while ((c = getopt(argc, argv, "f:")) != EOF)
		switch (c) {
		case 'f':
			rdb_commands = optarg;
			break;
		case '?':
			break;
		}

	if (error || (optind == argc)) {
		(void) printf("usage: %s [-f file] executable "
		    "[executable arguments ...]\n", command);
		(void) printf("\t-f	command file\n");
		exit(1);
	}

	/*
	 * set up for tracing the child.
	 */
	init_proc();

	/*
	 * create a child to fork and exec from.
	 */
	if ((cpid = fork()) == 0) {
		(void) execv(argv[optind], &argv[optind]);
		perr(argv[1]);
	}

	if (cpid == -1)	/* fork() failure */
		perr(command);

	/*
	 * initialize libelf
	 */
	if (elf_version(EV_CURRENT) == EV_NONE) {
		(void) fprintf(stderr, "elf_version() failed: %s\n",
		    elf_errmsg(0));
		exit(1);
	}

	/*
	 * initialize librtld_db
	 */
	if (rd_init(RD_VERSION) != RD_OK) {
		(void) fprintf(stderr, "librtld_db::rd_init() failed: version "
		    "submitted: %d\n", RD_VERSION);
		exit(1);
	}

	/* rd_log(1); */

	/*
	 * Child should now be waiting after the successful
	 * exec.
	 */
	(void) snprintf(procname, PROCSIZE, "/proc/%d/ctl", EC_SWORD(cpid));
	(void) printf("parent: %d child: %d child procname: %s\n",
	    EC_SWORD(getpid()), EC_SWORD(cpid), procname);
	if ((pctlfd = open(procname, O_WRONLY)) < 0) {
		perror(procname);
		(void) fprintf(stderr, "%s: can't open child %s\n",
		    command, procname);
		exit(1);
	}

	/*
	 * wait for child process.
	 */
	oper = PCWSTOP;
	piov[0].iov_base = (caddr_t)&oper;
	piov[0].iov_len = sizeof (oper);
	if (writev(pctlfd, piov, 1) == -1)
		perr("PCWSTOP");

	/*
	 * open /proc/<cpid>/status
	 */
	(void) snprintf(procname, PROCSIZE, "/proc/%d/status", EC_SWORD(cpid));
	if ((pstatusfd = open(procname, O_RDONLY)) == -1)
		perr(procname);

	if (read(pstatusfd, &pstatus, sizeof (pstatus)) == -1)
		perr("status read failed");

	/*
	 * Make sure that it stopped where we expected.
	 */
	while ((pstatus.pr_lwp.pr_why == PR_SYSEXIT) &&
	    (pstatus.pr_lwp.pr_what == SYS_execve)) {
		long	pflags = 0;
		if (!(pstatus.pr_lwp.pr_reg[R_PS] & ERRBIT)) {
			/* successfull exec(2) */
			break;
		}

		oper = PCRUN;
		piov[1].iov_base = (caddr_t)&pflags;
		piov[1].iov_len = sizeof (pflags);
		if (writev(pctlfd, piov, 2) == -1)
			perr("PCRUN1");

		oper = PCWSTOP;
		if (writev(pctlfd, piov, 1) == -1)
			perr("PCWSTOP");

		if (read(pstatusfd, &pstatus, sizeof (pstatus)) == -1)
			perr("status read failed");
	}

	premptyset(&sysset);
	oper = PCSEXIT;
	piov[1].iov_base = (caddr_t)&sysset;
	piov[1].iov_len = sizeof (sysset);
	if (writev(pctlfd, piov, 2) == -1)
		perr("PIOCSEXIT");

	/*
	 * Did we stop where we expected ?
	 */
	if ((pstatus.pr_lwp.pr_why != PR_SYSEXIT) ||
	    (pstatus.pr_lwp.pr_what != SYS_execve)) {
		long	pflags = 0;

		(void) fprintf(stderr, "Didn't catch the exec, why: %d "
		    "what: %d\n", pstatus.pr_lwp.pr_why,
		    pstatus.pr_lwp.pr_what);

		oper = PCRUN;
		piov[1].iov_base = (caddr_t)&pflags;
		piov[1].iov_len = sizeof (pflags);
		if (writev(pctlfd, piov, 2) == -1)
			perr("PCRUN2");
		exit(1);
	}

	(void) ps_init(pctlfd, pstatusfd, cpid, &proch);

	if (rdb_commands) {
		if ((yyin = fopen(rdb_commands, "r")) == NULL) {
			(void) printf("unable to open %s for input\n",
			    rdb_commands);
			perr("fopen");
		}
	} else {
		proch.pp_flags |= FLG_PP_PROMPT;
		rdb_prompt();
	}
	(void) yyparse();

	if (proch.pp_flags & FLG_PP_PACT) {
		long	pflags = PRCFAULT;

		(void) printf("\ncontinuing the hung process...\n");

		pctlfd = proch.pp_ctlfd;
		(void) ps_close(&proch);

		oper = PCRUN;
		piov[1].iov_base = (caddr_t)&pflags;
		piov[1].iov_len = sizeof (pflags);
		if (writev(pctlfd, piov, 2) == -1)
			perr("PCRUN2");
		(void) close(pctlfd);
	}

	return (0);
}
SWIGINTERN struct ps_decoder_s *new_ps_decoder_s__SWIG_0(void){
		Decoder *d = ps_init(cmd_ln_init(NULL, ps_args(), FALSE, NULL));
		return d;
	}
Exemplo n.º 11
0
void init_application(void)
{
	volatile unsigned char *ptr;

	// ---------------------------------------------------------------------
	// Enable watchdog

	// Watchdog triggers after 16 seconds when not cleared
#ifdef USE_WATCHDOG
	WDTCTL = WDTPW + WDTIS__512K + WDTSSEL__ACLK;
#else
	WDTCTL = WDTPW + WDTHOLD;
#endif

	// ---------------------------------------------------------------------
	// Configure port mapping

	// Disable all interrupts
	__disable_interrupt();
	// Get write-access to port mapping registers:
	PMAPPWD = 0x02D52;
	// Allow reconfiguration during runtime:
	PMAPCTL = PMAPRECFG;

	// P2.7 = TA0CCR1A or TA1CCR0A output (buzzer output)
	ptr  = &P2MAP0;
	*(ptr + 7) = PM_TA1CCR0A;
	P2OUT &= ~BIT7;
	P2DIR |= BIT7;

	// P1.5 = SPI MISO input
	ptr  = &P1MAP0;
	*(ptr + 5) = PM_UCA0SOMI;
	// P1.6 = SPI MOSI output
	*(ptr + 6) = PM_UCA0SIMO;
	// P1.7 = SPI CLK output
	*(ptr + 7) = PM_UCA0CLK;

	// Disable write-access to port mapping registers:
	PMAPPWD = 0;
	// Re-enable all interrupts
	__enable_interrupt();

	// Init the hardwre real time clock (RTC_A)
	rtca_init();

	// ---------------------------------------------------------------------
	// Configure ports

	// ---------------------------------------------------------------------
	// Reset radio core
	radio_reset();
	radio_powerdown();

#ifdef CONFIG_ACCELEROMETER
	// ---------------------------------------------------------------------
	// Init acceleration sensor
	as_init();
#else
	as_disconnect();
#endif

	// ---------------------------------------------------------------------
	// Init buttons
	init_buttons();

	// ---------------------------------------------------------------------
	// Configure Timer0 for use by the clock and delay functions
	timer0_init();

	/* Init buzzer */
	buzzer_init();

	// ---------------------------------------------------------------------
	// Init pressure sensor
	ps_init();

	/* drivers/battery */
	battery_init();

	/* drivers/temperature */
	temperature_init();

#ifdef CONFIG_INFOMEM
	if (infomem_ready() == -2) {
		infomem_init(INFOMEM_C, INFOMEM_C + 2 * INFOMEM_SEGMENT_SIZE);
	}
#endif
}
Exemplo n.º 12
0
int
main(int argc, char *argv[])
{
	ps_decoder_t *ps;
	bin_mdef_t *mdef;
	dict_t *dict;
	dict2pid_t *d2p;
	acmod_t *acmod;
	ps_alignment_t *al;
	ps_alignment_iter_t *itor;
	ps_search_t *search;
	state_align_search_t *sas;
	cmd_ln_t *config;
	int i;

	config = cmd_ln_init(NULL, ps_args(), FALSE,
			     "-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
			     "-dict", MODELDIR "/lm/en_US/cmu07a.dic",
			     "-input_endian", "little",
			     "-samprate", "16000", NULL);
	TEST_ASSERT(ps = ps_init(config));
	dict = ps->dict;
	d2p = ps->d2p;
	acmod = ps->acmod;
	mdef = d2p->mdef;

	al = ps_alignment_init(d2p);
	TEST_EQUAL(1, ps_alignment_add_word(al, dict_wordid(dict, "<s>"), 0));
	TEST_EQUAL(2, ps_alignment_add_word(al, dict_wordid(dict, "go"), 0));
	TEST_EQUAL(3, ps_alignment_add_word(al, dict_wordid(dict, "forward"), 0));
	TEST_EQUAL(4, ps_alignment_add_word(al, dict_wordid(dict, "ten"), 0));
	TEST_EQUAL(5, ps_alignment_add_word(al, dict_wordid(dict, "meters"), 0));
	TEST_EQUAL(6, ps_alignment_add_word(al, dict_wordid(dict, "</s>"), 0));
	TEST_EQUAL(0, ps_alignment_populate(al));

	TEST_ASSERT(search = state_align_search_init(config, acmod, al));
	sas = (state_align_search_t *)search;

	for (i = 0; i < 5; ++i)
		do_search(search, acmod);

	itor = ps_alignment_words(al);
	TEST_EQUAL(ps_alignment_iter_get(itor)->start, 0);
	TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 46);
	itor = ps_alignment_iter_next(itor);
	TEST_EQUAL(ps_alignment_iter_get(itor)->start, 46);
	TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 18);
	itor = ps_alignment_iter_next(itor);
	TEST_EQUAL(ps_alignment_iter_get(itor)->start, 64);
	TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 53);
	itor = ps_alignment_iter_next(itor);
	TEST_EQUAL(ps_alignment_iter_get(itor)->start, 117);
	TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 29);
	itor = ps_alignment_iter_next(itor);
	TEST_EQUAL(ps_alignment_iter_get(itor)->start, 146);
	TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 67);
	itor = ps_alignment_iter_next(itor);
	TEST_EQUAL(ps_alignment_iter_get(itor)->start, 213);
	TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 61);
	itor = ps_alignment_iter_next(itor);
	TEST_EQUAL(itor, NULL);

	ps_search_free(search);
	ps_alignment_free(al);
	ps_free(ps);
	return 0;
}
Exemplo n.º 13
0
int main(int argc, char *argv[])
{
    ps_program_name=argv[0];
    ps_control_open_logfile();

    if (argc == 2)
        if ( (strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "--help") == 0))
        {
            printf("%s", ps_control_options);
            return EXIT_SUCCESS;
        }

    if (argc < 3)
        ps_log(EXIT_FAILURE, LOG_ERROR("too few parameters"));

    ps_init();
    ps_set_name(argv[1]);
    ps_control_check_input(argv[2], argc-3);
    ps_log(0, LOG_INFO("creating controller"));

    if (strcmp(argv[2],"--create") == 0)
    {
        ps_control_prepare_daemon_logfile((argc == 4) ? argv[3] : "none");
        ps_control_create_daemon();
    }
    else
    {
        ps_control_connect_daemon();

        if (strcmp(argv[2],"--pid") == 0)
        {
            ps_pid=ps_control_get_daemon_pid();
            printf("%d\n",(ps_pid == -1) ? 0 : ps_pid);

            if (ps_pid == -1)
                ps_log(EXIT_FAILURE, LOG_ERROR("--pid: failed to receive daemon PID"));
        }

        if (strcmp(argv[2],"--kill") == 0)
        {
            ps_pid=ps_control_get_daemon_pid();

            if (ps_pid <= 1)
                ps_log(EXIT_FAILURE, LOG_ERROR("--kill : could not determine daemon PID"));

            if (kill(ps_pid, SIGTERM) == -1)
                ps_log(EXIT_FAILURE, LOG_ERROR("--kill : failed to kill daemon - error [%s]"), strerror(errno));
        }

        if (ps_fd_control == -1)
            return EXIT_FAILURE;

        if (strcmp(argv[2],"--net") == 0)
            ps_control_unshare_network();

        if (strcmp(argv[2],"--ipc") == 0)
            ps_control_unshare_ipc();

        if (strcmp(argv[2],"--chrootfs") == 0)
            ps_control_change_rootfs(argv[3]);

        if (strcmp(argv[2],"--cwd") == 0)
            ps_control_change_workingdir(argv[3]);

        if (strcmp(argv[2],"--run") == 0)
        {
            if (isatty(STDIN_FILENO))
            {
                ps_control_save_terminal_attributes();
                atexit(ps_control_restore_terminal_attributes);
                ps_control_set_terminal_raw_mode();
            }

            ps_control_run_program(argc-3, argv+3);
        }
    }

    ps_log(0, LOG_INFO("closing controller"));
    return EXIT_SUCCESS;
}
Exemplo n.º 14
0
int
ps_decoder_test(cmd_ln_t *config, char const *sname, char const *expected)
{
    ps_decoder_t *ps;
    mfcc_t **cepbuf;
    FILE *rawfh;
    int16 *buf;
    int16 const *bptr;
    size_t nread;
    size_t nsamps;
    int32 nfr, i, score, prob;
    char const *hyp;
    char const *uttid;
    double n_speech, n_cpu, n_wall;
    ps_seg_t *seg;

    TEST_ASSERT(ps = ps_init(config));
    /* Test it first with pocketsphinx_decode_raw() */
    TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb"));
    ps_decode_raw(ps, rawfh, "goforward", -1);
    hyp = ps_get_hyp(ps, &score, &uttid);
    prob = ps_get_prob(ps, &uttid);
    printf("%s (%s): %s (%d, %d)\n", sname, uttid, hyp, score, prob);
    TEST_EQUAL(0, strcmp(hyp, expected));
    TEST_ASSERT(prob <= 0);
    ps_get_utt_time(ps, &n_speech, &n_cpu, &n_wall);
    printf("%.2f seconds speech, %.2f seconds CPU, %.2f seconds wall\n",
           n_speech, n_cpu, n_wall);
    printf("%.2f xRT (CPU), %.2f xRT (elapsed)\n",
           n_cpu / n_speech, n_wall / n_speech);

    /* Test it with ps_process_raw() */
    clearerr(rawfh);
    fseek(rawfh, 0, SEEK_END);
    nsamps = ftell(rawfh) / sizeof(*buf);
    fseek(rawfh, 0, SEEK_SET);
    TEST_EQUAL(0, ps_start_utt(ps, NULL));
    nsamps = 2048;
    buf = ckd_calloc(nsamps, sizeof(*buf));
    while (!feof(rawfh)) {
        nread = fread(buf, sizeof(*buf), nsamps, rawfh);
        ps_process_raw(ps, buf, nread, FALSE, FALSE);
    }
    TEST_EQUAL(0, ps_end_utt(ps));
    hyp = ps_get_hyp(ps, &score, &uttid);
    prob = ps_get_prob(ps, &uttid);
    printf("%s (%s): %s (%d, %d)\n", sname, uttid, hyp, score, prob);
    TEST_EQUAL(0, strcmp(uttid, "000000000"));
    TEST_EQUAL(0, strcmp(hyp, expected));
    ps_get_utt_time(ps, &n_speech, &n_cpu, &n_wall);
    printf("%.2f seconds speech, %.2f seconds CPU, %.2f seconds wall\n",
           n_speech, n_cpu, n_wall);
    printf("%.2f xRT (CPU), %.2f xRT (elapsed)\n",
           n_cpu / n_speech, n_wall / n_speech);

    /* Now read the whole file and produce an MFCC buffer. */
    clearerr(rawfh);
    fseek(rawfh, 0, SEEK_END);
    nsamps = ftell(rawfh) / sizeof(*buf);
    fseek(rawfh, 0, SEEK_SET);
    bptr = buf = ckd_realloc(buf, nsamps * sizeof(*buf));
    TEST_EQUAL(nsamps, fread(buf, sizeof(*buf), nsamps, rawfh));
    fe_process_frames(ps->acmod->fe, &bptr, &nsamps, NULL, &nfr, NULL);
    cepbuf = ckd_calloc_2d(nfr + 1,
                   fe_get_output_size(ps->acmod->fe),
                   sizeof(**cepbuf));
    fe_start_utt(ps->acmod->fe);
    fe_process_frames(ps->acmod->fe, &bptr, &nsamps, cepbuf, &nfr, NULL);
    fe_end_utt(ps->acmod->fe, cepbuf[nfr], &i);

    /* Decode it with process_cep() */
    TEST_EQUAL(0, ps_start_utt(ps, NULL));
    for (i = 0; i < nfr; ++i) {
        ps_process_cep(ps, cepbuf + i, 1, FALSE, FALSE);
    }
    TEST_EQUAL(0, ps_end_utt(ps));
    hyp = ps_get_hyp(ps, &score, &uttid);
    prob = ps_get_prob(ps, &uttid);
    printf("%s (%s): %s (%d, %d)\n", sname, uttid, hyp, score, prob);
    TEST_EQUAL(0, strcmp(uttid, "000000001"));
    TEST_EQUAL(0, strcmp(hyp, expected));
    TEST_ASSERT(prob <= 0);
    for (seg = ps_seg_iter(ps, &score); seg;
         seg = ps_seg_next(seg)) {
        char const *word;
        int sf, ef;
        int32 post, lscr, ascr, lback;

        word = ps_seg_word(seg);
        ps_seg_frames(seg, &sf, &ef);
        post = ps_seg_prob(seg, &ascr, &lscr, &lback);
        printf("%s (%d:%d) P(w|o) = %f ascr = %d lscr = %d lback = %d\n", word, sf, ef,
               logmath_exp(ps_get_logmath(ps), post), ascr, lscr, lback);
        TEST_ASSERT(post <= 2); // Due to numerical errors with float it sometimes could go out of 0
    }

    ps_get_utt_time(ps, &n_speech, &n_cpu, &n_wall);
    printf("%.2f seconds speech, %.2f seconds CPU, %.2f seconds wall\n",
           n_speech, n_cpu, n_wall);
    printf("%.2f xRT (CPU), %.2f xRT (elapsed)\n",
           n_cpu / n_speech, n_wall / n_speech);
    ps_get_all_time(ps, &n_speech, &n_cpu, &n_wall);
    printf("TOTAL: %.2f seconds speech, %.2f seconds CPU, %.2f seconds wall\n",
           n_speech, n_cpu, n_wall);
    printf("TOTAL: %.2f xRT (CPU), %.2f xRT (elapsed)\n",
           n_cpu / n_speech, n_wall / n_speech);

    fclose(rawfh);
    ps_free(ps);
    cmd_ln_free_r(config);
    ckd_free_2d(cepbuf);
    ckd_free(buf);

    return 0;
}
Exemplo n.º 15
0
int
main(int argc, char *argv[])
{
    cmd_ln_t *config;
    ps_decoder_t *ps;

    int32 out_score;

    const char *input_file_path;
    const char *cfg;
    const char *utt_id;
    const char *hyp;
    FILE *input_file;
    int16 buf[PCM_BUF_LEN];
    int k;

    config = cmd_ln_parse_r(NULL, cont_args_def, argc, argv, TRUE);

    /* Handle argument file as -argfile. */
    if (config && (cfg = cmd_ln_str_r(config, "-argfile")) != NULL) {
        config = cmd_ln_parse_file_r(config, cont_args_def, cfg, FALSE);
    }
    if (config == NULL)
        return 1;

    if (cmd_ln_str_r(config, "-kws") == NULL && cmd_ln_str_r(config, "-keyphrase") == NULL) {
        E_ERROR("Keyword is missing. Use -keyphrase <keyphrase> or -kws <kws_file> to specify the phrase to look for.");
        return 1;
    }

    input_file_path = cmd_ln_str_r(config, "-infile");
    if (input_file_path == NULL) {
        E_ERROR("Input file is missing. Use -infile <input_file> to specify the file to look in.\n");
        return 1;
    }

    ps_default_search_args(config);
    ps = ps_init(config);
    
    if (ps == NULL) {
        E_ERROR("Failed to create the decoder\n");
        return 1;
    }
    
    input_file = fopen(input_file_path, "rb");
    if (input_file == NULL) {
        E_FATAL_SYSTEM("Failed to open input file '%s'", input_file_path);
    }
    
    ps_start_utt(ps, NULL);
    if (cmd_ln_boolean_r(config, "-adcin")) {
        fread(buf, 1, 44, input_file);
        while ((k = fread(buf, sizeof(int16), PCM_BUF_LEN, input_file)) > 0) {
            ps_process_raw(ps, buf, k, FALSE, FALSE);
        }
    } else {
        mfcc_t **mfcs;
        int nfr;

        if (NULL == (mfcs = read_mfc_file(input_file, &nfr, cmd_ln_int32_r(config, "-ceplen")))) {
            E_ERROR("Failed to read MFCC from the file '%s'\n", input_file_path);
            fclose(input_file);
            return -1;
        }
        ps_process_cep(ps, mfcs, nfr, FALSE, TRUE);
        ckd_free_2d(mfcs);
    }
    ps_end_utt(ps);

    hyp = ps_get_hyp(ps, &out_score, &utt_id);
    printf("hypothesis: %s\n", hyp);
    fflush(stdout);

    fclose(input_file);
    ps_free(ps);
    cmd_ln_free_r(config);

    return 0;
}
int
main(int argc, char *argv[])
{
    ps_decoder_t *ps;
    cmd_ln_t *config;
    acmod_t *acmod;
    ngram_search_t *ngs;
    ps_lattice_t *dag;
    clock_t c;
    int i;

    TEST_ASSERT(config =
            cmd_ln_init(NULL, ps_args(), TRUE,
                "-hmm", MODELDIR "/en-us/en-us",
                "-lm", MODELDIR "/en-us/en-us.lm.bin",
                "-dict", MODELDIR "/en-us/cmudict-en-us.dict",
                "-fwdtree", "yes",
                "-fwdflat", "no",
                "-bestpath", "yes",
                "-samprate", "16000", NULL));
    TEST_ASSERT(ps = ps_init(config));

    ngs = (ngram_search_t *)ps->search;
    acmod = ps->acmod;
        acmod_set_grow(ps->acmod, TRUE);

    setbuf(stdout, NULL);
    c = clock();
    for (i = 0; i < 5; ++i) {
        FILE *rawfh;
        int16 buf[2048];
        size_t nread;
        int16 const *bptr;
        int nfr;
        ps_astar_t *nbest;
        ps_latpath_t *path;
        char *besthyp;
        const char *astar_besthyp = NULL;
        int32 astar_hyp_score;
        int i;

        /* PocketSphinx API would do this for us but we have to do it manually here. */
        ps_lattice_free(ps->search->dag);
        ps->search->dag = NULL;

        TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb"));
        TEST_EQUAL(0, acmod_start_utt(acmod));
        ngram_fwdtree_start(ngs);
        while (!feof(rawfh)) {
            nread = fread(buf, sizeof(*buf), 2048, rawfh);
            bptr = buf;
            while ((nfr = acmod_process_raw(acmod, &bptr, &nread, FALSE)) > 0) {
                while (acmod->n_feat_frame > 0) {
                    ngram_fwdtree_search(ngs, acmod->output_frame);
                    acmod_advance(acmod);
                }
            }
        }
        ngram_fwdtree_finish(ngs);
        printf("FWDTREE: %s\n",
               ngram_search_bp_hyp(ngs, ngram_search_find_exit(ngs, -1, NULL)));

        TEST_ASSERT(acmod_end_utt(acmod) >= 0);
        fclose(rawfh);

        dag = ngram_search_lattice(ps->search);
        if (dag == NULL) {
            E_ERROR("Failed to build DAG!\n");
            return 1;
        }
        besthyp = ckd_salloc
            (ps_lattice_hyp(dag, ps_lattice_bestpath
                    (dag, ngs->lmset, 9.5/6.5, 1.0)));
        printf("BESTPATH: %s\n", besthyp);

        TEST_ASSERT(nbest = ps_astar_start(dag, ngs->lmset, 9.5/6.5, 0, -1, -1, -1));
        i = 0;
        astar_hyp_score = WORST_SCORE;
        while ((path = ps_astar_next(nbest))) {
            if (i < 10)
                printf("NBEST %d: %s (%d)\n", i, ps_astar_hyp(nbest, path), path->score);
            if (path->score > astar_hyp_score) {
                astar_hyp_score = path->score;
                astar_besthyp = ps_astar_hyp(nbest, path);
            }
            i++;
        }
        TEST_EQUAL(0, strcmp(besthyp, astar_besthyp));
        ps_astar_finish(nbest);
        ckd_free(besthyp);
    }
    printf("%s\n", ngram_search_bp_hyp(ngs, ngram_search_find_exit(ngs, -1, NULL)));
    TEST_EQUAL(0, strcmp("go forward ten meters",
                 ngram_search_bp_hyp(ngs, ngram_search_find_exit(ngs, -1, NULL))));
    c = clock() - c;
    printf("5 * fwdtree + bestpath + N-best search in %.2f sec\n",
           (double)c / CLOCKS_PER_SEC);
    ps_free(ps);
    cmd_ln_free_r(config);

    return 0;
}
Exemplo n.º 17
0
int main(int argc, char *argv[])
{
	ps_decoder_t *ps;
	cmd_ln_t *config;
	FILE *fh;
	char const *hyp, *uttid;
	int16 buf[512];
	int rv;
	int32 score;

	config = cmd_ln_init(NULL, ps_args(), TRUE,
			     "-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
			     "-dict", MODELDIR2 "/en.id001.a.dic",
			     "-lm", MODELDIR2 "/en.id001.arpabo",
			     NULL);
	if (config == NULL) return 1;

	ps = ps_init(config);
	if (ps == NULL) return 1;

	fh = fopen("/Users/kicoolzhang/Documents/1.mov", "rb");
	if (fh == NULL) {
		perror("Failed to open goforward.raw");
		return 1;
	}

	rv = ps_decode_raw(ps, fh, NULL, -1);
	if (rv < 0) return 1;
	printf("[K]Decoded No. of samples of audio: %d\n", rv);
	
	hyp = ps_get_hyp(ps, &score, &uttid);
	if (hyp == NULL) return 1;

	printf("Recognized: %s\n", hyp);

	fseek(fh, 0, SEEK_SET);

	rv = ps_start_utt(ps, NULL);
	if (rv < 0) return 1;

	while (!feof(fh)) {
		rv = ps_start_utt(ps, NULL);
		if (rv < 0)
			return 1;
		printf("ready:\n");
		size_t nsamp;
		nsamp = fread(buf, 2, 512, fh);
		printf("read:\n");
		//我们将每次从文件中读取512大小的样本,使用ps_process_raw()把它们放到解码器中:
		rv = ps_process_raw(ps, buf, nsamp, FALSE, FALSE);
		printf("process:\n");
	}

	//我们需要使用ps_end_utt()去标记说话的结尾处:
	rv = ps_end_utt(ps);

	if (rv < 0)
		return 1;

	//以相同精确的方式运行来检索假设的字符串:
	hyp = ps_get_hyp(ps, &score, &uttid);
	if (hyp == NULL)
		return 1;

	printf("Recognized: %s\n", hyp);
	fclose(fh);
	ps_free(ps);
	return 0;
}
Exemplo n.º 18
0
int
main(int argc, char *argv[])
{
    ps_decoder_t *ps;
    dict_t *dict;
    dict2pid_t *d2p;
    acmod_t *acmod;
    ps_alignment_t *al;
    ps_alignment_iter_t *itor;
    ps_search_t *search;
    cmd_ln_t *config;
    int i;

    config = cmd_ln_init(NULL, ps_args(), FALSE,
                 "-hmm", MODELDIR "/en-us/en-us",
                 "-dict", MODELDIR "/en-us/cmudict-en-us.dict",
                 "-input_endian", "little",
                 "-samprate", "16000", NULL);
    TEST_ASSERT(ps = ps_init(config));
    dict = ps->dict;
    d2p = ps->d2p;
    acmod = ps->acmod;

    al = ps_alignment_init(d2p);
    TEST_EQUAL(1, ps_alignment_add_word(al, dict_wordid(dict, "<s>"), 0));
    TEST_EQUAL(2, ps_alignment_add_word(al, dict_wordid(dict, "go"), 0));
    TEST_EQUAL(3, ps_alignment_add_word(al, dict_wordid(dict, "forward"), 0));
    TEST_EQUAL(4, ps_alignment_add_word(al, dict_wordid(dict, "ten"), 0));
    TEST_EQUAL(5, ps_alignment_add_word(al, dict_wordid(dict, "meters"), 0));
    TEST_EQUAL(6, ps_alignment_add_word(al, dict_wordid(dict, "</s>"), 0));
    TEST_EQUAL(0, ps_alignment_populate(al));

    TEST_ASSERT(search = state_align_search_init(config, acmod, al));

    for (i = 0; i < 5; ++i)
        do_search(search, acmod);

    itor = ps_alignment_words(al);
    TEST_EQUAL(ps_alignment_iter_get(itor)->start, 0);
    TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 3);
    itor = ps_alignment_iter_next(itor);
    TEST_EQUAL(ps_alignment_iter_get(itor)->start, 3);
    TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 12);
    itor = ps_alignment_iter_next(itor);
    TEST_EQUAL(ps_alignment_iter_get(itor)->start, 15);
    TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 53);
    itor = ps_alignment_iter_next(itor);
    TEST_EQUAL(ps_alignment_iter_get(itor)->start, 68);
    TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 36);
    itor = ps_alignment_iter_next(itor);
    TEST_EQUAL(ps_alignment_iter_get(itor)->start, 104);
    TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 59);
    itor = ps_alignment_iter_next(itor);
    TEST_EQUAL(ps_alignment_iter_get(itor)->start, 163);
    TEST_EQUAL(ps_alignment_iter_get(itor)->duration, 51);
    itor = ps_alignment_iter_next(itor);
    TEST_EQUAL(itor, NULL);

    ps_search_free(search);
    ps_alignment_free(al);
    ps_free(ps);
    cmd_ln_free_r(config);
    return 0;
}
Exemplo n.º 19
0
int main(int argc, char* argv[])
{
    ps_decoder_t *ps;
    cmd_ln_t *config;
    FILE *fh;
    int rv;
    char const *hyp, *uttid;
    int32 score;
    int16 buf[512];

    /*
     *config = cmd_ln_init(NULL, ps_args(), TRUE,
     *                    "-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
     *                    "-lm", MODELDIR "/lm/en/turtle.DMP",
     *                    "-dict", MODELDIR "/lm/en/turtle.dic",
     *                    NULL);
     */
    config = cmd_ln_parse_file_r(NULL, ps_args(), "commands.gram", FALSE);
    if ( config == NULL )
        return 1;
    
    ps = ps_init(config);
    if ( ps == NULL )
        return 1;

    // Audio file for test
    fh = fopen("goforward.raw", "rb");
    if ( fh == NULL ) {
        perror("Failed to open file");
        return 1;
    }
    
    // Decoding
    rv = ps_decode_raw(ps, fh, "goforward", -1);
    if ( rv < 0 )
        return 1;
    // Hypothesis
    hyp = ps_get_hyp(ps, &score, &uttid);
    if ( hyp == NULL )
        return 1;
    printf("Recognized: %s (%d %s)\n", hyp, score, uttid);

    /* Do it again, from block memory
    fseek(fh, 0, SEEK_SET);
    while ( !feof(fh) ) {
        size_t nsamp;
        nsamp = fread(buf, 2, 512, fh);
        rv = ps_process_raw(ps, buf, nsamp, FALSE, FALSE);
    }
    // End of the utterance
    rv = ps_end_utt(ps);
    if ( rv < 0 )
        return 1;
    // Retrieving hypothesis
    hyp = ps_get_hyp(ps, &score, &uttid);
    if ( hyp == NULL )
        return 1;
    printf("Recognized: %s (%d %s)\n", hyp, score, uttid);*/

    // Cleaning up
    fclose(fh);
    ps_free(ps);
    return 0;
}
static gboolean
gst_pocketsphinx_event(GstPad *pad, GstEvent *event)
{
    GstPocketSphinx *ps;

    ps = GST_POCKETSPHINX(GST_OBJECT_PARENT(pad));

    /* Pick out VAD events. */
    switch (event->type) {
    case GST_EVENT_NEWSEGMENT:
        /* Initialize the decoder once the audio starts, if it's not
         * there yet. */
        if (ps->ps == NULL) {
            ps->ps = ps_init(ps->config);
            if (ps->ps == NULL) {
                GST_ELEMENT_ERROR(GST_ELEMENT(ps), LIBRARY, INIT,
                                  ("Failed to initialize PocketSphinx"),
                                  ("Failed to initialize PocketSphinx"));
                return FALSE;
            }
        }
        return gst_pad_event_default(pad, event);
    case GST_EVENT_VADER_START:
        ps->listening = TRUE;
        ps_start_utt(ps->ps, NULL);
        /* Forward this event. */
        return gst_pad_event_default(pad, event);
    case GST_EVENT_EOS:
    case GST_EVENT_VADER_STOP: {
        GstBuffer *buffer;
        int32 score;
        char const *hyp;
        char const *uttid;

        hyp = NULL;
        if (ps->listening) {
            ps->listening = FALSE;
            ps_end_utt(ps->ps);
            hyp = ps_get_hyp(ps->ps, &score, &uttid);
            /* Dump the lattice if requested. */
            if (ps->latdir) {
                char *latfile = string_join(ps->latdir, "/", uttid, ".lat", NULL);
                ps_lattice_t *dag;

                if ((dag = ps_get_lattice(ps->ps)))
                    ps_lattice_write(dag, latfile);
                ckd_free(latfile);
            }
        }
        if (hyp) {
            /* Emit a signal for applications. */
            g_signal_emit(ps, gst_pocketsphinx_signals[SIGNAL_RESULT],
                          0, hyp, uttid);
            /* Forward this result in a buffer. */
            buffer = gst_buffer_new_and_alloc(strlen(hyp) + 2);
            strcpy((char *)GST_BUFFER_DATA(buffer), hyp);
            GST_BUFFER_DATA(buffer)[strlen(hyp)] = '\n';
            GST_BUFFER_DATA(buffer)[strlen(hyp)+1] = '\0';
            GST_BUFFER_TIMESTAMP(buffer) = GST_EVENT_TIMESTAMP(event);
            gst_buffer_set_caps(buffer, GST_PAD_CAPS(ps->srcpad));
            gst_pad_push(ps->srcpad, buffer);
        }

        /* Forward this event. */
        return gst_pad_event_default(pad, event);
    }
    default:
        /* Don't bother with other events. */
        return gst_pad_event_default(pad, event);
    }
}
Exemplo n.º 21
0
int main(int argc, char** argv)
{
    int i;
    int rv;
    FILE* fh;
    char const *hyp, *uttid;
    int32 score;
    ps_decoder_t *ps;
	cmd_ln_t *config;
    ps_lattice_t* dag;

    config = cmd_ln_init(NULL, ps_args(), TRUE,
			     "-hmm", "./hmm/zh_broadcastnews_ptm256_8000",
			     "-lm", "./lm/syllables.lm.DMP",
			     "-dict", "./lm/syllables_sorted.dic",
			     NULL);
	if (config == NULL)
		return 1;
	ps = ps_init(config);
	if (ps == NULL)
		return 1;
   
	fh = fopen(argv[1], "rb");
	if (fh == NULL) {
		perror("Failed to open audio file.");
		return 1;
	}

	rv = ps_decode_raw(ps, fh, "test", -1);
	if (rv < 0)
		return 1;

	hyp = ps_get_hyp(ps, &score, &uttid);
	if (hyp == NULL)
		return 1;
	printf("Recognized: %s\n", hyp);
	inverted_index_t* index = inverted_index_init("./syllable.lst");
    if (index == NULL) {
       exit(1);
    }

	dag = ps_get_lattice(ps);
	if (dag == NULL) {
	    perror("No lattice");
	    return 1;
	}

    /*
    printf("# Total number of words: %d\n", index->n_word);
    for(i = 0; i < index->n_word; i++) {
        printf("%3d: %s\n", i+1, index->word_list[i]);
    }*/
    float32 ascale = cmd_ln_float32_r(config, "-ascale");
    printf("ascale: %f\n", ascale);
    //printf("%d: %s\n", inverted_index_get_wid(index, "ba"), "ba");
    //printf("%d: %s\n", inverted_index_get_wid(index, "bia"), "bia");
    inverted_index_addhits(index, "test", dag, 1.0/ascale);
    inverted_index_write(index, "./index");
    inverted_index_free(index);
    index = inverted_index_read("./index");
    inverted_index_write(index, "./index2");
    
    char* query[] = {"jin", "tian", "jie", "mu"};
    result_list_t* rl;
    inverted_index_search(index, ps_get_lmset(ps), 1.0/ascale, query, 4, &rl);

	inverted_index_free(index);
	return 0;
}
Exemplo n.º 22
0
int
to_eps (const GEN_PAR *pg, const OUT_PAR *po)
{
    PlotCmd	cmd;
    HPGL_Pt	pt1 = {0,0};
    FILE		*md;
    int		pen_no=0, pencolor=0, err;
    PEN_W		pensize;

    err = 0;
    if (!pg->quiet)
        Eprintf ("\n\n- Writing EPS code to \"%s\"\n",
                 *po->outfile == '-' ? "stdout" : po->outfile);

    /* Init. of PostScript file: */
    if (*po->outfile != '-')
    {
        if ((md = fopen(po->outfile, "w")) == NULL)
        {
            PError("hp2xx (eps)");
            return ERROR;
        }
    }
    else
        md = stdout;

    /* PS header */

    pensize = pt.width[DEFAULT_PEN_NO]; /* Default pen	*/
    ps_init (pg, po, md, pensize);

    if (pensize > 0.05)
        fprintf(md," %6.3f W\n", pensize);

    /* Factor for transformation of HP coordinates to mm	*/

    xcoord2mm = po->width  / (po->xmax - po->xmin);
    ycoord2mm = po->height / (po->ymax - po->ymin);
    xmin	    = po->xmin;
    ymin	    = po->ymin;

    /**
     ** Command loop: While temporary file not empty: process command.
     **/

    while ((cmd = PlotCmd_from_tmpfile()) != CMD_EOF)
    {
        switch (cmd)
        {
        case NOP:
            break;
        case SET_PEN:
            if ((pen_no = fgetc(pg->td)) == EOF)
            {
                PError("Unexpected end of temp. file: ");
                err = ERROR;
                goto EPS_exit;
            }
            pensize = pt.width[pen_no];
            pencolor = pt.color[pen_no];
            break;
        case DEF_PW:
            if(!load_pen_width_table(pg->td)) {
                PError("Unexpected end of temp. file");
                err = ERROR;
                goto EPS_exit;
            }
            pensize=pt.width[pen_no];
            break;
        case DEF_PC:
            err=load_pen_color_table(pg->td);
            if (err<0) {
                PError("Unexpected end of temp. file");
                err = ERROR;
                goto EPS_exit;
            }
            if (err==pencolor) pencolor *=-1; /*current pen changed*/
            break;
        case DEF_LA:
            if(load_line_attr(pg->td) <0) {
                PError("Unexpected end of temp. file");
                err = ERROR;
                goto EPS_exit;
            }
            break;
        case MOVE_TO:
            ps_set_linewidth(pensize, &pt1, md);
            ps_set_linecap(CurrentLineAttr.End, pensize, &pt1, md);

            if(pencolor <0) {
                pencolor=pt.color[pen_no];
                ps_set_color (  pt.clut[pencolor][0]/255.0,
                                pt.clut[pencolor][1]/255.0,
                                pt.clut[pencolor][2]/255.0,
                                &pt1, md);
            }

            HPGL_Pt_from_tmpfile (&pt1);
            if (pensize > 0.05)
                ps_stroke_and_move_to (&pt1, md);
            break;
        case DRAW_TO:
            ps_set_linewidth(pensize, &pt1, md);
            ps_set_linecap(CurrentLineAttr.End, pensize, &pt1, md);

            if(pencolor <0) {
                pencolor=pt.color[pen_no];
                ps_set_color (  pt.clut[pencolor][0]/255.0,
                                pt.clut[pencolor][1]/255.0,
                                pt.clut[pencolor][2]/255.0,
                                &pt1, md);
            }

            HPGL_Pt_from_tmpfile (&pt1);
            if (pensize > 0.05)
                ps_line_to (&pt1, 'D', md);
            break;
        case PLOT_AT:
            ps_set_linewidth(pensize, &pt1, md);
            ps_set_linecap(CurrentLineAttr.End, pensize, &pt1, md);

            if(pencolor<0) {
                pencolor=pt.color[pen_no];
                ps_set_color (  pt.clut[pencolor][0]/255.0,
                                pt.clut[pencolor][1]/255.0,
                                pt.clut[pencolor][2]/255.0,
                                &pt1, md);
            }

            HPGL_Pt_from_tmpfile (&pt1);
            if (pensize > 0.05) {
                ps_line_to (&pt1, 'M', md);
                ps_line_to (&pt1, 'D', md); /* not sure whether this is needed */
                ps_draw_dot(&pt1,pensize/2,md);
            }
            break;
        default:
            Eprintf ("Illegal cmd in temp. file!");
            err = ERROR;
            goto EPS_exit;
        }
    }

    /* Finish up */

    ps_end (md);

EPS_exit:
    if (md != stdout)
        fclose (md);

    if (!pg->quiet)
        Eprintf ("\n");
    return err;
}
Exemplo n.º 23
0
int main(int argc, char *argv[]) {
	ps_decoder_t *ps;
	cmd_ln_t *config;
	FILE *fh;
	char const *hyp, *uttid;
	int16 buf[512];
	int rv;
	int32 score;

//	config = cmd_ln_init(NULL, ps_args(), TRUE,
//    			     "-hmm", MODELDIR "/en-us/en-us",
//    			     "-lm", MODELDIR "/en-us/en-us.lm.bin",
//    			     "-dict", MODELDIR "/en-us/cmudict-en-us.dict",
//    			     NULL);

	config = cmd_ln_init(NULL, ps_args(), TRUE,
    			     "-hmm", MODELDIR "/updated/cmusphinx-en-us-5.2",
    			     "-lm", MODELDIR "/updated/updated.lm",
    			     "-dict", MODELDIR "/updated/cmudict-updated.dict",
    			     NULL);

	if (config == NULL) {
		return 1;
	}

	ps = ps_init(config);
	if (ps == NULL) {
		return 1;
	}

//	fh = fopen("goforward.raw", "rb");
//	fh = fopen("testtest123test.raw", "rb");
//	fh = fopen("helloworld2.raw", "rb");
//	fh = fopen("helloworld3.raw", "rb");
	fh = fopen("jarviscreate.raw", "rb");
	if (fh == NULL) {
		printf("Count not find input file\n");
		return -1;
	}

	rv = ps_start_utt(ps);

	if (rv < 0) {
		return 1;
	}

	while (!feof(fh)) {
		size_t nsamp;
		nsamp = fread(buf, 2, 512, fh);
		rv = ps_process_raw(ps, buf, nsamp, FALSE, FALSE);
	}
	rv = ps_end_utt(ps);

	if (rv < 0) {
		return 1;
	}

	hyp = ps_get_hyp(ps, &score);
	if (hyp == NULL) {
		return 1;
	}

	printf("Recognized: %s\n", hyp);

	fclose(fh);
	ps_free(ps);
	cmd_ln_free_r(config);

	return 0;
}
Exemplo n.º 24
0
    void Node::run() {
        // declare variables
        const int BUFFER_SIZE = 2048;
        ad_rec_t *reader;
        size_t read_samples;
        int16 read_buffer[BUFFER_SIZE];
        cmd_ln_t *read_decoder_config;
        ps_decoder_t *read_decoder;

        // open audio record
        reader = ad_open_dev(NULL, 16000);
        if (reader == NULL) {
            throw NodeException("Failed to open read audio device");
        }

        // start audio record
        if (ad_start_rec(reader) < 0) {
            throw NodeException("Failed to start read audio device");
        }

        // instance audio decoder
        read_decoder_config = cmd_ln_init(
                NULL,
                ps_args(),
                TRUE,
                "-logfn", "/dev/null", // turn off console log
                "-hmm", "/usr/local/share/pocketsphinx/model/en-us/en-us",
                "-lm", "/usr/local/share/pocketsphinx/model/en-us/en-us.lm.dmp",
                "-dict", "/usr/local/share/pocketsphinx/model/en-us/cmudict-en-us.dict",
                NULL
        );
        read_decoder = ps_init(read_decoder_config);
        if (read_decoder == NULL) {
            throw NodeException("Failed to initialize audio decoder");
        }

        // start utterance
        if (ps_start_utt(read_decoder) < 0) {
            throw NodeException("Failed to start reader utterance");
        }
        bool utt_started = false;
        bool in_speech = false;
        char const *hypothesis;

        while (true) {
            try {
                // read from input device
                read_samples = ad_read(
                        reader,
                        read_buffer,
                        BUFFER_SIZE
                );
                if (read_samples < 0) {
                    throw NodeException("Failed to read audio");
                }

                // add data buffered from device to read decoder
                ps_process_raw(
                        read_decoder,
                        read_buffer,
                        read_samples,
                        false,
                        false
                );

                // check device in speech
                in_speech = ps_get_in_speech(read_decoder);
                if (in_speech && !utt_started) {
                    utt_started = true;
                }

                // check device in speech then add data to decoder
                if (!in_speech && utt_started) {
                    ps_end_utt(read_decoder);
                    hypothesis = ps_get_hyp(read_decoder, NULL);
                    if (hypothesis != NULL) {
                        cout<<"ENV: "<<hypothesis<<endl;
                        Command core_command = this->spec_.first("node-core");
                        int port = atoi(core_command.option("--port").c_str());
                        SocketWriter socket(core_command.option("--host"), port);
                        string response = socket.write_to(hypothesis);
                        cout << "IN: " << response << endl;
                    }
                    if (ps_start_utt(read_decoder) < 0) {
                        throw NodeException("Failed to start reader utterance");
                    }
                    utt_started = false;
                }
                sleep_milli_seconds(100);
            } catch (NodeException e) {
                cout<<"ERROR: "<<e.what()<<endl;
            }

        }
    }
Exemplo n.º 25
0
int
main(int argc, char *argv[])
{
    ps_decoder_t *ps;
    cmd_ln_t *config;
    acmod_t *acmod;
    fsg_search_t *fsgs;
    jsgf_t *jsgf;
    jsgf_rule_t *rule;
    fsg_model_t *fsg;
    ps_seg_t *seg;
    ps_lattice_t *dag;
    FILE *rawfh;
    char const *hyp, *uttid;
    int32 score, prob;
    clock_t c;
    int i;

    TEST_ASSERT(config =
            cmd_ln_init(NULL, ps_args(), TRUE,
                "-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
                "-dict", MODELDIR "/lm/en/turtle.dic",
                "-input_endian", "little",
                "-samprate", "16000", NULL));
    TEST_ASSERT(ps = ps_init(config));

    jsgf = jsgf_parse_file(DATADIR "/goforward.gram", NULL);
    TEST_ASSERT(jsgf);
    rule = jsgf_get_rule(jsgf, "<goforward.move2>");
    TEST_ASSERT(rule);
    fsg = jsgf_build_fsg(jsgf, rule, ps->lmath, 7.5);
    TEST_ASSERT(fsg);
    fsg_model_write(fsg, stdout);
  ps_set_fsg(ps, "<goforward.move2>", fsg);
  ps_set_search(ps, "<goforward.move2>"); 

    acmod = ps->acmod;
  fsgs = (fsg_search_t *) fsg_search_init(fsg, config, acmod, ps->dict, ps->d2p);

    setbuf(stdout, NULL);
    c = clock();
    for (i = 0; i < 5; ++i) {
        int16 buf[2048];
        size_t nread;
        int16 const *bptr;
        int nfr;
        int is_final;

        TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb"));
        TEST_EQUAL(0, acmod_start_utt(acmod));
        fsg_search_start(ps_search_base(fsgs));
        is_final = FALSE;
        while (!feof(rawfh)) {
            nread = fread(buf, sizeof(*buf), 2048, rawfh);
            bptr = buf;
            while ((nfr = acmod_process_raw(acmod, &bptr, &nread, FALSE)) > 0) {
                while (acmod->n_feat_frame > 0) {
                    fsg_search_step(ps_search_base(fsgs),
                            acmod->output_frame);
                    acmod_advance(acmod);
                }
            }
            hyp = fsg_search_hyp(ps_search_base(fsgs), &score, &is_final);
            printf("FSG: %s (%d) frame %d final %s\n", hyp, score, acmod->output_frame, is_final ? "FINAL" : "");
            TEST_EQUAL (is_final, (acmod->output_frame > 170));
        }
        fsg_search_finish(ps_search_base(fsgs));
        hyp = fsg_search_hyp(ps_search_base(fsgs), &score, NULL);
        printf("FSG: %s (%d)\n", hyp, score);

        TEST_ASSERT(acmod_end_utt(acmod) >= 0);
        fclose(rawfh);
    }
    TEST_EQUAL(0, strcmp("go forward ten meters",
                 fsg_search_hyp(ps_search_base(fsgs), &score, NULL)));
    ps->search = (ps_search_t *)fsgs;
    for (seg = ps_seg_iter(ps, &score); seg;
         seg = ps_seg_next(seg)) {
        char const *word;
        int sf, ef;

        word = ps_seg_word(seg);
        ps_seg_frames(seg, &sf, &ef);
        printf("%s %d %d\n", word, sf, ef);
    }
    c = clock() - c;
    printf("5 * fsg search in %.2f sec\n", (double)c / CLOCKS_PER_SEC);

    dag = ps_get_lattice(ps);
    ps_lattice_write(dag, "test_jsgf.lat");
    jsgf_grammar_free(jsgf);
    fsg_search_free(ps_search_base(fsgs));
    ps_free(ps);
    cmd_ln_free_r(config);

    TEST_ASSERT(config =
            cmd_ln_init(NULL, ps_args(), TRUE,
                "-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
                "-dict", MODELDIR "/lm/en/turtle.dic",
                "-jsgf", DATADIR "/goforward.gram",
                "-input_endian", "little",
                "-samprate", "16000", NULL));
    TEST_ASSERT(ps = ps_init(config));
    TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb"));
    ps_decode_raw(ps, rawfh, "goforward", -1);
    hyp = ps_get_hyp(ps, &score, &uttid);
    prob = ps_get_prob(ps, &uttid);
    printf("%s: %s (%d, %d)\n", uttid, hyp, score, prob);
    TEST_EQUAL(0, strcmp("go forward ten meters", hyp));
    ps_free(ps);
    fclose(rawfh);
    cmd_ln_free_r(config);

    TEST_ASSERT(config =
            cmd_ln_init(NULL, ps_args(), TRUE,
                "-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
                "-dict", MODELDIR "/lm/en/turtle.dic",
                "-jsgf", DATADIR "/goforward.gram",
                "-toprule", "goforward.move2",
                "-input_endian", "little",
                "-samprate", "16000", NULL));
    TEST_ASSERT(ps = ps_init(config));
    TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb"));
    ps_decode_raw(ps, rawfh, "goforward", -1);
    hyp = ps_get_hyp(ps, &score, &uttid);
    prob = ps_get_prob(ps, &uttid);
    printf("%s: %s (%d, %d)\n", uttid, hyp, score, prob);
    TEST_EQUAL(0, strcmp("go forward ten meters", hyp));
    ps_free(ps);
    cmd_ln_free_r(config);
    fclose(rawfh);

    TEST_ASSERT(config =
            cmd_ln_init(NULL, ps_args(), TRUE,
                "-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
                "-dict", MODELDIR "/lm/en/turtle.dic",
                "-jsgf", DATADIR "/defective.gram",
                NULL));
    TEST_ASSERT(NULL == ps_init(config));
    cmd_ln_free_r(config);

    return 0;
}
Exemplo n.º 26
0
SWIGINTERN Decoder *new_Decoder__SWIG_0(){
		Decoder *d = ps_init(cmd_ln_init(NULL, ps_args(), FALSE, NULL));
		return d;
	}
Exemplo n.º 27
0
int
main(int argc, char *argv[])
{
	ps_decoder_t *ps;
	cmd_ln_t *config;
	acmod_t *acmod;
	fsg_search_t *fsgs;
	ps_lattice_t *dag;
	ps_seg_t *seg;
	int32 score;

	TEST_ASSERT(config =
		    cmd_ln_init(NULL, ps_args(), TRUE,
				"-hmm", MODELDIR "/hmm/en_US/hub4wsj_sc_8k",
				"-fsg", DATADIR "/goforward.fsg",
				"-dict", MODELDIR "/lm/en/turtle.dic",
				"-bestpath", "no",
				"-input_endian", "little",
				"-samprate", "16000", NULL));
	TEST_ASSERT(ps = ps_init(config));

	fsgs = (fsg_search_t *)ps->search;
	acmod = ps->acmod;

	setbuf(stdout, NULL);
	{
		FILE *rawfh;
		int16 buf[2048];
		size_t nread;
		int16 const *bptr;
		char const *hyp;
		int nfr;
		int is_final;

		TEST_ASSERT(rawfh = fopen(DATADIR "/goforward.raw", "rb"));
		TEST_EQUAL(0, acmod_start_utt(acmod));
		fsg_search_start(ps_search_base(fsgs));
		while (!feof(rawfh)) {
			nread = fread(buf, sizeof(*buf), 2048, rawfh);
			bptr = buf;
			while ((nfr = acmod_process_raw(acmod, &bptr, &nread, FALSE)) > 0) {
				while (acmod->n_feat_frame > 0) {
					fsg_search_step(ps_search_base(fsgs),
							acmod->output_frame);
					acmod_advance(acmod);
				}
				hyp = fsg_search_hyp(ps_search_base(fsgs), &score, &is_final);
				TEST_EQUAL (is_final, (acmod->output_frame > 170));
			        printf("FSG: %s (%d) %s\n", hyp, score, is_final ? "FINAL" : "");
			}
		}
		fsg_search_finish(ps_search_base(fsgs));
		hyp = fsg_search_hyp(ps_search_base(fsgs), &score, NULL);
		printf("FSG: %s (%d)\n", hyp, score);

		TEST_ASSERT(acmod_end_utt(acmod) >= 0);
		fclose(rawfh);
	}
	TEST_EQUAL(0, strcmp("go forward ten meters",
			     fsg_search_hyp(ps_search_base(fsgs), &score, NULL)));
	for (seg = ps_seg_iter(ps, &score); seg;
	     seg = ps_seg_next(seg)) {
		char const *word;
		int sf, ef;
		int32 post, lscr, ascr, lback;

		word = ps_seg_word(seg);
		ps_seg_frames(seg, &sf, &ef);
		if (sf == ef)
			continue;
		post = ps_seg_prob(seg, &ascr, &lscr, &lback);
		printf("%s (%d:%d) P(w|o) = %f ascr = %d lscr = %d lback = %d\n", word, sf, ef,
		       logmath_exp(ps_get_logmath(ps), post), ascr, lscr, lback);
	}

	/* Now get the DAG and play with it. */
	dag = ps_get_lattice(ps);
	ps_lattice_write(dag, "test_fsg.lat");
	printf("BESTPATH: %s\n",
	       ps_lattice_hyp(dag, ps_lattice_bestpath(dag, NULL, 1.0, 15.0)));
	ps_lattice_posterior(dag, NULL, 15.0);
	ps_free(ps);
	cmd_ln_free_r(config);

	return 0;
}
Exemplo n.º 28
0
sbr_info *sbrDecodeInit(uint16_t framelength, uint8_t id_aac, uint8_t id_ele,
                        uint32_t sample_rate, uint8_t downSampledSBR, 
                        uint8_t IsDRM)
{
    (void)downSampledSBR;
#ifndef DRM
    (void)IsDRM;
#endif 

    /* Allocate sbr_info. */
#if defined(FAAD_STATIC_ALLOC)
    sbr_info *sbr = &s_sbr[id_ele];
#else
    (void)id_ele;
    sbr_info *sbr = (sbr_info*)faad_malloc(sizeof(sbr_info));
    if (sbr == NULL)
    {
        /* could not allocate memory */
        return NULL;
    }
#endif
    memset(sbr, 0, sizeof(sbr_info));
    
#ifdef PS_DEC
    /* initialize PS variables */
    ps_init(&sbr->ps);
#endif
    
    /* Allocate XLR temporary variable. Use static allocation if either 
     * FAAD_STATIC_ALLOC is set or XLR fits to IRAM. */
#if defined(FAAD_STATIC_ALLOC) || defined(HAVE_FAAD_XLR_IN_IRAM)
    p_XLR  = &s_XLR;
#else
    p_XLR  = (XLR_t*)faad_malloc(sizeof(XLR_t));
    if (p_XLR == NULL)
    {
        /* could not allocate memory */
        return NULL;
    }
#endif
    memset(p_XLR, 0, sizeof(XLR_t));

    /* save id of the parent element */
    sbr->id_aac = id_aac;
    sbr->sample_rate = sample_rate;

    sbr->bs_freq_scale = 2;
    sbr->bs_alter_scale = 1;
    sbr->bs_noise_bands = 2;
    sbr->bs_limiter_bands = 2;
    sbr->bs_limiter_gains = 2;
    sbr->bs_interpol_freq = 1;
    sbr->bs_smoothing_mode = 1;
    sbr->bs_start_freq = 5;
    sbr->bs_amp_res = 1;
    sbr->bs_samplerate_mode = 1;
    sbr->prevEnvIsShort[0] = -1;
    sbr->prevEnvIsShort[1] = -1;
    sbr->header_count = 0;
    sbr->Reset = 1;

#ifdef DRM
    sbr->Is_DRM_SBR = IsDRM;
#endif
    sbr->tHFGen = T_HFGEN;
    sbr->tHFAdj = T_HFADJ;

    sbr->bsco = 0;
    sbr->bsco_prev = 0;
    sbr->M_prev = 0;
    sbr->frame_len = framelength;

    /* force sbr reset */
    sbr->bs_start_freq_prev = -1;

    if (framelength == 960)
    {
        sbr->numTimeSlotsRate = RATE * NO_TIME_SLOTS_960;
        sbr->numTimeSlots = NO_TIME_SLOTS_960;
    } else {
        sbr->numTimeSlotsRate = RATE * NO_TIME_SLOTS;
        sbr->numTimeSlots = NO_TIME_SLOTS;
    }

    sbr->GQ_ringbuf_index[0] = 0;
    sbr->GQ_ringbuf_index[1] = 0;

    memset(sbr->qmfa, 0, 2*sizeof(qmfa_info));
    memset(sbr->qmfs, 0, 2*sizeof(qmfs_info));

    memset(sbr->Xsbr[0], 0, (sbr->numTimeSlotsRate+sbr->tHFGen)*64 * sizeof(qmf_t));
    memset(sbr->Xsbr[1], 0, (sbr->numTimeSlotsRate+sbr->tHFGen)*64 * sizeof(qmf_t));

    return sbr;
}
Exemplo n.º 29
0
static int F() { // function declaration
    Tdata_type ftype;

    switch (token.type) {
    case TT_INT:
    case TT_DOUBLE:
    case TT_STRING: // rule: type idf ( AL ) FD
        ftype = get_type();
        tmp_ftype = ftype;
        next();

        check(TT_ID);
        try(add_func(ftype, token.p_string));
        next();

        term(TT_L_BRACKET);
        call(AL);
        term(TT_R_BRACKET);
        return(FD);

    default:
        return ERR_PARSER;
    }
}

static int AL() { // first function argument
    switch (token.type) {
    case TT_INT:
    case TT_DOUBLE:
    case TT_STRING: // rule: AL -> AD AL2
        call(AD);
        return(AL2);

    default: // rule: AL -> eps
        return OK;
    }
}

static int AL2() { // remaining function arguments
    switch (token.type) {
    case TT_COMMA: // rule: AL2 -> , AD AL2
        next();
        call(AD);
        return(AL2);

    default: // rule: AL2 -> eps
        return OK;
    }
}

static int AD() { // argument
    Tdata_type atype;

    switch (token.type) {
    case TT_INT:
    case TT_DOUBLE:
    case TT_STRING: // rule: AD -> type id
        atype = get_type();
        next();

        check(TT_ID);
        try(add_param(atype, token.p_string));
        next();

        return OK;

    default:
        return ERR_PARSER;
    }
}

static int FD() { // function definition
    unsigned i;

    switch (token.type) {
    case TT_SEMICOLON: // rule: FD -> ;
        try(func_declaration());

        next();
        return OK;

    case TT_OPEN_BRACKET: // rule: FD -> { STL }
        i = get_line();
        try(func_definition(i)); // instruction pointer

        next();

        call(STL);

        term(TT_CLOSE_BRACKET);

        remove_block();
        generate(I_ERR, NULL, NULL, NULL); // no return => runtime error

        return OK;

    default:
        return ERR_PARSER;
    }
}

static int STL() { // stat list
    switch (token.type) {
    case TT_CLOSE_BRACKET: // rule: STL -> eps
        return OK;

    default: // rule: STL -> S STL
        call(S);
        return(STL);
    }
}

static int S() { // stat
    unsigned i;
    Tlocal_sym_tab_node *conv;

    switch (token.type) {
    case TT_AUTO:
    case TT_INT:
    case TT_DOUBLE:
    case TT_STRING: // rule: S -> D ;
        call(D);
        term(TT_SEMICOLON);
        return OK;

    case TT_OPEN_BRACKET: // rule: S -> { STL }
        next();

        try(add_block());

        call(STL);

        term(TT_CLOSE_BRACKET);

        remove_block();

        return OK;

    case TT_IF: // rule: S -> if ( E ) S else S
        next();
        term(TT_L_BRACKET);

        call(E);
        try(type_compare(tmp_psitem.type, TYPE_INT));

        if (tmp_psitem.type != TYPE_INT) {
            try(tmp_var(TYPE_INT, &conv));

            generate(I_CONVERT, tmp_psitem.value.ptr, NULL, conv);
        } else {
            conv = tmp_psitem.value.ptr;
        }

        Tlocal_sym_tab_node *label;
        try(tmp_var(TYPE_INT, &label));
        generate(I_JUMPIFN, conv, label, NULL);

        term(TT_R_BRACKET);
        call(S);

        Tlocal_sym_tab_node *endif;
        try(tmp_var(TYPE_INT, &endif));
        generate(I_JUMP, NULL, endif, NULL);

        i = get_line();
        set_var_value_int(label->name, i);

        call(ELSE);

        i = get_line();
        set_var_value_int(endif->name, i);

        return OK;

    case TT_FOR: // rule: S -> for ( D ; E ; E ) S
        try(add_block());

        next();
        term(TT_L_BRACKET);
        call(D);
        term(TT_SEMICOLON);

        Tlocal_sym_tab_node *cond;
        try(tmp_var(TYPE_INT, &cond));
        i = get_line();
        set_var_value_int(cond->name, i);

        call(E);
        try(type_compare(tmp_psitem.type, TYPE_INT));

        if (tmp_psitem.type != TYPE_INT) {
            try(tmp_var(TYPE_INT, &conv));

            generate(I_CONVERT, tmp_psitem.value.ptr, NULL, conv);
        } else {
            conv = tmp_psitem.value.ptr;
        }

        Tlocal_sym_tab_node *endfor;
        try(tmp_var(TYPE_INT, &endfor));
        generate(I_JUMPIFN, conv, endfor, NULL);

        Tlocal_sym_tab_node *statlist;
        try(tmp_var(TYPE_INT, &statlist));
        generate(I_JUMP, NULL, statlist, NULL);

        Tlocal_sym_tab_node *assign;
        try(tmp_var(TYPE_INT, &assign));
        i = get_line();
        set_var_value_int(assign->name, i);

        term(TT_SEMICOLON);
        call(E);

        generate(I_JUMP, NULL, cond, NULL);

        i = get_line();
        set_var_value_int(statlist->name, i);

        term(TT_R_BRACKET);
        call(S);

        generate(I_JUMP, NULL, assign, NULL);

        i = get_line();
        set_var_value_int(endfor->name, i);

        remove_block();

        return OK;

    case TT_WHILE: // rule: S -> while ( E ) S
        next();

        term(TT_L_BRACKET);

        Tlocal_sym_tab_node *wcond;
        try(tmp_var(TYPE_INT, &wcond));
        i = get_line();
        set_var_value_int(wcond->name, i);

        call(E);
        try(type_compare(tmp_psitem.type, TYPE_INT));

        if (tmp_psitem.type != TYPE_INT) {
            try(tmp_var(TYPE_INT, &conv));

            generate(I_CONVERT, tmp_psitem.value.ptr, NULL, conv);
        } else {
            conv = tmp_psitem.value.ptr;
        }

        Tlocal_sym_tab_node *endwhile;
        try(tmp_var(TYPE_INT, &endwhile));
        generate(I_JUMPIFN, conv, endwhile, NULL);

        term (TT_R_BRACKET);

        call(S);

        generate(I_JUMP, NULL, wcond, NULL);

        i = get_line();
        set_var_value_int(endwhile->name, i);

        return OK;

    case TT_DO: // rule: S -> do S while ( E ) ;
        next();

        Tlocal_sym_tab_node *dwbody;
        try(tmp_var(TYPE_INT, &dwbody));
        i = get_line();
        set_var_value_int(dwbody->name, i);

        call(S);

        term(TT_WHILE);

        term(TT_L_BRACKET);

        call(E);
        try(type_compare(tmp_psitem.type, TYPE_INT));

        if (tmp_psitem.type != TYPE_INT) {
            try(tmp_var(TYPE_INT, &conv));

            generate(I_CONVERT, tmp_psitem.value.ptr, NULL, conv);
        } else {
            conv = tmp_psitem.value.ptr;
        }

        generate(I_JUMPIF, conv, dwbody, NULL);

        term(TT_R_BRACKET);

        term(TT_SEMICOLON);

        return OK;

    case TT_RETURN: // rule: S -> return E ;
        next();

        call(E);
        try(type_compare(tmp_ftype, tmp_psitem.type));

        if (tmp_psitem.type != tmp_ftype) {
            try(tmp_var(tmp_ftype, &conv));

            generate(I_CONVERT, tmp_psitem.value.ptr, NULL, conv);
        } else {
            conv = tmp_psitem.value.ptr;
        }

        generate(I_RETURN, conv, NULL, NULL);

        term(TT_SEMICOLON);
        return OK;

    case TT_CIN: // rule: S -> cin >> id IN ;
        next();
        term(TT_IN);

        check(TT_ID);
        if (!var_exists(token.p_string))
            return ERR_UNDEF;
        Tlocal_sym_tab_node *var = get_var(token.p_string);

        generate(I_CIN, NULL, NULL, var);

        next();

        call(IN);
        term(TT_SEMICOLON);
        return OK;

    case TT_COUT: // rule: S -> cout << E OUT ;
        next();
        term(TT_OUT);

        call(E);

        generate(I_COUT, tmp_psitem.value.ptr, NULL, NULL);

        call(OUT);
        term(TT_SEMICOLON);
        return OK;

    default: // rule: S -> E ;
        call(E);
        term(TT_SEMICOLON);
        return OK;
    }
}

static int D() { // variable declaration
    Tdata_type vtype;

    switch (token.type) {
    case TT_AUTO:
    case TT_INT:
    case TT_DOUBLE:
    case TT_STRING: // rule: D -> type id I
        vtype = get_type();
        tmp_type = vtype;
        next();

        check(TT_ID);
        try(add_var(vtype, token.p_string));
        try(tmpstr(token.p_string));
        next();

        return(I);

    default:
        return ERR_PARSER;
    }
}

static int I() { // variable definition
    switch (token.type) {
    case TT_ASSIGN: // rule: I -> = E
        next();
        call(E);

        try(assign_type_compare(tmp_buffer.str, tmp_psitem.type));

        Tlocal_sym_tab_node *var = get_var(tmp_buffer.str);
        Tlocal_sym_tab_node *conv;

        if (tmp_psitem.type != var->data_type) {
            try(tmp_var(var->data_type, &conv));

            generate(I_CONVERT, tmp_psitem.value.ptr, NULL, conv);
        } else {
            conv = tmp_psitem.value.ptr;
        }

        generate(I_ASSIGN, conv, NULL, var);

        return OK;

    default: // rule: I -> eps
        if (tmp_type == TYPE_AUTO)
            return ERR_AUTO;
        return OK;
    }
}

static int ELSE() { // else
    switch (token.type) {
    case TT_ELSE: // rule: ELSE -> else S
        next();

        return(S);

    default: // rule: ELSE -> eps
        return OK;
    }
}

static int IN() { // input variables
    switch (token.type) {
    case TT_IN: // rule: IN -> >> id IN
        next();

        check(TT_ID);
        if (!var_exists(token.p_string))
            return ERR_UNDEF;
        Tlocal_sym_tab_node *var = get_var(token.p_string);

        generate(I_CIN, NULL, NULL, var);

        next();

        return(IN);

    default: // rule: IN -> eps
        return OK;
    }
}

static int OUT() { // output expressions
    switch (token.type) {
    case TT_OUT: // rule: OUT -> << E OUT
        next();
        call(E);

        generate(I_COUT, tmp_psitem.value.ptr, NULL, NULL);

        return(OUT);

    default: // rule: OUT -> eps
        return OK;
    }
}

static int E() { // expression
    Tpsa_stack *psa_stack = ps_init();

    ps_push(psa_stack, OP_END);

    if (get_prec(OP_END) == ' ') {
        fprintf(stderr, "Syntax error: 'expression' expected, but '%s' given.\n", token_[token.type]);

        return ERR_PARSER;
    }

    int err;

    do {
        Tps_item *ps_item = ps_first_term(psa_stack);
        switch (get_prec(ps_item->op)) {
        case '=':
            err = ps_push_token(psa_stack);
            if (err != OK) {
                ps_destroy(psa_stack);
                return err;
            }
            next();
            break;

        case '<':
            err = ps_ins_after(psa_stack, ps_item, OP_EXPR);
            if (err != OK) {
                ps_destroy(psa_stack);
                return err;
            }

            err = ps_push_token(psa_stack);
            if (err != OK) {
                ps_destroy(psa_stack);
                return err;
            }

            next();
            break;

        case '>':
            err = psa(psa_stack);
            if (err != OK) {
                ps_destroy(psa_stack);
                return err;
            }
            break;
        }
    } while (get_prec(ps_first_term(psa_stack)->op) != ' ');

    Tps_item *top = ps_top(psa_stack);

    if (top->op != OP_NTERM || ps_prev(psa_stack)->op != OP_END) {
        fprintf(stderr, "Syntax error: unexpected '%s'\n", token_[token.type]);
        return ERR_PARSER;
    }

    tmp_psitem.type = top->type;
    tmp_psitem.value = top->value;

    ps_destroy(psa_stack);

    return OK;
}

int parse() {
    next();

    strInit(&tmp_buffer);

    int err = P();

    strFree(&tmp_buffer);

    return err;
}