Example #1
0
 /* Init audio filters */
int init_audio_filters(sh_audio_t *sh_audio, 
	int in_samplerate, int in_channels, int in_format,
	int *out_samplerate, int *out_channels, int *out_format,
	int out_minsize, int out_maxsize){
  af_stream_t* afs=sh_audio->afilter;
  if(!afs){
    afs = malloc(sizeof(af_stream_t));
    memset(afs,0,sizeof(af_stream_t));
  }

  // input format: same as codec's output format:
  afs->input.rate   = in_samplerate;
  afs->input.nch    = in_channels;
  afs->input.format = in_format;
  af_fix_parameters(&(afs->input));

  // output format: same as ao driver's input format (if missing, fallback to input)
  afs->output.rate   = *out_samplerate;
  afs->output.nch    = *out_channels;
  afs->output.format = *out_format;
  af_fix_parameters(&(afs->output));

  // filter config:  
  memcpy(&afs->cfg,&af_cfg,sizeof(af_cfg_t));
  
  mp_msg(MSGT_DECAUDIO, MSGL_V, MSGTR_BuildingAudioFilterChain,
      afs->input.rate,afs->input.nch,af_fmt2str_short(afs->input.format),
      afs->output.rate,afs->output.nch,af_fmt2str_short(afs->output.format));
  
  // let's autoprobe it!
  if(0 != af_init(afs)){
    sh_audio->afilter=NULL;
    free(afs);
    return 0; // failed :(
  }

  *out_samplerate=afs->output.rate;
  *out_channels=afs->output.nch;
  *out_format=afs->output.format;
  
  if (out_maxsize || out_minsize) {
  // allocate the a_out_* buffers:
  if(out_maxsize<out_minsize) out_maxsize=out_minsize;
  if(out_maxsize<8192) out_maxsize=MAX_OUTBURST; // not sure this is ok

  sh_audio->a_out_buffer_size=out_maxsize;
  if (sh_audio->a_out_buffer != sh_audio->a_buffer)
      free(sh_audio->a_out_buffer);
  sh_audio->a_out_buffer=memalign(16,sh_audio->a_out_buffer_size);
  memset(sh_audio->a_out_buffer,0,sh_audio->a_out_buffer_size);
  sh_audio->a_out_buffer_len=0;
  }
  
  // ok!
  sh_audio->afilter=(void*)afs;
  return 1;
}
Example #2
0
int init_audio_filters(sh_audio_t *sh_audio, int in_samplerate,
		       int *out_samplerate, int *out_channels, int *out_format)
{
    af_stream_t *afs = sh_audio->afilter;
    if (!afs) {
	afs = malloc(sizeof(af_stream_t));
	memset(afs, 0, sizeof(af_stream_t));
    }
    // input format: same as codec's output format:
    afs->input.rate   = in_samplerate;
    afs->input.nch    = sh_audio->channels;
    afs->input.format = sh_audio->sample_format;
    af_fix_parameters(&(afs->input));

    // output format: same as ao driver's input format (if missing, fallback to input)
    afs->output.rate   = *out_samplerate;
    afs->output.nch    = *out_channels;
    afs->output.format = *out_format;
    af_fix_parameters(&(afs->output));

    // filter config:
    memcpy(&afs->cfg, &af_cfg, sizeof(af_cfg_t));

    mp_msg(MSGT_DECAUDIO, MSGL_V,
           "Building audio filter chain for %dHz/%dch/%s -> %dHz/%dch/%s...\n",
	   afs->input.rate, afs->input.nch,
	   af_fmt2str_short(afs->input.format), afs->output.rate,
	   afs->output.nch, af_fmt2str_short(afs->output.format));

    // let's autoprobe it!
    if (0 != af_init(afs)) {
	sh_audio->afilter = NULL;
	free(afs);
	return 0;   // failed :(
    }

    *out_samplerate = afs->output.rate;
    *out_channels = afs->output.nch;
    *out_format = afs->output.format;

    // Do not reset a_out_buffer_len. This may cause some
    // glitches/slow adaption of changes but it is better than
    // losing audio even for minor adjustments and avoids sync issues.

    // ok!
    sh_audio->afilter = (void *) afs;
    return 1;
}
Example #3
0
char *mp_audio_fmt_to_str(int srate, const struct mp_chmap *chmap, int format)
{
    char *chstr = mp_chmap_to_str(chmap);
    char *res = talloc_asprintf(NULL, "%dHz %s %dch %s", srate, chstr,
                                chmap->num, af_fmt2str_short(format));
    talloc_free(chstr);
    return res;
}
Example #4
0
int init_audio_filters(sh_audio_t *sh_audio, int in_samplerate,
		       int *out_samplerate, int *out_channels, int *out_format)
{
    af_stream_t *afs = sh_audio->afilter;
    if (!afs) {
	afs = malloc(sizeof(af_stream_t));
	memset(afs, 0, sizeof(af_stream_t));
    }
    // input format: same as codec's output format:
    afs->input.rate   = in_samplerate;
    afs->input.nch    = sh_audio->channels;
    afs->input.format = sh_audio->sample_format;
    af_fix_parameters(&(afs->input));

    // output format: same as ao driver's input format (if missing, fallback to input)
    afs->output.rate   = *out_samplerate;
    afs->output.nch    = *out_channels;
    afs->output.format = *out_format;
    af_fix_parameters(&(afs->output));

    // filter config:
    memcpy(&afs->cfg, &af_cfg, sizeof(af_cfg_t));

    mp_msg(MSGT_DECAUDIO, MSGL_V, MSGTR_BuildingAudioFilterChain,
	   afs->input.rate, afs->input.nch,
	   af_fmt2str_short(afs->input.format), afs->output.rate,
	   afs->output.nch, af_fmt2str_short(afs->output.format));

    // let's autoprobe it!
    if (0 != af_init(afs)) {
	sh_audio->afilter = NULL;
	free(afs);
	return 0;   // failed :(
    }

    *out_samplerate = afs->output.rate;
    *out_channels = afs->output.nch;
    *out_format = afs->output.format;

    sh_audio->a_out_buffer_len = 0;

    // ok!
    sh_audio->afilter = (void *) afs;
    return 1;
}
Example #5
0
File: format.c Project: kax4/mpv
/* Convert format to str input str is a buffer for the
   converted string, size is the size of the buffer */
char* af_fmt2str(int format, char* str, int size)
{
    const char *name = af_fmt2str_short(format);
    if (name) {
        snprintf(str, size, "%s", name);
    } else {
        snprintf(str, size, "%#x", format);
    }
    return str;
}
Example #6
0
int init_audio_filters(sh_audio_t *sh_audio, int in_samplerate,
		       int *out_samplerate, int *out_channels, int *out_format)
{
    af_stream_t *afs = sh_audio->afilter;
    if (!afs) {
	afs = calloc(1, sizeof(struct af_stream));
	afs->opts = sh_audio->opts;
    }
    // input format: same as codec's output format:
    afs->input.rate   = in_samplerate;
    afs->input.nch    = sh_audio->channels;
    afs->input.format = sh_audio->sample_format;
    af_fix_parameters(&(afs->input));

    // output format: same as ao driver's input format (if missing, fallback to input)
    afs->output.rate   = *out_samplerate;
    afs->output.nch    = *out_channels;
    afs->output.format = *out_format;
    af_fix_parameters(&(afs->output));

    // filter config:
    memcpy(&afs->cfg, &af_cfg, sizeof(af_cfg_t));

    mp_tmsg(MSGT_DECAUDIO, MSGL_V, "Building audio filter chain for %dHz/%dch/%s -> %dHz/%dch/%s...\n",
	   afs->input.rate, afs->input.nch,
	   af_fmt2str_short(afs->input.format), afs->output.rate,
	   afs->output.nch, af_fmt2str_short(afs->output.format));

    // let's autoprobe it!
    if (0 != af_init(afs)) {
	sh_audio->afilter = NULL;
	free(afs);
	return 0;   // failed :(
    }

    *out_samplerate = afs->output.rate;
    *out_channels = afs->output.nch;
    *out_format = afs->output.format;

    // ok!
    sh_audio->afilter = (void *) afs;
    return 1;
}
// Initialization and runtime control
static int control(struct af_instance_s* af, int cmd, void* arg)
{
    switch(cmd) {
    case AF_CONTROL_REINIT:
        memcpy(af->data,(af_data_t*)arg,sizeof(af_data_t));
        mp_msg(MSGT_AFILTER, MSGL_V, "[dummy] Was reinitialized: %iHz/%ich/%s\n",
               af->data->rate,af->data->nch,af_fmt2str_short(af->data->format));
        return AF_OK;
    }
    return AF_UNKNOWN;
}
Example #8
0
static int format2oss(int format)
{
    switch(format)
    {
    case AF_FORMAT_U8: return AFMT_U8;
    case AF_FORMAT_S8: return AFMT_S8;
    case AF_FORMAT_U16_LE: return AFMT_U16_LE;
    case AF_FORMAT_U16_BE: return AFMT_U16_BE;
    case AF_FORMAT_S16_LE: return AFMT_S16_LE;
    case AF_FORMAT_S16_BE: return AFMT_S16_BE;
#ifdef AFMT_U24_LE
    case AF_FORMAT_U24_LE: return AFMT_U24_LE;
#endif
#ifdef AFMT_U24_BE
    case AF_FORMAT_U24_BE: return AFMT_U24_BE;
#endif
#ifdef AFMT_S24_LE
    case AF_FORMAT_S24_LE: return AFMT_S24_LE;
#endif
#ifdef AFMT_S24_BE
    case AF_FORMAT_S24_BE: return AFMT_S24_BE;
#endif
#ifdef AFMT_U32_LE
    case AF_FORMAT_U32_LE: return AFMT_U32_LE;
#endif
#ifdef AFMT_U32_BE
    case AF_FORMAT_U32_BE: return AFMT_U32_BE;
#endif
#ifdef AFMT_S32_LE
    case AF_FORMAT_S32_LE: return AFMT_S32_LE;
#endif
#ifdef AFMT_S32_BE
    case AF_FORMAT_S32_BE: return AFMT_S32_BE;
#endif
#ifdef AFMT_FLOAT
    case AF_FORMAT_FLOAT_NE: return AFMT_FLOAT;
#endif
    // SPECIALS
    case AF_FORMAT_MU_LAW: return AFMT_MU_LAW;
    case AF_FORMAT_A_LAW: return AFMT_A_LAW;
    case AF_FORMAT_IMA_ADPCM: return AFMT_IMA_ADPCM;
#ifdef AFMT_MPEG
    case AF_FORMAT_MPEG2: return AFMT_MPEG;
#endif
#ifdef AFMT_AC3
    case AF_FORMAT_AC3: return AFMT_AC3;
#endif
    }
    mp_msg(MSGT_AO, MSGL_V, "OSS: Unknown/not supported internal format: %s\n", af_fmt2str_short(format));
    return -1;
}
Example #9
0
int init_best_audio_codec(sh_audio_t *sh_audio, char *audio_decoders)
{
    assert(!sh_audio->initialized);

    struct mp_decoder_entry *decoder = NULL;
    struct mp_decoder_list *list =
        mp_select_audio_decoders(sh_audio->gsh->codec, audio_decoders);

    mp_print_decoders(MSGT_DECAUDIO, MSGL_V, "Codec list:", list);

    for (int n = 0; n < list->num_entries; n++) {
        struct mp_decoder_entry *sel = &list->entries[n];
        const struct ad_functions *driver = find_driver(sel->family);
        if (!driver)
            continue;
        mp_tmsg(MSGT_DECAUDIO, MSGL_V, "Opening audio decoder %s:%s\n",
                sel->family, sel->decoder);
        sh_audio->ad_driver = driver;
        if (init_audio_codec(sh_audio, sel->decoder)) {
            decoder = sel;
            break;
        }
        sh_audio->ad_driver = NULL;
        mp_tmsg(MSGT_DECAUDIO, MSGL_WARN, "Audio decoder init failed for "
                "%s:%s\n", sel->family, sel->decoder);
    }

    if (sh_audio->initialized) {
        sh_audio->gsh->decoder_desc =
            talloc_asprintf(NULL, "%s [%s:%s]", decoder->desc, decoder->family,
                            decoder->decoder);
        mp_msg(MSGT_DECAUDIO, MSGL_INFO, "Selected audio codec: %s\n",
               sh_audio->gsh->decoder_desc);
        mp_msg(MSGT_DECAUDIO, MSGL_V,
               "AUDIO: %d Hz, %d ch, %s\n",
               sh_audio->samplerate, sh_audio->channels.num,
               af_fmt2str_short(sh_audio->sample_format));
        mp_msg(MSGT_IDENTIFY, MSGL_INFO,
               "ID_AUDIO_BITRATE=%d\nID_AUDIO_RATE=%d\n" "ID_AUDIO_NCH=%d\n",
               sh_audio->i_bps * 8, sh_audio->samplerate, sh_audio->channels.num);
    } else {
        mp_msg(MSGT_DECAUDIO, MSGL_ERR,
               "Failed to initialize an audio decoder for codec '%s'.\n",
               sh_audio->gsh->codec ? sh_audio->gsh->codec : "<unknown>");
    }

    talloc_free(list);
    return sh_audio->initialized;
}
int AudioDecoder::init_audio_codec(sh_audio_t *sh_audio){
    if (!((mpDecorder*)(sh_audio->ad_driver))->preinit(sh_audio)) {
	return 0;
    }
    
    /* allocate audio in buffer: */
    if (sh_audio->audio_in_minsize > 0) {
	sh_audio->a_in_buffer_size = sh_audio->audio_in_minsize;
	sh_audio->a_in_buffer = NULL;//av_mallocz(sh_audio->a_in_buffer_size);
	sh_audio->a_in_buffer_len = 0;
    }
    
    sh_audio->a_buffer_size = sh_audio->audio_out_minsize + MAX_OUTBURST;
    sh_audio->a_buffer = NULL;//av_mallocz(sh_audio->a_buffer_size);
    
    if (!((mpDecorder*)(sh_audio->ad_driver))->init(sh_audio)) {
	uninit_audio(sh_audio);	// free buffers
	return 0;
    }

    if(!sh_audio->wf && !sh_audio->codecdata)
      return 1;
#if 0
    if (!sh_audio->channels || !sh_audio->samplerate ) {
	uninit_audio(sh_audio);	// free buffers
	return 0;
    }
#endif
    if (!sh_audio->o_bps)
	sh_audio->o_bps = sh_audio->channels * sh_audio->samplerate * sh_audio->samplesize;

    mp_msg(MSGT_DECAUDIO, MSGL_INFO,
	   "AUDIO: %d Hz, %d ch, %s, %3.1f kbit/%3.2f%% (ratio: %d->%d)\n",
	   sh_audio->samplerate, sh_audio->channels,
	   af_fmt2str_short(sh_audio->sample_format),
	   sh_audio->i_bps * 8 * 0.001,
	   ((float) sh_audio->i_bps / sh_audio->o_bps) * 100.0,
	   sh_audio->i_bps, sh_audio->o_bps);
    mp_msg(MSGT_IDENTIFY, MSGL_INFO,
	   "ID_AUDIO_BITRATE=%d\nID_AUDIO_RATE=%d\n" "ID_AUDIO_NCH=%d\n",
	   sh_audio->i_bps * 8, sh_audio->samplerate, sh_audio->channels);

    sh_audio->a_out_buffer_size = 0;
    sh_audio->a_out_buffer = NULL;
    sh_audio->a_out_buffer_len = 0;

    return 1;
}
Example #11
0
// open & setup audio device
// return: 1=success 0=fail
static int init(int rate, int channels, int format, int flags) {

  int smpwidth, smpfmt;
  int rv = AL_DEFAULT_OUTPUT;

  smpfmt = fmt2sgial(&format, &smpwidth);

  mp_tmsg(MSGT_AO, MSGL_INFO, "[AO SGI] init: Samplerate: %iHz Channels: %s Format %s\n", rate, (channels > 1) ? "Stereo" : "Mono", af_fmt2str_short(format));

  { /* from /usr/share/src/dmedia/audio/setrate.c */

    double frate, realrate;
    ALpv x[2];

    if(ao_subdevice) {
      rv = alGetResourceByName(AL_SYSTEM, ao_subdevice, AL_OUTPUT_DEVICE_TYPE);
      if (!rv) {
	mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SGI] play: invalid device.\n");
	return 0;
      }
    }

    frate = rate;

    x[0].param = AL_RATE;
    x[0].value.ll = alDoubleToFixed(rate);
    x[1].param = AL_MASTER_CLOCK;
    x[1].value.i = AL_CRYSTAL_MCLK_TYPE;

    if (alSetParams(rv,x, 2)<0) {
      mp_tmsg(MSGT_AO, MSGL_WARN, "[AO SGI] init: setparams failed: %s\nCould not set desired samplerate.\n", alGetErrorString(oserror()));
    }

    if (x[0].sizeOut < 0) {
      mp_tmsg(MSGT_AO, MSGL_WARN, "[AO SGI] init: AL_RATE was not accepted on the given resource.\n");
    }

    if (alGetParams(rv,x, 1)<0) {
      mp_tmsg(MSGT_AO, MSGL_WARN, "[AO SGI] init: getparams failed: %s\n", alGetErrorString(oserror()));
    }

    realrate = alFixedToDouble(x[0].value.ll);
    if (frate != realrate) {
      mp_tmsg(MSGT_AO, MSGL_INFO, "[AO SGI] init: samplerate is now %f (desired rate is %f)\n", realrate, frate);
    }
    sample_rate = (int)realrate;
  }

  bytes_per_frame = channels * smpwidth;

  ao_data.samplerate = sample_rate;
  ao_data.channels = channels;
  ao_data.format = format;
  ao_data.bps = sample_rate * bytes_per_frame;
  ao_data.buffersize=131072;
  ao_data.outburst = ao_data.buffersize/16;

  ao_config = alNewConfig();

  if (!ao_config) {
    mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SGI] init: %s\n", alGetErrorString(oserror()));
    return 0;
  }

  if(alSetChannels(ao_config, channels) < 0 ||
     alSetWidth(ao_config, smpwidth) < 0 ||
     alSetSampFmt(ao_config, smpfmt) < 0 ||
     alSetQueueSize(ao_config, sample_rate) < 0 ||
     alSetDevice(ao_config, rv) < 0) {
    mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SGI] init: %s\n", alGetErrorString(oserror()));
    return 0;
  }

  ao_port = alOpenPort("mplayer", "w", ao_config);

  if (!ao_port) {
    mp_tmsg(MSGT_AO, MSGL_ERR, "[AO SGI] init: Unable to open audio channel: %s\n", alGetErrorString(oserror()));
    return 0;
  }

  // printf("ao_sgi, init: port %d config %d\n", ao_port, ao_config);
  queue_size = alGetQueueSize(ao_config);
  return 1;

}
Example #12
0
static int init_audio_codec(sh_audio_t *sh_audio)
{
    assert(!sh_audio->initialized);
    resync_audio_stream(sh_audio);
    if ((af_cfg.force & AF_INIT_FORMAT_MASK) == AF_INIT_FLOAT) {
	int fmt = AF_FORMAT_FLOAT_NE;
	if (sh_audio->ad_driver->control(sh_audio, ADCTRL_QUERY_FORMAT,
					 &fmt) == CONTROL_TRUE) {
	    sh_audio->sample_format = fmt;
	    sh_audio->samplesize = 4;
	}
    }
    sh_audio->audio_out_minsize = 8192; // default, preinit() may change it
    if (!sh_audio->ad_driver->preinit(sh_audio)) {
	mp_tmsg(MSGT_DECAUDIO, MSGL_ERR, "ADecoder preinit failed :(\n");
	return 0;
    }

    /* allocate audio in buffer: */
    if (sh_audio->audio_in_minsize > 0) {
	sh_audio->a_in_buffer_size = sh_audio->audio_in_minsize;
	mp_tmsg(MSGT_DECAUDIO, MSGL_V, "dec_audio: Allocating %d bytes for input buffer.\n",
	       sh_audio->a_in_buffer_size);
	sh_audio->a_in_buffer = av_mallocz(sh_audio->a_in_buffer_size);
    }

    const int base_size = 65536;
    // At least 64 KiB plus rounding up to next decodable unit size
    sh_audio->a_buffer_size = base_size + sh_audio->audio_out_minsize;

    mp_tmsg(MSGT_DECAUDIO, MSGL_V, "dec_audio: Allocating %d + %d = %d bytes for output buffer.\n",
	   sh_audio->audio_out_minsize, base_size, sh_audio->a_buffer_size);

    sh_audio->a_buffer = av_mallocz(sh_audio->a_buffer_size);
    if (!sh_audio->a_buffer) {
	mp_tmsg(MSGT_DECAUDIO, MSGL_ERR, "Cannot allocate audio out buffer.\n");
	return 0;
    }
    sh_audio->a_buffer_len = 0;

    if (!sh_audio->ad_driver->init(sh_audio)) {
	mp_tmsg(MSGT_DECAUDIO, MSGL_WARN, "ADecoder init failed :(\n");
	uninit_audio(sh_audio);	// free buffers
	return 0;
    }

    sh_audio->initialized = 1;

    if (!sh_audio->channels || !sh_audio->samplerate) {
	mp_tmsg(MSGT_DECAUDIO, MSGL_WARN, "Unknown/missing audio format -> no sound\n");
	uninit_audio(sh_audio);	// free buffers
	return 0;
    }

    if (!sh_audio->o_bps)
	sh_audio->o_bps = sh_audio->channels * sh_audio->samplerate
	                  * sh_audio->samplesize;

    mp_msg(MSGT_DECAUDIO, MSGL_INFO,
	   "AUDIO: %d Hz, %d ch, %s, %3.1f kbit/%3.2f%% (ratio: %d->%d)\n",
	   sh_audio->samplerate, sh_audio->channels,
	   af_fmt2str_short(sh_audio->sample_format),
	   sh_audio->i_bps * 8 * 0.001,
	   ((float) sh_audio->i_bps / sh_audio->o_bps) * 100.0,
	   sh_audio->i_bps, sh_audio->o_bps);
    mp_msg(MSGT_IDENTIFY, MSGL_INFO,
	   "ID_AUDIO_BITRATE=%d\nID_AUDIO_RATE=%d\n" "ID_AUDIO_NCH=%d\n",
	   sh_audio->i_bps * 8, sh_audio->samplerate, sh_audio->channels);

    return 1;
}
Example #13
0
// open & setup audio device
// return: 1=success 0=fail
static int init(int rate,int channels,int format,int flags)
{
	WAVEFORMATEXTENSIBLE wformat;
	MMRESULT result;
	unsigned char* buffer;
	int i;

	if (AF_FORMAT_IS_AC3(format))
		format = AF_FORMAT_AC3_NE;
	switch(format){
		case AF_FORMAT_AC3_NE:
		case AF_FORMAT_S24_LE:
		case AF_FORMAT_S16_LE:
		case AF_FORMAT_U8:
			break;
		default:
			mp_msg(MSGT_AO, MSGL_V,"ao_win32: format %s not supported defaulting to Signed 16-bit Little-Endian\n",af_fmt2str_short(format));
			format=AF_FORMAT_S16_LE;
	}

	//fill global ao_data
	ao_data.channels=channels;
	ao_data.samplerate=rate;
	ao_data.format=format;
	ao_data.bps=channels*rate;
	ao_data.bps*=af_fmt2bits(format)/8;
	if(ao_data.buffersize==-1)
	{
		ao_data.buffersize=af_fmt2bits(format)/8;
        ao_data.buffersize*= channels;
		ao_data.buffersize*= SAMPLESIZE;
	}
	ao_data.outburst = ao_data.buffersize;
	mp_msg(MSGT_AO, MSGL_V,"ao_win32: Samplerate:%iHz Channels:%i Format:%s\n",rate, channels, af_fmt2str_short(format));
    mp_msg(MSGT_AO, MSGL_V,"ao_win32: Buffersize:%d\n",ao_data.buffersize);

	//fill waveformatex
    ZeroMemory( &wformat, sizeof(WAVEFORMATEXTENSIBLE));
    wformat.Format.cbSize          = (channels>2)?sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX):0;
    wformat.Format.nChannels       = channels;
    wformat.Format.nSamplesPerSec  = rate;
    wformat.Format.wBitsPerSample  = af_fmt2bits(format);
    if(AF_FORMAT_IS_AC3(format))
    {
        wformat.Format.wFormatTag      = WAVE_FORMAT_DOLBY_AC3_SPDIF;
        wformat.Format.nBlockAlign     = 4;
    }
    else
    {
        wformat.Format.wFormatTag      = (channels>2)?WAVE_FORMAT_EXTENSIBLE:WAVE_FORMAT_PCM;
        wformat.Format.nBlockAlign     = wformat.Format.nChannels * (wformat.Format.wBitsPerSample >> 3);
    }
	if(channels>2)
	{
        wformat.dwChannelMask = channel_mask[channels-3];
        wformat.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
	    wformat.Samples.wValidBitsPerSample=af_fmt2bits(format);
    }

    wformat.Format.nAvgBytesPerSec = wformat.Format.nSamplesPerSec * wformat.Format.nBlockAlign;

    //open sound device
    //WAVE_MAPPER always points to the default wave device on the system
    result = waveOutOpen(&hWaveOut,WAVE_MAPPER,(WAVEFORMATEX*)&wformat,(DWORD_PTR)waveOutProc,0,CALLBACK_FUNCTION);
	if(result == WAVERR_BADFORMAT)
	{
		mp_msg(MSGT_AO, MSGL_ERR,"ao_win32: format not supported switching to default\n");
        ao_data.channels = wformat.Format.nChannels = 2;
	    ao_data.samplerate = wformat.Format.nSamplesPerSec = 44100;
	    ao_data.format = AF_FORMAT_S16_LE;
		ao_data.bps=ao_data.channels * ao_data.samplerate*2;
	    wformat.Format.wBitsPerSample=16;
        wformat.Format.wFormatTag=WAVE_FORMAT_PCM;
		wformat.Format.nBlockAlign     = wformat.Format.nChannels * (wformat.Format.wBitsPerSample >> 3);
        wformat.Format.nAvgBytesPerSec = wformat.Format.nSamplesPerSec * wformat.Format.nBlockAlign;
		ao_data.buffersize=(wformat.Format.wBitsPerSample>>3)*wformat.Format.nChannels*SAMPLESIZE;
        result = waveOutOpen(&hWaveOut,WAVE_MAPPER,(WAVEFORMATEX*)&wformat,(DWORD_PTR)waveOutProc,0,CALLBACK_FUNCTION);
	}
Example #14
0
// open & setup audio device
// return: 1=success 0=fail
static int init(int rate,int channels,int format,int flags){
	int bits;
	opt_t subopts[] = {
	  {"waveheader", OPT_ARG_BOOL, &ao_pcm_waveheader, NULL},
	  {"file",       OPT_ARG_MSTRZ, &ao_outputfilename, NULL},
	  {"fast",       OPT_ARG_BOOL, &fast, NULL},
	  {NULL}
	};
	// set defaults
	ao_pcm_waveheader = 1;

	if (subopt_parse(ao_subdevice, subopts) != 0) {
	  return 0;
	}
	if (!ao_outputfilename){
	  ao_outputfilename =
	    strdup(ao_pcm_waveheader?"audiodump.wav":"audiodump.pcm");
	}

	/* bits is only equal to format if (format == 8) or (format == 16);
	   this means that the following "if" is a kludge and should
	   really be a switch to be correct in all cases */

	bits=8;
	switch(format){
	case AF_FORMAT_S8:
	    format=AF_FORMAT_U8;
	case AF_FORMAT_U8:
	    break;
	default:
	    format=AF_FORMAT_S16_LE;
	    bits=16;
	    break;
	}

	ao_data.outburst = 65536;
	ao_data.buffersize= 2*65536;
	ao_data.channels=channels;
	ao_data.samplerate=rate;
	ao_data.format=format;
	ao_data.bps=channels*rate*(bits/8);

	wavhdr.riff = le2me_32(WAV_ID_RIFF);
	wavhdr.wave = le2me_32(WAV_ID_WAVE);
	wavhdr.fmt = le2me_32(WAV_ID_FMT);
	wavhdr.fmt_length = le2me_32(16);
	wavhdr.fmt_tag = le2me_16(WAV_ID_PCM);
	wavhdr.channels = le2me_16(ao_data.channels);
	wavhdr.sample_rate = le2me_32(ao_data.samplerate);
	wavhdr.bytes_per_second = le2me_32(ao_data.bps);
	wavhdr.bits = le2me_16(bits);
	wavhdr.block_align = le2me_16(ao_data.channels * (bits / 8));
	
	wavhdr.data = le2me_32(WAV_ID_DATA);
	wavhdr.data_length=le2me_32(0x7ffff000);
	wavhdr.file_length = wavhdr.data_length + sizeof(wavhdr) - 8;

	mp_msg(MSGT_AO, MSGL_INFO, MSGTR_AO_PCM_FileInfo, ao_outputfilename, 
	       (ao_pcm_waveheader?"WAVE":"RAW PCM"), rate, 
	       (channels > 1) ? "Stereo" : "Mono", af_fmt2str_short(format));
	mp_msg(MSGT_AO, MSGL_INFO, MSGTR_AO_PCM_HintInfo);

	fp = fopen(ao_outputfilename, "wb");
	if(fp) {
		if(ao_pcm_waveheader){ /* Reserve space for wave header */
			fwrite(&wavhdr,sizeof(wavhdr),1,fp);
			wavhdr.file_length=wavhdr.data_length=0;
		}
		return 1;
	}
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_PCM_CantOpenOutputFile, 
               ao_outputfilename);
	return 0;
}
Example #15
0
static int init_audio_codec(sh_audio_t *sh_audio)
{
    if ((af_cfg.force & AF_INIT_FORMAT_MASK) == AF_INIT_FLOAT) {
	int fmt = AF_FORMAT_FLOAT_NE;
	if (sh_audio->ad_driver->control(sh_audio, ADCTRL_QUERY_FORMAT,
					 &fmt) == CONTROL_TRUE) {
	    sh_audio->sample_format = fmt;
	    sh_audio->samplesize = 4;
	}
    }
    if (!sh_audio->ad_driver->preinit(sh_audio)) {
	mp_msg(MSGT_DECAUDIO, MSGL_ERR, MSGTR_ADecoderPreinitFailed);
	return 0;
    }

    /* allocate audio in buffer: */
    if (sh_audio->audio_in_minsize > 0) {
	sh_audio->a_in_buffer_size = sh_audio->audio_in_minsize;
	mp_msg(MSGT_DECAUDIO, MSGL_V, "dec_audio: Allocating %d bytes for input buffer.\n",
	       sh_audio->a_in_buffer_size);
	sh_audio->a_in_buffer = av_mallocz(sh_audio->a_in_buffer_size);
	sh_audio->a_in_buffer_len = 0;
    }

    sh_audio->a_buffer_size = sh_audio->audio_out_minsize + MAX_OUTBURST;

    mp_msg(MSGT_DECAUDIO, MSGL_V, "dec_audio: Allocating %d + %d = %d bytes for output buffer.\n",
	   sh_audio->audio_out_minsize, MAX_OUTBURST, sh_audio->a_buffer_size);

    sh_audio->a_buffer = av_mallocz(sh_audio->a_buffer_size);
    if (!sh_audio->a_buffer) {
	mp_msg(MSGT_DECAUDIO, MSGL_ERR, MSGTR_CantAllocAudioBuf);
	return 0;
    }
    sh_audio->a_buffer_len = 0;

    if (!sh_audio->ad_driver->init(sh_audio)) {
	mp_msg(MSGT_DECAUDIO, MSGL_WARN, MSGTR_ADecoderInitFailed);
	uninit_audio(sh_audio);	// free buffers
	return 0;
    }

    sh_audio->initialized = 1;

    if (!sh_audio->channels || !sh_audio->samplerate) {
	mp_msg(MSGT_DECAUDIO, MSGL_WARN, MSGTR_UnknownAudio);
	uninit_audio(sh_audio);	// free buffers
	return 0;
    }

    if (!sh_audio->o_bps)
	sh_audio->o_bps = sh_audio->channels * sh_audio->samplerate
	                  * sh_audio->samplesize;

    mp_msg(MSGT_DECAUDIO, MSGL_INFO,
	   "AUDIO: %d Hz, %d ch, %s, %3.1f kbit/%3.2f%% (ratio: %d->%d)\n",
	   sh_audio->samplerate, sh_audio->channels,
	   af_fmt2str_short(sh_audio->sample_format),
	   sh_audio->i_bps * 8 * 0.001,
	   ((float) sh_audio->i_bps / sh_audio->o_bps) * 100.0,
	   sh_audio->i_bps, sh_audio->o_bps);
    mp_msg(MSGT_IDENTIFY, MSGL_INFO,
	   "ID_AUDIO_BITRATE=%d\nID_AUDIO_RATE=%d\n" "ID_AUDIO_NCH=%d\n",
	   sh_audio->i_bps * 8, sh_audio->samplerate, sh_audio->channels);

    sh_audio->a_out_buffer_size = 0;
    sh_audio->a_out_buffer = NULL;
    sh_audio->a_out_buffer_len = 0;

    return 1;
}
Example #16
0
static int init(int rate,int channels,int format,int flags)
{
AudioStreamBasicDescription inDesc;
ComponentDescription desc;
Component comp;
AURenderCallbackStruct renderCallback;
OSStatus err;
UInt32 size, maxFrames, b_alive;
char *psz_name;
AudioDeviceID devid_def = 0;
int device_id, display_help = 0;

    const opt_t subopts[] = {
        {"device_id", OPT_ARG_INT,  &device_id,    NULL},
        {"help",      OPT_ARG_BOOL, &display_help, NULL},
        {NULL}
    };

    // set defaults
    device_id = 0;

    if (subopt_parse(ao_subdevice, subopts) != 0 || display_help) {
        print_help();
        if (!display_help)
            return 0;
    }

    ao_msg(MSGT_AO,MSGL_V, "init([%dHz][%dch][%s][%d])\n", rate, channels, af_fmt2str_short(format), flags);

    ao = calloc(1, sizeof(ao_coreaudio_t));

    ao->i_selected_dev = 0;
    ao->b_supports_digital = 0;
    ao->b_digital = 0;
    ao->b_muted = 0;
    ao->b_stream_format_changed = 0;
    ao->i_hog_pid = -1;
    ao->i_stream_id = 0;
    ao->i_stream_index = -1;
    ao->b_revert = 0;
    ao->b_changed_mixing = 0;

    if (device_id == 0) {
        /* Find the ID of the default Device. */
        err = GetAudioProperty(kAudioObjectSystemObject,
                               kAudioHardwarePropertyDefaultOutputDevice,
                               sizeof(UInt32), &devid_def);
        if (err != noErr)
        {
            ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device: [%4.4s]\n", (char *)&err);
            goto err_out;
        }
    } else {
        devid_def = device_id;
    }

    /* Retrieve the name of the device. */
    err = GetAudioPropertyString(devid_def,
                                 kAudioObjectPropertyName,
                                 &psz_name);
    if (err != noErr)
    {
        ao_msg(MSGT_AO, MSGL_WARN, "could not get default audio device name: [%4.4s]\n", (char *)&err);
        goto err_out;
    }

    ao_msg(MSGT_AO,MSGL_V, "got audio output device ID: %"PRIu32" Name: %s\n", devid_def, psz_name );

    /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
    if (AF_FORMAT_IS_AC3(format)) {
        if (AudioDeviceSupportsDigital(devid_def))
        {
            ao->b_supports_digital = 1;
        }
        ao_msg(MSGT_AO, MSGL_V,
               "probe default audio output device about support for digital s/pdif output: %d\n",
               ao->b_supports_digital );
    }

    free(psz_name);

    // Save selected device id
    ao->i_selected_dev = devid_def;

	// Build Description for the input format
	inDesc.mSampleRate=rate;
	inDesc.mFormatID=ao->b_supports_digital ? kAudioFormat60958AC3 : kAudioFormatLinearPCM;
	inDesc.mChannelsPerFrame=channels;
	inDesc.mBitsPerChannel=af_fmt2bits(format);

    if((format&AF_FORMAT_POINT_MASK)==AF_FORMAT_F) {
	// float
		inDesc.mFormatFlags = kAudioFormatFlagIsFloat|kAudioFormatFlagIsPacked;
    }
    else if((format&AF_FORMAT_SIGN_MASK)==AF_FORMAT_SI) {
	// signed int
		inDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger|kAudioFormatFlagIsPacked;
    }
    else {
	// unsigned int
		inDesc.mFormatFlags = kAudioFormatFlagIsPacked;
    }
    if ((format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
        inDesc.mFormatFlags |= kAudioFormatFlagIsBigEndian;

    inDesc.mFramesPerPacket = 1;
    ao->packetSize = inDesc.mBytesPerPacket = inDesc.mBytesPerFrame = inDesc.mFramesPerPacket*channels*(inDesc.mBitsPerChannel/8);
    print_format(MSGL_V, "source:",&inDesc);

    if (ao->b_supports_digital)
    {
        b_alive = 1;
        err = GetAudioProperty(ao->i_selected_dev,
                               kAudioDevicePropertyDeviceIsAlive,
                               sizeof(UInt32), &b_alive);
        if (err != noErr)
            ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is alive: [%4.4s]\n", (char *)&err);
        if (!b_alive)
            ao_msg(MSGT_AO, MSGL_WARN, "device is not alive\n" );

        /* S/PDIF output need device in HogMode. */
        err = GetAudioProperty(ao->i_selected_dev,
                               kAudioDevicePropertyHogMode,
                               sizeof(pid_t), &ao->i_hog_pid);
        if (err != noErr)
        {
            /* This is not a fatal error. Some drivers simply don't support this property. */
            ao_msg(MSGT_AO, MSGL_WARN, "could not check whether device is hogged: [%4.4s]\n",
                     (char *)&err);
            ao->i_hog_pid = -1;
        }

        if (ao->i_hog_pid != -1 && ao->i_hog_pid != getpid())
        {
            ao_msg(MSGT_AO, MSGL_WARN, "Selected audio device is exclusively in use by another program.\n" );
            goto err_out;
        }
        ao->stream_format = inDesc;
        return OpenSPDIF();
    }

	/* original analog output code */
	desc.componentType = kAudioUnitType_Output;
	desc.componentSubType = (device_id == 0) ? kAudioUnitSubType_DefaultOutput : kAudioUnitSubType_HALOutput;
	desc.componentManufacturer = kAudioUnitManufacturer_Apple;
	desc.componentFlags = 0;
	desc.componentFlagsMask = 0;

	comp = FindNextComponent(NULL, &desc);  //Finds an component that meets the desc spec's
	if (comp == NULL) {
		ao_msg(MSGT_AO, MSGL_WARN, "Unable to find Output Unit component\n");
		goto err_out;
	}

	err = OpenAComponent(comp, &(ao->theOutputUnit));  //gains access to the services provided by the component
	if (err) {
		ao_msg(MSGT_AO, MSGL_WARN, "Unable to open Output Unit component: [%4.4s]\n", (char *)&err);
		goto err_out;
	}

	// Initialize AudioUnit
	err = AudioUnitInitialize(ao->theOutputUnit);
	if (err) {
		ao_msg(MSGT_AO, MSGL_WARN, "Unable to initialize Output Unit component: [%4.4s]\n", (char *)&err);
		goto err_out1;
	}

	size =  sizeof(AudioStreamBasicDescription);
	err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &inDesc, size);

	if (err) {
		ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the input format: [%4.4s]\n", (char *)&err);
		goto err_out2;
	}

	size = sizeof(UInt32);
	err = AudioUnitGetProperty(ao->theOutputUnit, kAudioDevicePropertyBufferSize, kAudioUnitScope_Input, 0, &maxFrames, &size);

	if (err)
	{
		ao_msg(MSGT_AO,MSGL_WARN, "AudioUnitGetProperty returned [%4.4s] when getting kAudioDevicePropertyBufferSize\n", (char *)&err);
		goto err_out2;
	}

	//Set the Current Device to the Default Output Unit.
    err = AudioUnitSetProperty(ao->theOutputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &ao->i_selected_dev, sizeof(ao->i_selected_dev));

	ao->chunk_size = maxFrames;//*inDesc.mBytesPerFrame;

	ao_data.samplerate = inDesc.mSampleRate;
	ao_data.channels = inDesc.mChannelsPerFrame;
    ao_data.bps = ao_data.samplerate * inDesc.mBytesPerFrame;
    ao_data.outburst = ao->chunk_size;
	ao_data.buffersize = ao_data.bps;

	ao->num_chunks = (ao_data.bps+ao->chunk_size-1)/ao->chunk_size;
    ao->buffer_len = ao->num_chunks * ao->chunk_size;
    ao->buffer = av_fifo_alloc(ao->buffer_len);

	ao_msg(MSGT_AO,MSGL_V, "using %5d chunks of %d bytes (buffer len %d bytes)\n", (int)ao->num_chunks, (int)ao->chunk_size, (int)ao->buffer_len);

    renderCallback.inputProc = theRenderProc;
    renderCallback.inputProcRefCon = 0;
    err = AudioUnitSetProperty(ao->theOutputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &renderCallback, sizeof(AURenderCallbackStruct));
	if (err) {
		ao_msg(MSGT_AO, MSGL_WARN, "Unable to set the render callback: [%4.4s]\n", (char *)&err);
		goto err_out2;
	}

	reset();

    return CONTROL_OK;

err_out2:
    AudioUnitUninitialize(ao->theOutputUnit);
err_out1:
    CloseComponent(ao->theOutputUnit);
err_out:
    av_fifo_free(ao->buffer);
    free(ao);
    ao = NULL;
    return CONTROL_FALSE;
}
// open & setup audio device
// return: 1=success 0=fail
static int init(int rate, int channels, int format, int flags) {

  int smpwidth, smpfmt;
  int rv = AL_DEFAULT_OUTPUT;

  smpfmt = fmt2sgial(&format, &smpwidth);

  mp_msg(MSGT_AO, MSGL_INFO, MSGTR_AO_SGI_InitInfo, rate, (channels > 1) ? "Stereo" : "Mono", af_fmt2str_short(format));

  { /* from /usr/share/src/dmedia/audio/setrate.c */

    double frate, realrate;
    ALpv x[2];

    if(ao_subdevice) {
      rv = alGetResourceByName(AL_SYSTEM, ao_subdevice, AL_OUTPUT_DEVICE_TYPE);
      if (!rv) {
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_SGI_InvalidDevice);
	return 0;
      }
    }

    frate = rate;

    x[0].param = AL_RATE;
    x[0].value.ll = alDoubleToFixed(rate);
    x[1].param = AL_MASTER_CLOCK;
    x[1].value.i = AL_CRYSTAL_MCLK_TYPE;

    if (alSetParams(rv,x, 2)<0) {
      mp_msg(MSGT_AO, MSGL_WARN, MSGTR_AO_SGI_CantSetParms_Samplerate, alGetErrorString(oserror()));
    }

    if (x[0].sizeOut < 0) {
      mp_msg(MSGT_AO, MSGL_WARN, MSGTR_AO_SGI_CantSetAlRate);
    }

    if (alGetParams(rv,x, 1)<0) {
      mp_msg(MSGT_AO, MSGL_WARN, MSGTR_AO_SGI_CantGetParms, alGetErrorString(oserror()));
    }

    realrate = alFixedToDouble(x[0].value.ll);
    if (frate != realrate) {
      mp_msg(MSGT_AO, MSGL_INFO, MSGTR_AO_SGI_SampleRateInfo, realrate, frate);
    }
    sample_rate = (int)realrate;
  }

  bytes_per_frame = channels * smpwidth;

  ao_data.samplerate = sample_rate;
  ao_data.channels = channels;
  ao_data.format = format;
  ao_data.bps = sample_rate * bytes_per_frame;
  ao_data.buffersize=131072;
  ao_data.outburst = ao_data.buffersize/16;

  ao_config = alNewConfig();

  if (!ao_config) {
    mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_SGI_InitConfigError, alGetErrorString(oserror()));
    return 0;
  }

  if(alSetChannels(ao_config, channels) < 0 ||
     alSetWidth(ao_config, smpwidth) < 0 ||
     alSetSampFmt(ao_config, smpfmt) < 0 ||
     alSetQueueSize(ao_config, sample_rate) < 0 ||
     alSetDevice(ao_config, rv) < 0) {
    mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_SGI_InitConfigError, alGetErrorString(oserror()));
    return 0;
  }

  ao_port = alOpenPort("mplayer", "w", ao_config);

  if (!ao_port) {
    mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_SGI_InitOpenAudioFailed, alGetErrorString(oserror()));
    return 0;
  }

  // printf("ao_sgi, init: port %d config %d\n", ao_port, ao_config);
  queue_size = alGetQueueSize(ao_config);
  return 1;

}
Example #18
0
/**
\brief setup sound device
\param rate samplerate
\param channels number of channels
\param format format
\param flags unused
\return 0=success -1=fail
*/
static int init(struct ao *ao)
{
    struct priv *p = ao->priv;
    int res;

    if (!InitDirectSound(ao))
        return -1;

    ao->no_persistent_volume = true;
    p->audio_volume = 100;

    // ok, now create the buffers
    WAVEFORMATEXTENSIBLE wformat;
    DSBUFFERDESC dsbpridesc;
    DSBUFFERDESC dsbdesc;
    int format = ao->format;
    int rate = ao->samplerate;

    if (AF_FORMAT_IS_AC3(format))
        format = AF_FORMAT_AC3_NE;
    else {
        struct mp_chmap_sel sel = {0};
        mp_chmap_sel_add_waveext(&sel);
        if (!ao_chmap_sel_adjust(ao, &sel, &ao->channels))
            return -1;
    }
    switch (format) {
    case AF_FORMAT_AC3_NE:
    case AF_FORMAT_S24_LE:
    case AF_FORMAT_S16_LE:
    case AF_FORMAT_U8:
        break;
    default:
        MP_VERBOSE(ao, "format %s not supported defaulting to Signed 16-bit Little-Endian\n",
                   af_fmt2str_short(format));
        format = AF_FORMAT_S16_LE;
    }
    //set our audio parameters
    ao->samplerate = rate;
    ao->format = format;
    ao->bps = ao->channels.num * rate * (af_fmt2bits(format) >> 3);
    int buffersize = ao->bps; // space for 1 sec
    MP_VERBOSE(ao, "Samplerate:%iHz Channels:%i Format:%s\n", rate,
               ao->channels.num, af_fmt2str_short(format));
    MP_VERBOSE(ao, "Buffersize:%d bytes (%d msec)\n",
               buffersize, buffersize / ao->bps * 1000);

    //fill waveformatex
    ZeroMemory(&wformat, sizeof(WAVEFORMATEXTENSIBLE));
    wformat.Format.cbSize = (ao->channels.num > 2)
                            ? sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) : 0;
    wformat.Format.nChannels = ao->channels.num;
    wformat.Format.nSamplesPerSec = rate;
    if (AF_FORMAT_IS_AC3(format)) {
        wformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
        wformat.Format.wBitsPerSample = 16;
        wformat.Format.nBlockAlign = 4;
    } else {
        wformat.Format.wFormatTag = (ao->channels.num > 2)
                                    ? WAVE_FORMAT_EXTENSIBLE : WAVE_FORMAT_PCM;
        wformat.Format.wBitsPerSample = af_fmt2bits(format);
        wformat.Format.nBlockAlign = wformat.Format.nChannels *
                                     (wformat.Format.wBitsPerSample >> 3);
    }

    // fill in primary sound buffer descriptor
    memset(&dsbpridesc, 0, sizeof(DSBUFFERDESC));
    dsbpridesc.dwSize = sizeof(DSBUFFERDESC);
    dsbpridesc.dwFlags       = DSBCAPS_PRIMARYBUFFER;
    dsbpridesc.dwBufferBytes = 0;
    dsbpridesc.lpwfxFormat   = NULL;

    // fill in the secondary sound buffer (=stream buffer) descriptor
    memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 /** Better position accuracy */
                      | DSBCAPS_GLOBALFOCUS       /** Allows background playing */
                      | DSBCAPS_CTRLVOLUME;       /** volume control enabled */

    if (ao->channels.num > 2) {
        wformat.dwChannelMask = mp_chmap_to_waveext(&ao->channels);
        wformat.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
        wformat.Samples.wValidBitsPerSample = wformat.Format.wBitsPerSample;
        // Needed for 5.1 on emu101k - shit soundblaster
        dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE;
    }
    wformat.Format.nAvgBytesPerSec = wformat.Format.nSamplesPerSec *
                                     wformat.Format.nBlockAlign;

    dsbdesc.dwBufferBytes = buffersize;
    dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&wformat;
    p->buffer_size = dsbdesc.dwBufferBytes;
    p->write_offset = 0;
    p->min_free_space = wformat.Format.nBlockAlign;
    p->outburst = wformat.Format.nBlockAlign * 512;

    // create primary buffer and set its format

    res = IDirectSound_CreateSoundBuffer(p->hds, &dsbpridesc, &p->hdspribuf, NULL);
    if (res != DS_OK) {
        UninitDirectSound(ao);
        MP_ERR(ao, "cannot create primary buffer (%s)\n", dserr2str(res));
        return -1;
    }
    res = IDirectSoundBuffer_SetFormat(p->hdspribuf, (WAVEFORMATEX *)&wformat);
    if (res != DS_OK) {
        MP_WARN(ao, "cannot set primary buffer format (%s), using "
                "standard setting (bad quality)", dserr2str(res));
    }

    MP_VERBOSE(ao, "primary buffer created\n");

    // now create the stream buffer

    res = IDirectSound_CreateSoundBuffer(p->hds, &dsbdesc, &p->hdsbuf, NULL);
    if (res != DS_OK) {
        if (dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE) {
            // Try without DSBCAPS_LOCHARDWARE
            dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE;
            res = IDirectSound_CreateSoundBuffer(p->hds, &dsbdesc, &p->hdsbuf, NULL);
        }
        if (res != DS_OK) {
            UninitDirectSound(ao);
            MP_ERR(ao, "cannot create secondary (stream)buffer (%s)\n",
                   dserr2str(res));
            return -1;
        }
    }
    MP_VERBOSE(ao, "secondary (stream)buffer created\n");
    return 0;
}
Example #19
0
// open & setup audio device
// return: 1=success 0=fail
static int init(int rate,int channels,int format,int flags){

    audio_info_t info;
    int pass;
    int ok;
    int convert_u8_s8;

    setup_device_paths();

    if (enable_sample_timing == RTSC_UNKNOWN
	&& !getenv("AO_SUN_DISABLE_SAMPLE_TIMING")) {
	enable_sample_timing = realtime_samplecounter_available(audio_dev);
    }

    mp_msg(MSGT_AO,MSGL_STATUS,"ao2: %d Hz  %d chans  %s [0x%X]\n",
	   rate,channels,af_fmt2str_short(format),format);

    audio_fd=open(audio_dev, O_WRONLY);
    if(audio_fd<0){
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_SUN_CantOpenAudioDev, audio_dev, strerror(errno));
	return 0;
    }

    if (af2sunfmt(format) == AUDIO_ENCODING_NONE)
      format = AF_FORMAT_S16_NE;

    for (ok = pass = 0; pass <= 5; pass++) { /* pass 6&7 not useful */

	AUDIO_INITINFO(&info);
	info.play.encoding = af2sunfmt(ao_data.format = format);
	info.play.precision =
	    (format==AF_FORMAT_S16_NE
	     ? AUDIO_PRECISION_16
	     : AUDIO_PRECISION_8);
	info.play.channels = ao_data.channels = channels;
	info.play.sample_rate = ao_data.samplerate = rate;

	convert_u8_s8 = 0;

	if (pass & 1) {
	    /*
	     * on some sun audio drivers, 8-bit unsigned LINEAR8 encoding is
	     * not supported, but 8-bit signed encoding is.
	     *
	     * Try S8, and if it works, use our own U8->S8 conversion before
	     * sending the samples to the sound driver.
	     */
#ifdef AUDIO_ENCODING_LINEAR8
	    if (info.play.encoding != AUDIO_ENCODING_LINEAR8)
#endif
		continue;
	    info.play.encoding = AUDIO_ENCODING_LINEAR;
	    convert_u8_s8 = 1;
	}

	if (pass & 2) {
	    /*
	     * on some sun audio drivers, only certain fixed sample rates are
	     * supported.
	     *
	     * In case the requested sample rate is very close to one of the
	     * supported rates,  use the fixed supported rate instead.
	     */
	    if (!(info.play.sample_rate =
		  find_close_samplerate_match(audio_fd, rate)))
	      continue;

	    /*
	     * I'm not returning the correct sample rate in
	     * |ao_data.samplerate|, to avoid software resampling.
	     *
	     * ao_data.samplerate = info.play.sample_rate;
	     */
	}

	if (pass & 4) {
	    /* like "pass & 2", but use the highest supported sample rate */
	    if (!(info.play.sample_rate
		  = ao_data.samplerate
		  = find_highest_samplerate(audio_fd)))
		continue;
	}

	ok = ioctl(audio_fd, AUDIO_SETINFO, &info) >= 0;
	if (ok) {
	    /* audio format accepted by audio driver */
	    break;
	}

	/*
	 * format not supported?
	 * retry with different encoding and/or sample rate
	 */
    }

    if (!ok) {
	char buf[128];
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_SUN_UnsupSampleRate,
	       channels, af_fmt2str(format, buf, 128), rate);
	return 0;
    }

    if (convert_u8_s8)
      ao_data.format = AF_FORMAT_S8;

    bytes_per_sample = channels * info.play.precision / 8;
    ao_data.bps = byte_per_sec = bytes_per_sample * ao_data.samplerate;
    ao_data.outburst = byte_per_sec > 100000 ? 16384 : 8192;

    reset();

    return 1;
}
Example #20
0
/*
    open & setup audio device
    return: 1=success 0=fail
*/
static int init(int rate_hz, int channels, int format, int flags)
{
    int err;
    int cards = -1;
    snd_pcm_channel_params_t params;
    snd_pcm_channel_setup_t setup;
    snd_pcm_info_t info;
    snd_pcm_channel_info_t chninfo;

    mp_msg(MSGT_AO, MSGL_INFO, MSGTR_AO_ALSA5_InitInfo, rate_hz,
	channels, af_fmt2str_short(format));

    alsa_handler = NULL;

    mp_msg(MSGT_AO, MSGL_V, "alsa-init: compiled for ALSA-%s (%d)\n", SND_LIB_VERSION_STR,
        SND_LIB_VERSION);

    if ((cards = snd_cards()) < 0)
    {
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_ALSA5_SoundCardNotFound);
	return 0;
    }

    ao_data.format = format;
    ao_data.channels = channels;
    ao_data.samplerate = rate_hz;
    ao_data.bps = ao_data.samplerate*ao_data.channels;
    ao_data.outburst = OUTBURST;
    ao_data.buffersize = 16384;

    memset(&alsa_format, 0, sizeof(alsa_format));
    switch (format)
    {
	case AF_FORMAT_S8:
	    alsa_format.format = SND_PCM_SFMT_S8;
	    break;
	case AF_FORMAT_U8:
	    alsa_format.format = SND_PCM_SFMT_U8;
	    break;
	case AF_FORMAT_U16_LE:
	    alsa_format.format = SND_PCM_SFMT_U16_LE;
	    break;
	case AF_FORMAT_U16_BE:
	    alsa_format.format = SND_PCM_SFMT_U16_BE;
	    break;
	case AF_FORMAT_AC3_LE:
	case AF_FORMAT_S16_LE:
	    alsa_format.format = SND_PCM_SFMT_S16_LE;
	    break;
	case AF_FORMAT_AC3_BE:
	case AF_FORMAT_S16_BE:
	    alsa_format.format = SND_PCM_SFMT_S16_BE;
	    break;
	default:
	    alsa_format.format = SND_PCM_SFMT_MPEG;
	    break;
    }

    switch(alsa_format.format)
    {
	case SND_PCM_SFMT_S16_LE:
	case SND_PCM_SFMT_U16_LE:
	    ao_data.bps *= 2;
	    break;
	case -1:
	    mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_ALSA5_InvalidFormatReq,af_fmt2str_short(format));
	    return 0;
	default:
	    break;
    }

    switch(rate_hz)
    {
	case 8000:
	    alsa_rate = SND_PCM_RATE_8000;
	    break;
	case 11025:
	    alsa_rate = SND_PCM_RATE_11025;
	    break;
	case 16000:
	    alsa_rate = SND_PCM_RATE_16000;
	    break;
	case 22050:
	    alsa_rate = SND_PCM_RATE_22050;
	    break;
	case 32000:
	    alsa_rate = SND_PCM_RATE_32000;
	    break;
	case 44100:
	    alsa_rate = SND_PCM_RATE_44100;
	    break;
	case 48000:
	    alsa_rate = SND_PCM_RATE_48000;
	    break;
	case 88200:
	    alsa_rate = SND_PCM_RATE_88200;
	    break;
	case 96000:
	    alsa_rate = SND_PCM_RATE_96000;
	    break;
	case 176400:
	    alsa_rate = SND_PCM_RATE_176400;
	    break;
	case 192000:
	    alsa_rate = SND_PCM_RATE_192000;
	    break;
	default:
	    alsa_rate = SND_PCM_RATE_CONTINUOUS;
	    break;
    }

    alsa_format.rate = ao_data.samplerate;
    alsa_format.voices = ao_data.channels;
    alsa_format.interleave = 1;

    if ((err = snd_pcm_open(&alsa_handler, 0, 0, SND_PCM_OPEN_PLAYBACK)) < 0)
    {
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_ALSA5_PlayBackError, snd_strerror(err));
	return 0;
    }

    if ((err = snd_pcm_info(alsa_handler, &info)) < 0)
    {
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_ALSA5_PcmInfoError, snd_strerror(err));
	return 0;
    }

    mp_msg(MSGT_AO, MSGL_INFO, MSGTR_AO_ALSA5_SoundcardsFound,
	cards, info.name);

    if (info.flags & SND_PCM_INFO_PLAYBACK)
    {
	memset(&chninfo, 0, sizeof(chninfo));
	chninfo.channel = SND_PCM_CHANNEL_PLAYBACK;
	if ((err = snd_pcm_channel_info(alsa_handler, &chninfo)) < 0)
	{
	    mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_ALSA5_PcmChanInfoError, snd_strerror(err));
	    return 0;
	}

#ifndef __QNX__
	if (chninfo.buffer_size)
	    ao_data.buffersize = chninfo.buffer_size;
#endif

	mp_msg(MSGT_AO, MSGL_V, "alsa-init: setting preferred buffer size from driver: %d bytes\n",
	    ao_data.buffersize);
    }

    memset(&params, 0, sizeof(params));
    params.channel = SND_PCM_CHANNEL_PLAYBACK;
    params.mode = SND_PCM_MODE_STREAM;
    params.format = alsa_format;
    params.start_mode = SND_PCM_START_DATA;
    params.stop_mode = SND_PCM_STOP_ROLLOVER;
    params.buf.stream.queue_size = ao_data.buffersize;
    params.buf.stream.fill = SND_PCM_FILL_NONE;

    if ((err = snd_pcm_channel_params(alsa_handler, &params)) < 0)
    {
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_ALSA5_CantSetParms, snd_strerror(err));
	return 0;
    }

    memset(&setup, 0, sizeof(setup));
    setup.channel = SND_PCM_CHANNEL_PLAYBACK;
    setup.mode = SND_PCM_MODE_STREAM;
    setup.format = alsa_format;
    setup.buf.stream.queue_size = ao_data.buffersize;
    setup.msbits_per_sample = ao_data.bps;

    if ((err = snd_pcm_channel_setup(alsa_handler, &setup)) < 0)
    {
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_ALSA5_CantSetChan, snd_strerror(err));
	return 0;
    }

    if ((err = snd_pcm_channel_prepare(alsa_handler, SND_PCM_CHANNEL_PLAYBACK)) < 0)
    {
	mp_msg(MSGT_AO, MSGL_ERR, MSGTR_AO_ALSA5_ChanPrepareError, snd_strerror(err));
	return 0;
    }

    mp_msg(MSGT_AO, MSGL_INFO, "AUDIO: %d Hz/%d channels/%d bps/%d bytes buffer/%s\n",
	ao_data.samplerate, ao_data.channels, ao_data.bps, ao_data.buffersize,
	snd_pcm_get_format_name(alsa_format.format));
    return 1;
}
Example #21
0
/*
    open & setup audio device
    return: 1=success 0=fail
*/
static int init(int rate_hz, int channels, int format, int flags)
{
    unsigned int alsa_buffer_time = 500000; /* 0.5 s */
    unsigned int alsa_fragcount = 16;
    int err;
    int block;
    strarg_t device;
    snd_pcm_uframes_t chunk_size;
    snd_pcm_uframes_t bufsize;
    snd_pcm_uframes_t boundary;
    const opt_t subopts[] = {
      {"block", OPT_ARG_BOOL, &block, NULL},
      {"device", OPT_ARG_STR, &device, str_maxlen},
      {NULL}
    };

    char alsa_device[ALSA_DEVICE_SIZE + 1];
    // make sure alsa_device is null-terminated even when using strncpy etc.
    memset(alsa_device, 0, ALSA_DEVICE_SIZE + 1);

    mp_msg(MSGT_AO,MSGL_V,"alsa-init: requested format: %d Hz, %d channels, %x\n", rate_hz,
	channels, format);
    alsa_handler = NULL;
#if SND_LIB_VERSION >= 0x010005
    mp_msg(MSGT_AO,MSGL_V,"alsa-init: using ALSA %s\n", snd_asoundlib_version());
#else
    mp_msg(MSGT_AO,MSGL_V,"alsa-init: compiled for ALSA-%s\n", SND_LIB_VERSION_STR);
#endif

    snd_lib_error_set_handler(alsa_error_handler);

    ao_data.samplerate = rate_hz;
    ao_data.format = format;
    ao_data.channels = channels;

    switch (format)
      {
      case AF_FORMAT_S8:
	alsa_format = SND_PCM_FORMAT_S8;
	break;
      case AF_FORMAT_U8:
	alsa_format = SND_PCM_FORMAT_U8;
	break;
      case AF_FORMAT_U16_LE:
	alsa_format = SND_PCM_FORMAT_U16_LE;
	break;
      case AF_FORMAT_U16_BE:
	alsa_format = SND_PCM_FORMAT_U16_BE;
	break;
      case AF_FORMAT_AC3_LE:
      case AF_FORMAT_S16_LE:
      case AF_FORMAT_IEC61937_LE:
	alsa_format = SND_PCM_FORMAT_S16_LE;
	break;
      case AF_FORMAT_AC3_BE:
      case AF_FORMAT_S16_BE:
      case AF_FORMAT_IEC61937_BE:
	alsa_format = SND_PCM_FORMAT_S16_BE;
	break;
      case AF_FORMAT_U32_LE:
	alsa_format = SND_PCM_FORMAT_U32_LE;
	break;
      case AF_FORMAT_U32_BE:
	alsa_format = SND_PCM_FORMAT_U32_BE;
	break;
      case AF_FORMAT_S32_LE:
	alsa_format = SND_PCM_FORMAT_S32_LE;
	break;
      case AF_FORMAT_S32_BE:
	alsa_format = SND_PCM_FORMAT_S32_BE;
	break;
      case AF_FORMAT_U24_LE:
	alsa_format = SND_PCM_FORMAT_U24_3LE;
	break;
      case AF_FORMAT_U24_BE:
	alsa_format = SND_PCM_FORMAT_U24_3BE;
	break;
      case AF_FORMAT_S24_LE:
	alsa_format = SND_PCM_FORMAT_S24_3LE;
	break;
      case AF_FORMAT_S24_BE:
	alsa_format = SND_PCM_FORMAT_S24_3BE;
	break;
      case AF_FORMAT_FLOAT_LE:
	alsa_format = SND_PCM_FORMAT_FLOAT_LE;
	break;
      case AF_FORMAT_FLOAT_BE:
	alsa_format = SND_PCM_FORMAT_FLOAT_BE;
	break;
      case AF_FORMAT_MU_LAW:
	alsa_format = SND_PCM_FORMAT_MU_LAW;
	break;
      case AF_FORMAT_A_LAW:
	alsa_format = SND_PCM_FORMAT_A_LAW;
	break;

      default:
	alsa_format = SND_PCM_FORMAT_MPEG; //? default should be -1
	break;
      }

    //subdevice parsing
    // set defaults
    block = 1;
    /* switch for spdif
     * sets opening sequence for SPDIF
     * sets also the playback and other switches 'on the fly'
     * while opening the abstract alias for the spdif subdevice
     * 'iec958'
     */
    if (AF_FORMAT_IS_IEC61937(format)) {
	device.str = "iec958";
	mp_msg(MSGT_AO,MSGL_V,"alsa-spdif-init: playing AC3/iec61937/iec958, %i channels\n", channels);
    }
  else
        /* in any case for multichannel playback we should select
         * appropriate device
         */
        switch (channels) {
	case 1:
	case 2:
	  device.str = "default";
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: setup for 1/2 channel(s)\n");
	  break;
	case 4:
	  if (alsa_format == SND_PCM_FORMAT_FLOAT_LE)
	    // hack - use the converter plugin
	    device.str = "plug:surround40";
	  else
	    device.str = "surround40";
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: device set to surround40\n");
	  break;
	case 6:
	  if (alsa_format == SND_PCM_FORMAT_FLOAT_LE)
	    device.str = "plug:surround51";
	  else
	    device.str = "surround51";
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: device set to surround51\n");
	  break;
	case 8:
	  if (alsa_format == SND_PCM_FORMAT_FLOAT_LE)
	    device.str = "plug:surround71";
	  else
	    device.str = "surround71";
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: device set to surround71\n");
	  break;
	default:
	  device.str = "default";
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_ChannelsNotSupported,channels);
        }
    device.len = strlen(device.str);
    if (subopt_parse(ao_subdevice, subopts) != 0) {
        print_help();
        return 0;
    }
    parse_device(alsa_device, device.str, device.len);

    mp_msg(MSGT_AO,MSGL_V,"alsa-init: using device %s\n", alsa_device);

    if (!alsa_handler) {
      int open_mode = block ? 0 : SND_PCM_NONBLOCK;
      int isac3 =  AF_FORMAT_IS_IEC61937(format);
      //modes = 0, SND_PCM_NONBLOCK, SND_PCM_ASYNC
      mp_msg(MSGT_AO,MSGL_V,"alsa-init: opening device in %sblocking mode\n", block ? "" : "non-");
      if ((err = try_open_device(alsa_device, open_mode, isac3)) < 0)
	{
	  if (err != -EBUSY && !block) {
	    mp_msg(MSGT_AO,MSGL_INFO,MSGTR_AO_ALSA_OpenInNonblockModeFailed);
	    if ((err = try_open_device(alsa_device, 0, isac3)) < 0) {
	      mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_PlaybackOpenError, snd_strerror(err));
	      return 0;
	    }
	  } else {
	    mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_PlaybackOpenError, snd_strerror(err));
	    return 0;
	  }
	}

      if ((err = snd_pcm_nonblock(alsa_handler, 0)) < 0) {
         mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_ErrorSetBlockMode, snd_strerror(err));
      } else {
	mp_msg(MSGT_AO,MSGL_V,"alsa-init: device reopened in blocking mode\n");
      }

      snd_pcm_hw_params_alloca(&alsa_hwparams);
      snd_pcm_sw_params_alloca(&alsa_swparams);

      // setting hw-parameters
      if ((err = snd_pcm_hw_params_any(alsa_handler, alsa_hwparams)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetInitialParameters,
		 snd_strerror(err));
	  return 0;
	}

      err = snd_pcm_hw_params_set_access(alsa_handler, alsa_hwparams,
					 SND_PCM_ACCESS_RW_INTERLEAVED);
      if (err < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetAccessType,
	       snd_strerror(err));
	return 0;
      }

      /* workaround for nonsupported formats
	 sets default format to S16_LE if the given formats aren't supported */
      if ((err = snd_pcm_hw_params_test_format(alsa_handler, alsa_hwparams,
                                             alsa_format)) < 0)
      {
         mp_msg(MSGT_AO,MSGL_INFO,
		MSGTR_AO_ALSA_FormatNotSupportedByHardware, af_fmt2str_short(format));
         alsa_format = SND_PCM_FORMAT_S16_LE;
         if (AF_FORMAT_IS_AC3(ao_data.format))
           ao_data.format = AF_FORMAT_AC3_LE;
         else if (AF_FORMAT_IS_IEC61937(ao_data.format))
           ao_data.format = AF_FORMAT_IEC61937_LE;
         else
         ao_data.format = AF_FORMAT_S16_LE;
      }

      if ((err = snd_pcm_hw_params_set_format(alsa_handler, alsa_hwparams,
					      alsa_format)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetFormat,
		 snd_strerror(err));
	  return 0;
	}

      if ((err = snd_pcm_hw_params_set_channels_near(alsa_handler, alsa_hwparams,
						     &ao_data.channels)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetChannels,
		 snd_strerror(err));
	  return 0;
	}

      /* workaround for buggy rate plugin (should be fixed in ALSA 1.0.11)
         prefer our own resampler, since that allows users to choose the resampler,
         even per file if desired */
#if SND_LIB_VERSION >= 0x010009
      if ((err = snd_pcm_hw_params_set_rate_resample(alsa_handler, alsa_hwparams,
						     0)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToDisableResampling,
		 snd_strerror(err));
	  return 0;
	}
#endif

      if ((err = snd_pcm_hw_params_set_rate_near(alsa_handler, alsa_hwparams,
						 &ao_data.samplerate, NULL)) < 0)
        {
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetSamplerate2,
		 snd_strerror(err));
	  return 0;
        }

      bytes_per_sample = af_fmt2bits(ao_data.format) / 8;
      bytes_per_sample *= ao_data.channels;
      ao_data.bps = ao_data.samplerate * bytes_per_sample;

	if ((err = snd_pcm_hw_params_set_buffer_time_near(alsa_handler, alsa_hwparams,
							  &alsa_buffer_time, NULL)) < 0)
	  {
	    mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetBufferTimeNear,
		   snd_strerror(err));
	    return 0;
	  }

	if ((err = snd_pcm_hw_params_set_periods_near(alsa_handler, alsa_hwparams,
						      &alsa_fragcount, NULL)) < 0) {
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetPeriods,
		 snd_strerror(err));
	  return 0;
	}

      /* finally install hardware parameters */
      if ((err = snd_pcm_hw_params(alsa_handler, alsa_hwparams)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetHwParameters,
		 snd_strerror(err));
	  return 0;
	}
      // end setting hw-params


      // gets buffersize for control
      if ((err = snd_pcm_hw_params_get_buffer_size(alsa_hwparams, &bufsize)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetBufferSize, snd_strerror(err));
	  return 0;
	}
      else {
	ao_data.buffersize = bufsize * bytes_per_sample;
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: got buffersize=%i\n", ao_data.buffersize);
      }

      if ((err = snd_pcm_hw_params_get_period_size(alsa_hwparams, &chunk_size, NULL)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetPeriodSize, snd_strerror(err));
	return 0;
      } else {
	mp_msg(MSGT_AO,MSGL_V,"alsa-init: got period size %li\n", chunk_size);
      }
      ao_data.outburst = chunk_size * bytes_per_sample;

      /* setting software parameters */
      if ((err = snd_pcm_sw_params_current(alsa_handler, alsa_swparams)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetSwParameters,
	       snd_strerror(err));
	return 0;
      }
#if SND_LIB_VERSION >= 0x000901
      if ((err = snd_pcm_sw_params_get_boundary(alsa_swparams, &boundary)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetBoundary,
	       snd_strerror(err));
	return 0;
      }
#else
      boundary = 0x7fffffff;
#endif
      /* start playing when one period has been written */
      if ((err = snd_pcm_sw_params_set_start_threshold(alsa_handler, alsa_swparams, chunk_size)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetStartThreshold,
	       snd_strerror(err));
	return 0;
      }
      /* disable underrun reporting */
      if ((err = snd_pcm_sw_params_set_stop_threshold(alsa_handler, alsa_swparams, boundary)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetStopThreshold,
	       snd_strerror(err));
	return 0;
      }
#if SND_LIB_VERSION >= 0x000901
      /* play silence when there is an underrun */
      if ((err = snd_pcm_sw_params_set_silence_size(alsa_handler, alsa_swparams, boundary)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetSilenceSize,
	       snd_strerror(err));
	return 0;
      }
#endif
      if ((err = snd_pcm_sw_params(alsa_handler, alsa_swparams)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetSwParameters,
	       snd_strerror(err));
	return 0;
      }
      /* end setting sw-params */

      mp_msg(MSGT_AO,MSGL_V,"alsa: %d Hz/%d channels/%d bpf/%d bytes buffer/%s\n",
	     ao_data.samplerate, ao_data.channels, (int)bytes_per_sample, ao_data.buffersize,
	     snd_pcm_format_description(alsa_format));

    } // end switch alsa_handler (spdif)
    alsa_can_pause = snd_pcm_hw_params_can_pause(alsa_hwparams);
    return 1;
} // end init
Example #22
0
// open & setup audio device
// return: 1=success 0=fail
static int init(int rate,int channels,int format,int flags){

	/* SDL Audio Specifications */
	SDL_AudioSpec aspec, obtained;
	
	/* Allocate ring-buffer memory */
	buffer = (unsigned char *) malloc(BUFFSIZE);

	mp_msg(MSGT_AO,MSGL_INFO,MSGTR_AO_SDL_INFO, rate, (channels > 1) ? "Stereo" : "Mono", af_fmt2str_short(format));

	if(ao_subdevice) {
		setenv("SDL_AUDIODRIVER", ao_subdevice, 1);
		mp_msg(MSGT_AO,MSGL_INFO,MSGTR_AO_SDL_DriverInfo, ao_subdevice);
	}

	ao_data.channels=channels;
	ao_data.samplerate=rate;
	ao_data.format=format;

	ao_data.bps=channels*rate;
	if(format != AF_FORMAT_U8 && format != AF_FORMAT_S8)
	  ao_data.bps*=2;
	
	/* The desired audio format (see SDL_AudioSpec) */
	switch(format) {
	    case AF_FORMAT_U8:
		aspec.format = AUDIO_U8;
	    break;
	    case AF_FORMAT_S16_LE:
		aspec.format = AUDIO_S16LSB;
	    break;
	    case AF_FORMAT_S16_BE:
		aspec.format = AUDIO_S16MSB;
	    break;
	    case AF_FORMAT_S8:
		aspec.format = AUDIO_S8;
	    break;
	    case AF_FORMAT_U16_LE:
		aspec.format = AUDIO_U16LSB;
	    break;
	    case AF_FORMAT_U16_BE:
		aspec.format = AUDIO_U16MSB;
	    break;
	    default:
                aspec.format = AUDIO_S16LSB;
                ao_data.format = AF_FORMAT_S16_LE;
                mp_msg(MSGT_AO,MSGL_WARN,MSGTR_AO_SDL_UnsupportedAudioFmt, format);
	}

	/* The desired audio frequency in samples-per-second. */
	aspec.freq     = rate;

	/* Number of channels (mono/stereo) */
	aspec.channels = channels;

	/* The desired size of the audio buffer in samples. This number should be a power of two, and may be adjusted by the audio driver to a value more suitable for the hardware. Good values seem to range between 512 and 8192 inclusive, depending on the application and CPU speed. Smaller values yield faster response time, but can lead to underflow if the application is doing heavy processing and cannot fill the audio buffer in time. A stereo sample consists of both right and left channels in LR ordering. Note that the number of samples is directly related to time by the following formula: ms = (samples*1000)/freq */
	aspec.samples  = SAMPLESIZE;

	/* This should be set to a function that will be called when the audio device is ready for more data. It is passed a pointer to the audio buffer, and the length in bytes of the audio buffer. This function usually runs in a separate thread, and so you should protect data structures that it accesses by calling SDL_LockAudio and SDL_UnlockAudio in your code. The callback prototype is:
void callback(void *userdata, Uint8 *stream, int len); userdata is the pointer stored in userdata field of the SDL_AudioSpec. stream is a pointer to the audio buffer you want to fill with information and len is the length of the audio buffer in bytes. */
	aspec.callback = outputaudio;

	/* This pointer is passed as the first parameter to the callback function. */
	aspec.userdata = NULL;

	/* initialize the SDL Audio system */
        if (SDL_Init (SDL_INIT_AUDIO/*|SDL_INIT_NOPARACHUTE*/)) {
                mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_SDL_CantInit, SDL_GetError());
                return 0;
        }

	/* Open the audio device and start playing sound! */
	if(SDL_OpenAudio(&aspec, &obtained) < 0) {
        	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_SDL_CantOpenAudio, SDL_GetError());
        	return(0);
	} 

	/* did we got what we wanted ? */
	ao_data.channels=obtained.channels;
	ao_data.samplerate=obtained.freq;

	switch(obtained.format) {
	    case AUDIO_U8 :
		ao_data.format = AF_FORMAT_U8;
	    break;
	    case AUDIO_S16LSB :
		ao_data.format = AF_FORMAT_S16_LE;
	    break;
	    case AUDIO_S16MSB :
		ao_data.format = AF_FORMAT_S16_BE;
	    break;
	    case AUDIO_S8 :
		ao_data.format = AF_FORMAT_S8;
	    break;
	    case AUDIO_U16LSB :
		ao_data.format = AF_FORMAT_U16_LE;
	    break;
	    case AUDIO_U16MSB :
		ao_data.format = AF_FORMAT_U16_BE;
	    break;
	    default:
                mp_msg(MSGT_AO,MSGL_WARN,MSGTR_AO_SDL_UnsupportedAudioFmt, obtained.format);
                return 0;
	}

	mp_msg(MSGT_AO,MSGL_V,"SDL: buf size = %d\n",obtained.size);
	ao_data.buffersize=obtained.size;
	ao_data.outburst = CHUNK_SIZE;
	
	reset();
	/* unsilence audio, if callback is ready */
	SDL_PauseAudio(0);

	return 1;
}