diff options
author | J. Alexander Treuman <jat@spatialrift.net> | 2007-05-28 13:09:41 +0000 |
---|---|---|
committer | J. Alexander Treuman <jat@spatialrift.net> | 2007-05-28 13:09:41 +0000 |
commit | 6e5c90e098005b66f86a9fd99a26956cbaa0c392 (patch) | |
tree | d5699855fe945b0b02e511c87def301d119ae922 /trunk/src/audioOutputs | |
parent | 28c7a91d2462128a7df9a417cbbd59cad89ba19b (diff) | |
download | mpd-6e5c90e098005b66f86a9fd99a26956cbaa0c392.tar.gz mpd-6e5c90e098005b66f86a9fd99a26956cbaa0c392.tar.xz mpd-6e5c90e098005b66f86a9fd99a26956cbaa0c392.zip |
Re-tagging 0.13.0 release to fix a couple of bugs with the tarball.
git-svn-id: https://svn.musicpd.org/mpd/tags/release-0.13.0@6325 09075e82-0dd4-0310-85a5-a0d7c8717e4f
Diffstat (limited to '')
-rw-r--r-- | trunk/src/audioOutputs/audioOutput_alsa.c | 427 | ||||
-rw-r--r-- | trunk/src/audioOutputs/audioOutput_ao.c | 246 | ||||
-rw-r--r-- | trunk/src/audioOutputs/audioOutput_jack.c | 440 | ||||
-rw-r--r-- | trunk/src/audioOutputs/audioOutput_mvp.c | 284 | ||||
-rw-r--r-- | trunk/src/audioOutputs/audioOutput_oss.c | 575 | ||||
-rw-r--r-- | trunk/src/audioOutputs/audioOutput_osx.c | 374 | ||||
-rw-r--r-- | trunk/src/audioOutputs/audioOutput_pulse.c | 221 | ||||
-rw-r--r-- | trunk/src/audioOutputs/audioOutput_shout.c | 636 |
8 files changed, 3203 insertions, 0 deletions
diff --git a/trunk/src/audioOutputs/audioOutput_alsa.c b/trunk/src/audioOutputs/audioOutput_alsa.c new file mode 100644 index 000000000..3ade3df46 --- /dev/null +++ b/trunk/src/audioOutputs/audioOutput_alsa.c @@ -0,0 +1,427 @@ +/* the Music Player Daemon (MPD) + * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com) + * This project's homepage is: http://www.musicpd.org + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "../audioOutput.h" + +#include <stdlib.h> + +#ifdef HAVE_ALSA + +#define ALSA_PCM_NEW_HW_PARAMS_API +#define ALSA_PCM_NEW_SW_PARAMS_API + +#define MPD_ALSA_BUFFER_TIME_US 500000 +/* the default period time of xmms is 50 ms, so let's use that as well. + * a user can tweak this parameter via the "period_time" config parameter. + */ +#define MPD_ALSA_PERIOD_TIME_US 50000 +#define MPD_ALSA_RETRY_NR 5 + +#include "../conf.h" +#include "../log.h" + +#include <string.h> + +#include <alsa/asoundlib.h> + +typedef snd_pcm_sframes_t alsa_writei_t(snd_pcm_t * pcm, const void *buffer, + snd_pcm_uframes_t size); + +typedef struct _AlsaData { + char *device; + snd_pcm_t *pcmHandle; + alsa_writei_t *writei; + unsigned int buffer_time; + unsigned int period_time; + int sampleSize; + int useMmap; + int canPause; + int canResume; +} AlsaData; + +static AlsaData *newAlsaData(void) +{ + AlsaData *ret = xmalloc(sizeof(AlsaData)); + + ret->device = NULL; + ret->pcmHandle = NULL; + ret->writei = snd_pcm_writei; + ret->useMmap = 0; + ret->buffer_time = MPD_ALSA_BUFFER_TIME_US; + ret->period_time = MPD_ALSA_PERIOD_TIME_US; + + return ret; +} + +static void freeAlsaData(AlsaData * ad) +{ + if (ad->device) + free(ad->device); + + free(ad); +} + +static int alsa_initDriver(AudioOutput * audioOutput, ConfigParam * param) +{ + AlsaData *ad = newAlsaData(); + + if (param) { + BlockParam *bp = getBlockParam(param, "device"); + ad->device = bp ? xstrdup(bp->value) : xstrdup("default"); + + if ((bp = getBlockParam(param, "use_mmap")) && + !strcasecmp(bp->value, "yes")) + ad->useMmap = 1; + if ((bp = getBlockParam(param, "buffer_time"))) + ad->buffer_time = atoi(bp->value); + if ((bp = getBlockParam(param, "period_time"))) + ad->period_time = atoi(bp->value); + } else + ad->device = xstrdup("default"); + audioOutput->data = ad; + + return 0; +} + +static void alsa_finishDriver(AudioOutput * audioOutput) +{ + AlsaData *ad = audioOutput->data; + + freeAlsaData(ad); +} + +static int alsa_testDefault(void) +{ + snd_pcm_t *handle; + + int ret = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, + SND_PCM_NONBLOCK); + snd_config_update_free_global(); + + if (ret) { + WARNING("Error opening default alsa device: %s\n", + snd_strerror(-ret)); + return -1; + } else + snd_pcm_close(handle); + + return 0; +} + +static int alsa_openDevice(AudioOutput * audioOutput) +{ + AlsaData *ad = audioOutput->data; + AudioFormat *audioFormat = &audioOutput->outAudioFormat; + snd_pcm_format_t bitformat; + snd_pcm_hw_params_t *hwparams; + snd_pcm_sw_params_t *swparams; + unsigned int sampleRate = audioFormat->sampleRate; + unsigned int channels = audioFormat->channels; + snd_pcm_uframes_t alsa_buffer_size; + snd_pcm_uframes_t alsa_period_size; + int err; + const char *cmd = NULL; + int retry = MPD_ALSA_RETRY_NR; + unsigned int period_time, period_time_ro; + unsigned int buffer_time; + + switch (audioFormat->bits) { + case 8: + bitformat = SND_PCM_FORMAT_S8; + break; + case 16: + bitformat = SND_PCM_FORMAT_S16; + break; + case 24: + bitformat = SND_PCM_FORMAT_S24; + break; + case 32: + bitformat = SND_PCM_FORMAT_S32; + break; + default: + ERROR("ALSA device \"%s\" doesn't support %i bit audio\n", + ad->device, audioFormat->bits); + return -1; + } + + err = snd_pcm_open(&ad->pcmHandle, ad->device, + SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); + snd_config_update_free_global(); + if (err < 0) { + ad->pcmHandle = NULL; + goto error; + } + + cmd = "snd_pcm_nonblock"; + err = snd_pcm_nonblock(ad->pcmHandle, 0); + if (err < 0) + goto error; + + period_time_ro = period_time = ad->period_time; +configure_hw: + /* configure HW params */ + snd_pcm_hw_params_alloca(&hwparams); + + cmd = "snd_pcm_hw_params_any"; + err = snd_pcm_hw_params_any(ad->pcmHandle, hwparams); + if (err < 0) + goto error; + + if (ad->useMmap) { + err = snd_pcm_hw_params_set_access(ad->pcmHandle, hwparams, + SND_PCM_ACCESS_MMAP_INTERLEAVED); + if (err < 0) { + ERROR("Cannot set mmap'ed mode on alsa device \"%s\": " + " %s\n", ad->device, snd_strerror(-err)); + ERROR("Falling back to direct write mode\n"); + ad->useMmap = 0; + } else + ad->writei = snd_pcm_mmap_writei; + } + + if (!ad->useMmap) { + cmd = "snd_pcm_hw_params_set_access"; + err = snd_pcm_hw_params_set_access(ad->pcmHandle, hwparams, + SND_PCM_ACCESS_RW_INTERLEAVED); + if (err < 0) + goto error; + ad->writei = snd_pcm_writei; + } + + err = snd_pcm_hw_params_set_format(ad->pcmHandle, hwparams, bitformat); + if (err < 0) { + ERROR("ALSA device \"%s\" does not support %i bit audio: " + "%s\n", ad->device, audioFormat->bits, snd_strerror(-err)); + goto fail; + } + + err = snd_pcm_hw_params_set_channels_near(ad->pcmHandle, hwparams, + &channels); + if (err < 0) { + ERROR("ALSA device \"%s\" does not support %i channels: " + "%s\n", ad->device, (int)audioFormat->channels, + snd_strerror(-err)); + goto fail; + } + audioFormat->channels = channels; + + err = snd_pcm_hw_params_set_rate_near(ad->pcmHandle, hwparams, + &sampleRate, NULL); + if (err < 0 || sampleRate == 0) { + ERROR("ALSA device \"%s\" does not support %i Hz audio\n", + ad->device, (int)audioFormat->sampleRate); + goto fail; + } + audioFormat->sampleRate = sampleRate; + + buffer_time = ad->buffer_time; + cmd = "snd_pcm_hw_params_set_buffer_time_near"; + err = snd_pcm_hw_params_set_buffer_time_near(ad->pcmHandle, hwparams, + &buffer_time, NULL); + if (err < 0) + goto error; + + period_time = period_time_ro; + cmd = "snd_pcm_hw_params_set_period_time_near"; + err = snd_pcm_hw_params_set_period_time_near(ad->pcmHandle, hwparams, + &period_time, NULL); + if (err < 0) + goto error; + + cmd = "snd_pcm_hw_params"; + err = snd_pcm_hw_params(ad->pcmHandle, hwparams); + if (err == -EPIPE && --retry > 0) { + period_time_ro = period_time_ro >> 1; + goto configure_hw; + } else if (err < 0) + goto error; + if (retry != MPD_ALSA_RETRY_NR) + DEBUG("ALSA period_time set to %d\n", period_time); + + cmd = "snd_pcm_hw_params_get_buffer_size"; + err = snd_pcm_hw_params_get_buffer_size(hwparams, &alsa_buffer_size); + if (err < 0) + goto error; + + cmd = "snd_pcm_hw_params_get_period_size"; + err = snd_pcm_hw_params_get_period_size(hwparams, &alsa_period_size, + NULL); + if (err < 0) + goto error; + + ad->canPause = snd_pcm_hw_params_can_pause(hwparams); + ad->canResume = snd_pcm_hw_params_can_resume(hwparams); + + /* configure SW params */ + snd_pcm_sw_params_alloca(&swparams); + + cmd = "snd_pcm_sw_params_current"; + err = snd_pcm_sw_params_current(ad->pcmHandle, swparams); + if (err < 0) + goto error; + + cmd = "snd_pcm_sw_params_set_start_threshold"; + err = snd_pcm_sw_params_set_start_threshold(ad->pcmHandle, swparams, + alsa_buffer_size - + alsa_period_size); + if (err < 0) + goto error; + + cmd = "snd_pcm_sw_params_set_avail_min"; + err = snd_pcm_sw_params_set_avail_min(ad->pcmHandle, swparams, + alsa_period_size); + if (err < 0) + goto error; + + cmd = "snd_pcm_sw_params_set_xfer_align"; + err = snd_pcm_sw_params_set_xfer_align(ad->pcmHandle, swparams, 1); + if (err < 0) + goto error; + + cmd = "snd_pcm_sw_params"; + err = snd_pcm_sw_params(ad->pcmHandle, swparams); + if (err < 0) + goto error; + + ad->sampleSize = (audioFormat->bits / 8) * audioFormat->channels; + + audioOutput->open = 1; + + DEBUG("alsa device \"%s\" will be playing %i bit, %i channel audio at " + "%i Hz\n", ad->device, (int)audioFormat->bits, + channels, sampleRate); + + return 0; + +error: + if (cmd) { + ERROR("Error opening alsa device \"%s\" (%s): %s\n", + ad->device, cmd, snd_strerror(-err)); + } else { + ERROR("Error opening alsa device \"%s\": %s\n", ad->device, + snd_strerror(-err)); + } +fail: + if (ad->pcmHandle) + snd_pcm_close(ad->pcmHandle); + ad->pcmHandle = NULL; + audioOutput->open = 0; + return -1; +} + +static int alsa_errorRecovery(AlsaData * ad, int err) +{ + if (err == -EPIPE) { + DEBUG("Underrun on alsa device \"%s\"\n", ad->device); + } else if (err == -ESTRPIPE) { + DEBUG("alsa device \"%s\" was suspended\n", ad->device); + } + + switch (snd_pcm_state(ad->pcmHandle)) { + case SND_PCM_STATE_PAUSED: + err = snd_pcm_pause(ad->pcmHandle, /* disable */ 0); + break; + case SND_PCM_STATE_SUSPENDED: + err = ad->canResume ? + snd_pcm_resume(ad->pcmHandle) : + snd_pcm_prepare(ad->pcmHandle); + break; + case SND_PCM_STATE_SETUP: + case SND_PCM_STATE_XRUN: + err = snd_pcm_prepare(ad->pcmHandle); + break; + case SND_PCM_STATE_DISCONNECTED: + /* so alsa_closeDevice won't try to drain: */ + snd_pcm_close(ad->pcmHandle); + ad->pcmHandle = NULL; + break; + default: + /* unknown state, do nothing */ + break; + } + + return err; +} + +static void alsa_dropBufferedAudio(AudioOutput * audioOutput) +{ + AlsaData *ad = audioOutput->data; + + alsa_errorRecovery(ad, snd_pcm_drop(ad->pcmHandle)); +} + +static void alsa_closeDevice(AudioOutput * audioOutput) +{ + AlsaData *ad = audioOutput->data; + + if (ad->pcmHandle) { + snd_pcm_drain(ad->pcmHandle); + snd_pcm_close(ad->pcmHandle); + ad->pcmHandle = NULL; + } + + audioOutput->open = 0; +} + +static int alsa_playAudio(AudioOutput * audioOutput, char *playChunk, int size) +{ + AlsaData *ad = audioOutput->data; + int ret; + + size /= ad->sampleSize; + + while (size > 0) { + ret = ad->writei(ad->pcmHandle, playChunk, size); + + if (ret == -EAGAIN || ret == -EINTR) + continue; + + if (ret < 0) { + if (alsa_errorRecovery(ad, ret) < 0) { + ERROR("closing alsa device \"%s\" due to write " + "error: %s\n", ad->device, + snd_strerror(-errno)); + alsa_closeDevice(audioOutput); + return -1; + } + continue; + } + + playChunk += ret * ad->sampleSize; + size -= ret; + } + + return 0; +} + +AudioOutputPlugin alsaPlugin = { + "alsa", + alsa_testDefault, + alsa_initDriver, + alsa_finishDriver, + alsa_openDevice, + alsa_playAudio, + alsa_dropBufferedAudio, + alsa_closeDevice, + NULL, /* sendMetadataFunc */ +}; + +#else /* HAVE ALSA */ + +DISABLED_AUDIO_OUTPUT_PLUGIN(alsaPlugin) +#endif /* HAVE_ALSA */ diff --git a/trunk/src/audioOutputs/audioOutput_ao.c b/trunk/src/audioOutputs/audioOutput_ao.c new file mode 100644 index 000000000..a7f437ef4 --- /dev/null +++ b/trunk/src/audioOutputs/audioOutput_ao.c @@ -0,0 +1,246 @@ +/* the Music Player Daemon (MPD) + * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com) + * This project's homepage is: http://www.musicpd.org + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "../audioOutput.h" + +#ifdef HAVE_AO + +#include "../conf.h" +#include "../log.h" + +#include <string.h> + +#include <ao/ao.h> + +static int driverInitCount; + +typedef struct _AoData { + int writeSize; + int driverId; + ao_option *options; + ao_device *device; +} AoData; + +static AoData *newAoData(void) +{ + AoData *ret = xmalloc(sizeof(AoData)); + ret->device = NULL; + ret->options = NULL; + + return ret; +} + +static void audioOutputAo_error(void) +{ + if (errno == AO_ENOTLIVE) { + ERROR("not a live ao device\n"); + } else if (errno == AO_EOPENDEVICE) { + ERROR("not able to open audio device\n"); + } else if (errno == AO_EBADOPTION) { + ERROR("bad driver option\n"); + } +} + +static int audioOutputAo_initDriver(AudioOutput * audioOutput, + ConfigParam * param) +{ + ao_info *ai; + char *dup; + char *stk1; + char *stk2; + char *n1; + char *key; + char *value; + char *test; + AoData *ad = newAoData(); + BlockParam *blockParam; + + audioOutput->data = ad; + + if ((blockParam = getBlockParam(param, "write_size"))) { + ad->writeSize = strtol(blockParam->value, &test, 10); + if (*test != '\0') { + FATAL("\"%s\" is not a valid write size at line %i\n", + blockParam->value, blockParam->line); + } + } else + ad->writeSize = 1024; + + if (driverInitCount == 0) { + ao_initialize(); + } + driverInitCount++; + + blockParam = getBlockParam(param, "driver"); + + if (!blockParam || 0 == strcmp(blockParam->value, "default")) { + ad->driverId = ao_default_driver_id(); + } else if ((ad->driverId = ao_driver_id(blockParam->value)) < 0) { + FATAL("\"%s\" is not a valid ao driver at line %i\n", + blockParam->value, blockParam->line); + } + + if ((ai = ao_driver_info(ad->driverId)) == NULL) { + FATAL("problems getting driver info for device defined at line %i\n" + "you may not have permission to the audio device\n", param->line); + } + + DEBUG("using ao driver \"%s\" for \"%s\"\n", ai->short_name, + audioOutput->name); + + blockParam = getBlockParam(param, "options"); + + if (blockParam) { + dup = xstrdup(blockParam->value); + } else + dup = xstrdup(""); + + if (strlen(dup)) { + stk1 = NULL; + n1 = strtok_r(dup, ";", &stk1); + while (n1) { + stk2 = NULL; + key = strtok_r(n1, "=", &stk2); + if (!key) + FATAL("problems parsing options \"%s\"\n", n1); + /*found = 0; + for(i=0;i<ai->option_count;i++) { + if(strcmp(ai->options[i],key)==0) { + found = 1; + break; + } + } + if(!found) { + FATAL("\"%s\" is not an option for " + "\"%s\" ao driver\n",key, + ai->short_name); + } */ + value = strtok_r(NULL, "", &stk2); + if (!value) + FATAL("problems parsing options \"%s\"\n", n1); + ao_append_option(&ad->options, key, value); + n1 = strtok_r(NULL, ";", &stk1); + } + } + free(dup); + + return 0; +} + +static void freeAoData(AoData * ad) +{ + ao_free_options(ad->options); + free(ad); +} + +static void audioOutputAo_finishDriver(AudioOutput * audioOutput) +{ + AoData *ad = (AoData *) audioOutput->data; + freeAoData(ad); + + driverInitCount--; + + if (driverInitCount == 0) + ao_shutdown(); +} + +static void audioOutputAo_dropBufferedAudio(AudioOutput * audioOutput) +{ + /* not supported by libao */ +} + +static void audioOutputAo_closeDevice(AudioOutput * audioOutput) +{ + AoData *ad = (AoData *) audioOutput->data; + + if (ad->device) { + ao_close(ad->device); + ad->device = NULL; + } + + audioOutput->open = 0; +} + +static int audioOutputAo_openDevice(AudioOutput * audioOutput) +{ + ao_sample_format format; + AoData *ad = (AoData *) audioOutput->data; + + if (ad->device) { + audioOutputAo_closeDevice(audioOutput); + } + + format.bits = audioOutput->outAudioFormat.bits; + format.rate = audioOutput->outAudioFormat.sampleRate; + format.byte_format = AO_FMT_NATIVE; + format.channels = audioOutput->outAudioFormat.channels; + + ad->device = ao_open_live(ad->driverId, &format, ad->options); + + if (ad->device == NULL) + return -1; + + audioOutput->open = 1; + + return 0; +} + +static int audioOutputAo_play(AudioOutput * audioOutput, char *playChunk, + int size) +{ + int send; + AoData *ad = (AoData *) audioOutput->data; + + if (ad->device == NULL) + return -1; + + while (size > 0) { + send = ad->writeSize > size ? size : ad->writeSize; + + if (ao_play(ad->device, playChunk, send) == 0) { + audioOutputAo_error(); + ERROR("closing audio device due to write error\n"); + audioOutputAo_closeDevice(audioOutput); + return -1; + } + + playChunk += send; + size -= send; + } + + return 0; +} + +AudioOutputPlugin aoPlugin = { + "ao", + NULL, + audioOutputAo_initDriver, + audioOutputAo_finishDriver, + audioOutputAo_openDevice, + audioOutputAo_play, + audioOutputAo_dropBufferedAudio, + audioOutputAo_closeDevice, + NULL, /* sendMetadataFunc */ +}; + +#else + +#include <stdio.h> + +DISABLED_AUDIO_OUTPUT_PLUGIN(aoPlugin) +#endif diff --git a/trunk/src/audioOutputs/audioOutput_jack.c b/trunk/src/audioOutputs/audioOutput_jack.c new file mode 100644 index 000000000..1fdfaf4bb --- /dev/null +++ b/trunk/src/audioOutputs/audioOutput_jack.c @@ -0,0 +1,440 @@ +/* jack plug in for the Music Player Daemon (MPD) + * (c)2006 by anarch(anarchsss@gmail.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "../audioOutput.h" + +#ifdef HAVE_JACK + +#include <stdlib.h> +#include <errno.h> + +#include "../conf.h" +#include "../log.h" + +#include <string.h> +#include <pthread.h> + +#include <jack/jack.h> +#include <jack/types.h> +#include <jack/ringbuffer.h> + +pthread_mutex_t play_audio_lock = PTHREAD_MUTEX_INITIALIZER; +pthread_cond_t play_audio = PTHREAD_COND_INITIALIZER; + +/*#include "dmalloc.h"*/ + +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +/*#define SAMPLE_SIZE sizeof(jack_default_audio_sample_t);*/ + + +static char *name = "mpd"; +static char *output_ports[2]; +static int ringbuf_sz = 32768; +size_t sample_size = sizeof(jack_default_audio_sample_t); + +typedef struct _JackData { + jack_port_t *ports[2]; + jack_client_t *client; + jack_ringbuffer_t *ringbuffer[2]; + int bps; + int shutdown; +} JackData; + +/*JackData *jd = NULL;*/ + +static JackData *newJackData(void) +{ + JackData *ret; + ret = xcalloc(sizeof(JackData), 1); + + return ret; +} + +static void freeJackData(AudioOutput *audioOutput) +{ + JackData *jd = audioOutput->data; + if (jd) { + if (jd->ringbuffer[0]) + jack_ringbuffer_free(jd->ringbuffer[0]); + if (jd->ringbuffer[1]) + jack_ringbuffer_free(jd->ringbuffer[1]); + free(jd); + audioOutput->data = NULL; + } +} + +static void jack_finishDriver(AudioOutput *audioOutput) +{ + JackData *jd = audioOutput->data; + int i; + + if ( jd && jd->client ) { + jack_deactivate(jd->client); + jack_client_close(jd->client); + } + DEBUG("disconnect_jack (pid=%d)\n", getpid ()); + + if ( strcmp(name, "mpd") ) { + free(name); + name = "mpd"; + } + + for ( i = ARRAY_SIZE(output_ports); --i >= 0; ) { + if (!output_ports[i]) + continue; + free(output_ports[i]); + output_ports[i] = NULL; + } + + freeJackData(audioOutput); +} + +static int srate(jack_nframes_t rate, void *data) +{ + JackData *jd = (JackData *) ((AudioOutput*) data)->data; + AudioFormat *audioFormat = &(((AudioOutput*) data)->outAudioFormat); + + audioFormat->sampleRate = (int)jack_get_sample_rate(jd->client); + + return 0; +} + +static int process(jack_nframes_t nframes, void *arg) +{ + size_t i; + JackData *jd = (JackData *) arg; + jack_default_audio_sample_t *out[2]; + size_t avail_data, avail_frames; + + if ( nframes <= 0 ) + return 0; + + out[0] = jack_port_get_buffer(jd->ports[0], nframes); + out[1] = jack_port_get_buffer(jd->ports[1], nframes); + + while ( nframes ) { + avail_data = jack_ringbuffer_read_space(jd->ringbuffer[1]); + + if ( avail_data > 0 ) { + avail_frames = avail_data / sample_size; + + if (avail_frames > nframes) { + avail_frames = nframes; + avail_data = nframes*sample_size; + } + + jack_ringbuffer_read(jd->ringbuffer[0], (char *)out[0], + avail_data); + jack_ringbuffer_read(jd->ringbuffer[1], (char *)out[1], + avail_data); + + nframes -= avail_frames; + out[0] += avail_data; + out[1] += avail_data; + } else { + for (i = 0; i < nframes; i++) + out[0][i] = out[1][i] = 0.0; + nframes = 0; + } + + if (pthread_mutex_trylock (&play_audio_lock) == 0) { + pthread_cond_signal (&play_audio); + pthread_mutex_unlock (&play_audio_lock); + } + } + + + /*DEBUG("process (pid=%d)\n", getpid());*/ + return 0; +} + +static void shutdown_callback(void *arg) +{ + JackData *jd = (JackData *) arg; + jd->shutdown = 1; +} + +static void set_audioformat(AudioOutput *audioOutput) +{ + JackData *jd = audioOutput->data; + AudioFormat *audioFormat = &audioOutput->outAudioFormat; + + audioFormat->sampleRate = (int) jack_get_sample_rate(jd->client); + DEBUG("samplerate = %d\n", audioFormat->sampleRate); + audioFormat->channels = 2; + audioFormat->bits = 16; + jd->bps = audioFormat->channels + * sizeof(jack_default_audio_sample_t) + * audioFormat->sampleRate; +} + +static void error_callback(const char *msg) +{ + ERROR("jack: %s\n", msg); +} + +static int jack_initDriver(AudioOutput *audioOutput, ConfigParam *param) +{ + BlockParam *bp; + char *endptr; + int val; + char *cp = NULL; + + DEBUG("jack_initDriver (pid=%d)\n", getpid()); + if ( ! param ) return 0; + + if ( (bp = getBlockParam(param, "ports")) ) { + DEBUG("output_ports=%s\n", bp->value); + + if (!(cp = strchr(bp->value, ','))) + FATAL("expected comma and a second value for '%s' " + "at line %d: %s\n", + bp->name, bp->line, bp->value); + + *cp = '\0'; + output_ports[0] = xstrdup(bp->value); + *cp++ = ','; + + if (!*cp) + FATAL("expected a second value for '%s' at line %d: " + "%s\n", bp->name, bp->line, bp->value); + + output_ports[1] = xstrdup(cp); + + if (strchr(cp,',')) + FATAL("Only %d values are supported for '%s' " + "at line %d\n", (int)ARRAY_SIZE(output_ports), + bp->name, bp->line); + } + + if ( (bp = getBlockParam(param, "ringbuffer_size")) ) { + errno = 0; + val = strtol(bp->value, &endptr, 10); + + if ( errno == 0 && endptr != bp->value) { + ringbuf_sz = val < 32768 ? 32768 : val; + DEBUG("ringbuffer_size=%d\n", ringbuf_sz); + } else { + FATAL("%s is not a number; ringbuf_size=%d\n", + bp->value, ringbuf_sz); + } + } + + if ( (bp = getBlockParam(param, "name")) + && (strcmp(bp->value, "mpd") != 0) ) { + name = xstrdup(bp->value); + DEBUG("name=%s\n", name); + } + + return 0; +} + +static int jack_testDefault(void) +{ + return 0; +} + +static int connect_jack(AudioOutput *audioOutput) +{ + JackData *jd = audioOutput->data; + char **jports; + char *port_name; + + if ( (jd->client = jack_client_new(name)) == NULL ) { + ERROR("jack server not running?\n"); + freeJackData(audioOutput); + return -1; + } + + jack_set_error_function(error_callback); + jack_set_process_callback(jd->client, process, (void *)jd); + jack_set_sample_rate_callback(jd->client, (JackProcessCallback)srate, + (void *)audioOutput); + jack_on_shutdown(jd->client, shutdown_callback, (void *)jd); + + if ( jack_activate(jd->client) ) { + ERROR("cannot activate client"); + freeJackData(audioOutput); + return -1; + } + + jd->ports[0] = jack_port_register(jd->client, "left", + JACK_DEFAULT_AUDIO_TYPE, + JackPortIsOutput, 0); + if ( !jd->ports[0] ) { + ERROR("Cannot register left output port.\n"); + freeJackData(audioOutput); + return -1; + } + + jd->ports[1] = jack_port_register(jd->client, "right", + JACK_DEFAULT_AUDIO_TYPE, + JackPortIsOutput, 0); + if ( !jd->ports[1] ) { + ERROR("Cannot register right output port.\n"); + freeJackData(audioOutput); + return -1; + } + + /* hay que buscar que hay */ + if ( !output_ports[1] + && (jports = (char **)jack_get_ports(jd->client, NULL, NULL, + JackPortIsPhysical| + JackPortIsInput)) ) { + output_ports[0] = jports[0]; + output_ports[1] = jports[1] ? jports[1] : jports[0]; + DEBUG("output_ports: %s %s\n", output_ports[0], output_ports[1]); + free(jports); + } + + if ( output_ports[1] ) { + jd->ringbuffer[0] = jack_ringbuffer_create(ringbuf_sz); + jd->ringbuffer[1] = jack_ringbuffer_create(ringbuf_sz); + memset(jd->ringbuffer[0]->buf, 0, jd->ringbuffer[0]->size); + memset(jd->ringbuffer[1]->buf, 0, jd->ringbuffer[1]->size); + + port_name = xmalloc(sizeof(char)*(7+strlen(name))); + + sprintf(port_name, "%s:left", name); + if ( (jack_connect(jd->client, port_name, + output_ports[0])) != 0 ) { + ERROR("%s is not a valid Jack Client / Port ", + output_ports[0]); + freeJackData(audioOutput); + free(port_name); + return -1; + } + sprintf(port_name, "%s:right", name); + if ( (jack_connect(jd->client, port_name, + output_ports[1])) != 0 ) { + ERROR("%s is not a valid Jack Client / Port ", + output_ports[1]); + freeJackData(audioOutput); + free(port_name); + return -1; + } + free(port_name); + } + + DEBUG("connect_jack (pid=%d)\n", getpid()); + return 1; +} + +static int jack_openDevice(AudioOutput *audioOutput) +{ + JackData *jd = audioOutput->data; + + if ( !jd ) { + DEBUG("connect!\n"); + jd = newJackData(); + audioOutput->data = jd; + + if (connect_jack(audioOutput) < 0) { + freeJackData(audioOutput); + audioOutput->open = 0; + return -1; + } + } + + set_audioformat(audioOutput); + audioOutput->open = 1; + + DEBUG("jack_openDevice (pid=%d)!\n", getpid ()); + return 0; +} + + +static void jack_closeDevice(AudioOutput * audioOutput) +{ + /*jack_finishDriver(audioOutput);*/ + audioOutput->open = 0; + DEBUG("jack_closeDevice (pid=%d)\n", getpid()); +} + +static void jack_dropBufferedAudio (AudioOutput * audioOutput) +{ +} + +static int jack_playAudio(AudioOutput * audioOutput, char *buff, int size) +{ + JackData *jd = audioOutput->data; + size_t space; + int i; + short *buffer = (short *) buff; + jack_default_audio_sample_t sample; + size_t samples = size/4; + + /*DEBUG("jack_playAudio: (pid=%d)!\n", getpid());*/ + + if ( jd->shutdown ) { + ERROR("Refusing to play, because there is no client thread.\n"); + freeJackData(audioOutput); + audioOutput->open = 0; + return 0; + } + + while ( samples && !jd->shutdown ) { + + if ( (space = jack_ringbuffer_write_space(jd->ringbuffer[0])) + >= samples*sample_size ) { + + /*space = MIN(space, samples*sample_size);*/ + /*space = samples*sample_size;*/ + + /*for(i=0; i<space/sample_size; i++) {*/ + for(i=0; i<samples; i++) { + sample = (jack_default_audio_sample_t) *(buffer++)/32768.0; + + jack_ringbuffer_write(jd->ringbuffer[0], (void*)&sample, + sample_size); + + sample = (jack_default_audio_sample_t) *(buffer++)/32768.0; + + jack_ringbuffer_write(jd->ringbuffer[1], (void*)&sample, + sample_size); + + /*samples--;*/ + } + samples=0; + + } else { + pthread_mutex_lock(&play_audio_lock); + pthread_cond_wait(&play_audio, &play_audio_lock); + pthread_mutex_unlock(&play_audio_lock); + } + + } + return 0; +} + +AudioOutputPlugin jackPlugin = { + "jack", + jack_testDefault, + jack_initDriver, + jack_finishDriver, + jack_openDevice, + jack_playAudio, + jack_dropBufferedAudio, + jack_closeDevice, + NULL, /* sendMetadataFunc */ +}; + +#else /* HAVE JACK */ + +DISABLED_AUDIO_OUTPUT_PLUGIN(jackPlugin) + +#endif /* HAVE_JACK */ diff --git a/trunk/src/audioOutputs/audioOutput_mvp.c b/trunk/src/audioOutputs/audioOutput_mvp.c new file mode 100644 index 000000000..ea365c657 --- /dev/null +++ b/trunk/src/audioOutputs/audioOutput_mvp.c @@ -0,0 +1,284 @@ +/* the Music Player Daemon (MPD) + * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com) + * This project's homepage is: http://www.musicpd.org + * + * Media MVP audio output based on code from MVPMC project: + * http://mvpmc.sourceforge.net/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "../audioOutput.h" + +#include <stdlib.h> + +#ifdef HAVE_MVP + +#include "../conf.h" +#include "../log.h" + +#include <string.h> + +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <fcntl.h> +#include <unistd.h> +#include <errno.h> + +typedef struct { + unsigned long dsp_status; + unsigned long stream_decode_type; + unsigned long sample_rate; + unsigned long bit_rate; + unsigned long raw[64 / sizeof(unsigned long)]; +} aud_status_t; + +#define MVP_SET_AUD_STOP _IOW('a',1,int) +#define MVP_SET_AUD_PLAY _IOW('a',2,int) +#define MVP_SET_AUD_PAUSE _IOW('a',3,int) +#define MVP_SET_AUD_UNPAUSE _IOW('a',4,int) +#define MVP_SET_AUD_SRC _IOW('a',5,int) +#define MVP_SET_AUD_MUTE _IOW('a',6,int) +#define MVP_SET_AUD_BYPASS _IOW('a',8,int) +#define MVP_SET_AUD_CHANNEL _IOW('a',9,int) +#define MVP_GET_AUD_STATUS _IOR('a',10,aud_status_t) +#define MVP_SET_AUD_VOLUME _IOW('a',13,int) +#define MVP_GET_AUD_VOLUME _IOR('a',14,int) +#define MVP_SET_AUD_STREAMTYPE _IOW('a',15,int) +#define MVP_SET_AUD_FORMAT _IOW('a',16,int) +#define MVP_GET_AUD_SYNC _IOR('a',21,pts_sync_data_t*) +#define MVP_SET_AUD_STC _IOW('a',22,long long int *) +#define MVP_SET_AUD_SYNC _IOW('a',23,int) +#define MVP_SET_AUD_END_STREAM _IOW('a',25,int) +#define MVP_SET_AUD_RESET _IOW('a',26,int) +#define MVP_SET_AUD_DAC_CLK _IOW('a',27,int) +#define MVP_GET_AUD_REGS _IOW('a',28,aud_ctl_regs_t*) + +typedef struct _MvpData { + int fd; +} MvpData; + +static int pcmfrequencies[][3] = { + {9, 8000, 32000}, + {10, 11025, 44100}, + {11, 12000, 48000}, + {1, 16000, 32000}, + {2, 22050, 44100}, + {3, 24000, 48000}, + {5, 32000, 32000}, + {0, 44100, 44100}, + {7, 48000, 48000}, + {13, 64000, 32000}, + {14, 88200, 44100}, + {15, 96000, 48000} +}; + +static int numfrequencies = sizeof(pcmfrequencies) / 12; + +static int mvp_testDefault(void) +{ + int fd; + + fd = open("/dev/adec_pcm", O_WRONLY); + + if (fd) { + close(fd); + return 0; + } + + WARNING("Error opening PCM device \"/dev/adec_pcm\": %s\n", + strerror(errno)); + + return -1; +} + +static int mvp_initDriver(AudioOutput * audioOutput, ConfigParam * param) +{ + MvpData *md = xmalloc(sizeof(MvpData)); + md->fd = -1; + audioOutput->data = md; + + return 0; +} + +static void mvp_finishDriver(AudioOutput * audioOutput) +{ + MvpData *md = audioOutput->data; + free(md); +} + +static int mvp_setPcmParams(MvpData * md, unsigned long rate, int channels, + int big_endian, int bits) +{ + int iloop; + int mix[5]; + + if (channels == 1) + mix[0] = 1; + else if (channels == 2) + mix[0] = 0; + else + return -1; + + /* 0,1=24bit(24) , 2,3=16bit */ + if (bits == 16) + mix[1] = 2; + else if (bits == 24) + mix[1] = 0; + else + return -1; + + mix[3] = 0; /* stream type? */ + + if (big_endian == 1) + mix[4] = 1; + else if (big_endian == 0) + mix[4] = 0; + else + return -1; + + /* + * if there is an exact match for the frequency, use it. + */ + for (iloop = 0; iloop < numfrequencies; iloop++) { + if (rate == pcmfrequencies[iloop][1]) { + mix[2] = pcmfrequencies[iloop][0]; + break; + } + } + + if (iloop >= numfrequencies) { + ERROR("Can not find suitable output frequency for %ld\n", rate); + return -1; + } + + if (ioctl(md->fd, MVP_SET_AUD_FORMAT, &mix) < 0) { + ERROR("Can not set audio format\n"); + return -1; + } + + if (ioctl(md->fd, MVP_SET_AUD_SYNC, 2) != 0) { + ERROR("Can not set audio sync\n"); + return -1; + } + + if (ioctl(md->fd, MVP_SET_AUD_PLAY, 0) < 0) { + ERROR("Can not set audio play mode\n"); + return -1; + } + + return 0; +} + +static int mvp_openDevice(AudioOutput * audioOutput) +{ + long long int stc = 0; + MvpData *md = audioOutput->data; + AudioFormat *audioFormat = &audioOutput->outAudioFormat; + int mix[5] = { 0, 2, 7, 1, 0 }; + + if ((md->fd = open("/dev/adec_pcm", O_RDWR | O_NONBLOCK)) < 0) { + ERROR("Error opening /dev/adec_pcm: %s\n", strerror(errno)); + return -1; + } + if (ioctl(md->fd, MVP_SET_AUD_SRC, 1) < 0) { + ERROR("Error setting audio source: %s\n", strerror(errno)); + return -1; + } + if (ioctl(md->fd, MVP_SET_AUD_STREAMTYPE, 0) < 0) { + ERROR("Error setting audio streamtype: %s\n", strerror(errno)); + return -1; + } + if (ioctl(md->fd, MVP_SET_AUD_FORMAT, &mix) < 0) { + ERROR("Error setting audio format: %s\n", strerror(errno)); + return -1; + } + ioctl(md->fd, MVP_SET_AUD_STC, &stc); + if (ioctl(md->fd, MVP_SET_AUD_BYPASS, 1) < 0) { + ERROR("Error setting audio streamtype: %s\n", strerror(errno)); + return -1; + } +#ifdef WORDS_BIGENDIAN + mvp_setPcmParams(md, audioFormat->sampleRate, audioFormat->channels, 0, + audioFormat->bits); +#else + mvp_setPcmParams(md, audioFormat->sampleRate, audioFormat->channels, 1, + audioFormat->bits); +#endif + audioOutput->open = 1; + return 0; +} + +static void mvp_closeDevice(AudioOutput * audioOutput) +{ + MvpData *md = audioOutput->data; + if (md->fd >= 0) + close(md->fd); + md->fd = -1; + audioOutput->open = 0; +} + +static void mvp_dropBufferedAudio(AudioOutput * audioOutput) +{ + MvpData *md = audioOutput->data; + if (md->fd >= 0) { + ioctl(md->fd, MVP_SET_AUD_RESET, 0x11); + close(md->fd); + md->fd = -1; + audioOutput->open = 0; + } +} + +static int mvp_playAudio(AudioOutput * audioOutput, char *playChunk, int size) +{ + MvpData *md = audioOutput->data; + int ret; + + /* reopen the device since it was closed by dropBufferedAudio */ + if (md->fd < 0) + mvp_openDevice(audioOutput); + + while (size > 0) { + ret = write(md->fd, playChunk, size); + if (ret < 0) { + if (errno == EINTR) + continue; + ERROR("closing mvp PCM device due to write error: " + "%s\n", strerror(errno)); + mvp_closeDevice(audioOutput); + return -1; + } + playChunk += ret; + size -= ret; + } + return 0; +} + +AudioOutputPlugin mvpPlugin = { + "mvp", + mvp_testDefault, + mvp_initDriver, + mvp_finishDriver, + mvp_openDevice, + mvp_playAudio, + mvp_dropBufferedAudio, + mvp_closeDevice, + NULL, /* sendMetadataFunc */ +}; + +#else /* HAVE_MVP */ + +DISABLED_AUDIO_OUTPUT_PLUGIN(mvpPlugin) +#endif /* HAVE_MVP */ diff --git a/trunk/src/audioOutputs/audioOutput_oss.c b/trunk/src/audioOutputs/audioOutput_oss.c new file mode 100644 index 000000000..01293cbd1 --- /dev/null +++ b/trunk/src/audioOutputs/audioOutput_oss.c @@ -0,0 +1,575 @@ +/* the Music Player Daemon (MPD) + * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com) + * This project's homepage is: http://www.musicpd.org + * + * OSS audio output (c) 2004, 2005, 2006, 2007 by Eric Wong <eric@petta-tech.com> + * and Warren Dukes <warren.dukes@gmail.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "../audioOutput.h" + +#include <stdlib.h> + +#ifdef HAVE_OSS + +#include "../conf.h" +#include "../log.h" + +#include <string.h> + +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <fcntl.h> +#include <unistd.h> +#include <errno.h> + +#if defined(__OpenBSD__) || defined(__NetBSD__) +# include <soundcard.h> +#else /* !(defined(__OpenBSD__) || defined(__NetBSD__) */ +# include <sys/soundcard.h> +#endif /* !(defined(__OpenBSD__) || defined(__NetBSD__) */ + +#ifdef WORDS_BIGENDIAN +# define AFMT_S16_MPD AFMT_S16_BE +#else +# define AFMT_S16_MPD AFMT_S16_LE +#endif /* WORDS_BIGENDIAN */ + +typedef struct _OssData { + int fd; + const char *device; + int channels; + int sampleRate; + int bitFormat; + int bits; + int *supported[3]; + int numSupported[3]; + int *unsupported[3]; + int numUnsupported[3]; +} OssData; + +#define OSS_SUPPORTED 1 +#define OSS_UNSUPPORTED 0 +#define OSS_UNKNOWN -1 + +#define OSS_RATE 0 +#define OSS_CHANNELS 1 +#define OSS_BITS 2 + +static int getIndexForParam(int param) +{ + int index = 0; + + switch (param) { + case SNDCTL_DSP_SPEED: + index = OSS_RATE; + break; + case SNDCTL_DSP_CHANNELS: + index = OSS_CHANNELS; + break; + case SNDCTL_DSP_SAMPLESIZE: + index = OSS_BITS; + break; + } + + return index; +} + +static int findSupportedParam(OssData * od, int param, int val) +{ + int i; + int index = getIndexForParam(param); + + for (i = 0; i < od->numSupported[index]; i++) { + if (od->supported[index][i] == val) + return 1; + } + + return 0; +} + +static int canConvert(int index, int val) +{ + switch (index) { + case OSS_BITS: + if (val != 16) + return 0; + break; + case OSS_CHANNELS: + if (val != 2) + return 0; + break; + } + + return 1; +} + +static int getSupportedParam(OssData * od, int param, int val) +{ + int i; + int index = getIndexForParam(param); + int ret = -1; + int least = val; + int diff; + + for (i = 0; i < od->numSupported[index]; i++) { + diff = od->supported[index][i] - val; + if (diff < 0) + diff = -diff; + if (diff < least) { + if (!canConvert(index, od->supported[index][i])) { + continue; + } + least = diff; + ret = od->supported[index][i]; + } + } + + return ret; +} + +static int findUnsupportedParam(OssData * od, int param, int val) +{ + int i; + int index = getIndexForParam(param); + + for (i = 0; i < od->numUnsupported[index]; i++) { + if (od->unsupported[index][i] == val) + return 1; + } + + return 0; +} + +static void addSupportedParam(OssData * od, int param, int val) +{ + int index = getIndexForParam(param); + + od->numSupported[index]++; + od->supported[index] = xrealloc(od->supported[index], + od->numSupported[index] * sizeof(int)); + od->supported[index][od->numSupported[index] - 1] = val; +} + +static void addUnsupportedParam(OssData * od, int param, int val) +{ + int index = getIndexForParam(param); + + od->numUnsupported[index]++; + od->unsupported[index] = xrealloc(od->unsupported[index], + od->numUnsupported[index] * + sizeof(int)); + od->unsupported[index][od->numUnsupported[index] - 1] = val; +} + +static void removeSupportedParam(OssData * od, int param, int val) +{ + int i = 0; + int j = 0; + int index = getIndexForParam(param); + + for (i = 0; i < od->numSupported[index] - 1; i++) { + if (od->supported[index][i] == val) + j = 1; + od->supported[index][i] = od->supported[index][i + j]; + } + + od->numSupported[index]--; + od->supported[index] = xrealloc(od->supported[index], + od->numSupported[index] * sizeof(int)); +} + +static void removeUnsupportedParam(OssData * od, int param, int val) +{ + int i = 0; + int j = 0; + int index = getIndexForParam(param); + + for (i = 0; i < od->numUnsupported[index] - 1; i++) { + if (od->unsupported[index][i] == val) + j = 1; + od->unsupported[index][i] = od->unsupported[index][i + j]; + } + + od->numUnsupported[index]--; + od->unsupported[index] = xrealloc(od->unsupported[index], + od->numUnsupported[index] * + sizeof(int)); +} + +static int isSupportedParam(OssData * od, int param, int val) +{ + if (findSupportedParam(od, param, val)) + return OSS_SUPPORTED; + if (findUnsupportedParam(od, param, val)) + return OSS_UNSUPPORTED; + return OSS_UNKNOWN; +} + +static void supportParam(OssData * od, int param, int val) +{ + int supported = isSupportedParam(od, param, val); + + if (supported == OSS_SUPPORTED) + return; + + if (supported == OSS_UNSUPPORTED) { + removeUnsupportedParam(od, param, val); + } + + addSupportedParam(od, param, val); +} + +static void unsupportParam(OssData * od, int param, int val) +{ + int supported = isSupportedParam(od, param, val); + + if (supported == OSS_UNSUPPORTED) + return; + + if (supported == OSS_SUPPORTED) { + removeSupportedParam(od, param, val); + } + + addUnsupportedParam(od, param, val); +} + +static OssData *newOssData(void) +{ + OssData *ret = xmalloc(sizeof(OssData)); + + ret->device = NULL; + ret->fd = -1; + + ret->supported[OSS_RATE] = NULL; + ret->supported[OSS_CHANNELS] = NULL; + ret->supported[OSS_BITS] = NULL; + ret->unsupported[OSS_RATE] = NULL; + ret->unsupported[OSS_CHANNELS] = NULL; + ret->unsupported[OSS_BITS] = NULL; + + ret->numSupported[OSS_RATE] = 0; + ret->numSupported[OSS_CHANNELS] = 0; + ret->numSupported[OSS_BITS] = 0; + ret->numUnsupported[OSS_RATE] = 0; + ret->numUnsupported[OSS_CHANNELS] = 0; + ret->numUnsupported[OSS_BITS] = 0; + + supportParam(ret, SNDCTL_DSP_SPEED, 48000); + supportParam(ret, SNDCTL_DSP_SPEED, 44100); + supportParam(ret, SNDCTL_DSP_CHANNELS, 2); + supportParam(ret, SNDCTL_DSP_SAMPLESIZE, 16); + + return ret; +} + +static void freeOssData(OssData * od) +{ + if (od->supported[OSS_RATE]) + free(od->supported[OSS_RATE]); + if (od->supported[OSS_CHANNELS]) + free(od->supported[OSS_CHANNELS]); + if (od->supported[OSS_BITS]) + free(od->supported[OSS_BITS]); + if (od->unsupported[OSS_RATE]) + free(od->unsupported[OSS_RATE]); + if (od->unsupported[OSS_CHANNELS]) + free(od->unsupported[OSS_CHANNELS]); + if (od->unsupported[OSS_BITS]) + free(od->unsupported[OSS_BITS]); + + free(od); +} + +#define OSS_STAT_NO_ERROR 0 +#define OSS_STAT_NOT_CHAR_DEV -1 +#define OSS_STAT_NO_PERMS -2 +#define OSS_STAT_DOESN_T_EXIST -3 +#define OSS_STAT_OTHER -4 + +static int oss_statDevice(const char *device, int *stErrno) +{ + struct stat st; + + if (0 == stat(device, &st)) { + if (!S_ISCHR(st.st_mode)) { + return OSS_STAT_NOT_CHAR_DEV; + } + } else { + *stErrno = errno; + + switch (errno) { + case ENOENT: + case ENOTDIR: + return OSS_STAT_DOESN_T_EXIST; + case EACCES: + return OSS_STAT_NO_PERMS; + default: + return OSS_STAT_OTHER; + } + } + + return 0; +} + +static const char *default_devices[] = { "/dev/sound/dsp", "/dev/dsp" }; + +static int oss_testDefault(void) +{ + int fd, i; + + for (i = ARRAY_SIZE(default_devices); --i >= 0; ) { + if ((fd = open(default_devices[i], O_WRONLY)) >= 0) { + xclose(fd); + return 0; + } + WARNING("Error opening OSS device \"%s\": %s\n", + default_devices[i], strerror(errno)); + } + + return -1; +} + +static int oss_open_default(AudioOutput *ao, ConfigParam *param, OssData *od) +{ + int i; + int err[ARRAY_SIZE(default_devices)]; + int ret[ARRAY_SIZE(default_devices)]; + + for (i = ARRAY_SIZE(default_devices); --i >= 0; ) { + ret[i] = oss_statDevice(default_devices[i], &err[i]); + if (ret[i] == 0) { + od->device = default_devices[i]; + return 0; + } + } + + if (param) + ERROR("error trying to open specified OSS device" + " at line %i\n", param->line); + else + ERROR("error trying to open default OSS device\n"); + + for (i = ARRAY_SIZE(default_devices); --i >= 0; ) { + const char *dev = default_devices[i]; + switch(ret[i]) { + case OSS_STAT_DOESN_T_EXIST: + ERROR("%s not found\n", dev); + break; + case OSS_STAT_NOT_CHAR_DEV: + ERROR("%s is not a character device\n", dev); + break; + case OSS_STAT_NO_PERMS: + ERROR("%s: permission denied\n", dev); + break; + default: + ERROR("Error accessing %s: %s", dev, strerror(err[i])); + } + } + exit(EXIT_FAILURE); + return 0; /* some compilers can be dumb... */ +} + +static int oss_initDriver(AudioOutput * audioOutput, ConfigParam * param) +{ + OssData *od = newOssData(); + audioOutput->data = od; + if (param) { + BlockParam *bp = getBlockParam(param, "device"); + if (bp) { + od->device = bp->value; + return 0; + } + } + return oss_open_default(audioOutput, param, od); +} + +static void oss_finishDriver(AudioOutput * audioOutput) +{ + OssData *od = audioOutput->data; + + freeOssData(od); +} + +static int setParam(OssData * od, int param, int *value) +{ + int val = *value; + int copy; + int supported = isSupportedParam(od, param, val); + + do { + if (supported == OSS_UNSUPPORTED) { + val = getSupportedParam(od, param, val); + if (copy < 0) + return -1; + } + copy = val; + if (ioctl(od->fd, param, ©)) { + unsupportParam(od, param, val); + supported = OSS_UNSUPPORTED; + } else { + if (supported == OSS_UNKNOWN) { + supportParam(od, param, val); + supported = OSS_SUPPORTED; + } + val = copy; + } + } while (supported == OSS_UNSUPPORTED); + + *value = val; + + return 0; +} + +static void oss_close(OssData * od) +{ + if (od->fd >= 0) + while (close(od->fd) && errno == EINTR) ; + od->fd = -1; +} + +static int oss_open(AudioOutput * audioOutput) +{ + int tmp; + OssData *od = audioOutput->data; + + if ((od->fd = open(od->device, O_WRONLY)) < 0) { + ERROR("Error opening OSS device \"%s\": %s\n", od->device, + strerror(errno)); + goto fail; + } + + if (setParam(od, SNDCTL_DSP_CHANNELS, &od->channels)) { + ERROR("OSS device \"%s\" does not support %i channels: %s\n", + od->device, od->channels, strerror(errno)); + goto fail; + } + + if (setParam(od, SNDCTL_DSP_SPEED, &od->sampleRate)) { + ERROR("OSS device \"%s\" does not support %i Hz audio: %s\n", + od->device, od->sampleRate, strerror(errno)); + goto fail; + } + + switch (od->bits) { + case 8: + tmp = AFMT_S8; + break; + case 16: + tmp = AFMT_S16_MPD; + } + + if (setParam(od, SNDCTL_DSP_SAMPLESIZE, &tmp)) { + ERROR("OSS device \"%s\" does not support %i bit audio: %s\n", + od->device, tmp, strerror(errno)); + goto fail; + } + + audioOutput->open = 1; + + return 0; + +fail: + oss_close(od); + audioOutput->open = 0; + return -1; +} + +static int oss_openDevice(AudioOutput * audioOutput) +{ + int ret = -1; + OssData *od = audioOutput->data; + AudioFormat *audioFormat = &audioOutput->outAudioFormat; + + od->channels = audioFormat->channels; + od->sampleRate = audioFormat->sampleRate; + od->bits = audioFormat->bits; + + if ((ret = oss_open(audioOutput)) < 0) + return ret; + + audioFormat->channels = od->channels; + audioFormat->sampleRate = od->sampleRate; + audioFormat->bits = od->bits; + + DEBUG("oss device \"%s\" will be playing %i bit %i channel audio at " + "%i Hz\n", od->device, od->bits, od->channels, od->sampleRate); + + return ret; +} + +static void oss_closeDevice(AudioOutput * audioOutput) +{ + OssData *od = audioOutput->data; + + oss_close(od); + + audioOutput->open = 0; +} + +static void oss_dropBufferedAudio(AudioOutput * audioOutput) +{ + OssData *od = audioOutput->data; + + if (od->fd >= 0) { + ioctl(od->fd, SNDCTL_DSP_RESET, 0); + oss_close(od); + } +} + +static int oss_playAudio(AudioOutput * audioOutput, char *playChunk, int size) +{ + OssData *od = audioOutput->data; + int ret; + + /* reopen the device since it was closed by dropBufferedAudio */ + if (od->fd < 0 && oss_open(audioOutput) < 0) + return -1; + + while (size > 0) { + ret = write(od->fd, playChunk, size); + if (ret < 0) { + if (errno == EINTR) + continue; + ERROR("closing oss device \"%s\" due to write error: " + "%s\n", od->device, strerror(errno)); + oss_closeDevice(audioOutput); + return -1; + } + playChunk += ret; + size -= ret; + } + + return 0; +} + +AudioOutputPlugin ossPlugin = { + "oss", + oss_testDefault, + oss_initDriver, + oss_finishDriver, + oss_openDevice, + oss_playAudio, + oss_dropBufferedAudio, + oss_closeDevice, + NULL, /* sendMetadataFunc */ +}; + +#else /* HAVE OSS */ + +DISABLED_AUDIO_OUTPUT_PLUGIN(ossPlugin) +#endif /* HAVE_OSS */ diff --git a/trunk/src/audioOutputs/audioOutput_osx.c b/trunk/src/audioOutputs/audioOutput_osx.c new file mode 100644 index 000000000..1caebade5 --- /dev/null +++ b/trunk/src/audioOutputs/audioOutput_osx.c @@ -0,0 +1,374 @@ +/* the Music Player Daemon (MPD) + * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com) + * This project's homepage is: http://www.musicpd.org + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "../audioOutput.h" + +#ifdef HAVE_OSX + +#include <AudioUnit/AudioUnit.h> +#include <stdlib.h> +#include <pthread.h> + +#include "../log.h" + +typedef struct _OsxData { + AudioUnit au; + pthread_mutex_t mutex; + pthread_cond_t condition; + char *buffer; + int bufferSize; + int pos; + int len; + int started; +} OsxData; + +static OsxData *newOsxData() +{ + OsxData *ret = xmalloc(sizeof(OsxData)); + + pthread_mutex_init(&ret->mutex, NULL); + pthread_cond_init(&ret->condition, NULL); + + ret->pos = 0; + ret->len = 0; + ret->started = 0; + ret->buffer = NULL; + ret->bufferSize = 0; + + return ret; +} + +static int osx_testDefault() +{ + /*AudioUnit au; + ComponentDescription desc; + Component comp; + + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = kAudioUnitSubType_Output; + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; + + comp = FindNextComponent(NULL, &desc); + if(!comp) { + ERROR("Unable to open default OS X defice\n"); + return -1; + } + + if(OpenAComponent(comp, &au) != noErr) { + ERROR("Unable to open default OS X defice\n"); + return -1; + } + + CloseComponent(au); */ + + return 0; +} + +static int osx_initDriver(AudioOutput * audioOutput, ConfigParam * param) +{ + OsxData *od = newOsxData(); + + audioOutput->data = od; + + return 0; +} + +static void freeOsxData(OsxData * od) +{ + if (od->buffer) + free(od->buffer); + pthread_mutex_destroy(&od->mutex); + pthread_cond_destroy(&od->condition); + free(od); +} + +static void osx_finishDriver(AudioOutput * audioOutput) +{ + OsxData *od = (OsxData *) audioOutput->data; + freeOsxData(od); +} + +static void osx_dropBufferedAudio(AudioOutput * audioOutput) +{ + OsxData *od = (OsxData *) audioOutput->data; + + pthread_mutex_lock(&od->mutex); + od->len = 0; + pthread_mutex_unlock(&od->mutex); +} + +static void osx_closeDevice(AudioOutput * audioOutput) +{ + OsxData *od = (OsxData *) audioOutput->data; + + pthread_mutex_lock(&od->mutex); + while (od->len) { + pthread_cond_wait(&od->condition, &od->mutex); + } + pthread_mutex_unlock(&od->mutex); + + if (od->started) { + AudioOutputUnitStop(od->au); + od->started = 0; + } + + CloseComponent(od->au); + AudioUnitUninitialize(od->au); + + audioOutput->open = 0; +} + +static OSStatus osx_render(void *vdata, + AudioUnitRenderActionFlags * ioActionFlags, + const AudioTimeStamp * inTimeStamp, + UInt32 inBusNumber, UInt32 inNumberFrames, + AudioBufferList * bufferList) +{ + OsxData *od = (OsxData *) vdata; + AudioBuffer *buffer = &bufferList->mBuffers[0]; + int bufferSize = buffer->mDataByteSize; + int bytesToCopy; + int curpos = 0; + + /*DEBUG("osx_render: enter : %i\n", (int)bufferList->mNumberBuffers); + DEBUG("osx_render: ioActionFlags: %p\n", ioActionFlags); + if(ioActionFlags) { + if(*ioActionFlags & kAudioUnitRenderAction_PreRender) { + DEBUG("prerender\n"); + } + if(*ioActionFlags & kAudioUnitRenderAction_PostRender) { + DEBUG("post render\n"); + } + if(*ioActionFlags & kAudioUnitRenderAction_OutputIsSilence) { + DEBUG("post render\n"); + } + if(*ioActionFlags & kAudioOfflineUnitRenderAction_Preflight) { + DEBUG("prefilight\n"); + } + if(*ioActionFlags & kAudioOfflineUnitRenderAction_Render) { + DEBUG("render\n"); + } + if(*ioActionFlags & kAudioOfflineUnitRenderAction_Complete) { + DEBUG("complete\n"); + } + } */ + + /* while(bufferSize) { + DEBUG("osx_render: lock\n"); */ + pthread_mutex_lock(&od->mutex); + /* + DEBUG("%i:%i\n", bufferSize, od->len); + while(od->go && od->len < bufferSize && + od->len < od->bufferSize) + { + DEBUG("osx_render: wait\n"); + pthread_cond_wait(&od->condition, &od->mutex); + } + */ + + bytesToCopy = od->len < bufferSize ? od->len : bufferSize; + bufferSize = bytesToCopy; + od->len -= bytesToCopy; + + if (od->pos + bytesToCopy > od->bufferSize) { + int bytes = od->bufferSize - od->pos; + memcpy(buffer->mData + curpos, od->buffer + od->pos, bytes); + od->pos = 0; + curpos += bytes; + bytesToCopy -= bytes; + } + + memcpy(buffer->mData + curpos, od->buffer + od->pos, bytesToCopy); + od->pos += bytesToCopy; + curpos += bytesToCopy; + + if (od->pos >= od->bufferSize) + od->pos = 0; + /* DEBUG("osx_render: unlock\n"); */ + pthread_mutex_unlock(&od->mutex); + pthread_cond_signal(&od->condition); + /* } */ + + buffer->mDataByteSize = bufferSize; + + if (!bufferSize) { + my_usleep(1000); + } + + /* DEBUG("osx_render: leave\n"); */ + return 0; +} + +static int osx_openDevice(AudioOutput * audioOutput) +{ + OsxData *od = (OsxData *) audioOutput->data; + ComponentDescription desc; + Component comp; + AURenderCallbackStruct callback; + AudioFormat *audioFormat = &audioOutput->outAudioFormat; + AudioStreamBasicDescription streamDesc; + + desc.componentType = kAudioUnitType_Output; + desc.componentSubType = kAudioUnitSubType_DefaultOutput; + desc.componentManufacturer = kAudioUnitManufacturer_Apple; + desc.componentFlags = 0; + desc.componentFlagsMask = 0; + + comp = FindNextComponent(NULL, &desc); + if (comp == 0) { + ERROR("Error finding OS X component\n"); + return -1; + } + + if (OpenAComponent(comp, &od->au) != noErr) { + ERROR("Unable to open OS X component\n"); + return -1; + } + + if (AudioUnitInitialize(od->au) != 0) { + CloseComponent(od->au); + ERROR("Unable to initialize OS X audio unit\n"); + return -1; + } + + callback.inputProc = osx_render; + callback.inputProcRefCon = od; + + if (AudioUnitSetProperty(od->au, kAudioUnitProperty_SetRenderCallback, + kAudioUnitScope_Input, 0, + &callback, sizeof(callback)) != 0) { + AudioUnitUninitialize(od->au); + CloseComponent(od->au); + ERROR("unable to set callback for OS X audio unit\n"); + return -1; + } + + streamDesc.mSampleRate = audioFormat->sampleRate; + streamDesc.mFormatID = kAudioFormatLinearPCM; + streamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; +#ifdef WORDS_BIGENDIAN + streamDesc.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; +#endif + + streamDesc.mBytesPerPacket = + audioFormat->channels * audioFormat->bits / 8; + streamDesc.mFramesPerPacket = 1; + streamDesc.mBytesPerFrame = streamDesc.mBytesPerPacket; + streamDesc.mChannelsPerFrame = audioFormat->channels; + streamDesc.mBitsPerChannel = audioFormat->bits; + + if (AudioUnitSetProperty(od->au, kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, 0, + &streamDesc, sizeof(streamDesc)) != 0) { + AudioUnitUninitialize(od->au); + CloseComponent(od->au); + ERROR("Unable to set format on OS X device\n"); + return -1; + } + + /* create a buffer of 1s */ + od->bufferSize = (audioFormat->sampleRate) * + (audioFormat->bits >> 3) * (audioFormat->channels); + od->buffer = xrealloc(od->buffer, od->bufferSize); + + od->pos = 0; + od->len = 0; + + audioOutput->open = 1; + + return 0; +} + +static int osx_play(AudioOutput * audioOutput, char *playChunk, int size) +{ + OsxData *od = (OsxData *) audioOutput->data; + int bytesToCopy; + int curpos; + + /* DEBUG("osx_play: enter\n"); */ + + if (!od->started) { + int err; + od->started = 1; + err = AudioOutputUnitStart(od->au); + if (err) { + ERROR("unable to start audio output: %i\n", err); + return -1; + } + } + + pthread_mutex_lock(&od->mutex); + + while (size) { + /* DEBUG("osx_play: lock\n"); */ + curpos = od->pos + od->len; + if (curpos >= od->bufferSize) + curpos -= od->bufferSize; + + bytesToCopy = od->bufferSize < size ? od->bufferSize : size; + + while (od->len > od->bufferSize - bytesToCopy) { + /* DEBUG("osx_play: wait\n"); */ + pthread_cond_wait(&od->condition, &od->mutex); + } + + bytesToCopy = od->bufferSize - od->len; + bytesToCopy = bytesToCopy < size ? bytesToCopy : size; + size -= bytesToCopy; + od->len += bytesToCopy; + + if (curpos + bytesToCopy > od->bufferSize) { + int bytes = od->bufferSize - curpos; + memcpy(od->buffer + curpos, playChunk, bytes); + curpos = 0; + playChunk += bytes; + bytesToCopy -= bytes; + } + + memcpy(od->buffer + curpos, playChunk, bytesToCopy); + curpos += bytesToCopy; + playChunk += bytesToCopy; + + } + /* DEBUG("osx_play: unlock\n"); */ + pthread_mutex_unlock(&od->mutex); + + /* DEBUG("osx_play: leave\n"); */ + return 0; +} + +AudioOutputPlugin osxPlugin = { + "osx", + osx_testDefault, + osx_initDriver, + osx_finishDriver, + osx_openDevice, + osx_play, + osx_dropBufferedAudio, + osx_closeDevice, + NULL, /* sendMetadataFunc */ +}; + +#else + +#include <stdio.h> + +DISABLED_AUDIO_OUTPUT_PLUGIN(osxPlugin) +#endif diff --git a/trunk/src/audioOutputs/audioOutput_pulse.c b/trunk/src/audioOutputs/audioOutput_pulse.c new file mode 100644 index 000000000..8948e0263 --- /dev/null +++ b/trunk/src/audioOutputs/audioOutput_pulse.c @@ -0,0 +1,221 @@ +/* the Music Player Daemon (MPD) + * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com) + * This project's homepage is: http://www.musicpd.org + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "../audioOutput.h" + +#include <stdlib.h> + +#ifdef HAVE_PULSE + +#include "../conf.h" +#include "../log.h" + +#include <string.h> +#include <time.h> + +#include <pulse/simple.h> +#include <pulse/error.h> + +#define MPD_PULSE_NAME "mpd" +#define CONN_ATTEMPT_INTERVAL 60 + +typedef struct _PulseData { + pa_simple *s; + char *server; + char *sink; + int connAttempts; + time_t lastAttempt; +} PulseData; + +static PulseData *newPulseData(void) +{ + PulseData *ret; + + ret = xmalloc(sizeof(PulseData)); + + ret->s = NULL; + ret->server = NULL; + ret->sink = NULL; + ret->connAttempts = 0; + ret->lastAttempt = 0; + + return ret; +} + +static void freePulseData(PulseData * pd) +{ + if (pd->server) + free(pd->server); + if (pd->sink) + free(pd->sink); + free(pd); +} + +static int pulse_initDriver(AudioOutput * audioOutput, ConfigParam * param) +{ + BlockParam *server = NULL; + BlockParam *sink = NULL; + PulseData *pd; + + if (param) { + server = getBlockParam(param, "server"); + sink = getBlockParam(param, "sink"); + } + + pd = newPulseData(); + pd->server = server ? xstrdup(server->value) : NULL; + pd->sink = sink ? xstrdup(sink->value) : NULL; + audioOutput->data = pd; + + return 0; +} + +static void pulse_finishDriver(AudioOutput * audioOutput) +{ + freePulseData((PulseData *) audioOutput->data); +} + +static int pulse_testDefault(void) +{ + pa_simple *s; + pa_sample_spec ss; + int error; + + ss.format = PA_SAMPLE_S16NE; + ss.rate = 44100; + ss.channels = 2; + + s = pa_simple_new(NULL, MPD_PULSE_NAME, PA_STREAM_PLAYBACK, NULL, + MPD_PULSE_NAME, &ss, NULL, NULL, &error); + if (!s) { + WARNING("Cannot connect to default PulseAudio server: %s\n", + pa_strerror(error)); + return -1; + } + + pa_simple_free(s); + + return 0; +} + +static int pulse_openDevice(AudioOutput * audioOutput) +{ + PulseData *pd; + AudioFormat *audioFormat; + pa_sample_spec ss; + time_t t; + int error; + + t = time(NULL); + pd = audioOutput->data; + audioFormat = &audioOutput->outAudioFormat; + + if (pd->connAttempts != 0 && + (t - pd->lastAttempt) < CONN_ATTEMPT_INTERVAL) + return -1; + + pd->connAttempts++; + pd->lastAttempt = t; + + if (audioFormat->bits != 16) { + ERROR("PulseAudio doesn't support %i bit audio\n", + audioFormat->bits); + return -1; + } + + ss.format = PA_SAMPLE_S16NE; + ss.rate = audioFormat->sampleRate; + ss.channels = audioFormat->channels; + + pd->s = pa_simple_new(pd->server, MPD_PULSE_NAME, PA_STREAM_PLAYBACK, + pd->sink, audioOutput->name, &ss, NULL, NULL, + &error); + if (!pd->s) { + ERROR("Cannot connect to server in PulseAudio output " + "\"%s\" (attempt %i): %s\n", audioOutput->name, + pd->connAttempts, pa_strerror(error)); + return -1; + } + + pd->connAttempts = 0; + audioOutput->open = 1; + + DEBUG("PulseAudio output \"%s\" connected and playing %i bit, %i " + "channel audio at %i Hz\n", audioOutput->name, audioFormat->bits, + audioFormat->channels, audioFormat->sampleRate); + + return 0; +} + +static void pulse_dropBufferedAudio(AudioOutput * audioOutput) +{ + PulseData *pd; + int error; + + pd = audioOutput->data; + if (pa_simple_flush(pd->s, &error) < 0) + WARNING("Flush failed in PulseAudio output \"%s\": %s\n", + audioOutput->name, pa_strerror(error)); +} + +static void pulse_closeDevice(AudioOutput * audioOutput) +{ + PulseData *pd; + + pd = audioOutput->data; + if (pd->s) { + pa_simple_drain(pd->s, NULL); + pa_simple_free(pd->s); + } + + audioOutput->open = 0; +} + +static int pulse_playAudio(AudioOutput * audioOutput, char *playChunk, int size) +{ + PulseData *pd; + int error; + + pd = audioOutput->data; + + if (pa_simple_write(pd->s, playChunk, size, &error) < 0) { + ERROR("PulseAudio output \"%s\" disconnecting due to write " + "error: %s\n", audioOutput->name, pa_strerror(error)); + pulse_closeDevice(audioOutput); + return -1; + } + + return 0; +} + +AudioOutputPlugin pulsePlugin = { + "pulse", + pulse_testDefault, + pulse_initDriver, + pulse_finishDriver, + pulse_openDevice, + pulse_playAudio, + pulse_dropBufferedAudio, + pulse_closeDevice, + NULL, /* sendMetadataFunc */ +}; + +#else /* HAVE_PULSE */ + +DISABLED_AUDIO_OUTPUT_PLUGIN(pulsePlugin) +#endif /* HAVE_PULSE */ diff --git a/trunk/src/audioOutputs/audioOutput_shout.c b/trunk/src/audioOutputs/audioOutput_shout.c new file mode 100644 index 000000000..7d93f8f85 --- /dev/null +++ b/trunk/src/audioOutputs/audioOutput_shout.c @@ -0,0 +1,636 @@ +/* the Music Player Daemon (MPD) + * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com) + * This project's homepage is: http://www.musicpd.org + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "../audioOutput.h" + +#include <stdlib.h> + +#ifdef HAVE_SHOUT + +#include "../conf.h" +#include "../log.h" +#include "../pcm_utils.h" + +#include <string.h> +#include <time.h> + +#include <shout/shout.h> +#include <vorbis/vorbisenc.h> + +#define CONN_ATTEMPT_INTERVAL 60 + +static int shoutInitCount; + +/* lots of this code blatantly stolent from bossogg/bossao2 */ + +typedef struct _ShoutData { + shout_t *shoutConn; + int shoutError; + + ogg_stream_state os; + ogg_page og; + ogg_packet op; + ogg_packet header_main; + ogg_packet header_comments; + ogg_packet header_codebooks; + + vorbis_dsp_state vd; + vorbis_block vb; + vorbis_info vi; + vorbis_comment vc; + + float quality; + int bitrate; + + int opened; + + MpdTag *tag; + int tagToSend; + + int connAttempts; + time_t lastAttempt; + int last_err; + + /* just a pointer to audioOutput->outAudioFormat */ + AudioFormat *audioFormat; +} ShoutData; + +static ShoutData *newShoutData(void) +{ + ShoutData *ret = xmalloc(sizeof(ShoutData)); + + ret->shoutConn = shout_new(); + ret->opened = 0; + ret->tag = NULL; + ret->tagToSend = 0; + ret->bitrate = -1; + ret->quality = -2.0; + ret->connAttempts = 0; + ret->lastAttempt = 0; + ret->audioFormat = NULL; + ret->last_err = SHOUTERR_UNCONNECTED; + + return ret; +} + +static void freeShoutData(ShoutData * sd) +{ + if (sd->shoutConn) + shout_free(sd->shoutConn); + if (sd->tag) + freeMpdTag(sd->tag); + + free(sd); +} + +#define checkBlockParam(name) { \ + blockParam = getBlockParam(param, name); \ + if (!blockParam) { \ + FATAL("no \"%s\" defined for shout device defined at line " \ + "%i\n", name, param->line); \ + } \ +} + +static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) +{ + ShoutData *sd; + char *test; + int port; + char *host; + char *mount; + char *passwd; + char *user; + char *name; + BlockParam *blockParam; + unsigned int public = 0; + + sd = newShoutData(); + + if (shoutInitCount == 0) + shout_init(); + + shoutInitCount++; + + checkBlockParam("host"); + host = blockParam->value; + + checkBlockParam("mount"); + mount = blockParam->value; + + checkBlockParam("port"); + + port = strtol(blockParam->value, &test, 10); + + if (*test != '\0' || port <= 0) { + FATAL("shout port \"%s\" is not a positive integer, line %i\n", + blockParam->value, blockParam->line); + } + + checkBlockParam("password"); + passwd = blockParam->value; + + checkBlockParam("name"); + name = blockParam->value; + + blockParam = getBlockParam(param, "public"); + if (blockParam) { + if (0 == strcmp(blockParam->value, "yes")) { + public = 1; + } else if (0 == strcmp(blockParam->value, "no")) { + public = 0; + } else { + FATAL("public \"%s\" is not \"yes\" or \"no\" at line " + "%i\n", param->value, param->line); + } + } + + blockParam = getBlockParam(param, "user"); + if (blockParam) + user = blockParam->value; + else + user = "source"; + + blockParam = getBlockParam(param, "quality"); + + if (blockParam) { + int line = blockParam->line; + + sd->quality = strtod(blockParam->value, &test); + + if (*test != '\0' || sd->quality < -1.0 || sd->quality > 10.0) { + FATAL("shout quality \"%s\" is not a number in the " + "range -1 to 10, line %i\n", blockParam->value, + blockParam->line); + } + + blockParam = getBlockParam(param, "bitrate"); + + if (blockParam) { + FATAL("quality (line %i) and bitrate (line %i) are " + "both defined for shout output\n", line, + blockParam->line); + } + } else { + blockParam = getBlockParam(param, "bitrate"); + + if (!blockParam) { + FATAL("neither bitrate nor quality defined for shout " + "output at line %i\n", param->line); + } + + sd->bitrate = strtol(blockParam->value, &test, 10); + + if (*test != '\0' || sd->bitrate <= 0) { + FATAL("bitrate at line %i should be a positive integer " + "\n", blockParam->line); + } + } + + checkBlockParam("format"); + sd->audioFormat = &audioOutput->outAudioFormat; + + if (shout_set_host(sd->shoutConn, host) != SHOUTERR_SUCCESS || + shout_set_port(sd->shoutConn, port) != SHOUTERR_SUCCESS || + shout_set_password(sd->shoutConn, passwd) != SHOUTERR_SUCCESS || + shout_set_mount(sd->shoutConn, mount) != SHOUTERR_SUCCESS || + shout_set_name(sd->shoutConn, name) != SHOUTERR_SUCCESS || + shout_set_user(sd->shoutConn, user) != SHOUTERR_SUCCESS || + shout_set_public(sd->shoutConn, public) != SHOUTERR_SUCCESS || + shout_set_nonblocking(sd->shoutConn, 1) != SHOUTERR_SUCCESS || + shout_set_format(sd->shoutConn, SHOUT_FORMAT_VORBIS) + != SHOUTERR_SUCCESS || + shout_set_protocol(sd->shoutConn, SHOUT_PROTOCOL_HTTP) + != SHOUTERR_SUCCESS || + shout_set_agent(sd->shoutConn, "MPD") != SHOUTERR_SUCCESS) { + FATAL("error configuring shout defined at line %i: %s\n", + param->line, shout_get_error(sd->shoutConn)); + } + + /* optional paramters */ + blockParam = getBlockParam(param, "genre"); + if (blockParam && shout_set_genre(sd->shoutConn, blockParam->value)) { + FATAL("error configuring shout defined at line %i: %s\n", + param->line, shout_get_error(sd->shoutConn)); + } + + blockParam = getBlockParam(param, "description"); + if (blockParam && shout_set_description(sd->shoutConn, + blockParam->value)) { + FATAL("error configuring shout defined at line %i: %s\n", + param->line, shout_get_error(sd->shoutConn)); + } + + { + char temp[11]; + memset(temp, 0, sizeof(temp)); + + snprintf(temp, sizeof(temp), "%d", sd->audioFormat->channels); + shout_set_audio_info(sd->shoutConn, SHOUT_AI_CHANNELS, temp); + + snprintf(temp, sizeof(temp), "%d", sd->audioFormat->sampleRate); + + shout_set_audio_info(sd->shoutConn, SHOUT_AI_SAMPLERATE, temp); + + if (sd->quality >= -1.0) { + snprintf(temp, sizeof(temp), "%2.2f", sd->quality); + shout_set_audio_info(sd->shoutConn, SHOUT_AI_QUALITY, + temp); + } else { + snprintf(temp, sizeof(temp), "%d", sd->bitrate); + shout_set_audio_info(sd->shoutConn, SHOUT_AI_BITRATE, + temp); + } + } + + audioOutput->data = sd; + + return 0; +} + +static int myShout_handleError(ShoutData * sd, int err) +{ + switch (err) { + case SHOUTERR_SUCCESS: + break; + case SHOUTERR_UNCONNECTED: + case SHOUTERR_SOCKET: + ERROR("Lost shout connection to %s:%i : %s\n", + shout_get_host(sd->shoutConn), + shout_get_port(sd->shoutConn), + shout_get_error(sd->shoutConn)); + sd->shoutError = 1; + return -1; + default: + ERROR("shout: connection to %s:%i error : %s\n", + shout_get_host(sd->shoutConn), + shout_get_port(sd->shoutConn), + shout_get_error(sd->shoutConn)); + sd->shoutError = 1; + return -1; + } + + return 0; +} + +static int write_page(ShoutData * sd) +{ + int err = 0; + + /*DEBUG("shout_delay: %i\n", shout_delay(sd->shoutConn)); */ + shout_sync(sd->shoutConn); + err = shout_send(sd->shoutConn, sd->og.header, sd->og.header_len); + if (myShout_handleError(sd, err) < 0) + return -1; + err = shout_send(sd->shoutConn, sd->og.body, sd->og.body_len); + if (myShout_handleError(sd, err) < 0) + return -1; + + return 0; +} + +static void finishEncoder(ShoutData * sd) +{ + vorbis_analysis_wrote(&sd->vd, 0); + + while (vorbis_analysis_blockout(&sd->vd, &sd->vb) == 1) { + vorbis_analysis(&sd->vb, NULL); + vorbis_bitrate_addblock(&sd->vb); + while (vorbis_bitrate_flushpacket(&sd->vd, &sd->op)) { + ogg_stream_packetin(&sd->os, &sd->op); + } + } +} + +static int flushEncoder(ShoutData * sd) +{ + return (ogg_stream_pageout(&sd->os, &sd->og) > 0); +} + +static void clearEncoder(ShoutData * sd) +{ + finishEncoder(sd); + while (1 == flushEncoder(sd)) { + if (!sd->shoutError) + write_page(sd); + } + + vorbis_comment_clear(&sd->vc); + ogg_stream_clear(&sd->os); + vorbis_block_clear(&sd->vb); + vorbis_dsp_clear(&sd->vd); + vorbis_info_clear(&sd->vi); +} + +static void myShout_closeShoutConn(ShoutData * sd) +{ + if (sd->opened) { + clearEncoder(sd); + + if (shout_close(sd->shoutConn) != SHOUTERR_SUCCESS) { + ERROR("problem closing connection to shout server: " + "%s\n", shout_get_error(sd->shoutConn)); + } + } + + sd->last_err = SHOUTERR_UNCONNECTED; + sd->opened = 0; +} + +static void myShout_finishDriver(AudioOutput * audioOutput) +{ + ShoutData *sd = (ShoutData *) audioOutput->data; + + myShout_closeShoutConn(sd); + + freeShoutData(sd); + + shoutInitCount--; + + if (shoutInitCount == 0) + shout_shutdown(); +} + +static void myShout_dropBufferedAudio(AudioOutput * audioOutput) +{ + /* needs to be implemented */ +} + +static void myShout_closeDevice(AudioOutput * audioOutput) +{ + ShoutData *sd = (ShoutData *) audioOutput->data; + + myShout_closeShoutConn(sd); + + audioOutput->open = 0; +} + +#define addTag(name, value) { \ + if(value) vorbis_comment_add_tag(&(sd->vc), name, value); \ +} + +static void copyTagToVorbisComment(ShoutData * sd) +{ + if (sd->tag) { + int i; + + for (i = 0; i < sd->tag->numOfItems; i++) { + switch (sd->tag->items[i].type) { + case TAG_ITEM_ARTIST: + addTag("ARTIST", sd->tag->items[i].value); + break; + case TAG_ITEM_ALBUM: + addTag("ALBUM", sd->tag->items[i].value); + break; + case TAG_ITEM_TITLE: + addTag("TITLE", sd->tag->items[i].value); + break; + } + } + } +} + +static int initEncoder(ShoutData * sd) +{ + vorbis_info_init(&(sd->vi)); + + if (sd->quality >= -1.0) { + if (0 != vorbis_encode_init_vbr(&(sd->vi), + sd->audioFormat->channels, + sd->audioFormat->sampleRate, + sd->quality * 0.1)) { + ERROR("problem setting up vorbis encoder for shout\n"); + vorbis_info_clear(&(sd->vi)); + return -1; + } + } else { + if (0 != vorbis_encode_init(&(sd->vi), + sd->audioFormat->channels, + sd->audioFormat->sampleRate, -1.0, + sd->bitrate * 1000, -1.0)) { + ERROR("problem setting up vorbis encoder for shout\n"); + vorbis_info_clear(&(sd->vi)); + return -1; + } + } + + vorbis_analysis_init(&(sd->vd), &(sd->vi)); + vorbis_block_init(&(sd->vd), &(sd->vb)); + + ogg_stream_init(&(sd->os), rand()); + + vorbis_comment_init(&(sd->vc)); + + return 0; +} + +static int myShout_openShoutConn(AudioOutput * audioOutput) +{ + ShoutData *sd = (ShoutData *) audioOutput->data; + time_t t = time(NULL); + + if (sd->connAttempts != 0 && + (t - sd->lastAttempt) < CONN_ATTEMPT_INTERVAL) { + return -1; + } + + sd->connAttempts++; + + if (sd->last_err == SHOUTERR_UNCONNECTED) + sd->last_err = shout_open(sd->shoutConn); + switch (sd->last_err) { + case SHOUTERR_SUCCESS: + case SHOUTERR_CONNECTED: + break; + case SHOUTERR_BUSY: + sd->last_err = shout_get_connected(sd->shoutConn); + if (sd->last_err == SHOUTERR_CONNECTED) + break; + return -1; + default: + sd->lastAttempt = t; + ERROR("problem opening connection to shout server %s:%i " + "(attempt %i): %s\n", + shout_get_host(sd->shoutConn), + shout_get_port(sd->shoutConn), + sd->connAttempts, shout_get_error(sd->shoutConn)); + return -1; + } + + if (initEncoder(sd) < 0) { + shout_close(sd->shoutConn); + return -1; + } + + sd->shoutError = 0; + + copyTagToVorbisComment(sd); + + vorbis_analysis_headerout(&(sd->vd), &(sd->vc), &(sd->header_main), + &(sd->header_comments), + &(sd->header_codebooks)); + + ogg_stream_packetin(&(sd->os), &(sd->header_main)); + ogg_stream_packetin(&(sd->os), &(sd->header_comments)); + ogg_stream_packetin(&(sd->os), &(sd->header_codebooks)); + + sd->opened = 1; + sd->tagToSend = 0; + + while (ogg_stream_flush(&(sd->os), &(sd->og))) { + if (write_page(sd) < 0) { + myShout_closeShoutConn(sd); + return -1; + } + } + + sd->connAttempts = 0; + + return 0; +} + +static int myShout_openDevice(AudioOutput * audioOutput) +{ + ShoutData *sd = (ShoutData *) audioOutput->data; + + audioOutput->open = 1; + + if (sd->opened) + return 0; + + if (myShout_openShoutConn(audioOutput) < 0) { + audioOutput->open = 0; + return -1; + } + + return 0; +} + +static void myShout_sendMetadata(ShoutData * sd) +{ + if (!sd->opened || !sd->tag) + return; + + clearEncoder(sd); + if (initEncoder(sd) < 0) + return; + + copyTagToVorbisComment(sd); + + vorbis_analysis_headerout(&(sd->vd), &(sd->vc), &(sd->header_main), + &(sd->header_comments), + &(sd->header_codebooks)); + + ogg_stream_packetin(&(sd->os), &(sd->header_main)); + ogg_stream_packetin(&(sd->os), &(sd->header_comments)); + ogg_stream_packetin(&(sd->os), &(sd->header_codebooks)); + + while (ogg_stream_flush(&(sd->os), &(sd->og))) { + if (write_page(sd) < 0) { + myShout_closeShoutConn(sd); + return; + } + } + + /*if(sd->tag) freeMpdTag(sd->tag); + sd->tag = NULL; */ + sd->tagToSend = 0; +} + +static int myShout_play(AudioOutput * audioOutput, char *playChunk, int size) +{ + int i, j; + ShoutData *sd = (ShoutData *) audioOutput->data; + float **vorbbuf; + int samples; + int bytes = sd->audioFormat->bits / 8; + + if (sd->opened && sd->tagToSend) + myShout_sendMetadata(sd); + + if (!sd->opened) { + if (myShout_openShoutConn(audioOutput) < 0) { + return -1; + } + } + + samples = size / (bytes * sd->audioFormat->channels); + + /* this is for only 16-bit audio */ + + vorbbuf = vorbis_analysis_buffer(&(sd->vd), samples); + + for (i = 0; i < samples; i++) { + for (j = 0; j < sd->audioFormat->channels; j++) { + vorbbuf[j][i] = (*((mpd_sint16 *) playChunk)) / 32768.0; + playChunk += bytes; + } + } + + vorbis_analysis_wrote(&(sd->vd), samples); + + while (1 == vorbis_analysis_blockout(&(sd->vd), &(sd->vb))) { + vorbis_analysis(&(sd->vb), NULL); + vorbis_bitrate_addblock(&(sd->vb)); + + while (vorbis_bitrate_flushpacket(&(sd->vd), &(sd->op))) { + ogg_stream_packetin(&(sd->os), &(sd->op)); + } + } + + while (ogg_stream_pageout(&(sd->os), &(sd->og)) != 0) { + if (write_page(sd) < 0) { + myShout_closeShoutConn(sd); + return -1; + } + } + + return 0; +} + +static void myShout_setTag(AudioOutput * audioOutput, MpdTag * tag) +{ + ShoutData *sd = (ShoutData *) audioOutput->data; + + if (sd->tag) + freeMpdTag(sd->tag); + sd->tag = NULL; + sd->tagToSend = 0; + + if (!tag) + return; + + sd->tag = mpdTagDup(tag); + sd->tagToSend = 1; +} + +AudioOutputPlugin shoutPlugin = { + "shout", + NULL, + myShout_initDriver, + myShout_finishDriver, + myShout_openDevice, + myShout_play, + myShout_dropBufferedAudio, + myShout_closeDevice, + myShout_setTag, +}; + +#else + +DISABLED_AUDIO_OUTPUT_PLUGIN(shoutPlugin) +#endif |