Example #1
0
AudioSink::AudioSink(long const srate, int const latency, int const periods)
: rbuf_(nearestPowerOf2(srate * latency / ((periods + 1) * 1000)) * periods * 2)
, rateEst_(srate, rbuf_.size() / periods)
, mut_(SDL_CreateMutex())
, bufReadyCond_(SDL_CreateCond())
, failed_(openAudio(srate, rbuf_.size() / 2 / periods, fillBuffer, this) < 0)
{
	rbuf_.fill(0);
}
Example #2
0
void
SDL_sound_handler::unpause() 
{
    if (hasInputStreams()) {
        openAudio();
        SDL_PauseAudio(0);
    }

    sound_handler::unpause();
}
Example #3
0
void
SDL_sound_handler::initAudio()
{
    // NOTE: we open and close the audio card for the sole purpose
    //       of throwing an exception on error (unavailable audio
    //       card). Normally we'd want to open the audio card only
    //       when needed (it has a cost in number of wakeups).
    //
    openAudio();
    closeAudio();

}
/** Initialise the device */
int sa_stream_open(sa_stream_t *s) {  
  int status = SA_SUCCESS;

  ERROR_IF_NO_INIT(s);

  switch (s->rwMode) {
    case SA_MODE_WRONLY: 
      status = openAudio(s);
      break;
	default:
      status = SA_ERROR_NOT_SUPPORTED;      
      break;
  }    
  return status;
}
Example #5
0
void
SDL_sound_handler::plugInputStream(std::auto_ptr<InputStream> newStreamer)
{
    boost::mutex::scoped_lock lock(_mutex);

    sound_handler::plugInputStream(newStreamer);

    { // TODO: this whole block should only be executed when adding
      // the first stream. 

#ifdef GNASH_DEBUG_SDL_AUDIO_PAUSING
        log_debug("Unpausing SDL Audio on inpust stream plug...");
#endif
        openAudio(); // lazy sound card initialization
        SDL_PauseAudio(0); // start polling data from us 
    }
}
Example #6
0
void
Mkit_sound_handler::plugInputStream(std::auto_ptr<InputStream> newStreamer)
{
    boost::mutex::scoped_lock lock(_mutex);

    sound_handler::plugInputStream(newStreamer);

    { // TODO: this whole block should only be executed when adding
      // the first stream.

#ifdef GNASH_DEBUG_Mkit_AUDIO_PAUSING
        log_debug("Unpausing Mkit Audio on inpust stream plug...");
#endif
        openAudio();
        sound_handler::unpause();

    }
}
Example #7
0
void
SDL_sound_handler::initAudio()
{
    // NOTE: we open and close the audio card for the sole purpose
    //       of throwing an exception on error (unavailable audio
    //       card). Normally we'd want to open the audio card only
    //       when needed (it has a cost in number of wakeups).
    openAudio();

#ifdef WIN32
    // SDL can hang on windows if SDL_CloseAudio() is called immediately
    // after SDL_OpenAudio(). It's evidently to do with threading, but
    // internal to SDL. This is a tacky solution, but it's only windows.
    gnashSleep(1);
#endif

    closeAudio();

}
int ONScripter::playAVI( const char *filename, bool click_flag )
{
    unsigned long length = script_h.cBR->getFileLength( filename );
    if (length == 0){
        fprintf( stderr, " *** can't find file [%s] ***\n", filename );
        return 0;
    }

#ifdef ANDROID
    playVideoAndroid(filename);
    return 0;
#endif

#if defined(USE_AVIFILE) && !defined(USE_SDL_RENDERER)
    char *absolute_filename = new char[ strlen(archive_path) + strlen(filename) + 1 ];
    sprintf( absolute_filename, "%s%s", archive_path, filename );
    for ( unsigned int i=0 ; i<strlen( absolute_filename ) ; i++ )
        if ( absolute_filename[i] == '/' ||
             absolute_filename[i] == '\\' )
            absolute_filename[i] = DELIMITER;

    if ( audio_open_flag ) Mix_CloseAudio();

    AVIWrapper *avi = new AVIWrapper();
    if ( avi->init( absolute_filename, false ) == 0 &&
         avi->initAV( screen_surface, audio_open_flag ) == 0 ){
        if (avi->play( click_flag )) return 1;
    }
    delete avi;
    delete[] absolute_filename;

    if ( audio_open_flag ){
        Mix_CloseAudio();
        openAudio();
    }
#else
    fprintf( stderr, "avi command is disabled.\n" );
#endif

    return 0;
}
Example #9
0
/* AudioEntryPanel::open
 * Opens the current entry and performs the appropriate conversions
 *******************************************************************/
bool AudioEntryPanel::open()
{
	// Check if already opened
	if (opened)
		return true;

	// Stop if sound currently playing
	resetStream();

	subsong = 0;
	num_tracks = 1;

	// Get entry data
	MemChunk& mcdata = entry->getMCData();

	// Setup temp filename
	wxFileName path(appPath(entry->getName(), DIR_TEMP));
	// Add extension if missing
	if (path.GetExt().IsEmpty())
		path.SetExt(entry->getType()->getExtension());

	// Convert if necessary, then write to file
	MemChunk convdata;
	if (entry->getType()->getFormat() == "snd_doom" ||			// Doom Sound -> WAV
	        entry->getType()->getFormat() == "snd_doom_mac")
		Conversions::doomSndToWav(mcdata, convdata);
	else if (entry->getType()->getFormat() == "snd_speaker")	// Doom PC Speaker Sound -> WAV
		Conversions::spkSndToWav(mcdata, convdata);
	else if (entry->getType()->getFormat() == "snd_audiot")		// AudioT PC Speaker Sound -> WAV
		Conversions::spkSndToWav(mcdata, convdata, true);
	else if (entry->getType()->getFormat() == "snd_wolf")		// Wolfenstein 3D Sound -> WAV
		Conversions::wolfSndToWav(mcdata, convdata);
	else if (entry->getType()->getFormat() == "snd_voc")		// Creative Voice File -> WAV
		Conversions::vocToWav(mcdata, convdata);
	else if (entry->getType()->getFormat() == "snd_jaguar")		// Jaguar Doom Sound -> WAV
		Conversions::jagSndToWav(mcdata, convdata);
	else if (entry->getType()->getFormat() == "snd_bloodsfx")	// Blood Sound -> WAV
		Conversions::bloodToWav(entry, convdata);
	else if (entry->getType()->getFormat() == "midi_mus")  			// MUS -> MIDI
	{
		Conversions::musToMidi(mcdata, convdata);
		path.SetExt("mid");
	}
	else if (entry->getType()->getFormat() == "midi_xmi" ||  		// HMI/HMP/XMI -> MIDI
			 entry->getType()->getFormat() == "midi_hmi" || entry->getType()->getFormat() == "midi_hmp")
	{
		Conversions::zmusToMidi(mcdata, convdata, 0, &num_tracks);
		path.SetExt("mid");
	}
	else if (entry->getType()->getFormat() == "midi_gmid")  		// GMID -> MIDI
	{
		Conversions::gmidToMidi(mcdata, convdata);
		path.SetExt("mid");
	}
	else
		convdata.importMem(mcdata.getData(), mcdata.getSize());

	// MIDI format
	if (entry->getType()->getFormat().StartsWith("midi_"))
	{
		audio_type = AUTYPE_MIDI;
		openMidi(convdata, path.GetFullPath());
	}

	// MOD format
	else if (entry->getType()->getFormat().StartsWith("mod_"))
		openMod(convdata);

	// Other format
	else
		openAudio(convdata, path.GetFullPath());

	// Keep filename so we can delete it later
	prevfile = path.GetFullPath();

	txt_title->SetLabel(entry->getPath(true));
	txt_track->SetLabel(S_FMT("%d/%d", subsong+1, num_tracks));
	updateInfo();

	// Disable prev/next track buttons if only one track is available
	if (num_tracks < 2)
	{
		btn_prev->Disable();
		btn_next->Disable();
	}

	opened = true;
	return true;
}
Example #10
0
void InitSDLAudio()
{
   SDL_Init(SDL_INIT_AUDIO);
   openAudio();
}
int estimateChannelMean()
{
  int result;
  int retval = 0;  /***** return value */

  int width = 45, height = 11, i, j;               /***** ncurses related variables */
  WINDOW *channelscr = popupWindow (width, height);

  wattrset (channelscr, color_term ? COLOR_PAIR(2) | A_BOLD : A_NORMAL); /***** set bg color of the dialog */

  /*****
   * draw a box around the dialog window
   * and empty it.
   *****/
  werase (channelscr);
  box (channelscr, 0, 0);
  for (i = 1; i < width-1; i++)
    for (j = 1; j < height-1; j++)
      mvwaddch(channelscr, j, i, ' ');

  /***** dialog header */

  mvwaddstr(channelscr, 1, 2, "Estimating Channel Characteristics:");
  mvwaddseparator(channelscr, 2, width);

  /***** dialog message */

  mvwaddstr(channelscr, 4, 2, "I'll calculate the characteristics of");
  mvwaddstr(channelscr, 5, 2, "the recording channel now. Please remain");
  mvwaddstr(channelscr, 6, 2, "silent until I say I'm done:");
  mvwaddstrcntr(channelscr, 8, width, "Press any key to start ...");
  wmove(channelscr, 1, 38);  /***** set cursor to an appropriate location */
  wrefresh (channelscr);     /***** refresh the dialog */
  getch();                  /***** wait for keyboard reaction */

  /***** clear dialog */

  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(channelscr, j, i, ' ');

  /***** update dialog */

  mvwaddstrcntr(channelscr, 5, width, "stand by ...");
  wmove(channelscr, 1, 38);  /***** set cursor to an appropriate location */
  wrefresh (channelscr);     /***** refresh the dialog */

  if (openAudio() == AUDIO_ERR)
  {
    /*****
     * if the audio device could not be opened,
     * show a warning dialog and return to main menu
     *****/

    /***** clear dialog */

    for (i = 1; i < width-1; i++)
      mvwaddch(channelscr, 1, i, ' ');
    for (i = 1; i < width-1; i++)
      for (j = 3; j < height-1; j++)
	mvwaddch(channelscr, j, i, ' ');

    /***** show header and message */

    mvwaddstr(channelscr, 1, 2, "Warning!");

    mvwaddstr(channelscr, 5, 2, "Failed to open sound device!!");
    mvwaddstrcntr(channelscr, 8, width, "Press any key to return to menu ...");
    wmove(channelscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (channelscr);     /***** refresh the dialog */
    getch();                   /***** wait for keyboard reaction */

    retval = 0;                /***** set return value to ERROR */
    goto estimateChannelMeanReturn;
  }

  result = calculateChannelMean(); /***** calculate the characteristics of the recording channel */

  closeAudio(); /***** disconnect from the microphone */

  /***** clear dialog */

  for (i = 1; i < width-1; i++)
    mvwaddch(channelscr, 1, i, ' ');
  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(channelscr, j, i, ' ');

  if (result == AUDIO_ERR)
  {
    /***** if an error occurred during the calculation of the channel mean ... */

    retval = 0; /***** set return value to ERROR */

    /***** dialog header and message */

    mvwaddstr(channelscr, 1, 2, "Error!");

    mvwaddstr(channelscr, 3, 2, "I didn't manage to estimate the channel");
    mvwaddstr(channelscr, 4, 2, "characteristics for some unknown reason!");
    mvwaddstr(channelscr, 5, 2, "Make sure that no application uses the");
    mvwaddstr(channelscr, 6, 2, "sound card and then try again!");
    mvwaddstrcntr(channelscr, 8, width, "Press any key to return to menu ...");

    wmove(channelscr, 1, 9);  /***** set cursor to an appropriate location */
    wrefresh (channelscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */
  }
  else /***** channel mean calculation was ok */
  {
    retval = 1; /***** set return value to ok */

    /***** dialog header and message */

    mvwaddstr(channelscr, 1, 2, "Success!");

    mvwaddstr(channelscr, 4, 2, "You may stop talking now! The channel");
    mvwaddstr(channelscr, 5, 2, "characteristics have been estimated!");
    mvwaddstrcntr(channelscr, 8, width, "Press any key to return to menu ...");

    wmove(channelscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (channelscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */
  }

 estimateChannelMeanReturn:
  delwin(channelscr);   /***** delete ncurses dialog window */
  return(retval);
}
int calculateThresholds()
{
  int samples;
  int max = 0, value;
  int silence_level_tmp; /***** need int (instead of short) to sum up several values */
  int silence_max;

  int retval = 0;  /***** return value */

  int width = 45, height = 11, i, j;               /***** ncurses related variables */
  WINDOW *threshscr = popupWindow (width, height);

  /*****
   * first step: define silence level
   *****/

  wattrset (threshscr, color_term ? COLOR_PAIR(2) | A_BOLD : A_NORMAL); /***** set bg color of the dialog */

  /*****
   * draw a box around the dialog window
   * and empty it.
   *****/
  werase (threshscr);
  box (threshscr, 0, 0);
  for (i = 1; i < width-1; i++)
    for (j = 1; j < height-1; j++)
      mvwaddch(threshscr, j, i, ' ');

  /***** dialog header */

  mvwaddstr(threshscr, 1, 2, "Calculate Thresholds:");
  mvwaddseparator(threshscr, 2, width);

  /***** dialog message */

  mvwaddstr(threshscr, 3, 2, "I'll calculate some values now. First,");
  mvwaddstr(threshscr, 4, 2, "I need to know the silence level of the");
  mvwaddstr(threshscr, 5, 2, "microphone. Please be silent until I");
  mvwaddstr(threshscr, 6, 2, "say I'm done:");
  mvwaddstrcntr(threshscr, 8, width, "Press any key to start ...");

  wmove(threshscr, 1, 24);  /***** set cursor to an appropriate location */
  wrefresh (threshscr);     /***** refresh the dialog */
  getch();                  /***** wait for keyboard reaction */

  /***** clear dialog window */

  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(threshscr, j, i, ' ');

  mvwaddstrcntr(threshscr, 5, width, "stand by ..."); /***** update dialog */
  wmove(threshscr, 1, 24);  /***** set cursor to an appropriate location */
  wrefresh (threshscr);     /***** refresh the dialog */

  if (openAudio() == AUDIO_ERR)
  {
    /*****
     * if the audio device could not be opened,
     * show a warning dialog and return to main menu
     *****/

    /***** clear dialog */

    for (i = 1; i < width-1; i++)
      mvwaddch(threshscr, 1, i, ' ');
    for (i = 1; i < width-1; i++)
      for (j = 3; j < height-1; j++)
	mvwaddch(threshscr, j, i, ' ');

    /***** show header and message */

    mvwaddstr(threshscr, 1, 2, "Warning!");

    mvwaddstr(threshscr, 5, 2, "Failed to open sound device!!");
    mvwaddstrcntr(threshscr, 8, width, "Press any key to return to menu ...");
    wmove(threshscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (threshscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */

    retval = 0;               /***** set return value to ERROR */
    goto calculateThresholdsReturn;
  }

  /*****
   * define the silence_level as the average of a specified number
   * of subsequent block maxima
   *****/
  samples           = 40;
  silence_level_tmp = 0;
  silence_max   = 0;
  for (i = 0; i < samples; i++)
  {
    int value = getBlockMax(); /***** should check for value == -1 (case of an error!) */
      silence_level_tmp += value;
    if (value > silence_max)
      silence_max = value;
  }
  silence_level_tmp /= samples;
  silence_level = silence_level_tmp;

  /***** rec_level and stop_level */

  /***** clear dialog */

  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(threshscr, j, i, ' ');

  /***** update dialog */

  mvwaddstr(threshscr, 3, 2, "Now, I'll define the thresholds at which");
  mvwaddstr(threshscr, 4, 2, "to start/stop recording. Please talk");
  mvwaddstr(threshscr, 5, 2, "at a conversational volume (speech");
  mvwaddstr(threshscr, 6, 2, "recognition volume) until I say stop!");
  mvwaddstrcntr(threshscr, 8, width, "Press any key to start ...");

  wmove(threshscr, 1, 24);  /***** set cursor to an appropriate location */
  wrefresh (threshscr);     /***** refresh the dialog */
  getch();                  /***** wait for keyboard reaction */

  /***** clear dialog */

  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(threshscr, j, i, ' ');

  mvwaddstrcntr(threshscr, 5, width, "keep on talking ..."); /***** update dialog */
  wmove(threshscr, 1, 24);  /***** set cursor to an appropriate location */
  wrefresh (threshscr);     /***** refresh the dialog */

  /***** get maximum value 'max' of a prespecified number of subsequent block maxima */

  samples = 80;
  for (i = 0; i < samples; i++)
  {
    value = getBlockMax(); /***** should check for value == -1 (case of an error!) */
    if (value > max)
      max = value;
  }

  /***** set the rec_level  to be the average of silence_level and 'max' */
  /***** set the stop_level to be three quarters of silence_level plus one quarter of 'max' */

  rec_level =  (silence_level + max) / 2;
  stop_level = (3*silence_level + max) / 4;

  closeAudio(); /***** disconnect from microphone */

  /***** clear dialog */

  for (i = 1; i < width-1; i++)
    mvwaddch(threshscr, 1, i, ' ');
  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(threshscr, j, i, ' ');

  /***** check that the thresholds are reasonable */

  if (silence_level >= stop_level ||
      silence_max >= stop_level    ||
      silence_level < 0 || stop_level < 0 || rec_level < 0)
  {
    /***** dialog header */

    mvwaddstr(threshscr, 1, 2, "Warning!");

    /***** dialog message */

    mvwaddstr(threshscr, 4, 2, "You have to run this step once again!");
    mvwaddstr(threshscr, 5, 2, "The calculated thresholds don't look");
    mvwaddstr(threshscr, 6, 2, "reasonable to me!");
    mvwaddstrcntr(threshscr, 8, width, "Press any key to return to menu ...");
    wmove(threshscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (threshscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */

    retval = 0;
  }
  else /***** the values seem ok */
  {
    /***** dialog header */

    mvwaddstr(threshscr, 1, 2, "Success!");

    /***** dialog message */

    mvwaddstr(threshscr, 4, 2, "You may stop talking now! The thresholds");
    mvwaddstr(threshscr, 5, 2, "have been defined!");

    /* Debugging stuff:
       mvwaddint(threshscr, 6, 2, silence_level);
       mvwaddint(threshscr, 6,10, stop_level);
       mvwaddint(threshscr, 6,20, rec_level);
       */
    
    mvwaddstrcntr(threshscr, 8, width, "Press any key to return to menu ...");

    wmove(threshscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (threshscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */

    retval = 1; /***** set return value = ok */
  }

 calculateThresholdsReturn:
  delwin(threshscr);   /***** delete ncurses dialog window */
  return(retval);
}
int adjustMixerLevels()
{
  int mic_level    = 99; /***** initial values for Microphone and */

  int igain_level  = 0;  /***** Input Gain level */
  
  int max_sample   = 32500; /***** max 16-bit sample value coming from the sound card */

  int count;           /**** temporary variables */
  int max_gain;
  char tmp_string[10];

  int width = 45, height = 11, i, j;               /***** ncurses related variables */
  WINDOW *adjustscr = popupWindow (width, height);

  int retval = 0;  /***** return value */

  /* ***** display information */

  wattrset (adjustscr, color_term ? COLOR_PAIR(2) | A_BOLD : A_NORMAL); /***** set bg color of the dialog */

  /*****
   * draw a box around the dialog window
   * and empty it.
   *****/
  werase (adjustscr);
  box (adjustscr, 0, 0);
  for (i = 1; i < width-1; i++)
    for (j = 1; j < height-1; j++)
      mvwaddch(adjustscr, j, i, ' ');

  setMicLevel(mic_level);

  if (mixerHasIGain() == MIXER_OK)
  {
    igain_level = 1;
    setIGainLevel(igain_level); /***** set initial levels in mixer */
  }
  else
    goto no_igain;

  /***** dialog header */

  mvwaddstr(adjustscr, 1, 2, "Adjust Input Gain Level:");
  mvwaddseparator(adjustscr, 2, width);

  /***** dialog message */

  mvwaddstr(adjustscr, 3, 2, "Please grab your microphone and speak");
  mvwaddstr(adjustscr, 4, 2, "nonsense at a conversational volume");
  mvwaddstr(adjustscr, 5, 2, "(speech recognition volume) until I");
  mvwaddstr(adjustscr, 6, 2, "say stop:");
  mvwaddstrcntr(adjustscr, 8, width, "Press any key to start ...");

  wmove(adjustscr, 1, 27);  /***** set cursor to an appropriate location */
  wrefresh (adjustscr);     /***** refresh the dialog */
  getch();                  /***** wait for keyboard reaction */

  /***** update dialog */

  mvwaddstr(adjustscr, 8, 2, "Current Gain Level:               ");
  sprintf(tmp_string, "%d", igain_level);
  mvwaddstr(adjustscr, 8, 22, tmp_string);

  wmove(adjustscr, 1, 27);  /***** set cursor to an appropriate location */
  wrefresh (adjustscr);     /***** refresh the dialog */

  count    = 0;
  max_gain = 0;

  if (openAudio() == AUDIO_ERR)
  {
    /*****
     * if the audio device could not be opened,
     * show a warning dialog and return to main menu
     *****/

    /***** empty dialog */

    for (i = 1; i < width-1; i++)
      mvwaddch(adjustscr, 1, i, ' ');
    for (i = 1; i < width-1; i++)
      for (j = 3; j < height-1; j++)
	mvwaddch(adjustscr, j, i, ' ');

    /***** show header and message */

    mvwaddstr(adjustscr, 1, 2, "Warning!");

    mvwaddstr(adjustscr, 5, 2, "Failed to open sound device!!");
    mvwaddstrcntr(adjustscr, 8, width, "Press any key to return to menu ...");
    wmove(adjustscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (adjustscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */

    retval = 0;               /***** set return value to ERROR */
    goto adjustMixerLevelsReturn;
  }

  /***** repeat until the input gain level has been adjusted properly */

  while (1)
  {
    int max;          /***** maximum sample value in a sequence of audio samples */
    int samples = 10; /***** number of blocks to get from the audio device */

    count++;

    /*****
     * get the maximum values of 'samples' blocks of data from the sound card
     * the maximum of these values is stored in 'max'9
     *****/
    max = 0;
    for (i = 0; i < samples; i++)
    {
      int value = getBlockMax(); /***** should check for value == -1 (case of an error!) */
      if (value > max)
	max = value;
    }

    /***** max_gain holds the highest maximum sample found */

    if (max > max_gain)
      max_gain = max;

    if (count == 5) /***** after five iterations, check the value of 'max_gain' */
    {
      /*****
       * if max_gain is too low (i.e. it is between silence and low_volume)
       * the input gain level is increased
       *****/
      if (max_gain >= silence * max_sample && max_gain < low_volume * max_sample)
      {
	igain_level++;
	if (igain_level > 99)
	  igain_level = 99;
	setIGainLevel(igain_level);

	sprintf(tmp_string, "%d", igain_level); /***** update display of igain level */
	mvwaddstr(adjustscr, 8, 22, tmp_string);

	wmove(adjustscr, 1, 27);  /***** set cursor to an appropriate location */
	wrefresh (adjustscr);     /***** refresh the dialog */
      }
      /*****
       * if the level is above 'low_volume'
       * we assume that the input gain is high enough and break the current while loop
       *****/
      else if (max_gain >= low_volume * max_sample)
	break;

      /***** reset count and max_gain */

      count    = 0;
      max_gain = 0;
    }
  }
  closeAudio(); /***** disconnect from microphone */

  /***** update dialog window */

  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(adjustscr, j, i, ' ');
  mvwaddstrcntr(adjustscr, 5, width, "STOP!!");
  mvwaddstrcntr(adjustscr, 8, width, "Press any key to continue ...");

  wmove(adjustscr, 1, 27);  /***** set cursor to an appropriate location */
  wrefresh (adjustscr);     /***** refresh the dialog */
  getch();                  /***** wait for keyboard reaction */

 no_igain:
  
  count = 0; /***** reset count */

  /***** adjusting microphone level */

  /***** dialog header */

  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(adjustscr, j, i, ' ');
  mvwaddstr(adjustscr, 1, 2, "Adjust Microphone Level:");

  /***** dialog message */

  mvwaddstr(adjustscr, 3, 2, "Please grab your microphone and speak");
  mvwaddstr(adjustscr, 4, 2, "very loudly (laughing loudly is good)");
  mvwaddstr(adjustscr, 5, 2, "until I say stop:");
  mvwaddstrcntr(adjustscr, 8, width, "Press any key to start ...");

  wmove(adjustscr, 1, 27);  /***** set cursor to an appropriate location */
  wrefresh (adjustscr);     /***** refresh the dialog */
  getch();                  /***** wait for keyboard reaction */

  /***** update dialog */

  mvwaddstr(adjustscr, 8, 2, "Current Microphone Level:               ");
  sprintf(tmp_string, "%d", mic_level);
  mvwaddstr(adjustscr, 8, 28, tmp_string);

  wmove(adjustscr, 1, 27);  /***** set cursor to an appropriate location */
  wrefresh (adjustscr);     /***** refresh the dialog */

  if (openAudio() == AUDIO_ERR)
  {
    /*****
     * if the audio device could not be opened,
     * show a warning dialog and return to main menu
     *****/

    /***** empty dialog */

    for (i = 1; i < width-1; i++)
      mvwaddch(adjustscr, 1, i, ' ');
    for (i = 1; i < width-1; i++)
      for (j = 3; j < height-1; j++)
	mvwaddch(adjustscr, j, i, ' ');

    /***** show header and message */

    mvwaddstr(adjustscr, 1, 2, "Warning!");

    mvwaddstr(adjustscr, 5, 2, "Failed to open sound device!!");
    mvwaddstrcntr(adjustscr, 8, width, "Press any key to return to menu ...");
    wmove(adjustscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (adjustscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */

    retval = 0;               /***** set return value to ERROR */
    goto adjustMixerLevelsReturn;
  }

  /***** repeat until the microphone level has been adjusted properly */

  while (1)
  {
    int max;         /***** maximum sample value in a sequence of audio samples */
    int samples = 4; /***** number of blocks to get from the audio device */

    /*****
     * get the maximum values of 'samples' blocks of data from the sound card
     * the maximum of these values is stored in 'max'9
     *****/
    max = 0;
    for (i = 0; i < samples; i++)
    {
      int value = getBlockMax(); /***** should check for value == -1 (case of an error!) */
      if (value > max)
	max = value;
    }

    if (max >= high_volume * max_sample)
    {
      /*****
       * if max is too high (i.e. above high_volume)
       * the microphone level is dereased
       *****/
      mic_level -= 1;
      if (mic_level < 5)
	mic_level = 5;
      setMicLevel(mic_level);

      count = 0; /***** reset count */

      sprintf(tmp_string, "%d", mic_level); /***** update display of mic level */
      mvwaddstr(adjustscr, 8, 28, tmp_string);

      wmove(adjustscr, 1, 27);  /***** set cursor to an appropriate location */
      wrefresh (adjustscr);     /***** refresh the dialog */
    }
    else if (max >= silence * max_sample)
    {
      /*****
       * if there is a signal above silence coming in,
       * increase count
       * if count >= a specified constant, we assume that
       * the microphone level is not too high any more and
       * thus, break the while loop
       ****/
      count++;

      if (count >= 20)
	break;
    }
    else
    {
      /*****
       * this was a silence frame, decrease count if it is > 0
       *****/
      if (count > 0)
	count--;
    }
  }
  closeAudio(); /***** disconnect from microphone */

  /***** clear dialog window */

  for (i = 1; i < width-1; i++)
    mvwaddch(adjustscr, 1, i, ' ');
  for (i = 1; i < width-1; i++)
    for (j = 3; j < height-1; j++)
      mvwaddch(adjustscr, j, i, ' ');

  /***** check the mixer values, to make sure they look reasonable */

  if (igain_level >= mic_level ||
      mic_level < MIN_REASONABLE_MIC_LEVEL ||
      igain_level > MAX_REASONABLE_IGAIN_LEVEL)
  {
    int pos = 0;

    /***** dialog header */

    mvwaddstr(adjustscr, 1, 2, "Warning!");

    /***** dialog message */

    mvwaddstr(adjustscr, 3, 2, "You have to run this step once again!");
    mvwaddstr(adjustscr, 4, 2, "The estimated level results don't look");
    mvwaddstr(adjustscr, 5, 2, "reasonable to me!");
    if (igain_level >= mic_level || igain_level > MAX_REASONABLE_IGAIN_LEVEL)
      mvwaddstr(adjustscr, 6+(pos++), 2, "- Input gain level looks too high!");
    if (igain_level >= mic_level || mic_level < MIN_REASONABLE_MIC_LEVEL)
      mvwaddstr(adjustscr, 6+(pos++), 2, "- Microphone level looks too low?!");
    mvwaddstrcntr(adjustscr, 8, width, "Press any key to return to menu ...");

    wmove(adjustscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (adjustscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */

    retval = 0;
  }
  else /***** the mixer values seem ok */
  {
    /***** dialog header */

    mvwaddstr(adjustscr, 1, 2, "Success!");

    /***** dialog message */

    mvwaddstrcntr(adjustscr, 4, width, "The mixer levels have been");
    mvwaddstrcntr(adjustscr, 5, width, "adjusted successfully!");
    mvwaddstrcntr(adjustscr, 8, width, "Press any key to return to menu ...");

    wmove(adjustscr, 1, 11);  /***** set cursor to an appropriate location */
    wrefresh (adjustscr);     /***** refresh the dialog */
    getch();                  /***** wait for keyboard reaction */

    retval = 1; /***** set return value = ok */
  }

 adjustMixerLevelsReturn:
  delwin(adjustscr);   /***** delete ncurses dialog window */
  return(retval);
}
Example #14
0
// setup libAV related structs.
bool AV::setupAV() {

	ct.of = av_guess_format(NULL, "roxlu.flv", NULL);
	if(!ct.of) {
		printf("Cannot create flv AVOutputFormat\n");
		return false;
	}
	
	ct.c = avformat_alloc_context();
	if(!ct.c) {
		printf("Cannot allocate the AVFormatContext\n");
		return false;
	}
	ct.c->video_codec_id = CODEC_ID_H264;
	ct.c->debug = 3;
	ct.c->oformat = ct.of;

//	const char* output_filename = "tcp://127.0.0.1:6665";
//	const char* output_filename = "rtmp://gethinlewis.rtmphost.com";
	const char* output_filename = "rtmp://gethinlewis.rtmphost.com/event/_definst_";
//	const char* output_filename = "test.flv";
	snprintf(ct.c->filename, sizeof(ct.c->filename), "%s", output_filename);
	//ct.vs = addVideoStream(ct, ct.of->video_codec);

	printf("%d -- %d \n", CODEC_ID_H264, ct.of->video_codec);
	ct.of->video_codec = CODEC_ID_H264;
	ct.vs = addVideoStream(ct, ct.of->video_codec);
	if(!ct.vs) {
		printf("Cannot create video stream: %d.\n", ct.of->video_codec);
		return false;
	}
	
	if(!openVideo(ct)) {
		printf("Cannot open video stream.\n");
		return false;
	}
	
	//av_dict_set(&ct.c->metadata, "streamName", "video_test", 0);
	av_dict_set(&ct.c->metadata, "streamName", "livefeed", 0);
	
	if(use_audio) {
		bool use_mp3 = true;
		if(!use_mp3) {
			ct.asample_fmt = AV_SAMPLE_FMT_S16;
			ct.abit_rate = 64000;
			ct.asample_rate = 8000;
			ct.as = addAudioStream(ct, CODEC_ID_SPEEX);
		}
		else {
			ct.asample_fmt = AV_SAMPLE_FMT_S16;
			ct.abit_rate = 64000;
			ct.asample_rate = 44100;
			ct.as = addAudioStream(ct, CODEC_ID_MP3);
		}
		
		if(!ct.as) {
			printf("Cannot create audio stream.\n");
			return false;
		}
		
		if(!openAudio(ct)) {
			printf("Cannot open audio stream.\n");
			return false;
		}
	}
	
	av_dump_format(ct.c, 0, output_filename, 1);
	
	if(!(ct.of->flags & AVFMT_NOFILE)) {
		if(avio_open(&ct.c->pb, output_filename, AVIO_FLAG_WRITE) < 0) {
			printf("Cannot open: %s\n", output_filename);
			return false;
		}
	}
	avformat_write_header(ct.c, NULL);
	
	return true;
}
Example #15
0
int EncoderFfmpegCore::initEncoder(int bitrate, int samplerate) {

#ifndef avformat_alloc_output_context2
    qDebug() << "EncoderFfmpegCore::initEncoder: Old Style initialization";
    m_pEncodeFormatCtx = avformat_alloc_context();
#endif

    m_lBitrate = bitrate * 1000;
    m_lSampleRate = samplerate;

#if LIBAVCODEC_VERSION_INT > 3544932
    if (m_SCcodecId == AV_CODEC_ID_MP3) {
#else
    if (m_SCcodecId == CODEC_ID_MP3) {
#endif // LIBAVCODEC_VERSION_INT > 3544932
        qDebug() << "EncoderFfmpegCore::initEncoder: Codec MP3";
#ifdef avformat_alloc_output_context2
        avformat_alloc_output_context2(&m_pEncodeFormatCtx, NULL, NULL, "output.mp3");
#else
        m_pEncoderFormat = av_guess_format(NULL, "output.mp3", NULL);
#endif // avformat_alloc_output_context2

#if LIBAVCODEC_VERSION_INT > 3544932
    } else if (m_SCcodecId == AV_CODEC_ID_AAC) {
#else
    } else if (m_SCcodecId == CODEC_ID_AAC) {
#endif // LIBAVCODEC_VERSION_INT > 3544932
        qDebug() << "EncoderFfmpegCore::initEncoder: Codec M4A";
#ifdef avformat_alloc_output_context2
        avformat_alloc_output_context2(&m_pEncodeFormatCtx, NULL, NULL, "output.m4a");
#else
        m_pEncoderFormat = av_guess_format(NULL, "output.m4a", NULL);
#endif // avformat_alloc_output_context2

    } else {
        qDebug() << "EncoderFfmpegCore::initEncoder: Codec OGG/Vorbis";
#ifdef avformat_alloc_output_context2
        avformat_alloc_output_context2(&m_pEncodeFormatCtx, NULL, NULL, "output.ogg");
        m_pEncodeFormatCtx->oformat->audio_codec=AV_CODEC_ID_VORBIS;
#else
        m_pEncoderFormat = av_guess_format(NULL, "output.ogg", NULL);
#if LIBAVCODEC_VERSION_INT > 3544932
        m_pEncoderFormat->audio_codec=AV_CODEC_ID_VORBIS;
#else
        m_pEncoderFormat->audio_codec=CODEC_ID_VORBIS;
#endif // LIBAVCODEC_VERSION_INT > 3544932
#endif // avformat_alloc_output_context2
    }

#ifdef avformat_alloc_output_context2
    m_pEncoderFormat = m_pEncodeFormatCtx->oformat;
#else
    m_pEncodeFormatCtx->oformat = m_pEncoderFormat;
#endif // avformat_alloc_output_context2

    m_pEncoderAudioStream = addStream(m_pEncodeFormatCtx, &m_pEncoderAudioCodec,
                                      m_pEncoderFormat->audio_codec);

    openAudio(m_pEncoderAudioCodec, m_pEncoderAudioStream);

    // qDebug() << "jepusti";

    return 0;
}

// Private methods

int EncoderFfmpegCore::writeAudioFrame(AVFormatContext *formatctx,
                                       AVStream *stream) {
    AVCodecContext *l_SCodecCtx = NULL;;
    AVPacket l_SPacket;
    AVFrame *l_SFrame = avcodec_alloc_frame();
    int l_iGotPacket;
    int l_iRet;
#ifdef av_make_error_string
    char l_strErrorBuff[256];
#endif // av_make_error_string

    av_init_packet(&l_SPacket);
    l_SPacket.size = 0;
    l_SPacket.data = NULL;

    // Calculate correct DTS for FFMPEG
    m_lDts = round(((double)m_lRecordedBytes / (double)44100 / (double)2. *
                    (double)m_pEncoderAudioStream->time_base.den));
    m_lPts = m_lDts;

    l_SCodecCtx = stream->codec;
#ifdef av_make_error_string
    memset(l_strErrorBuff, 0x00, 256);
#endif // av_make_error_string

    l_SFrame->nb_samples = m_iAudioInputFrameSize;
    // Mixxx uses float (32 bit) samples..
    l_SFrame->format = AV_SAMPLE_FMT_FLT;
#ifndef __FFMPEGOLDAPI__
    l_SFrame->channel_layout = l_SCodecCtx->channel_layout;
#endif // __FFMPEGOLDAPI__

    l_iRet = avcodec_fill_audio_frame(l_SFrame,
                                      l_SCodecCtx->channels,
                                      AV_SAMPLE_FMT_FLT,
                                      (const uint8_t *)m_pFltSamples,
                                      m_iFltAudioCpyLen,
                                      1);

    if (l_iRet != 0) {
#ifdef av_make_error_string
        qDebug() << "Can't fill FFMPEG frame: error " << l_iRet << "String '" <<
                 av_make_error_string(l_strErrorBuff, 256, l_iRet) << "'" <<
                 m_iFltAudioCpyLen;
#endif // av_make_error_string
        qDebug() << "Can't refill 1st FFMPEG frame!";
        return -1;
    }

    // If we have something else than AV_SAMPLE_FMT_FLT we have to convert it
    // to something that fits..
    if (l_SCodecCtx->sample_fmt != AV_SAMPLE_FMT_FLT) {

        reSample(l_SFrame);
        // After we have turned our samples to destination
        // Format we must re-alloc l_SFrame.. it easier like this..
#if LIBAVCODEC_VERSION_INT > 3544932
        avcodec_free_frame(&l_SFrame);
#else
        av_free(l_SFrame);
#endif // LIBAVCODEC_VERSION_INT > 3544932
        l_SFrame = NULL;
        l_SFrame = avcodec_alloc_frame();
        l_SFrame->nb_samples = m_iAudioInputFrameSize;
        l_SFrame->format = l_SCodecCtx->sample_fmt;
#ifndef __FFMPEGOLDAPI__
        l_SFrame->channel_layout = m_pEncoderAudioStream->codec->channel_layout;
#endif // __FFMPEGOLDAPI__

        l_iRet = avcodec_fill_audio_frame(l_SFrame, l_SCodecCtx->channels,
                                          l_SCodecCtx->sample_fmt,
                                          (const uint8_t *)m_pResample->getBuffer(),
                                          m_iAudioCpyLen,
                                          1);

        if (l_iRet != 0) {
#ifdef av_make_error_string
            qDebug() << "Can't refill FFMPEG frame: error " << l_iRet << "String '" <<
                     av_make_error_string(l_strErrorBuff, 256,
                                          l_iRet) << "'" <<  m_iAudioCpyLen <<
                     " " <<  av_samples_get_buffer_size(
                         NULL, 2,
                         m_iAudioInputFrameSize,
                         m_pEncoderAudioStream->codec->sample_fmt,
                         1) << " " << m_pOutSize;
#endif // av_make_error_string
            qDebug() << "Can't refill 2nd FFMPEG frame!";
            return -1;
        }
    }

    //qDebug() << "!!" << l_iRet;
    l_iRet = avcodec_encode_audio2(l_SCodecCtx, &l_SPacket, l_SFrame,
                                   &l_iGotPacket);

    if (l_iRet < 0) {
        qDebug() << "Error encoding audio frame";
        return -1;
    }

    if (!l_iGotPacket) {
        // qDebug() << "No packet! Can't encode audio!!";
        return -1;
    }

    l_SPacket.stream_index = stream->index;

    // Let's calculate DTS/PTS and give it to FFMPEG..
    // THEN codecs like OGG/Voris works ok!!
    l_SPacket.dts = m_lDts;
    l_SPacket.pts = m_lDts;

    // Some times den is zero.. so 0 dived by 0 is
    // Something?
    if (m_pEncoderAudioStream->pts.den == 0) {
        qDebug() << "Time hack!";
        m_pEncoderAudioStream->pts.den = 1;
    }

    // Write the compressed frame to the media file. */
    l_iRet = av_interleaved_write_frame(formatctx, &l_SPacket);

    if (l_iRet != 0) {
        qDebug() << "Error while writing audio frame";
        return -1;
    }

    av_free_packet(&l_SPacket);
    av_destruct_packet(&l_SPacket);
    av_free(l_SFrame);

    return 0;
}
Example #16
0
/**
 * Initialises OpenJazz.
 *
 * Establishes the paths from which to read files, loads configuration, sets up
 * the game window and loads required data.
 *
 * @param argc Number of arguments, as passed to main function
 * @param argv Array of argument strings, as passed to main function
 */
void startUp (int argc, char *argv[]) {

	File* file;
	unsigned char* pixels = NULL;
	int count;
	int screenW = DEFAULT_SCREEN_WIDTH;
	int screenH = DEFAULT_SCREEN_HEIGHT;
	int scaleFactor = 1;
#ifdef FULLSCREEN_ONLY
	bool fullscreen = true;
#else
	bool fullscreen = false;
#endif


	// Determine paths

	// Use hard-coded paths, if available

#ifdef DATAPATH
	firstPath = new Path(NULL, createString(DATAPATH));
#else
	firstPath = NULL;
#endif

#ifdef __HAIKU__
	dev_t volume = dev_for_path("/boot");
	char buffer[10 + B_PATH_NAME_LENGTH + B_FILE_NAME_LENGTH];
	status_t result;

	result = find_directory(B_SYSTEM_DATA_DIRECTORY,
		volume, false, buffer, sizeof(buffer));
	strncat(buffer, "/openjazz/", sizeof(buffer));
	firstPath = new Path(firstPath, createString(buffer));

	result = find_directory(B_USER_NONPACKAGED_DATA_DIRECTORY,
		volume, false, buffer, sizeof(buffer));
	strncat(buffer, "/openjazz/", sizeof(buffer));
	firstPath = new Path(firstPath, createString(buffer));
#endif

#ifdef __SYMBIAN32__
	#ifdef UIQ3
	firstPath = new Path(firstPath, createString("c:\\shared\\openjazz\\"));
	#else
	firstPath = new Path(firstPath, createString("c:\\data\\openjazz\\"));
	#endif
	firstPath = new Path(firstPath, createString(KOpenJazzPath));
#endif


	// Use any provided paths, appending a directory separator as necessary

	for (count = 1; count < argc; count++) {

		// If it isn't an option, it should be a path
		if (argv[count][0] != '-') {

#ifdef _WIN32
			if (argv[count][strlen(argv[count]) - 1] != '\\') {

				firstPath = new Path(firstPath, createString(argv[count], "\\"));
#else
			if (argv[count][strlen(argv[count]) - 1] != '/') {

				firstPath = new Path(firstPath, createString(argv[count], "/"));
#endif

			} else {

				firstPath = new Path(firstPath, createString(argv[count]));

			}

		}

	}

	// Use the path of the program, but not on Wii as this does crash in
	// dolphin emulator. Also is not needed, because CWD is used there

#ifndef WII
	count = strlen(argv[0]) - 1;

	// Search for directory separator
#ifdef _WIN32
	while ((argv[0][count] != '\\') && (count >= 0)) count--;
#else
	while ((argv[0][count] != '/') && (count >= 0)) count--;
#endif

	// If a directory was found, copy it to the path
	if (count > 0) {

		firstPath = new Path(firstPath, new char[count + 2]);
		memcpy(firstPath->path, argv[0], count + 1);
		firstPath->path[count + 1] = 0;

	}
#endif


	// Use the user's home directory, if available

#ifdef HOMEDIR
	#ifdef _WIN32
	firstPath = new Path(firstPath, createString(getenv("HOME"), "\\"));
	#else
	firstPath = new Path(firstPath, createString(getenv("HOME"), "/."));
	#endif
#endif


	// Use the current working directory

	firstPath = new Path(firstPath, createString(""));



	// Default settings

	// Sound settings
#if defined(WIZ) || defined(GP2X)
	volume = 40;
#endif

	// Create the network address
	netAddress = createString(NET_ADDRESS);


	// Load settings from config file
	setup.load(&screenW, &screenH, &fullscreen, &scaleFactor);


	// Get command-line override
	for (count = 1; count < argc; count++) {

		// If there's a hyphen, it should be an option
		if (argv[count][0] == '-') {

#ifndef FULLSCREEN_ONLY
			if (argv[count][1] == 'f') fullscreen = true;
#endif
			if (argv[count][1] == 'm') {
				setMusicVolume(0);
				setSoundVolume(0);
			}

		}

	}


	// Create the game's window

	canvas = NULL;

	if (!video.init(screenW, screenH, fullscreen)) {

		delete firstPath;

		throw E_VIDEO;

	}

#ifdef SCALE
	video.setScaleFactor(scaleFactor);
#endif


	if (SDL_NumJoysticks() > 0) SDL_JoystickOpen(0);


	// Set up audio
	openAudio();



	// Load fonts

	// Open the panel, which contains two fonts

	try {

		file = new File("PANEL.000", false);

	} catch (int e) {

		closeAudio();

		delete firstPath;

		log("Unable to find game data files. When launching OpenJazz, pass the location");
		log("of the original game data, eg:");
		log("  OpenJazz ~/jazz1");

#ifdef __HAIKU__
		char alertBuffer[100+B_PATH_NAME_LENGTH+B_FILE_NAME_LENGTH];
		strcpy(alertBuffer, "Unable to find game data files!\n"
			"Put the data into the folder:\n");
		strncat(alertBuffer, buffer, sizeof(alertBuffer));
		BAlert* alert = new BAlert("OpenJazz", alertBuffer, "Exit", NULL, NULL,
			B_WIDTH_AS_USUAL, B_STOP_ALERT);
		alert->Go();
#endif

		throw e;

	}

	pixels = file->loadRLE(46272);

	delete file;

	panelBigFont = NULL;
	panelSmallFont = NULL;
	font2 = NULL;
	fontbig = NULL;
	fontiny = NULL;
	fontmn1 = NULL;

	try {

		panelBigFont = new Font(pixels + (40 * 320), true);
		panelSmallFont = new Font(pixels + (48 * 320), false);
		font2 = new Font("FONT2.0FN");
		fontbig = new Font("FONTBIG.0FN");
		fontiny = new Font("FONTINY.0FN");
		fontmn1 = new Font("FONTMN1.0FN");
		fontmn2 = new Font("FONTMN2.0FN");

	} catch (int e) {

		if (panelBigFont) delete panelBigFont;
		if (panelSmallFont) delete panelSmallFont;
		if (font2) delete font2;
		if (fontbig) delete fontbig;
		if (fontiny) delete fontiny;
		if (fontmn1) delete fontmn1;

		delete[] pixels;

		closeAudio();

		delete firstPath;

		throw e;

	}

	delete[] pixels;


	// Establish arbitrary timing
	globalTicks = SDL_GetTicks() - 20;


	// Fill trigonometric function look-up tables
	for (count = 0; count < 1024; count++)
		sinLut[count] = fixed(sinf(2 * PI * float(count) / 1024.0f) * 1024.0f);


	// Initiate networking
	net = new Network();


	level = NULL;
	jj2Level = NULL;

}


/**
 * De-initialises OpenJazz.
 *
 * Frees data, writes configuration, and shuts down SDL.
 */
void shutDown () {

	delete net;

	delete panelBigFont;
	delete panelSmallFont;
	delete font2;
	delete fontbig;
	delete fontiny;
	delete fontmn1;
	delete fontmn2;

#ifdef SCALE
	if (video.getScaleFactor() > 1) SDL_FreeSurface(canvas);
#endif

	closeAudio();


	// Save settings to config file
	setup.save();


	delete firstPath;

}
Example #17
0
ModelItemSample *recordSample()
{
  /***** allocate memory for the new sample */

  ModelItemSample *new_sample = (ModelItemSample *)malloc(sizeof(ModelItemSample));

  char *tmp_string;
  time_t timer;     /***** used to get the current time, which will become */
  time(&timer);     /***** the main part of the new utterance's ID */

  /***** initialize the audio device */

  if (initMixer() == MIXER_ERR) /***** if mixer error, return nothing */
  {
    free(new_sample);
    return NULL;
  }
  if (igain_level > 0)
    setIGainLevel(igain_level); /***** set IGain and Mic level according */
  setMicLevel(mic_level);     /***** to configuration */

  if (initAudio() == AUDIO_ERR) /***** if audio error, return nothing */
  {
    free(new_sample);
    return NULL;
  }

  /***** connect to microphone, get utterance, disconnect */

  openAudio();
  new_sample->wav_data = getUtterance(&new_sample->wav_length);
  closeAudio();


  if (new_sample->wav_data == NULL) /***** if nothing was recorded, return nothing */
  {
    new_sample->wav_length = 0;
    new_sample->has_wav    = 0;
    free(new_sample);
    return NULL;
  }
  else
    /***** flag says that this sample utterance also contains its original
     * wave data, not only the preprocessed feature vectors
     *****/
    new_sample->has_wav    = 1;

  /***** preprocess the wave data */

  new_sample->data = preprocessUtterance(new_sample->wav_data, new_sample->wav_length, &new_sample->length);

  if (new_sample->data == NULL) /***** if preprocessing failed, return nothing */
  {
    new_sample->length = 0;
    free(new_sample->wav_data);
    free(new_sample);
    return NULL;
  }

  /***** set ID */

  tmp_string = ctime(&timer); /***** get current time */

  /***** set sample ID looks like:  [Thu Feb 10 12:10:53 2000] */

  new_sample->id         = malloc(strlen(tmp_string)+2);
  new_sample->id[0] = '[';
  strcpy(new_sample->id+1, tmp_string);
  new_sample->id[strlen(tmp_string)] = ']';

  new_sample->next   = NULL; /***** next sample pointer is NULL */
  {
    int i;
    for (i = 0; i < 3; i++)
      new_sample->matrix[i] = NULL;
  }

  modified = 1; /***** speaker model has been modified now */

  return(new_sample);
}