Example #1
0
int output_alsa_close(struct output *h)
{
	struct output_stream *s;

	if(h == NULL)
		return 0;

	/* Stop thread */
	h->stop = 1;

	/* Join thread */
	if(pthread_join(h->thread, NULL) < 0)
		return -1;

	/* Free streams */
	while(h->streams != NULL)
	{
		s = h->streams;
		h->streams = s->next;
		output_alsa_free_stream(s);
	}

	/* Close alsa */
	if(h->alsa != NULL)
		snd_pcm_close(h->alsa);

	/* Free ALSA config */
	snd_config_update_free_global();

	/* Free structure */
	free(h);

	return 0;
}
Example #2
0
void
RKR::InitMIDI ()
{

  // Open Alsa Seq

  int alsaport_in;

  int err = snd_seq_open (&midi_in, "default", SND_SEQ_OPEN_INPUT, 0);
  if (err < 0)
    printf ("Cannot activate ALSA seq client\n");
  snd_seq_set_client_name (midi_in, "rakarrack");
  snd_config_update_free_global ();



 char portname[50];

  // Create Alsa Seq Client

  sprintf (portname, "rakarrack IN");
  alsaport_in = snd_seq_create_simple_port (midi_in, portname,
					    SND_SEQ_PORT_CAP_WRITE |
					    SND_SEQ_PORT_CAP_SUBS_WRITE,
					    SND_SEQ_PORT_TYPE_SYNTH);


}
Example #3
0
void printInDevices() {
    char **hints;
    /* Enumerate sound devices */
    int err = snd_device_name_hint(0, "pcm", (void***)&hints);
    if (err != 0) {
        fprintf(stderr, "Can't read data\n");
        exit(EXIT_FAILURE);
    }

    char** n = hints;
    while (*n != NULL) {
        char *name = snd_device_name_get_hint(*n, "NAME");
        char *desc = snd_device_name_get_hint(*n, "DESC");
        char *type = snd_device_name_get_hint(*n, "IOID");
        if (name != NULL && desc != NULL) {
            if (type == NULL || !strcmp(type, "Input")) {
                printf("%s\n%s: <%s>\n\n", desc, type == NULL ? "Input/Output" : "Input",name);
            }
        }
        if (name != NULL) free(name);
        if (name != NULL) free(desc);
        if (name != NULL) free(type);
        n++;
    }

    //Free hint buffer too
    snd_device_name_free_hint((void**)hints);
    snd_config_update_free_global();
}
Example #4
0
/*
Close the alsa handler
*/
snd_pcm_t* alsa_close(){
        if(handle!=NULL){
            return snd_pcm_close(handle);
        }
 		snd_config_update_free_global();
        return 0;
}
Example #5
0
AlsaWork::~AlsaWork()
{
	if (!devices_.empty())
		devices_.clear();
	currentAlsaDevice_.reset();
	snd_config_update_free_global();
}
Example #6
0
bool AudioInputALSA::Open(uint sample_bits, uint sample_rate, uint channels)
{
    if (alsa_device.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC + QString("invalid alsa device name, %1")
            .arg(alsa_device.constData()));
        return false;
    }
    (void)AlsaBad(snd_config_update_free_global(), "failed to update snd config");
    m_audio_sample_rate = sample_rate;
    m_audio_channels = channels;
    m_audio_sample_bits = sample_bits;
    if (AlsaBad(snd_pcm_open(&pcm_handle, alsa_device.constData(),
                             SND_PCM_STREAM_CAPTURE, 0), // blocking mode
                "pcm open failed"))
    {
        pcm_handle = NULL;
        return false;
    }
    if (!(PrepHwParams() && PrepSwParams()))
    {
        (void)snd_pcm_close(pcm_handle);
        pcm_handle = NULL;
        return false;
    }
    LOG(VB_AUDIO, LOG_INFO, LOC_DEV + "pcm open");
    return true;
}
Example #7
0
void Mouth::close(){
    snd_pcm_hw_params_free(params);
    snd_pcm_drain(capture_handle);
    snd_pcm_close(capture_handle);
    snd_config_update_free_global();
    open=false;
}
Example #8
0
static void installAlsaPhononDeviceHandle()
{
#ifdef HAVE_LIBASOUND2
    // after recreating the global configuration we can go and install custom configuration
    snd_config_update_free_global();
    snd_config_update();
    Q_ASSERT(snd_config);

    // x-phonon: device
    QFile phononDefinition(":/phonon/phonondevice.alsa");
    phononDefinition.open(QIODevice::ReadOnly);
    const QByteArray &phononDefinitionData = phononDefinition.readAll();

    snd_input_t *sndInput = 0;
    if (0 == snd_input_buffer_open(&sndInput, phononDefinitionData.constData(), phononDefinitionData.size())) {
        Q_ASSERT(sndInput);
        snd_config_load(snd_config, sndInput);
        snd_input_close(sndInput);
    }

#if 0
    // phonon_softvol: device
    QFile softvolDefinition(":/phonon/softvol.alsa");
    softvolDefinition.open(QIODevice::ReadOnly);
    const QByteArray softvolDefinitionData = softvolDefinition.readAll();

    sndInput = 0;
    if (0 == snd_input_buffer_open(&sndInput, softvolDefinitionData.constData(), softvolDefinitionData.size())) {
        Q_ASSERT(sndInput);
        snd_config_load(snd_config, sndInput);
        snd_input_close(sndInput);
    }
#endif
#endif // HAVE_LIBASOUND2
}
Example #9
0
int main(int argc, char **argv)
{
   register int  err;
   int           cardNum, totalCards;

   // No cards found yet
   totalCards = 0;

   // Start with first card
   cardNum = -1;

   for (;;)
   {
      // Get next sound card's card number. When "cardNum" == -1, then ALSA
      // fetches the first card
      if ((err = snd_card_next(&cardNum)) < 0)
      {
         printf("Can't get the next card number: %s\n", snd_strerror(err));
         break;
      }

      // No more cards? ALSA sets "cardNum" to -1 if so
      if (cardNum < 0) break;

      // Another card found, so bump the count
      ++totalCards;
   }

   printf("ALSA found %i cards\n", totalCards);

   // ALSA allocates some mem to load its config file when we call
   // snd_card_next. Now that we're done getting the info, let's tell ALSA
   // to unload the info and free up that mem
   snd_config_update_free_global();
}
Example #10
0
void alsa_clear_config_cache(void)
{
    int r;

    r = snd_config_update_free_global();
    if (r < 0)
        alsa_error("config_update_free_global", r);
}
Example #11
0
int main(int argc, char **argv)
{
   register int  err;
   int           cardNum;

   // Start with first card
   cardNum = -1;

   for (;;)
   {
      snd_ctl_t *cardHandle;

      // Get next sound card's card number. When "cardNum" == -1, then ALSA
      // fetches the first card
      if ((err = snd_card_next(&cardNum)) < 0)
      {
         printf("Can't get the next card number: %s\n", snd_strerror(err));
         break;
      }

      // No more cards? ALSA sets "cardNum" to -1 if so
      if (cardNum < 0) break;

      // Open this card's control interface. We specify only the card number -- not
      // any device nor sub-device too
      {
      char   str[64];

      sprintf(str, "hw:%i", cardNum);
      if ((err = snd_ctl_open(&cardHandle, str, 0)) < 0)
      {
         printf("Can't open card %i: %s\n", cardNum, snd_strerror(err));
         continue;
      }
      }

      {
      snd_ctl_card_info_t *cardInfo;

      // We need to get a snd_ctl_card_info_t. Just alloc it on the stack
      snd_ctl_card_info_alloca(&cardInfo);

      // Tell ALSA to fill in our snd_ctl_card_info_t with info about this card
      if ((err = snd_ctl_card_info(cardHandle, cardInfo)) < 0)
         printf("Can't get info for card %i: %s\n", cardNum, snd_strerror(err));
      else
         printf("Card %i = %s\n", cardNum, snd_ctl_card_info_get_name(cardInfo));
      }

      // Close the card's control interface after we're done with it
      snd_ctl_close(cardHandle);
   }

   // ALSA allocates some mem to load its config file when we call some of the
   // above functions. Now that we're done getting the info, let's tell ALSA
   // to unload the info and free up that mem
   snd_config_update_free_global();
}
Example #12
0
int do_play(char* file_name)
{
	char *pcm_name = "default";
	int tmp, err, c;
	snd_pcm_info_t *info;

	snd_pcm_info_alloca(&info);

	err = snd_output_stdio_attach(&log, stderr, 0);
	assert(err >= 0);

	stream = SND_PCM_STREAM_PLAYBACK;

	chunk_size = -1;
	rhwparams.format = DEFAULT_FORMAT;
	rhwparams.rate = DEFAULT_SPEED;
	rhwparams.channels = 1;

	err = snd_pcm_open(&handle, pcm_name, stream, open_mode);
	if (err < 0) {
		error(_("audio open error: %s"), snd_strerror(err));
		return 1;
	}

	if ((err = snd_pcm_info(handle, info)) < 0) {
		error(_("info error: %s"), snd_strerror(err));
		return 1;
	}

	if (nonblock) {
		err = snd_pcm_nonblock(handle, 1);
		if (err < 0) {
			error(_("nonblock setting error: %s"), snd_strerror(err));
			return 1;
		}
	}

	chunk_size = 1024;
	hwparams = rhwparams;

	audiobuf = (u_char *)malloc(1024);
	if (audiobuf == NULL) {
		error(_("not enough memory"));
		return 1;
	}

	signal(SIGINT, signal_handler);
	signal(SIGTERM, signal_handler);
	signal(SIGABRT, signal_handler);
	
	playback(file_name);

	snd_pcm_close(handle);
	free(audiobuf);
	snd_output_close(log);
	snd_config_update_free_global();
	return EXIT_SUCCESS;
}
/**
* @brief AlsaPlayback destructor
*/
AlsaPlayback::~AlsaPlayback()
{
	if(alsa_handle)
	{
		snd_pcm_close(alsa_handle);
		alsa_handle = NULL;
	}

	snd_config_update_free_global();
}
Example #14
0
static void
alsa_finish(void *data)
{
	struct alsa_data *ad = data;

	alsa_data_free(ad);

	/* free libasound's config cache */
	snd_config_update_free_global();
}
Example #15
0
static void
alsa_mixer_finish(struct mixer *data)
{
	struct alsa_mixer *am = (struct alsa_mixer *)data;

	g_free(am);

	/* free libasound's config cache */
	snd_config_update_free_global();
}
Example #16
0
void audio_free(struct audio *audio)
{
	if (audio->pcm) {
		snd_pcm_close(audio->pcm);
	}

	free(audio);

	snd_config_update_free_global();
}
Example #17
0
AlsaBackend::~AlsaBackend()
{
    Log("%s\n",__PRETTY_FUNCTION__);
    snd_lib_error_set_handler(0);
    snd_config_update_free_global();
    std::map<AudioStream*, AlsaThread*>::iterator iter;
    for (iter = p_alsathread.begin(); iter != p_alsathread.end(); iter++)
    {
        delete iter->second;
        delete iter->first;
    }
}
void VolumeControl::setupAlsa(){
    const char *card = "default";
    const char *selem_name = "Master";//or Master
    if(snd_mixer_open(&handle, 0) == 0 ) mixer_opened = true;
    if(mixer_opened){
        //std::cout << "Mixer Opened" << std::endl;
        snd_config_update_free_global();//should make valgrind STFU
        snd_mixer_attach(handle, card);
        snd_mixer_selem_register(handle, NULL, NULL);
        snd_mixer_load(handle);
        snd_mixer_selem_id_alloca(&sid);
        snd_mixer_selem_id_set_index(sid, 0);
        snd_mixer_selem_id_set_name(sid, selem_name);
        elem = snd_mixer_find_selem(handle, sid);
        snd_mixer_selem_get_playback_volume_range(elem, &min, &max);
        //std::cout << "Min:" << min << " Max:" << max << std::endl;
        snd_config_update_free_global();//should make valgrind STFU
    }else{
        std::cout << "Failed to open mixer" << std::endl;
    }
}
Example #19
0
/**
 * ags_devout_list_cards:
 * @soundcard: the #AgsSoundcard
 * @card_id: alsa identifier
 * @card_name: card name
 *
 * List available soundcards.
 *
 * Since: 0.4
 */
void
ags_devout_list_cards(AgsSoundcard *soundcard,
		      GList **card_id, GList **card_name)
{
  snd_ctl_t *card_handle;
  snd_ctl_card_info_t *card_info;
  char *name;
  gchar *str;
  int card_num;
  int error;

  *card_id = NULL;
  *card_name = NULL;
  card_num = -1;

  while(TRUE){
    error = snd_card_next(&card_num);

    if(card_num < 0){
      break;
    }

    if(error < 0){
      continue;
    }

    str = g_strdup_printf("hw:%i\0", card_num);
    error = snd_ctl_open(&card_handle, str, 0);

    if(error < 0){
      continue;
    }

    snd_ctl_card_info_alloca(&card_info);
    error = snd_ctl_card_info(card_handle, card_info);

    if(error < 0){
      continue;
    }

    *card_id = g_list_prepend(*card_id, str);
    *card_name = g_list_prepend(*card_name, g_strdup(snd_ctl_card_info_get_name(card_info)));

    snd_ctl_close(card_handle);
  }

  snd_config_update_free_global();

  *card_id = g_list_reverse(*card_id);
  *card_name = g_list_reverse(*card_name);
}
mastermidibus::~mastermidibus ()
{
    for (int i = 0; i < m_num_out_buses; ++i)
    {
        if (not_nullptr(m_buses_out[i]))
        {
            delete m_buses_out[i];
            m_buses_out[i] = nullptr;
        }
    }
    for (int i = 0; i < m_num_in_buses; ++i)
    {
        if (not_nullptr(m_buses_in[i]))
        {
            delete m_buses_in[i];
            m_buses_in[i] = nullptr;
        }
    }

#ifdef SEQ64_HAVE_LIBASOUND
    snd_seq_event_t ev;
    snd_seq_ev_clear(&ev);                          /* kill timer           */
    snd_seq_stop_queue(m_alsa_seq, m_queue, &ev);
    snd_seq_free_queue(m_alsa_seq, m_queue);
    snd_seq_close(m_alsa_seq);                      /* close client         */
    (void) snd_config_update_free_global();         /* additional cleanup   */
#endif

    /*
     * Still more cleanup, not in seq24.
     */

    if (not_nullptr(m_poll_descriptors))
    {
        delete [] m_poll_descriptors;
        m_poll_descriptors = nullptr;
    }
    if (not_nullptr(m_bus_announce))
    {
        delete m_bus_announce;
        m_bus_announce = nullptr;
    }
}
Example #21
0
int audio_close_alsa(cst_audiodev *ad)
{
  int result;
  snd_pcm_t *pcm_handle;

  if (ad == NULL)
      return 0;

  pcm_handle = (snd_pcm_t *) ad->platform_data;

  snd_pcm_drain(pcm_handle); /* wait for current stuff in buffer to finish */

  result = snd_pcm_close(pcm_handle);
  snd_config_update_free_global();
  if (result < 0)
  {
	cst_errmsg("audio_close_alsa: Error: %s.\n", snd_strerror(result));
  }
  cst_free(ad);
  return result;
}
Example #22
0
/******************************************************************************
 * Sound_alsa_delete
 ******************************************************************************/
Int Sound_alsa_delete(Sound_Handle hSound)
{
    if (hSound) {
        if (hSound->rcIn) {
            snd_pcm_close(hSound->rcIn);
        }

        if (hSound->rcOut) {
            snd_pcm_close(hSound->rcOut);
        }

        if (hSound->hwParamsIn) {
            /* Free the H/W param structure */
            snd_pcm_hw_params_free(hSound->hwParamsIn);
        }

        if (hSound->swParamsIn) {
            /* Free the S/W param structure */
            snd_pcm_sw_params_free(hSound->swParamsIn);
        }

        if (hSound->hwParamsOut) {
            /* Free the H/W param structure */
            snd_pcm_hw_params_free(hSound->hwParamsOut);
        }

        if (hSound->swParamsOut) {
            /* Free the S/W param structure */
            snd_pcm_sw_params_free(hSound->swParamsOut);
        }

        free(hSound);
        snd_config_update_free_global();
    }

    return Dmai_EOK;
}
Example #23
0
void CAESinkALSA::EnumerateDevicesEx(AEDeviceInfoList &list, bool force)
{
  /* ensure that ALSA has been initialized */
  snd_lib_error_set_handler(sndLibErrorHandler);
  if(!snd_config || force)
  {
    if(force)
      snd_config_update_free_global();

    snd_config_update();
  }

  snd_config_t *config;
  snd_config_copy(&config, snd_config);

  /* Always enumerate the default device.
   * Note: If "default" is a stereo device, EnumerateDevice()
   * will automatically add "@" instead to enable surroundXX mangling.
   * We don't want to do that if "default" can handle multichannel
   * itself (e.g. in case of a pulseaudio server). */
  EnumerateDevice(list, "default", "", config);

  void **hints;

  if (snd_device_name_hint(-1, "pcm", &hints) < 0)
  {
    CLog::Log(LOGINFO, "CAESinkALSA - Unable to get a list of devices");
    return;
  }

  std::string defaultDescription;

  for (void** hint = hints; *hint != NULL; ++hint)
  {
    char *io = snd_device_name_get_hint(*hint, "IOID");
    char *name = snd_device_name_get_hint(*hint, "NAME");
    char *desc = snd_device_name_get_hint(*hint, "DESC");
    if ((!io || strcmp(io, "Output") == 0) && name
        && strcmp(name, "null") != 0)
    {
      std::string baseName = std::string(name);
      baseName = baseName.substr(0, baseName.find(':'));

      if (strcmp(name, "default") == 0)
      {
        /* added already, but lets get the description if we have one */
        if (desc)
          defaultDescription = desc;
      }
      else if (baseName == "front")
      {
        /* Enumerate using the surroundXX mangling */
        /* do not enumerate basic "front", it is already handled
         * by the default "@" entry added in the very beginning */
        if (strcmp(name, "front") != 0)
          EnumerateDevice(list, std::string("@") + (name+5), desc ? desc : name, config);
      }

      /* Do not enumerate "default", it is already enumerated above. */

      /* Do not enumerate the sysdefault or surroundXX devices, those are
       * always accompanied with a "front" device and it is handled above
       * as "@". The below devices will be automatically used if available
       * for a "@" device. */

      /* Ubuntu has patched their alsa-lib so that "defaults.namehint.extended"
       * defaults to "on" instead of upstream "off", causing lots of unwanted
       * extra devices (many of which are not actually routed properly) to be
       * found by the enumeration process. Skip them as well ("hw", "dmix",
       * "plughw", "dsnoop"). */

      else if (baseName != "default"
            && baseName != "sysdefault"
            && baseName != "surround40"
            && baseName != "surround41"
            && baseName != "surround50"
            && baseName != "surround51"
            && baseName != "surround71"
            && baseName != "hw"
            && baseName != "dmix"
            && baseName != "plughw"
            && baseName != "dsnoop")
      {
        EnumerateDevice(list, name, desc ? desc : name, config);
      }
    }
    free(io);
    free(name);
    free(desc);
  }
  snd_device_name_free_hint(hints);

  /* set the displayname for default device */
  if (!list.empty() && list[0].m_deviceName == "default")
  {
    /* If we have one from a hint (DESC), use it */
    if (!defaultDescription.empty())
      list[0].m_displayName = defaultDescription;
    /* Otherwise use the discovered name or (unlikely) "Default" */
    else if (list[0].m_displayName.empty())
      list[0].m_displayName = "Default";
  }

  /* lets check uniqueness, we may need to append DEV or CARD to DisplayName */
  /* If even a single device of card/dev X clashes with Y, add suffixes to
   * all devices of both them, for clarity. */

  /* clashing card names, e.g. "NVidia", "NVidia_2" */
  std::set<std::string> cardsToAppend;

  /* clashing basename + cardname combinations, e.g. ("hdmi","Nvidia") */
  std::set<std::pair<std::string, std::string> > devsToAppend;

  for (AEDeviceInfoList::iterator it1 = list.begin(); it1 != list.end(); ++it1)
  {
    for (AEDeviceInfoList::iterator it2 = it1+1; it2 != list.end(); ++it2)
    {
      if (it1->m_displayName == it2->m_displayName
       && it1->m_displayNameExtra == it2->m_displayNameExtra)
      {
        /* something needs to be done */
        std::string cardString1 = GetParamFromName(it1->m_deviceName, "CARD");
        std::string cardString2 = GetParamFromName(it2->m_deviceName, "CARD");

        if (cardString1 != cardString2)
        {
          /* card name differs, add identifiers to all devices */
          cardsToAppend.insert(cardString1);
          cardsToAppend.insert(cardString2);
          continue;
        }

        std::string devString1 = GetParamFromName(it1->m_deviceName, "DEV");
        std::string devString2 = GetParamFromName(it2->m_deviceName, "DEV");

        if (devString1 != devString2)
        {
          /* device number differs, add identifiers to all such devices */
          devsToAppend.insert(std::make_pair(it1->m_deviceName.substr(0, it1->m_deviceName.find(':')), cardString1));
          devsToAppend.insert(std::make_pair(it2->m_deviceName.substr(0, it2->m_deviceName.find(':')), cardString2));
          continue;
        }

        /* if we got here, the configuration is really weird, just append the whole device string */
        it1->m_displayName += " (" + it1->m_deviceName + ")";
        it2->m_displayName += " (" + it2->m_deviceName + ")";
      }
    }
  }

  for (std::set<std::string>::iterator it = cardsToAppend.begin();
       it != cardsToAppend.end(); ++it)
  {
    for (AEDeviceInfoList::iterator itl = list.begin(); itl != list.end(); ++itl)
    {
      std::string cardString = GetParamFromName(itl->m_deviceName, "CARD");
      if (cardString == *it)
        /* "HDA NVidia (NVidia)", "HDA NVidia (NVidia_2)", ... */
        itl->m_displayName += " (" + cardString + ")";
    }
  }

  for (std::set<std::pair<std::string, std::string> >::iterator it = devsToAppend.begin();
       it != devsToAppend.end(); ++it)
  {
    for (AEDeviceInfoList::iterator itl = list.begin(); itl != list.end(); ++itl)
    {
      std::string baseName = itl->m_deviceName.substr(0, itl->m_deviceName.find(':'));
      std::string cardString = GetParamFromName(itl->m_deviceName, "CARD");
      if (baseName == it->first && cardString == it->second)
      {
        std::string devString = GetParamFromName(itl->m_deviceName, "DEV");
        /* "HDMI #0", "HDMI #1" ... */
        itl->m_displayNameExtra += " #" + devString;
      }
    }
  }
}
Example #24
0
 void alsa_module::teardown() {
   m_mixer.clear();
   m_ctrl.clear();
   snd_config_update_free_global();
 }
Example #25
0
static int findSoundCards(char **cardname)
{
	int idx, dev, err;
	snd_ctl_t *handle;
	snd_hctl_t *hctlhandle;
	snd_ctl_card_info_t *cardinfo;
	snd_pcm_info_t *pcminfo;
	char str[32];

	snd_ctl_card_info_alloca(&cardinfo);
	snd_pcm_info_alloca(&pcminfo);

	snd_hctl_elem_t *elem;
	snd_ctl_elem_id_t *id;
	snd_ctl_elem_info_t *info;
	snd_ctl_elem_id_alloca(&id);
	snd_ctl_elem_info_alloca(&info);

	idx = -1;
	while (1) {
		if ((err = snd_card_next(&idx)) < 0) {
			LOGE("Card next error: %s\n", snd_strerror(err));
			break;
		}
		if (idx < 0)
			break;
		sprintf(str, "hw:CARD=%i", idx);
		if ((err = snd_ctl_open(&handle, str, 0)) < 0) {
			LOGE("Open error: %s\n", snd_strerror(err));
			continue;
		}
		if ((err = snd_ctl_card_info(handle, cardinfo)) < 0) {
			LOGE("HW info error: %s\n", snd_strerror(err));
			continue;
		}
		LOGD("Soundcard #%i:\n", idx + 1);
		LOGD("  card - %i\n", snd_ctl_card_info_get_card(cardinfo));
		LOGD("  id - '%s'\n", snd_ctl_card_info_get_id(cardinfo));
		LOGD("  driver - '%s'\n", snd_ctl_card_info_get_driver(cardinfo));
		LOGD("  name - '%s'\n", snd_ctl_card_info_get_name(cardinfo));
		LOGD("  longname - '%s'\n", snd_ctl_card_info_get_longname(cardinfo));
		LOGD("  mixername - '%s'\n", snd_ctl_card_info_get_mixername(cardinfo));
		LOGD("  components - '%s'\n", snd_ctl_card_info_get_components(cardinfo));

		strcpy(cardname[idx], snd_ctl_card_info_get_name(cardinfo));
		LOGD("\n\n-----get cart name and id: %s : %d",cardname[idx],idx);
		snd_ctl_close(handle);

		if ((err = snd_hctl_open(&hctlhandle, str, 0)) < 0) {
			LOGE("Control %s open error: %s", str, snd_strerror(err));
			return err;
		}
		if ((err = snd_hctl_load(hctlhandle)) < 0) {
			LOGE("Control %s local error: %s\n", str, snd_strerror(err));
			return err;
		}

		for (elem = snd_hctl_first_elem(hctlhandle); elem; elem = snd_hctl_elem_next(elem)) {
			if ((err = snd_hctl_elem_info(elem, info)) < 0) {
				LOGE("Control %s snd_hctl_elem_info error: %s\n", str, snd_strerror(err));
				return err;
			}
			snd_hctl_elem_get_id(elem, id);
			show_control_id(id);
		}
		snd_hctl_close(hctlhandle);
	}
	snd_config_update_free_global();
	return 0;
}
Example #26
0
//list all the midi interfaces
void list_midi_interfaces(char* midi_dev, int bufsize)
{
    register int  err;
    int  cardNum;
    char devices[5][14];
    char user_midi[bufsize];

    // Start with first card
    cardNum = -1;

    for (;;)
    {
        snd_ctl_t *cardHandle;

        // Get next sound card's card number. When "cardNum" == -1, then ALSA
        // fetches the first card
        if ((err = snd_card_next(&cardNum)) < 0)
        {
            printf("Can't get the next card number: %s\n", snd_strerror(err));
            break;
        }

        // No more cards? ALSA sets "cardNum" to -1 if so
        if (cardNum < 0) break;

        // Open this card's control interface. We specify only the card number -- not
        // any device nor sub-device too
        {
            char   str[64];

            sprintf(str, "hw:%i", cardNum);
            if ((err = snd_ctl_open(&cardHandle, str, 0)) < 0)
            {
                printf("Can't open card %i: %s\n", cardNum, snd_strerror(err));
                continue;
            }
        }

        {
            int      devNum;

            // Start with the first MIDI device on this card
            devNum = -1;

            for (;;)
            {
                snd_rawmidi_info_t  *rawMidiInfo;
                register int        subDevCount, i;

                // Get the number of the next MIDI device on this card
                if ((err = snd_ctl_rawmidi_next_device(cardHandle, &devNum)) < 0)
                {
                    printf("Can't get next MIDI device number: %s\n", snd_strerror(err));
                    break;
                }

                // No more MIDI devices on this card? ALSA sets "devNum" to -1 if so.
                // NOTE: It's possible that this sound card may have no MIDI devices on it
                // at all, for example if it's only a digital audio card
                if (devNum < 0) break;

                // To get some info about the subdevices of this MIDI device (on the card), we need a
                // snd_rawmidi_info_t, so let's allocate one on the stack
                snd_rawmidi_info_alloca(&rawMidiInfo);
                memset(rawMidiInfo, 0, snd_rawmidi_info_sizeof());

                // Tell ALSA which device (number) we want info about
                snd_rawmidi_info_set_device(rawMidiInfo, devNum);

                // Get info on the MIDI outs of this device
                snd_rawmidi_info_set_stream(rawMidiInfo, SND_RAWMIDI_STREAM_INPUT);

                i = -1;
                subDevCount = 1;

                // More subdevices?
                while (++i < subDevCount)
                {
                    // Tell ALSA to fill in our snd_rawmidi_info_t with info on this subdevice
                    snd_rawmidi_info_set_subdevice(rawMidiInfo, i);
                    if ((err = snd_ctl_rawmidi_info(cardHandle, rawMidiInfo)) < 0)
                    {
                        printf("Can't get info for MIDI input subdevice hw:%i,%i,%i: %s\n", cardNum, devNum, i, snd_strerror(err));
                        continue;
                    }

                    // Print out how many subdevices (once only)
                    if (!i)
                    {
                        subDevCount = snd_rawmidi_info_get_subdevices_count(rawMidiInfo);
                        printf("\nFound %i MIDI input subdevices on card %i\n", subDevCount, cardNum);
                    }

                    // NOTE: If there's only one subdevice, then the subdevice number is immaterial,
                    // and can be omitted when you specify the hardware name
                    printf((subDevCount > 1 ? "[%i] -    hw:%i,%i,%i\n" : "[%i] -    hw:%i,%i\n"), i, cardNum, devNum, i);
                    sprintf(devices[i], (subDevCount > 1 ? "hw:%i,%i,%i\n":"hw:%i,%i\n"),cardNum, devNum, i);
                }
            }
        }

        // Close the card's control interface after we're done with it
        snd_ctl_close(cardHandle);


    }

    snd_config_update_free_global();

    printf("\nEnter the MIDI input to use (eg hw:1,0) > ");
    scanf("%s",user_midi);

    strncpy(midi_dev,user_midi,bufsize);
}
int main(int argc, char *argv[])
{
	static const struct option long_option[] =
	{
		{"help", 0, NULL, 'h'},
		{"file", 1, NULL, 'f'},
		{"env", 1, NULL, 'E'},
		{"initfile", 1, NULL, 'i'},
		{"no-init-fallback", 0, NULL, 'I'},
		{"force", 0, NULL, 'F'},
		{"ignore", 0, NULL, 'g'},
		{"pedantic", 0, NULL, 'P'},
		{"runstate", 0, NULL, 'r'},
		{"remove", 0, NULL, 'R'},
		{"debug", 0, NULL, 'd'},
		{"version", 0, NULL, 'v'},
		{NULL, 0, NULL, 0},
	};
	static const char *const devfiles[] = {
		"/dev/snd/controlC",
		"/dev/snd/pcmC",
		"/dev/snd/midiC",
		"/dev/snd/hwC",
		NULL
	};
	char *cfgfile = SYS_ASOUNDRC;
	char *initfile = DATADIR "/init/00main";
	char *cardname, ncardname[16];
	const char *const *tmp;
	int removestate = 0;
	int init_fallback = 1; /* new default behavior */
	int res;

	command = argv[0];
	while (1) {
		int c;

		if ((c = getopt_long(argc, argv, "hdvf:FgE:i:IPr:R", long_option, NULL)) < 0)
			break;
		switch (c) {
		case 'h':
			help();
			return EXIT_SUCCESS;
		case 'f':
			cfgfile = optarg;
			break;
		case 'F':
			force_restore = 1;
			break;
		case 'g':
			ignore_nocards = 1;
			break;
		case 'E':
			if (putenv(optarg)) {
				fprintf(stderr, "environment string '%s' is wrong\n", optarg);
				return EXIT_FAILURE;
			}
			break;
		case 'i':
			initfile = optarg;
			break;
		case 'I':
			init_fallback = 0;
			break;
		case 'r':
			statefile = optarg;
			break;
		case 'R':
			removestate = 1;
			break;
		case 'P':
			force_restore = 0;
			break;
		case 'd':
			debugflag = 1;
			break;
		case 'v':
			printf("alsactl version " SND_UTIL_VERSION_STR "\n");
			return EXIT_SUCCESS;
		case '?':		// error msg already printed
			help();
			return EXIT_FAILURE;
			break;
		default:		// should never happen
			fprintf(stderr, 
			"Invalid option '%c' (%d) not handled??\n", c, c);
		}
	}
	if (argc - optind <= 0) {
		fprintf(stderr, "alsactl: Specify command...\n");
		return 0;
	}

	cardname = argc - optind > 1 ? argv[optind + 1] : NULL;
	for (tmp = devfiles; cardname != NULL && *tmp != NULL; tmp++) {
		int len = strlen(*tmp);
		if (!strncmp(cardname, *tmp, len)) {
			long l = strtol(cardname + len, NULL, 0);
			sprintf(ncardname, "%li", l);
			cardname = ncardname;
			break;
		}
	}

	if (!strcmp(argv[optind], "init")) {
		res = init(initfile, cardname);
	} else if (!strcmp(argv[optind], "store")) {
		res = save_state(cfgfile, cardname);
	} else if (!strcmp(argv[optind], "restore")) {
		if (removestate)
			remove(statefile);
		res = load_state(cfgfile, initfile, cardname, init_fallback);
	} else {
		fprintf(stderr, "alsactl: Unknown command '%s'...\n", 
			argv[optind]);
		res = -ENODEV;
	}

	snd_config_update_free_global();
	return res < 0 ? res : 0;
}
Example #28
0
int main(int argc, char *argv[])
{
    static const char *const devfiles[] = {
        "/dev/snd/controlC",
        "/dev/snd/pcmC",
        "/dev/snd/midiC",
        "/dev/snd/hwC",
        NULL
    };
    char *cfgfile = SYS_ASOUNDRC;
    char *initfile = DATADIR "/init/00main";
    char *pidfile = SYS_PIDFILE;
    char *cardname, ncardname[16];
    char *cmd;
    const char *const *tmp;
    int removestate = 0;
    int init_fallback = 1; /* new default behavior */
    int period = 5*60;
    int background = 0;
    int daemoncmd = 0;
    int use_nice = NO_NICE;
    int sched_idle = 0;
    struct arg *a;
    struct option *o;
    int i, j, k, res;
    struct option *long_option;
    char *short_option;

    long_option = calloc(ARRAY_SIZE(args), sizeof(struct option));
    if (long_option == NULL)
        exit(EXIT_FAILURE);
    short_option = malloc(128);
    if (short_option == NULL) {
        free(long_option);
        exit(EXIT_FAILURE);
    }
    for (i = j = k = 0; i < ARRAY_SIZE(args); i++) {
        a = &args[i];
        if ((a->sarg & 0xff) == 0)
            continue;
        o = &long_option[j];
        o->name = a->larg;
        o->has_arg = (a->sarg & (ENVARG|FILEARG|INTARG)) != 0;
        o->flag = NULL;
        o->val = a->sarg & 0xff;
        j++;
        short_option[k++] = o->val;
        if (o->has_arg)
            short_option[k++] = ':';
    }
    short_option[k] = '\0';
    command = argv[0];
    while (1) {
        int c;

        if ((c = getopt_long(argc, argv, short_option, long_option,
                             NULL)) < 0)
            break;
        switch (c) {
        case 'h':
            help();
            res = EXIT_SUCCESS;
            goto out;
        case 'f':
            cfgfile = optarg;
            break;
        case 'l':
            do_lock = 1;
            break;
        case 'F':
            force_restore = 1;
            break;
        case 'g':
            ignore_nocards = 1;
            break;
        case 'E':
            if (putenv(optarg)) {
                fprintf(stderr, "environment string '%s' is wrong\n", optarg);
                res = EXIT_FAILURE;
                goto out;
            }
            break;
        case 'i':
            initfile = optarg;
            break;
        case 'I':
            init_fallback = 0;
            break;
        case 'r':
            statefile = optarg;
            break;
        case 'R':
            removestate = 1;
            break;
        case 'P':
            force_restore = 0;
            break;
        case 'p':
            period = atoi(optarg);
            if (period < 10)
                period = 5*60;
            else if (period > 24*60*60)
                period = 24*60*60;
            break;
        case 'e':
            pidfile = optarg;
            break;
        case 'b':
            background = 1;
            break;
        case 's':
            use_syslog = 1;
            break;
        case 'n':
            use_nice = atoi(optarg);
            if (use_nice < -20)
                use_nice = -20;
            else if (use_nice > 19)
                use_nice = 19;
            break;
        case 'c':
            sched_idle = 1;
            break;
        case 'd':
            debugflag = 1;
            break;
        case 'v':
            printf("alsactl version " SND_UTIL_VERSION_STR "\n");
            res = EXIT_SUCCESS;
            goto out;
        case '?':		// error msg already printed
            help();
            res = EXIT_FAILURE;
            goto out;
        default:		// should never happen
            fprintf(stderr,
                    "Invalid option '%c' (%d) not handled??\n", c, c);
        }
    }
    free(short_option);
    short_option = NULL;
    free(long_option);
    long_option = NULL;
    if (argc - optind <= 0) {
        fprintf(stderr, "alsactl: Specify command...\n");
        res = 0;
        goto out;
    }

    cardname = argc - optind > 1 ? argv[optind + 1] : NULL;
    for (tmp = devfiles; cardname != NULL && *tmp != NULL; tmp++) {
        int len = strlen(*tmp);
        if (!strncmp(cardname, *tmp, len)) {
            long l = strtol(cardname + len, NULL, 0);
            sprintf(ncardname, "%li", l);
            cardname = ncardname;
            break;
        }
    }

    /* the global system file should be always locked */
    if (strcmp(cfgfile, SYS_ASOUNDRC) == 0)
        do_lock = 1;

    /* when running in background, use syslog for reports */
    if (background) {
        use_syslog = 1;
        daemon(0, 0);
    }

    cmd = argv[optind];
    daemoncmd = strcmp(cmd, "daemon") == 0 || strcmp(cmd, "rdaemon") == 0;

    if (use_syslog) {
        openlog("alsactl", LOG_CONS|LOG_PID, LOG_DAEMON);
        if (daemoncmd)
            syslog(LOG_INFO, "alsactl " SND_UTIL_VERSION_STR " daemon started");
    }

    if (!strcmp(cmd, "init")) {
        res = init(initfile, cardname);
        snd_config_update_free_global();
    } else if (!strcmp(cmd, "store")) {
        res = save_state(cfgfile, cardname);
    } else if (!strcmp(cmd, "restore") ||
               !strcmp(cmd, "rdaemon") ||
               !strcmp(cmd, "nrestore")) {
        if (removestate)
            remove(statefile);
        res = load_state(cfgfile, initfile, cardname, init_fallback);
        if (!strcmp(cmd, "rdaemon")) {
            do_nice(use_nice, sched_idle);
            res = state_daemon(cfgfile, cardname, period, pidfile);
        }
        if (!strcmp(cmd, "nrestore"))
            res = state_daemon_kill(pidfile, "rescan");
    } else if (!strcmp(cmd, "daemon")) {
        do_nice(use_nice, sched_idle);
        res = state_daemon(cfgfile, cardname, period, pidfile);
    } else if (!strcmp(cmd, "kill")) {
        res = state_daemon_kill(pidfile, cardname);
    } else {
        fprintf(stderr, "alsactl: Unknown command '%s'...\n", cmd);
        res = -ENODEV;
    }

    snd_config_update_free_global();
    if (use_syslog) {
        if (daemoncmd)
            syslog(LOG_INFO, "alsactl daemon stopped");
        closelog();
    }
    return res < 0 ? -res : 0;

out:
    free(short_option);
    free(long_option);
    return res;
}
Example #29
0
la_errno_t la_playback_probe()
{
    snd_pcm_t* handle;
    la_playback_t* playback;
	int maxfd = 0;

    list_for_each_entry(la_get_playback_head(), playback, node)
    {
        char pcm[LA_PLAYBACK_PCM_NAME_MAX]={0};
    
        sprintf(pcm, "%s%d", LA_PLAYBACK_PCM_NAME, playback->id);
        
		playback->card_num = 0;
        playback->mutex = la_mutex_new(true,true);
        playback->mutex_stream = la_mutex_new(true,true);
		playback->chunk = LA_CARD_BUFFER_SIZE;
        playback->stream_len = LA_CARD_BUFFER_SIZE;
	    playback->stream = (char*)la_calloc(LA_CARD_BUFFER_SIZE);
        playback->card_list = (la_playback_pcm_t**)la_calloc(LA_PLAYBACK_CARD_MAX * sizeof(la_playback_pcm_t*));
        
        if(snd_pcm_open((snd_pcm_t**)&handle, pcm, SND_PCM_STREAM_PLAYBACK, 0) == 0)
        {         
            snd_pcm_close((snd_pcm_t*)handle);
            snd_config_update_free_global();
        }
        
        if(la_playback_set_master_softvol(playback, "0%") == LA_ERRNO_SUCCESS)
        {
            playback->master_mute = true;
            la_log_debug("init %s done", pcm);
        }
        else
        {
            la_log_debug("init %s fail", pcm);
        }


	    if(playback->stream == NULL)
            return LA_ERRNO_ALLOC;
	
        if (mkfifo(playback->fifo, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) == -1)
        {
            if(errno != EEXIST)
            {
                la_log_error("make %s error", playback->fifo);
                continue;
            }
            else
                la_log_notice("%s exist",playback->fifo);
        }

        // All of the writer close the FIFO, the reader sees the EOF and executes the request
        // select() will always return readable, but read nothing.
        // To open with  O_RDWR ensures that you have at least one writer on the FIFO
        if( (playback->fd = open(playback->fifo, O_RDWR | O_NONBLOCK)) >= 0 )
        {
            la_log_info("Open %s", playback->fifo);
			if(playback->fd > maxfd)
				maxfd = playback->fd;
        }
		else
		{
			la_log_error("Open %s error", playback->fifo);
		}
    }
Example #30
0
cst_audiodev *audio_open_alsa(unsigned int sps, int channels)
{
  cst_audiodev *ad;
  int err;

  /* alsa specific stuff */
  snd_pcm_t *pcm_handle;
  snd_pcm_hw_params_t *hwparams;
  snd_pcm_format_t format;

  /* Allocate the snd_pcm_hw_params_t structure on the stack. */
  snd_pcm_hw_params_alloca(&hwparams);

  /* Open pcm device */
  err = snd_pcm_open(&pcm_handle, pcm_dev_name, SND_PCM_STREAM_PLAYBACK, 0);
  if (err < 0) 
  {
	cst_errmsg("audio_open_alsa: failed to open audio device %s. %s\n",
			   pcm_dev_name, snd_strerror(err));
	return NULL;
  }

  /* Init hwparams with full configuration space */
  err = snd_pcm_hw_params_any(pcm_handle, hwparams);
  if (err < 0) 
  {
	snd_pcm_close(pcm_handle);
        snd_config_update_free_global();
	cst_errmsg("audio_open_alsa: failed to get hardware parameters from audio device. %s\n", snd_strerror(err));
	return NULL;
  }

  /* Set access mode */
  err = snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED);
  if (err < 0) 
  {
	snd_pcm_close(pcm_handle);
        snd_config_update_free_global();
	cst_errmsg("audio_open_alsa: failed to set access mode. %s.\n", snd_strerror(err));
	return NULL;
  }

#ifdef WORDS_BIGENDIAN
  format = SND_PCM_FORMAT_S16_BE;
#else
  format = SND_PCM_FORMAT_S16_LE;
#endif

  /* Set sample format */
  err = snd_pcm_hw_params_set_format(pcm_handle, hwparams, format);
  if (err <0) 
  {
	snd_pcm_close(pcm_handle);
        snd_config_update_free_global();
	cst_errmsg("audio_open_alsa: failed to set format. %s.\n", snd_strerror(err));
	return NULL;
  }

  /* Set sample rate */
  err = snd_pcm_hw_params_set_rate(pcm_handle, hwparams, sps, 0);
  if (err < 0)   
  {
	snd_pcm_close(pcm_handle);
        snd_config_update_free_global();
	cst_errmsg("audio_open_alsa: failed to set sample rate near %d. %s.\n", sps, snd_strerror(err));
	return NULL;
  }

  /* Set number of channels */
  assert(channels >0);
  err = snd_pcm_hw_params_set_channels(pcm_handle, hwparams, channels);
  if (err < 0) 
  {
	snd_pcm_close(pcm_handle);
        snd_config_update_free_global();
	cst_errmsg("audio_open_alsa: failed to set number of channels to %d. %s.\n", channels, snd_strerror(err));
	return NULL;
  }

  /* Commit hardware parameters */
  err = snd_pcm_hw_params(pcm_handle, hwparams);
  if (err < 0) 
  {
	snd_pcm_close(pcm_handle);
        snd_config_update_free_global();
	cst_errmsg("audio_open_alsa: failed to set hw parameters. %s.\n", snd_strerror(err));
	return NULL;
  }

  /* Make sure the device is ready to accept data */
  assert(snd_pcm_state(pcm_handle) == SND_PCM_STATE_PREPARED);

  /* Write hardware parameters to audio device data structure */
  ad = cst_alloc(cst_audiodev, 1);
  assert(ad != NULL);
  ad->sps = sps;
  ad->channels = channels;
  ad->platform_data = (void *) pcm_handle;

  return ad;
}