Commit 29a25b99 authored by Avuton Olrich's avatar Avuton Olrich

Add mpd-indent.sh

Indent the entire tree, hopefully we can keep it indented. git-svn-id: https://svn.musicpd.org/mpd/trunk@4410 09075e82-0dd4-0310-85a5-a0d7c8717e4f
parent 099f0e10
...@@ -42,7 +42,7 @@ int cmpAudioFormat(AudioFormat * dest, AudioFormat * src); ...@@ -42,7 +42,7 @@ int cmpAudioFormat(AudioFormat * dest, AudioFormat * src);
void getOutputAudioFormat(AudioFormat * inFormat, AudioFormat * outFormat); void getOutputAudioFormat(AudioFormat * inFormat, AudioFormat * outFormat);
int parseAudioConfig(AudioFormat * audioFormat, char * conf); int parseAudioConfig(AudioFormat * audioFormat, char *conf);
/* make sure initPlayerData is called before this function!! */ /* make sure initPlayerData is called before this function!! */
void initAudioConfig(); void initAudioConfig();
...@@ -55,7 +55,7 @@ void finishAudioDriver(); ...@@ -55,7 +55,7 @@ void finishAudioDriver();
int openAudioDevice(AudioFormat * audioFormat); int openAudioDevice(AudioFormat * audioFormat);
int playAudio(char * playChunk,int size); int playAudio(char *playChunk, int size);
void dropBufferedAudio(); void dropBufferedAudio();
......
...@@ -28,24 +28,30 @@ ...@@ -28,24 +28,30 @@
#define AUDIO_OUTPUT_NAME "name" #define AUDIO_OUTPUT_NAME "name"
#define AUDIO_OUTPUT_FORMAT "format" #define AUDIO_OUTPUT_FORMAT "format"
static List * audioOutputPluginList; static List *audioOutputPluginList;
void loadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin) { void loadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin)
if(!audioOutputPlugin->name) return; {
if (!audioOutputPlugin->name)
return;
insertInList(audioOutputPluginList, audioOutputPlugin->name, insertInList(audioOutputPluginList, audioOutputPlugin->name,
audioOutputPlugin); audioOutputPlugin);
} }
void unloadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin) { void unloadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin)
if(!audioOutputPlugin->name) return; {
if (!audioOutputPlugin->name)
return;
deleteFromList(audioOutputPluginList, audioOutputPlugin->name); deleteFromList(audioOutputPluginList, audioOutputPlugin->name);
} }
void initAudioOutputPlugins(void) { void initAudioOutputPlugins(void)
{
audioOutputPluginList = makeList(NULL, 0); audioOutputPluginList = makeList(NULL, 0);
} }
void finishAudioOutputPlugins(void) { void finishAudioOutputPlugins(void)
{
freeList(audioOutputPluginList); freeList(audioOutputPluginList);
} }
...@@ -60,52 +66,50 @@ void finishAudioOutputPlugins(void) { ...@@ -60,52 +66,50 @@ void finishAudioOutputPlugins(void) {
if(bp) str = bp->value; \ if(bp) str = bp->value; \
} }
AudioOutput * newAudioOutput(ConfigParam * param) { AudioOutput *newAudioOutput(ConfigParam * param)
AudioOutput * ret = NULL; {
void * data = NULL; AudioOutput *ret = NULL;
char * name = NULL; void *data = NULL;
char * format = NULL; char *name = NULL;
char * type = NULL; char *format = NULL;
BlockParam * bp = NULL; char *type = NULL;
AudioOutputPlugin * plugin = NULL; BlockParam *bp = NULL;
AudioOutputPlugin *plugin = NULL;
if(param) {
if (param) {
getBlockParam(AUDIO_OUTPUT_NAME, name, 1); getBlockParam(AUDIO_OUTPUT_NAME, name, 1);
getBlockParam(AUDIO_OUTPUT_TYPE, type, 1); getBlockParam(AUDIO_OUTPUT_TYPE, type, 1);
getBlockParam(AUDIO_OUTPUT_FORMAT, format, 0); getBlockParam(AUDIO_OUTPUT_FORMAT, format, 0);
if(!findInList(audioOutputPluginList, type, &data)) { if (!findInList(audioOutputPluginList, type, &data)) {
ERROR("couldn't find audio output plugin for type " ERROR("couldn't find audio output plugin for type "
"\"%s\" at line %i\n", type, "\"%s\" at line %i\n", type, param->line);
param->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
plugin = (AudioOutputPlugin *) data; plugin = (AudioOutputPlugin *) data;
} } else {
else { ListNode *node = audioOutputPluginList->firstNode;
ListNode * node = audioOutputPluginList->firstNode;
WARNING("No \"%s\" defined in config file\n", WARNING("No \"%s\" defined in config file\n",
CONF_AUDIO_OUTPUT); CONF_AUDIO_OUTPUT);
WARNING("Attempt to detect audio output device\n"); WARNING("Attempt to detect audio output device\n");
while(node) { while (node) {
plugin = (AudioOutputPlugin *) node->data; plugin = (AudioOutputPlugin *) node->data;
if(plugin->testDefaultDeviceFunc) { if (plugin->testDefaultDeviceFunc) {
WARNING("Attempting to detect a %s audio " WARNING("Attempting to detect a %s audio "
"device\n", plugin->name); "device\n", plugin->name);
if(plugin->testDefaultDeviceFunc() == 0) { if (plugin->testDefaultDeviceFunc() == 0) {
WARNING("Successfully detected a %s " WARNING("Successfully detected a %s "
"audio device\n", "audio device\n", plugin->name);
plugin->name);
break; break;
} }
} }
node = node->nextNode; node = node->nextNode;
} }
if(!node) { if (!node) {
WARNING("Unable to detect an audio device\n"); WARNING("Unable to detect an audio device\n");
return NULL; return NULL;
} }
...@@ -134,20 +138,18 @@ AudioOutput * newAudioOutput(ConfigParam * param) { ...@@ -134,20 +138,18 @@ AudioOutput * newAudioOutput(ConfigParam * param) {
memset(&ret->outAudioFormat, 0, sizeof(AudioFormat)); memset(&ret->outAudioFormat, 0, sizeof(AudioFormat));
memset(&ret->reqAudioFormat, 0, sizeof(AudioFormat)); memset(&ret->reqAudioFormat, 0, sizeof(AudioFormat));
if(format) { if (format) {
ret->convertAudioFormat = 1; ret->convertAudioFormat = 1;
if(0 != parseAudioConfig(&ret->reqAudioFormat, format)) if (0 != parseAudioConfig(&ret->reqAudioFormat, format)) {
{ ERROR("error parsing format at line %i\n", bp->line);
ERROR("error parsing format at line %i\n",
bp->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
copyAudioFormat(&ret->outAudioFormat, &ret->reqAudioFormat); copyAudioFormat(&ret->outAudioFormat, &ret->reqAudioFormat);
} }
if(plugin->initDriverFunc(ret, param) != 0) { if (plugin->initDriverFunc(ret, param) != 0) {
free(ret); free(ret);
ret = NULL; ret = NULL;
} }
...@@ -155,13 +157,13 @@ AudioOutput * newAudioOutput(ConfigParam * param) { ...@@ -155,13 +157,13 @@ AudioOutput * newAudioOutput(ConfigParam * param) {
return ret; return ret;
} }
int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat) { int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat)
{
int ret; int ret;
if(audioOutput->open) { if (audioOutput->open) {
if(cmpAudioFormat(audioFormat, &audioOutput->inAudioFormat) if (cmpAudioFormat(audioFormat, &audioOutput->inAudioFormat)
== 0) == 0) {
{
return 0; return 0;
} }
closeAudioOutput(audioOutput); closeAudioOutput(audioOutput);
...@@ -169,35 +171,36 @@ int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat) { ...@@ -169,35 +171,36 @@ int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat) {
copyAudioFormat(&audioOutput->inAudioFormat, audioFormat); copyAudioFormat(&audioOutput->inAudioFormat, audioFormat);
if(audioOutput->convertAudioFormat) { if (audioOutput->convertAudioFormat) {
copyAudioFormat(&audioOutput->outAudioFormat, copyAudioFormat(&audioOutput->outAudioFormat,
&audioOutput->reqAudioFormat); &audioOutput->reqAudioFormat);
} } else {
else {
copyAudioFormat(&audioOutput->outAudioFormat, copyAudioFormat(&audioOutput->outAudioFormat,
&audioOutput->inAudioFormat); &audioOutput->inAudioFormat);
} }
ret = audioOutput->openDeviceFunc(audioOutput); ret = audioOutput->openDeviceFunc(audioOutput);
if(cmpAudioFormat(&audioOutput->inAudioFormat, if (cmpAudioFormat(&audioOutput->inAudioFormat,
&audioOutput->outAudioFormat) == 0) &audioOutput->outAudioFormat) == 0) {
{
audioOutput->sameInAndOutFormats = 1; audioOutput->sameInAndOutFormats = 1;
} } else
else audioOutput->sameInAndOutFormats = 0; audioOutput->sameInAndOutFormats = 0;
return ret; return ret;
} }
static void convertAudioFormat(AudioOutput * audioOutput, char ** chunkArgPtr, static void convertAudioFormat(AudioOutput * audioOutput, char **chunkArgPtr,
int * sizeArgPtr) int *sizeArgPtr)
{ {
int size = pcm_sizeOfOutputBufferForAudioFormatConversion( int size =
&(audioOutput->inAudioFormat), *sizeArgPtr, pcm_sizeOfOutputBufferForAudioFormatConversion(&
&(audioOutput->outAudioFormat)); (audioOutput->
inAudioFormat),
if(size > audioOutput->convBufferLen) { *sizeArgPtr,
&(audioOutput->outAudioFormat));
if (size > audioOutput->convBufferLen) {
audioOutput->convBuffer = audioOutput->convBuffer =
realloc(audioOutput->convBuffer, size); realloc(audioOutput->convBuffer, size);
audioOutput->convBufferLen = size; audioOutput->convBufferLen = size;
...@@ -211,49 +214,59 @@ static void convertAudioFormat(AudioOutput * audioOutput, char ** chunkArgPtr, ...@@ -211,49 +214,59 @@ static void convertAudioFormat(AudioOutput * audioOutput, char ** chunkArgPtr,
*chunkArgPtr = audioOutput->convBuffer; *chunkArgPtr = audioOutput->convBuffer;
} }
int playAudioOutput(AudioOutput * audioOutput, char * playChunk, int size) { int playAudioOutput(AudioOutput * audioOutput, char *playChunk, int size)
{
int ret; int ret;
if(!audioOutput->open) return -1; if (!audioOutput->open)
return -1;
if(!audioOutput->sameInAndOutFormats) { if (!audioOutput->sameInAndOutFormats) {
convertAudioFormat(audioOutput, &playChunk, &size); convertAudioFormat(audioOutput, &playChunk, &size);
} }
ret = audioOutput->playFunc(audioOutput, playChunk, size); ret = audioOutput->playFunc(audioOutput, playChunk, size);
return ret; return ret;
} }
void dropBufferedAudioOutput(AudioOutput * audioOutput) { void dropBufferedAudioOutput(AudioOutput * audioOutput)
if(audioOutput->open) audioOutput->dropBufferedAudioFunc(audioOutput); {
if (audioOutput->open)
audioOutput->dropBufferedAudioFunc(audioOutput);
} }
void closeAudioOutput(AudioOutput * audioOutput) { void closeAudioOutput(AudioOutput * audioOutput)
if(audioOutput->open) audioOutput->closeDeviceFunc(audioOutput); {
if (audioOutput->open)
audioOutput->closeDeviceFunc(audioOutput);
} }
void finishAudioOutput(AudioOutput * audioOutput) { void finishAudioOutput(AudioOutput * audioOutput)
{
closeAudioOutput(audioOutput); closeAudioOutput(audioOutput);
audioOutput->finishDriverFunc(audioOutput); audioOutput->finishDriverFunc(audioOutput);
if(audioOutput->convBuffer) free(audioOutput->convBuffer); if (audioOutput->convBuffer)
free(audioOutput->convBuffer);
free(audioOutput->type); free(audioOutput->type);
free(audioOutput->name); free(audioOutput->name);
free(audioOutput); free(audioOutput);
} }
void sendMetadataToAudioOutput(AudioOutput * audioOutput, MpdTag * tag) { void sendMetadataToAudioOutput(AudioOutput * audioOutput, MpdTag * tag)
if(!audioOutput->sendMetdataFunc) return; {
if (!audioOutput->sendMetdataFunc)
return;
audioOutput->sendMetdataFunc(audioOutput, tag); audioOutput->sendMetdataFunc(audioOutput, tag);
} }
void printAllOutputPluginTypes(FILE *fp) { void printAllOutputPluginTypes(FILE * fp)
{
ListNode *node = audioOutputPluginList->firstNode; ListNode *node = audioOutputPluginList->firstNode;
AudioOutputPlugin *plugin; AudioOutputPlugin *plugin;
while(node) { while (node) {
plugin = (AudioOutputPlugin *)node->data; plugin = (AudioOutputPlugin *) node->data;
myfprintf(fp, "%s ", plugin->name); myfprintf(fp, "%s ", plugin->name);
node = node->nextNode; node = node->nextNode;
} }
......
...@@ -40,29 +40,29 @@ ...@@ -40,29 +40,29 @@
typedef struct _AudioOutput AudioOutput; typedef struct _AudioOutput AudioOutput;
typedef int (* AudioOutputTestDefaultDeviceFunc) (); typedef int (*AudioOutputTestDefaultDeviceFunc) ();
typedef int (* AudioOutputInitDriverFunc) (AudioOutput * audioOutput, typedef int (*AudioOutputInitDriverFunc) (AudioOutput * audioOutput,
ConfigParam * param); ConfigParam * param);
typedef void (* AudioOutputFinishDriverFunc) (AudioOutput * audioOutput); typedef void (*AudioOutputFinishDriverFunc) (AudioOutput * audioOutput);
typedef int (* AudioOutputOpenDeviceFunc) (AudioOutput * audioOutput); typedef int (*AudioOutputOpenDeviceFunc) (AudioOutput * audioOutput);
typedef int (* AudioOutputPlayFunc) (AudioOutput * audioOutput, typedef int (*AudioOutputPlayFunc) (AudioOutput * audioOutput,
char * playChunk, int size); char *playChunk, int size);
typedef void (* AudioOutputDropBufferedAudioFunc) (AudioOutput * audioOutput); typedef void (*AudioOutputDropBufferedAudioFunc) (AudioOutput * audioOutput);
typedef void (* AudioOutputCloseDeviceFunc) (AudioOutput * audioOutput); typedef void (*AudioOutputCloseDeviceFunc) (AudioOutput * audioOutput);
typedef void (* AudioOutputSendMetadataFunc) (AudioOutput * audioOutput, typedef void (*AudioOutputSendMetadataFunc) (AudioOutput * audioOutput,
MpdTag * tag); MpdTag * tag);
struct _AudioOutput { struct _AudioOutput {
int open; int open;
char * name; char *name;
char * type; char *type;
AudioOutputFinishDriverFunc finishDriverFunc; AudioOutputFinishDriverFunc finishDriverFunc;
AudioOutputOpenDeviceFunc openDeviceFunc; AudioOutputOpenDeviceFunc openDeviceFunc;
...@@ -75,15 +75,15 @@ struct _AudioOutput { ...@@ -75,15 +75,15 @@ struct _AudioOutput {
AudioFormat inAudioFormat; AudioFormat inAudioFormat;
AudioFormat outAudioFormat; AudioFormat outAudioFormat;
AudioFormat reqAudioFormat; AudioFormat reqAudioFormat;
char * convBuffer; char *convBuffer;
int convBufferLen; int convBufferLen;
int sameInAndOutFormats; int sameInAndOutFormats;
void * data; void *data;
}; };
typedef struct _AudioOutputPlugin { typedef struct _AudioOutputPlugin {
char * name; char *name;
AudioOutputTestDefaultDeviceFunc testDefaultDeviceFunc; AudioOutputTestDefaultDeviceFunc testDefaultDeviceFunc;
AudioOutputInitDriverFunc initDriverFunc; AudioOutputInitDriverFunc initDriverFunc;
...@@ -101,14 +101,14 @@ void finishAudioOutputPlugins(); ...@@ -101,14 +101,14 @@ void finishAudioOutputPlugins();
void loadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin); void loadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin);
void unloadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin); void unloadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin);
AudioOutput * newAudioOutput(ConfigParam * param); AudioOutput *newAudioOutput(ConfigParam * param);
int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat); int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat);
int playAudioOutput(AudioOutput * audioOutput, char * playChunk, int size); int playAudioOutput(AudioOutput * audioOutput, char *playChunk, int size);
void dropBufferedAudioOutput(AudioOutput * audioOutput); void dropBufferedAudioOutput(AudioOutput * audioOutput);
void closeAudioOutput(AudioOutput * audioOutput); void closeAudioOutput(AudioOutput * audioOutput);
void finishAudioOutput(AudioOutput * audioOutput); void finishAudioOutput(AudioOutput * audioOutput);
int keepAudioOutputAlive(AudioOutput * audioOutput, int ms); int keepAudioOutputAlive(AudioOutput * audioOutput, int ms);
void sendMetadataToAudioOutput(AudioOutput * audioOutput, MpdTag * tag); void sendMetadataToAudioOutput(AudioOutput * audioOutput, MpdTag * tag);
void printAllOutputPluginTypes(FILE *fp); void printAllOutputPluginTypes(FILE * fp);
#endif #endif
...@@ -34,26 +34,26 @@ static int driverInitCount = 0; ...@@ -34,26 +34,26 @@ static int driverInitCount = 0;
typedef struct _AoData { typedef struct _AoData {
int writeSize; int writeSize;
int driverId; int driverId;
ao_option * options; ao_option *options;
ao_device * device; ao_device *device;
} AoData; } AoData;
static AoData * newAoData() { static AoData *newAoData()
AoData * ret = malloc(sizeof(AoData)); {
AoData *ret = malloc(sizeof(AoData));
ret->device = NULL; ret->device = NULL;
ret->options = NULL; ret->options = NULL;
return ret; return ret;
} }
static void audioOutputAo_error() { static void audioOutputAo_error()
if(errno==AO_ENOTLIVE) { {
if (errno == AO_ENOTLIVE) {
ERROR("not a live ao device\n"); ERROR("not a live ao device\n");
} } else if (errno == AO_EOPENDEVICE) {
else if(errno==AO_EOPENDEVICE) {
ERROR("not able to open audio device\n"); ERROR("not able to open audio device\n");
} } else if (errno == AO_EBADOPTION) {
else if(errno==AO_EBADOPTION) {
ERROR("bad driver option\n"); ERROR("bad driver option\n");
} }
} }
...@@ -61,47 +61,45 @@ static void audioOutputAo_error() { ...@@ -61,47 +61,45 @@ static void audioOutputAo_error() {
static int audioOutputAo_initDriver(AudioOutput * audioOutput, static int audioOutputAo_initDriver(AudioOutput * audioOutput,
ConfigParam * param) ConfigParam * param)
{ {
ao_info * ai; ao_info *ai;
char * dup; char *dup;
char * stk1; char *stk1;
char * stk2; char *stk2;
char * n1; char *n1;
char * key; char *key;
char * value; char *value;
char * test; char *test;
AoData * ad = newAoData(); AoData *ad = newAoData();
BlockParam * blockParam; BlockParam *blockParam;
audioOutput->data = ad; audioOutput->data = ad;
if((blockParam = getBlockParam(param, "write_size"))) { if ((blockParam = getBlockParam(param, "write_size"))) {
ad->writeSize = strtol(blockParam->value, &test, 10); ad->writeSize = strtol(blockParam->value, &test, 10);
if (*test!='\0') { if (*test != '\0') {
ERROR("\"%s\" is not a valid write size at line %i\n", ERROR("\"%s\" is not a valid write size at line %i\n",
blockParam->value, blockParam->line); blockParam->value, blockParam->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} } else
else ad->writeSize = 1024; ad->writeSize = 1024;
if(driverInitCount == 0) { if (driverInitCount == 0) {
ao_initialize(); ao_initialize();
} }
driverInitCount++; driverInitCount++;
blockParam = getBlockParam(param, "driver"); blockParam = getBlockParam(param, "driver");
if(!blockParam || 0 == strcmp(blockParam->value,"default")) { if (!blockParam || 0 == strcmp(blockParam->value, "default")) {
ad->driverId = ao_default_driver_id(); ad->driverId = ao_default_driver_id();
} } else if ((ad->driverId = ao_driver_id(blockParam->value)) < 0) {
else if((ad->driverId =
ao_driver_id(blockParam->value))<0) {
ERROR("\"%s\" is not a valid ao driver at line %i\n", ERROR("\"%s\" is not a valid ao driver at line %i\n",
blockParam->value, blockParam->line); blockParam->value, blockParam->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if((ai = ao_driver_info(ad->driverId))==NULL) { if ((ai = ao_driver_info(ad->driverId)) == NULL) {
ERROR("problems getting driver info for device defined at " ERROR("problems getting driver info for device defined at "
"line %i\n", param->line); "line %i\n", param->line);
ERROR("you may not have permission to the audio device\n"); ERROR("you may not have permission to the audio device\n");
...@@ -113,18 +111,18 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput, ...@@ -113,18 +111,18 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput,
blockParam = getBlockParam(param, "options"); blockParam = getBlockParam(param, "options");
if(blockParam) { if (blockParam) {
dup = strdup(blockParam->value); dup = strdup(blockParam->value);
} } else
else dup = strdup(""); dup = strdup("");
if(strlen(dup)) { if (strlen(dup)) {
stk1 = NULL; stk1 = NULL;
n1 = strtok_r(dup,";",&stk1); n1 = strtok_r(dup, ";", &stk1);
while(n1) { while (n1) {
stk2 = NULL; stk2 = NULL;
key = strtok_r(n1,"=",&stk2); key = strtok_r(n1, "=", &stk2);
if(!key) { if (!key) {
ERROR("problems parsing " ERROR("problems parsing "
"ao_driver_options \"%s\"\n", n1); "ao_driver_options \"%s\"\n", n1);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
...@@ -141,15 +139,15 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput, ...@@ -141,15 +139,15 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput,
"\"%s\" ao driver\n",key, "\"%s\" ao driver\n",key,
ai->short_name); ai->short_name);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
}*/ } */
value = strtok_r(NULL,"",&stk2); value = strtok_r(NULL, "", &stk2);
if(!value) { if (!value) {
ERROR("problems parsing " ERROR("problems parsing "
"ao_driver_options \"%s\"\n", n1); "ao_driver_options \"%s\"\n", n1);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
ao_append_option(&ad->options,key,value); ao_append_option(&ad->options, key, value);
n1 = strtok_r(NULL,";",&stk1); n1 = strtok_r(NULL, ";", &stk1);
} }
} }
free(dup); free(dup);
...@@ -157,28 +155,33 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput, ...@@ -157,28 +155,33 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput,
return 0; return 0;
} }
static void freeAoData(AoData * ad) { static void freeAoData(AoData * ad)
{
ao_free_options(ad->options); ao_free_options(ad->options);
free(ad); free(ad);
} }
static void audioOutputAo_finishDriver(AudioOutput * audioOutput) { static void audioOutputAo_finishDriver(AudioOutput * audioOutput)
AoData * ad = (AoData *)audioOutput->data; {
AoData *ad = (AoData *) audioOutput->data;
freeAoData(ad); freeAoData(ad);
driverInitCount--; driverInitCount--;
if(driverInitCount == 0) ao_shutdown(); if (driverInitCount == 0)
ao_shutdown();
} }
static void audioOutputAo_dropBufferedAudio(AudioOutput * audioOutput) { static void audioOutputAo_dropBufferedAudio(AudioOutput * audioOutput)
{
/* not supported by libao */ /* not supported by libao */
} }
static void audioOutputAo_closeDevice(AudioOutput * audioOutput) { static void audioOutputAo_closeDevice(AudioOutput * audioOutput)
AoData * ad = (AoData *) audioOutput->data; {
AoData *ad = (AoData *) audioOutput->data;
if(ad->device) { if (ad->device) {
ao_close(ad->device); ao_close(ad->device);
ad->device = NULL; ad->device = NULL;
} }
...@@ -186,11 +189,12 @@ static void audioOutputAo_closeDevice(AudioOutput * audioOutput) { ...@@ -186,11 +189,12 @@ static void audioOutputAo_closeDevice(AudioOutput * audioOutput) {
audioOutput->open = 0; audioOutput->open = 0;
} }
static int audioOutputAo_openDevice(AudioOutput * audioOutput) { static int audioOutputAo_openDevice(AudioOutput * audioOutput)
{
ao_sample_format format; ao_sample_format format;
AoData * ad = (AoData *)audioOutput->data; AoData *ad = (AoData *) audioOutput->data;
if(ad->device) { if (ad->device) {
audioOutputAo_closeDevice(audioOutput); audioOutputAo_closeDevice(audioOutput);
} }
...@@ -201,41 +205,41 @@ static int audioOutputAo_openDevice(AudioOutput * audioOutput) { ...@@ -201,41 +205,41 @@ static int audioOutputAo_openDevice(AudioOutput * audioOutput) {
ad->device = ao_open_live(ad->driverId, &format, ad->options); ad->device = ao_open_live(ad->driverId, &format, ad->options);
if(ad->device==NULL) return -1; if (ad->device == NULL)
return -1;
audioOutput->open = 1; audioOutput->open = 1;
return 0; return 0;
} }
static int audioOutputAo_play(AudioOutput * audioOutput, char *playChunk,
static int audioOutputAo_play(AudioOutput * audioOutput, char * playChunk,
int size) int size)
{ {
int send; int send;
AoData * ad = (AoData *)audioOutput->data; AoData *ad = (AoData *) audioOutput->data;
if(ad->device==NULL) return -1; if (ad->device == NULL)
return -1;
while(size>0) { while (size > 0) {
send = ad->writeSize > size ? size : ad->writeSize; send = ad->writeSize > size ? size : ad->writeSize;
if(ao_play(ad->device, playChunk, send)==0) { if (ao_play(ad->device, playChunk, send) == 0) {
audioOutputAo_error(); audioOutputAo_error();
ERROR("closing audio device due to write error\n"); ERROR("closing audio device due to write error\n");
audioOutputAo_closeDevice(audioOutput); audioOutputAo_closeDevice(audioOutput);
return -1; return -1;
} }
playChunk+=send; playChunk += send;
size-=send; size -= send;
} }
return 0; return 0;
} }
AudioOutputPlugin aoPlugin = AudioOutputPlugin aoPlugin = {
{
"ao", "ao",
NULL, NULL,
audioOutputAo_initDriver, audioOutputAo_initDriver,
...@@ -252,5 +256,4 @@ AudioOutputPlugin aoPlugin = ...@@ -252,5 +256,4 @@ AudioOutputPlugin aoPlugin =
#include <stdio.h> #include <stdio.h>
DISABLED_AUDIO_OUTPUT_PLUGIN(aoPlugin) DISABLED_AUDIO_OUTPUT_PLUGIN(aoPlugin)
#endif #endif
...@@ -31,15 +31,16 @@ typedef struct _OsxData { ...@@ -31,15 +31,16 @@ typedef struct _OsxData {
AudioUnit au; AudioUnit au;
pthread_mutex_t mutex; pthread_mutex_t mutex;
pthread_cond_t condition; pthread_cond_t condition;
char * buffer; char *buffer;
int bufferSize; int bufferSize;
int pos; int pos;
int len; int len;
int started; int started;
} OsxData; } OsxData;
static OsxData * newOsxData() { static OsxData *newOsxData()
OsxData * ret = malloc(sizeof(OsxData)); {
OsxData *ret = malloc(sizeof(OsxData));
pthread_mutex_init(&ret->mutex, NULL); pthread_mutex_init(&ret->mutex, NULL);
pthread_cond_init(&ret->condition, NULL); pthread_cond_init(&ret->condition, NULL);
...@@ -53,7 +54,8 @@ static OsxData * newOsxData() { ...@@ -53,7 +54,8 @@ static OsxData * newOsxData() {
return ret; return ret;
} }
static int osx_testDefault() { static int osx_testDefault()
{
/*AudioUnit au; /*AudioUnit au;
ComponentDescription desc; ComponentDescription desc;
Component comp; Component comp;
...@@ -75,49 +77,55 @@ static int osx_testDefault() { ...@@ -75,49 +77,55 @@ static int osx_testDefault() {
return -1; return -1;
} }
CloseComponent(au);*/ CloseComponent(au); */
return 0; return 0;
} }
static int osx_initDriver(AudioOutput * audioOutput, ConfigParam * param) { static int osx_initDriver(AudioOutput * audioOutput, ConfigParam * param)
OsxData * od = newOsxData(); {
OsxData *od = newOsxData();
audioOutput->data = od; audioOutput->data = od;
return 0; return 0;
} }
static void freeOsxData(OsxData * od) { static void freeOsxData(OsxData * od)
if(od->buffer) free(od->buffer); {
if (od->buffer)
free(od->buffer);
pthread_mutex_destroy(&od->mutex); pthread_mutex_destroy(&od->mutex);
pthread_cond_destroy(&od->condition); pthread_cond_destroy(&od->condition);
free(od); free(od);
} }
static void osx_finishDriver(AudioOutput * audioOutput) { static void osx_finishDriver(AudioOutput * audioOutput)
OsxData * od = (OsxData *)audioOutput->data; {
OsxData *od = (OsxData *) audioOutput->data;
freeOsxData(od); freeOsxData(od);
} }
static void osx_dropBufferedAudio(AudioOutput * audioOutput) { static void osx_dropBufferedAudio(AudioOutput * audioOutput)
OsxData * od = (OsxData *)audioOutput->data; {
OsxData *od = (OsxData *) audioOutput->data;
pthread_mutex_lock(&od->mutex); pthread_mutex_lock(&od->mutex);
od->len = 0; od->len = 0;
pthread_mutex_unlock(&od->mutex); pthread_mutex_unlock(&od->mutex);
} }
static void osx_closeDevice(AudioOutput * audioOutput) { static void osx_closeDevice(AudioOutput * audioOutput)
OsxData * od = (OsxData *) audioOutput->data; {
OsxData *od = (OsxData *) audioOutput->data;
pthread_mutex_lock(&od->mutex); pthread_mutex_lock(&od->mutex);
while(od->len) { while (od->len) {
pthread_cond_wait(&od->condition, &od->mutex); pthread_cond_wait(&od->condition, &od->mutex);
} }
pthread_mutex_unlock(&od->mutex); pthread_mutex_unlock(&od->mutex);
if(od->started) { if (od->started) {
AudioOutputUnitStop(od->au); AudioOutputUnitStop(od->au);
od->started = 0; od->started = 0;
} }
...@@ -128,14 +136,14 @@ static void osx_closeDevice(AudioOutput * audioOutput) { ...@@ -128,14 +136,14 @@ static void osx_closeDevice(AudioOutput * audioOutput) {
audioOutput->open = 0; audioOutput->open = 0;
} }
static OSStatus osx_render(void * vdata, static OSStatus osx_render(void *vdata,
AudioUnitRenderActionFlags *ioActionFlags, AudioUnitRenderActionFlags * ioActionFlags,
const AudioTimeStamp * inTimeStamp, const AudioTimeStamp * inTimeStamp,
UInt32 inBusNumber, UInt32 inNumberFrames, UInt32 inBusNumber, UInt32 inNumberFrames,
AudioBufferList *bufferList) AudioBufferList * bufferList)
{ {
OsxData * od = (OsxData *)vdata; OsxData *od = (OsxData *) vdata;
AudioBuffer * buffer = &bufferList->mBuffers[0]; AudioBuffer *buffer = &bufferList->mBuffers[0];
int bufferSize = buffer->mDataByteSize; int bufferSize = buffer->mDataByteSize;
int bytesToCopy; int bytesToCopy;
int curpos = 0; int curpos = 0;
...@@ -161,7 +169,7 @@ static OSStatus osx_render(void * vdata, ...@@ -161,7 +169,7 @@ static OSStatus osx_render(void * vdata,
if(*ioActionFlags & kAudioOfflineUnitRenderAction_Complete) { if(*ioActionFlags & kAudioOfflineUnitRenderAction_Complete) {
DEBUG("complete\n"); DEBUG("complete\n");
} }
}*/ } */
/* while(bufferSize) { /* while(bufferSize) {
DEBUG("osx_render: lock\n"); */ DEBUG("osx_render: lock\n"); */
...@@ -180,19 +188,20 @@ static OSStatus osx_render(void * vdata, ...@@ -180,19 +188,20 @@ static OSStatus osx_render(void * vdata,
bufferSize = bytesToCopy; bufferSize = bytesToCopy;
od->len -= bytesToCopy; od->len -= bytesToCopy;
if(od->pos+bytesToCopy > od->bufferSize) { if (od->pos + bytesToCopy > od->bufferSize) {
int bytes = od->bufferSize-od->pos; int bytes = od->bufferSize - od->pos;
memcpy(buffer->mData+curpos, od->buffer+od->pos, bytes); memcpy(buffer->mData + curpos, od->buffer + od->pos, bytes);
od->pos = 0; od->pos = 0;
curpos += bytes; curpos += bytes;
bytesToCopy -= bytes; bytesToCopy -= bytes;
} }
memcpy(buffer->mData+curpos, od->buffer+od->pos, bytesToCopy); memcpy(buffer->mData + curpos, od->buffer + od->pos, bytesToCopy);
od->pos += bytesToCopy; od->pos += bytesToCopy;
curpos += bytesToCopy; curpos += bytesToCopy;
if(od->pos >= od->bufferSize) od->pos = 0; if (od->pos >= od->bufferSize)
od->pos = 0;
/* DEBUG("osx_render: unlock\n"); */ /* DEBUG("osx_render: unlock\n"); */
pthread_mutex_unlock(&od->mutex); pthread_mutex_unlock(&od->mutex);
pthread_cond_signal(&od->condition); pthread_cond_signal(&od->condition);
...@@ -200,7 +209,7 @@ static OSStatus osx_render(void * vdata, ...@@ -200,7 +209,7 @@ static OSStatus osx_render(void * vdata,
buffer->mDataByteSize = bufferSize; buffer->mDataByteSize = bufferSize;
if(!bufferSize) { if (!bufferSize) {
my_usleep(1000); my_usleep(1000);
} }
...@@ -208,12 +217,13 @@ static OSStatus osx_render(void * vdata, ...@@ -208,12 +217,13 @@ static OSStatus osx_render(void * vdata,
return 0; return 0;
} }
static int osx_openDevice(AudioOutput * audioOutput) { static int osx_openDevice(AudioOutput * audioOutput)
OsxData * od = (OsxData *)audioOutput->data; {
OsxData *od = (OsxData *) audioOutput->data;
ComponentDescription desc; ComponentDescription desc;
Component comp; Component comp;
AURenderCallbackStruct callback; AURenderCallbackStruct callback;
AudioFormat * audioFormat = &audioOutput->outAudioFormat; AudioFormat *audioFormat = &audioOutput->outAudioFormat;
AudioStreamBasicDescription streamDesc; AudioStreamBasicDescription streamDesc;
desc.componentType = kAudioUnitType_Output; desc.componentType = kAudioUnitType_Output;
...@@ -223,17 +233,17 @@ static int osx_openDevice(AudioOutput * audioOutput) { ...@@ -223,17 +233,17 @@ static int osx_openDevice(AudioOutput * audioOutput) {
desc.componentFlagsMask = 0; desc.componentFlagsMask = 0;
comp = FindNextComponent(NULL, &desc); comp = FindNextComponent(NULL, &desc);
if(comp == 0) { if (comp == 0) {
ERROR("Error finding OS X component\n"); ERROR("Error finding OS X component\n");
return -1; return -1;
} }
if(OpenAComponent(comp, &od->au) != noErr) { if (OpenAComponent(comp, &od->au) != noErr) {
ERROR("Unable to open OS X component\n"); ERROR("Unable to open OS X component\n");
return -1; return -1;
} }
if(AudioUnitInitialize(od->au) != 0) { if (AudioUnitInitialize(od->au) != 0) {
CloseComponent(od->au); CloseComponent(od->au);
ERROR("Unable to initialuze OS X audio unit\n"); ERROR("Unable to initialuze OS X audio unit\n");
return -1; return -1;
...@@ -242,10 +252,9 @@ static int osx_openDevice(AudioOutput * audioOutput) { ...@@ -242,10 +252,9 @@ static int osx_openDevice(AudioOutput * audioOutput) {
callback.inputProc = osx_render; callback.inputProc = osx_render;
callback.inputProcRefCon = od; callback.inputProcRefCon = od;
if(AudioUnitSetProperty(od->au, kAudioUnitProperty_SetRenderCallback, if (AudioUnitSetProperty(od->au, kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input, 0, kAudioUnitScope_Input, 0,
&callback, sizeof(callback)) != 0) &callback, sizeof(callback)) != 0) {
{
AudioUnitUninitialize(od->au); AudioUnitUninitialize(od->au);
CloseComponent(od->au); CloseComponent(od->au);
ERROR("unable to set callbak for OS X audio unit\n"); ERROR("unable to set callbak for OS X audio unit\n");
...@@ -256,16 +265,16 @@ static int osx_openDevice(AudioOutput * audioOutput) { ...@@ -256,16 +265,16 @@ static int osx_openDevice(AudioOutput * audioOutput) {
streamDesc.mFormatID = kAudioFormatLinearPCM; streamDesc.mFormatID = kAudioFormatLinearPCM;
streamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | streamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger |
kLinearPCMFormatFlagIsBigEndian; kLinearPCMFormatFlagIsBigEndian;
streamDesc.mBytesPerPacket = audioFormat->channels*audioFormat->bits/8; streamDesc.mBytesPerPacket =
audioFormat->channels * audioFormat->bits / 8;
streamDesc.mFramesPerPacket = 1; streamDesc.mFramesPerPacket = 1;
streamDesc.mBytesPerFrame = streamDesc.mBytesPerPacket; streamDesc.mBytesPerFrame = streamDesc.mBytesPerPacket;
streamDesc.mChannelsPerFrame = audioFormat->channels; streamDesc.mChannelsPerFrame = audioFormat->channels;
streamDesc.mBitsPerChannel = audioFormat->bits; streamDesc.mBitsPerChannel = audioFormat->bits;
if(AudioUnitSetProperty(od->au, kAudioUnitProperty_StreamFormat, if (AudioUnitSetProperty(od->au, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input, 0, kAudioUnitScope_Input, 0,
&streamDesc, sizeof(streamDesc)) != 0) &streamDesc, sizeof(streamDesc)) != 0) {
{
AudioUnitUninitialize(od->au); AudioUnitUninitialize(od->au);
CloseComponent(od->au); CloseComponent(od->au);
ERROR("Unable to set format on OS X device\n"); ERROR("Unable to set format on OS X device\n");
...@@ -285,18 +294,19 @@ static int osx_openDevice(AudioOutput * audioOutput) { ...@@ -285,18 +294,19 @@ static int osx_openDevice(AudioOutput * audioOutput) {
return 0; return 0;
} }
static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) { static int osx_play(AudioOutput * audioOutput, char *playChunk, int size)
OsxData * od = (OsxData *)audioOutput->data; {
OsxData *od = (OsxData *) audioOutput->data;
int bytesToCopy; int bytesToCopy;
int curpos; int curpos;
/* DEBUG("osx_play: enter\n"); */ /* DEBUG("osx_play: enter\n"); */
if(!od->started) { if (!od->started) {
int err; int err;
od->started = 1; od->started = 1;
err = AudioOutputUnitStart(od->au); err = AudioOutputUnitStart(od->au);
if(err) { if (err) {
ERROR("unable to start audio output: %i\n", err); ERROR("unable to start audio output: %i\n", err);
return -1; return -1;
} }
...@@ -304,14 +314,15 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) { ...@@ -304,14 +314,15 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) {
pthread_mutex_lock(&od->mutex); pthread_mutex_lock(&od->mutex);
while(size) { while (size) {
/* DEBUG("osx_play: lock\n"); */ /* DEBUG("osx_play: lock\n"); */
curpos = od->pos+od->len; curpos = od->pos + od->len;
if(curpos >= od->bufferSize) curpos -= od->bufferSize; if (curpos >= od->bufferSize)
curpos -= od->bufferSize;
bytesToCopy = od->bufferSize < size ? od->bufferSize : size; bytesToCopy = od->bufferSize < size ? od->bufferSize : size;
while(od->len > od->bufferSize-bytesToCopy) { while (od->len > od->bufferSize - bytesToCopy) {
/* DEBUG("osx_play: wait\n"); */ /* DEBUG("osx_play: wait\n"); */
pthread_cond_wait(&od->condition, &od->mutex); pthread_cond_wait(&od->condition, &od->mutex);
} }
...@@ -321,15 +332,15 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) { ...@@ -321,15 +332,15 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) {
size -= bytesToCopy; size -= bytesToCopy;
od->len += bytesToCopy; od->len += bytesToCopy;
if(curpos+bytesToCopy > od->bufferSize) { if (curpos + bytesToCopy > od->bufferSize) {
int bytes = od->bufferSize-curpos; int bytes = od->bufferSize - curpos;
memcpy(od->buffer+curpos, playChunk, bytes); memcpy(od->buffer + curpos, playChunk, bytes);
curpos = 0; curpos = 0;
playChunk += bytes; playChunk += bytes;
bytesToCopy -= bytes; bytesToCopy -= bytes;
} }
memcpy(od->buffer+curpos, playChunk, bytesToCopy); memcpy(od->buffer + curpos, playChunk, bytesToCopy);
curpos += bytesToCopy; curpos += bytesToCopy;
playChunk += bytesToCopy; playChunk += bytesToCopy;
...@@ -341,8 +352,7 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) { ...@@ -341,8 +352,7 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) {
return 0; return 0;
} }
AudioOutputPlugin osxPlugin = AudioOutputPlugin osxPlugin = {
{
"osx", "osx",
osx_testDefault, osx_testDefault,
osx_initDriver, osx_initDriver,
...@@ -359,5 +369,4 @@ AudioOutputPlugin osxPlugin = ...@@ -359,5 +369,4 @@ AudioOutputPlugin osxPlugin =
#include <stdio.h> #include <stdio.h>
DISABLED_AUDIO_OUTPUT_PLUGIN(osxPlugin) DISABLED_AUDIO_OUTPUT_PLUGIN(osxPlugin)
#endif #endif
...@@ -34,16 +34,16 @@ ...@@ -34,16 +34,16 @@
#define CONN_ATTEMPT_INTERVAL 60 #define CONN_ATTEMPT_INTERVAL 60
typedef struct _PulseData { typedef struct _PulseData {
pa_simple * s; pa_simple *s;
char * server; char *server;
char * sink; char *sink;
int connAttempts; int connAttempts;
time_t lastAttempt; time_t lastAttempt;
} PulseData; } PulseData;
static PulseData * newPulseData() static PulseData *newPulseData()
{ {
PulseData * ret; PulseData *ret;
ret = malloc(sizeof(PulseData)); ret = malloc(sizeof(PulseData));
...@@ -58,16 +58,18 @@ static PulseData * newPulseData() ...@@ -58,16 +58,18 @@ static PulseData * newPulseData()
static void freePulseData(PulseData * pd) static void freePulseData(PulseData * pd)
{ {
if (pd->server) free(pd->server); if (pd->server)
if (pd->sink) free(pd->sink); free(pd->server);
if (pd->sink)
free(pd->sink);
free(pd); free(pd);
} }
static int pulse_initDriver(AudioOutput * audioOutput, ConfigParam * param) static int pulse_initDriver(AudioOutput * audioOutput, ConfigParam * param)
{ {
BlockParam * server = NULL; BlockParam *server = NULL;
BlockParam * sink = NULL; BlockParam *sink = NULL;
PulseData * pd; PulseData *pd;
if (param) { if (param) {
server = getBlockParam(param, "server"); server = getBlockParam(param, "server");
...@@ -89,7 +91,7 @@ static void pulse_finishDriver(AudioOutput * audioOutput) ...@@ -89,7 +91,7 @@ static void pulse_finishDriver(AudioOutput * audioOutput)
static int pulse_testDefault() static int pulse_testDefault()
{ {
pa_simple * s; pa_simple *s;
pa_sample_spec ss; pa_sample_spec ss;
int error; int error;
...@@ -112,8 +114,8 @@ static int pulse_testDefault() ...@@ -112,8 +114,8 @@ static int pulse_testDefault()
static int pulse_openDevice(AudioOutput * audioOutput) static int pulse_openDevice(AudioOutput * audioOutput)
{ {
PulseData * pd; PulseData *pd;
AudioFormat * audioFormat; AudioFormat *audioFormat;
pa_sample_spec ss; pa_sample_spec ss;
time_t t; time_t t;
int error; int error;
...@@ -123,7 +125,8 @@ static int pulse_openDevice(AudioOutput * audioOutput) ...@@ -123,7 +125,8 @@ static int pulse_openDevice(AudioOutput * audioOutput)
audioFormat = &audioOutput->outAudioFormat; audioFormat = &audioOutput->outAudioFormat;
if (pd->connAttempts != 0 && if (pd->connAttempts != 0 &&
(t - pd->lastAttempt) < CONN_ATTEMPT_INTERVAL) return -1; (t - pd->lastAttempt) < CONN_ATTEMPT_INTERVAL)
return -1;
pd->connAttempts++; pd->connAttempts++;
pd->lastAttempt = t; pd->lastAttempt = t;
...@@ -142,7 +145,7 @@ static int pulse_openDevice(AudioOutput * audioOutput) ...@@ -142,7 +145,7 @@ static int pulse_openDevice(AudioOutput * audioOutput)
pd->sink, audioOutput->name, &ss, NULL, NULL, pd->sink, audioOutput->name, &ss, NULL, NULL,
&error); &error);
if (!pd->s) { if (!pd->s) {
ERROR("Cannot connect to server in PulseAudio output " \ ERROR("Cannot connect to server in PulseAudio output "
"\"%s\" (attempt %i): %s\n", audioOutput->name, "\"%s\" (attempt %i): %s\n", audioOutput->name,
pd->connAttempts, pa_strerror(error)); pd->connAttempts, pa_strerror(error));
return -1; return -1;
...@@ -151,7 +154,7 @@ static int pulse_openDevice(AudioOutput * audioOutput) ...@@ -151,7 +154,7 @@ static int pulse_openDevice(AudioOutput * audioOutput)
pd->connAttempts = 0; pd->connAttempts = 0;
audioOutput->open = 1; audioOutput->open = 1;
DEBUG("PulseAudio output \"%s\" connected and playing %i bit, %i " \ DEBUG("PulseAudio output \"%s\" connected and playing %i bit, %i "
"channel audio at %i Hz\n", audioOutput->name, audioFormat->bits, "channel audio at %i Hz\n", audioOutput->name, audioFormat->bits,
audioFormat->channels, audioFormat->sampleRate); audioFormat->channels, audioFormat->sampleRate);
...@@ -160,7 +163,7 @@ static int pulse_openDevice(AudioOutput * audioOutput) ...@@ -160,7 +163,7 @@ static int pulse_openDevice(AudioOutput * audioOutput)
static void pulse_dropBufferedAudio(AudioOutput * audioOutput) static void pulse_dropBufferedAudio(AudioOutput * audioOutput)
{ {
PulseData * pd; PulseData *pd;
int error; int error;
pd = audioOutput->data; pd = audioOutput->data;
...@@ -171,7 +174,7 @@ static void pulse_dropBufferedAudio(AudioOutput * audioOutput) ...@@ -171,7 +174,7 @@ static void pulse_dropBufferedAudio(AudioOutput * audioOutput)
static void pulse_closeDevice(AudioOutput * audioOutput) static void pulse_closeDevice(AudioOutput * audioOutput)
{ {
PulseData * pd; PulseData *pd;
pd = audioOutput->data; pd = audioOutput->data;
if (pd->s) { if (pd->s) {
...@@ -182,16 +185,15 @@ static void pulse_closeDevice(AudioOutput * audioOutput) ...@@ -182,16 +185,15 @@ static void pulse_closeDevice(AudioOutput * audioOutput)
audioOutput->open = 0; audioOutput->open = 0;
} }
static int pulse_playAudio(AudioOutput * audioOutput, char * playChunk, static int pulse_playAudio(AudioOutput * audioOutput, char *playChunk, int size)
int size)
{ {
PulseData * pd; PulseData *pd;
int error; int error;
pd = audioOutput->data; pd = audioOutput->data;
if (pa_simple_write(pd->s, playChunk, size, &error) < 0) { if (pa_simple_write(pd->s, playChunk, size, &error) < 0) {
ERROR("PulseAudio output \"%s\" disconnecting due to write " \ ERROR("PulseAudio output \"%s\" disconnecting due to write "
"error: %s\n", audioOutput->name, pa_strerror(error)); "error: %s\n", audioOutput->name, pa_strerror(error));
pulse_closeDevice(audioOutput); pulse_closeDevice(audioOutput);
return -1; return -1;
...@@ -215,5 +217,4 @@ AudioOutputPlugin pulsePlugin = { ...@@ -215,5 +217,4 @@ AudioOutputPlugin pulsePlugin = {
#else /* HAVE_PULSE */ #else /* HAVE_PULSE */
DISABLED_AUDIO_OUTPUT_PLUGIN(pulsePlugin) DISABLED_AUDIO_OUTPUT_PLUGIN(pulsePlugin)
#endif /* HAVE_PULSE */ #endif /* HAVE_PULSE */
...@@ -22,79 +22,74 @@ ...@@ -22,79 +22,74 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
int buffer2array(char * origBuffer, char *** array) { int buffer2array(char *origBuffer, char ***array)
{
int quotes = 0; int quotes = 0;
int count = 0; int count = 0;
int i; int i;
int curr; int curr;
int * beginArray; int *beginArray;
char * buffer = strdup(origBuffer); char *buffer = strdup(origBuffer);
int bufferLength = strlen(buffer); int bufferLength = strlen(buffer);
char * markArray = malloc(sizeof(char)*(bufferLength+1)); char *markArray = malloc(sizeof(char) * (bufferLength + 1));
for(curr=0;curr<bufferLength;curr++) { for (curr = 0; curr < bufferLength; curr++) {
if(!quotes && (buffer[curr]==' ' || buffer[curr]=='\t') ) { if (!quotes && (buffer[curr] == ' ' || buffer[curr] == '\t')) {
markArray[curr] = '0'; markArray[curr] = '0';
} } else if (buffer[curr] == '\"') {
else if(buffer[curr] == '\"') { if (curr > 0 && buffer[curr - 1] != '\\') {
if(curr>0 && buffer[curr-1]!='\\') { quotes = quotes ? 0 : 1;
quotes = quotes?0:1;
markArray[curr] = '0'; markArray[curr] = '0';
} } else {
else {
markArray[curr] = '1'; markArray[curr] = '1';
} }
} } else {
else {
markArray[curr] = '1'; markArray[curr] = '1';
} }
if(markArray[curr]=='1') { if (markArray[curr] == '1') {
if(curr>0) { if (curr > 0) {
if(markArray[curr-1]=='0') { if (markArray[curr - 1] == '0') {
count++; count++;
} }
} } else {
else {
count++; count++;
} }
} }
} }
markArray[bufferLength] = '\0'; markArray[bufferLength] = '\0';
if(!count) { if (!count) {
free(buffer); free(buffer);
free(markArray); free(markArray);
return count; return count;
} }
beginArray = malloc(sizeof(int)*count); beginArray = malloc(sizeof(int) * count);
(*array) = malloc(sizeof(char *)*count); (*array) = malloc(sizeof(char *) * count);
count = 0; count = 0;
for(curr=0;curr<bufferLength;curr++) { for (curr = 0; curr < bufferLength; curr++) {
if(markArray[curr]=='1') { if (markArray[curr] == '1') {
if(curr>0) { if (curr > 0) {
if(markArray[curr-1]=='0') { if (markArray[curr - 1] == '0') {
beginArray[count++] = curr; beginArray[count++] = curr;
} }
} } else {
else {
beginArray[count++] = curr; beginArray[count++] = curr;
} }
} } else {
else {
buffer[curr] = '\0'; buffer[curr] = '\0';
} }
} }
for(i=0;i<count;i++) { for (i = 0; i < count; i++) {
int len = strlen(buffer+beginArray[i])+1; int len = strlen(buffer + beginArray[i]) + 1;
int arrayCurr = 0; int arrayCurr = 0;
(*array)[i] = malloc(sizeof(char)*len); (*array)[i] = malloc(sizeof(char) * len);
for(curr=beginArray[i];buffer[curr]!='\0';curr++) { for (curr = beginArray[i]; buffer[curr] != '\0'; curr++) {
if(buffer[curr]=='\\') { if (buffer[curr] == '\\') {
if(buffer[curr+1]!='\0') { if (buffer[curr + 1] != '\0') {
curr++; curr++;
} }
} }
...@@ -110,12 +105,14 @@ int buffer2array(char * origBuffer, char *** array) { ...@@ -110,12 +105,14 @@ int buffer2array(char * origBuffer, char *** array) {
return count; return count;
} }
void freeArgArray(char ** array, int argArrayLength) { void freeArgArray(char **array, int argArrayLength)
{
int i; int i;
if(argArrayLength==0) return; if (argArrayLength == 0)
return;
for(i=0;i<argArrayLength;i++) { for (i = 0; i < argArrayLength; i++) {
free(array[i]); free(array[i]);
} }
free(array); free(array);
......
...@@ -21,8 +21,8 @@ ...@@ -21,8 +21,8 @@
#include "../config.h" #include "../config.h"
int buffer2array(char * buffer, char *** array); int buffer2array(char *buffer, char ***array);
void freeArgArray(char ** array, int argArrayLength); void freeArgArray(char **array, int argArrayLength);
#endif #endif
...@@ -29,8 +29,8 @@ ...@@ -29,8 +29,8 @@
iconv_t char_conv_iconv; iconv_t char_conv_iconv;
#endif #endif
char * char_conv_to = NULL; char *char_conv_to = NULL;
char * char_conv_from = NULL; char *char_conv_from = NULL;
mpd_sint8 char_conv_same = 0; mpd_sint8 char_conv_same = 0;
mpd_sint8 char_conv_use_iconv = 0; mpd_sint8 char_conv_use_iconv = 0;
...@@ -43,37 +43,37 @@ mpd_sint8 char_conv_latin1ToUtf8 = 0; ...@@ -43,37 +43,37 @@ mpd_sint8 char_conv_latin1ToUtf8 = 0;
static void closeCharSetConversion(); static void closeCharSetConversion();
int setCharSetConversion(char * to, char * from) { int setCharSetConversion(char *to, char *from)
if(char_conv_to && char_conv_from && {
strcmp(to,char_conv_to)==0 && strcmp(from,char_conv_from)==0) if (char_conv_to && char_conv_from &&
strcmp(to, char_conv_to) == 0 && strcmp(from, char_conv_from) == 0)
{ {
return 0; return 0;
} }
closeCharSetConversion(); closeCharSetConversion();
if(0==strcmp(to,from)) { if (0 == strcmp(to, from)) {
char_conv_same = 1; char_conv_same = 1;
char_conv_to = strdup(to); char_conv_to = strdup(to);
char_conv_from = strdup(from); char_conv_from = strdup(from);
return 0; return 0;
} }
if(strcmp(to,"UTF-8")==0 && strcmp(from,"ISO-8859-1")==0) { if (strcmp(to, "UTF-8") == 0 && strcmp(from, "ISO-8859-1") == 0) {
char_conv_latin1ToUtf8 = 1; char_conv_latin1ToUtf8 = 1;
} } else if (strcmp(to, "ISO-8859-1") == 0 && strcmp(from, "UTF-8") == 0) {
else if(strcmp(to,"ISO-8859-1")==0 && strcmp(from,"UTF-8")==0) {
char_conv_latin1ToUtf8 = -1; char_conv_latin1ToUtf8 = -1;
} }
if(char_conv_latin1ToUtf8!=0) { if (char_conv_latin1ToUtf8 != 0) {
char_conv_to = strdup(to); char_conv_to = strdup(to);
char_conv_from = strdup(from); char_conv_from = strdup(from);
return 0; return 0;
} }
#ifdef HAVE_ICONV #ifdef HAVE_ICONV
if((char_conv_iconv = iconv_open(to,from))==(iconv_t)(-1)) return -1; if ((char_conv_iconv = iconv_open(to, from)) == (iconv_t) (-1))
return -1;
char_conv_to = strdup(to); char_conv_to = strdup(to);
char_conv_from = strdup(from); char_conv_from = strdup(from);
...@@ -85,37 +85,42 @@ int setCharSetConversion(char * to, char * from) { ...@@ -85,37 +85,42 @@ int setCharSetConversion(char * to, char * from) {
return -1; return -1;
} }
char * convStrDup(char * string) { char *convStrDup(char *string)
if(!char_conv_to) return NULL; {
if (!char_conv_to)
return NULL;
if(char_conv_same) return strdup(string); if (char_conv_same)
return strdup(string);
#ifdef HAVE_ICONV #ifdef HAVE_ICONV
if(char_conv_use_iconv) { if (char_conv_use_iconv) {
char buffer[BUFFER_SIZE]; char buffer[BUFFER_SIZE];
size_t inleft = strlen(string); size_t inleft = strlen(string);
char * ret; char *ret;
size_t outleft; size_t outleft;
size_t retlen = 0; size_t retlen = 0;
size_t err; size_t err;
char * bufferPtr; char *bufferPtr;
ret = malloc(1); ret = malloc(1);
ret[0] = '\0'; ret[0] = '\0';
while(inleft) { while (inleft) {
bufferPtr = buffer; bufferPtr = buffer;
outleft = BUFFER_SIZE; outleft = BUFFER_SIZE;
err = iconv(char_conv_iconv,&string,&inleft,&bufferPtr, err =
iconv(char_conv_iconv, &string, &inleft, &bufferPtr,
&outleft); &outleft);
if(outleft==BUFFER_SIZE || (err<0 && errno!=E2BIG)) { if (outleft == BUFFER_SIZE
|| (err < 0 && errno != E2BIG)) {
free(ret); free(ret);
return NULL; return NULL;
} }
ret = realloc(ret,retlen+BUFFER_SIZE-outleft+1); ret = realloc(ret, retlen + BUFFER_SIZE - outleft + 1);
memcpy(ret+retlen,buffer,BUFFER_SIZE-outleft); memcpy(ret + retlen, buffer, BUFFER_SIZE - outleft);
retlen+=BUFFER_SIZE-outleft; retlen += BUFFER_SIZE - outleft;
ret[retlen] = '\0'; ret[retlen] = '\0';
} }
...@@ -123,7 +128,7 @@ char * convStrDup(char * string) { ...@@ -123,7 +128,7 @@ char * convStrDup(char * string) {
} }
#endif #endif
switch(char_conv_latin1ToUtf8) { switch (char_conv_latin1ToUtf8) {
case 1: case 1:
return latin1StrToUtf8Dup(string); return latin1StrToUtf8Dup(string);
break; break;
...@@ -135,10 +140,12 @@ char * convStrDup(char * string) { ...@@ -135,10 +140,12 @@ char * convStrDup(char * string) {
return NULL; return NULL;
} }
static void closeCharSetConversion(void) { static void closeCharSetConversion(void)
if(char_conv_to) { {
if (char_conv_to) {
#ifdef HAVE_ICONV #ifdef HAVE_ICONV
if(char_conv_use_iconv) iconv_close(char_conv_iconv); if (char_conv_use_iconv)
iconv_close(char_conv_iconv);
#endif #endif
free(char_conv_to); free(char_conv_to);
free(char_conv_from); free(char_conv_from);
......
...@@ -21,8 +21,8 @@ ...@@ -21,8 +21,8 @@
#include "../config.h" #include "../config.h"
int setCharSetConversion(char * to, char * from); int setCharSetConversion(char *to, char *from);
char * convStrDup(char * string); char *convStrDup(char *string);
#endif #endif
...@@ -32,13 +32,13 @@ ...@@ -32,13 +32,13 @@
#define COMMAND_RETURN_CLOSE 20 #define COMMAND_RETURN_CLOSE 20
#define COMMAND_MASTER_READY 30 #define COMMAND_MASTER_READY 30
extern char * current_command; extern char *current_command;
extern int command_listNum; extern int command_listNum;
int processListOfCommands(FILE * fp, int * permission, int * expired, int processListOfCommands(FILE * fp, int *permission, int *expired,
int listOK, List * list); int listOK, List * list);
int processCommand(FILE * fp, int * permission, char * commandString); int processCommand(FILE * fp, int *permission, char *commandString);
void initCommands(); void initCommands();
......
...@@ -60,33 +60,33 @@ ...@@ -60,33 +60,33 @@
#define CONF_ID3V1_ENCODING "id3v1_encoding" #define CONF_ID3V1_ENCODING "id3v1_encoding"
typedef struct _BlockParam { typedef struct _BlockParam {
char * name; char *name;
char * value; char *value;
int line; int line;
} BlockParam; } BlockParam;
typedef struct _ConfigParam { typedef struct _ConfigParam {
char * value; char *value;
unsigned int line; unsigned int line;
BlockParam * blockParams; BlockParam *blockParams;
int numberOfBlockParams; int numberOfBlockParams;
} ConfigParam; } ConfigParam;
void initConf(); void initConf();
void finishConf(); void finishConf();
void readConf(char * file); void readConf(char *file);
/* don't free the returned value /* don't free the returned value
set _last_ to NULL to get first entry */ set _last_ to NULL to get first entry */
ConfigParam * getNextConfigParam(char * name, ConfigParam * last); ConfigParam *getNextConfigParam(char *name, ConfigParam * last);
#define getConfigParam(name) getNextConfigParam(name, NULL) #define getConfigParam(name) getNextConfigParam(name, NULL)
char * getConfigParamValue(char * name); char *getConfigParamValue(char *name);
BlockParam * getBlockParam(ConfigParam * param, char * name); BlockParam *getBlockParam(ConfigParam * param, char *name);
ConfigParam * parseConfigFilePath(char * name, int force); ConfigParam *parseConfigFilePath(char *name, int force);
#endif #endif
...@@ -27,38 +27,36 @@ ...@@ -27,38 +27,36 @@
typedef struct _LocateTagItem { typedef struct _LocateTagItem {
mpd_sint8 tagType; mpd_sint8 tagType;
/* what we are looking for */ /* what we are looking for */
char * needle; char *needle;
} LocateTagItem; } LocateTagItem;
int getLocateTagItemType(char * str); int getLocateTagItemType(char *str);
/* returns NULL if not a known type */ /* returns NULL if not a known type */
LocateTagItem * newLocateTagItem(char * typeString, char * needle); LocateTagItem *newLocateTagItem(char *typeString, char *needle);
/* return number of items or -1 on error */ /* return number of items or -1 on error */
int newLocateTagItemArrayFromArgArray(char * argArray[], int numArgs, int newLocateTagItemArrayFromArgArray(char *argArray[], int numArgs,
LocateTagItem ** arrayRet); LocateTagItem ** arrayRet);
void freeLocateTagItemArray(int count, LocateTagItem * array); void freeLocateTagItemArray(int count, LocateTagItem * array);
void freeLocateTagItem(LocateTagItem * item); void freeLocateTagItem(LocateTagItem * item);
int printAllIn(FILE * fp, char * name); int printAllIn(FILE * fp, char *name);
int addAllIn(FILE * fp, char * name); int addAllIn(FILE * fp, char *name);
int printInfoForAllIn(FILE * fp, char * name); int printInfoForAllIn(FILE * fp, char *name);
int searchForSongsIn(FILE * fp, char * name, int numItems, int searchForSongsIn(FILE * fp, char *name, int numItems,
LocateTagItem * items); LocateTagItem * items);
int findSongsIn(FILE * fp, char * name, int numItems, int findSongsIn(FILE * fp, char *name, int numItems, LocateTagItem * items);
LocateTagItem * items);
int countSongsIn(FILE * fp, char * name); int countSongsIn(FILE * fp, char *name);
unsigned long sumSongTimesIn(FILE * fp, char * name); unsigned long sumSongTimesIn(FILE * fp, char *name);
int listAllUniqueTags(FILE * fp, int type, int numConditiionals, int listAllUniqueTags(FILE * fp, int type, int numConditiionals,
LocateTagItem * conditionals); LocateTagItem * conditionals);
......
...@@ -58,11 +58,11 @@ typedef struct _DecoderControl { ...@@ -58,11 +58,11 @@ typedef struct _DecoderControl {
volatile mpd_sint8 cycleLogFiles; volatile mpd_sint8 cycleLogFiles;
volatile double seekWhere; volatile double seekWhere;
AudioFormat audioFormat; AudioFormat audioFormat;
char utf8url[MAXPATHLEN+1]; char utf8url[MAXPATHLEN + 1];
volatile float totalTime; volatile float totalTime;
} DecoderControl; } DecoderControl;
void decodeSigHandler(int sig, siginfo_t * siginfo, void * v); void decodeSigHandler(int sig, siginfo_t * siginfo, void *v);
void decode(); void decode();
......
...@@ -32,11 +32,11 @@ typedef struct _DirectoryStat { ...@@ -32,11 +32,11 @@ typedef struct _DirectoryStat {
} DirectoryStat; } DirectoryStat;
typedef struct _Directory { typedef struct _Directory {
char * path; char *path;
DirectoryList * subDirectories; DirectoryList *subDirectories;
SongList * songs; SongList *songs;
struct _Directory * parent; struct _Directory *parent;
DirectoryStat * stat; DirectoryStat *stat;
} Directory; } Directory;
void readDirectoryDBIfUpdateIsFinished(); void readDirectoryDBIfUpdateIsFinished();
...@@ -51,7 +51,7 @@ void initMp3Directory(); ...@@ -51,7 +51,7 @@ void initMp3Directory();
void closeMp3Directory(); void closeMp3Directory();
int printDirectoryInfo(FILE * fp, char * dirname); int printDirectoryInfo(FILE * fp, char *dirname);
int checkDirectoryDB(); int checkDirectoryDB();
...@@ -61,14 +61,13 @@ int readDirectoryDB(); ...@@ -61,14 +61,13 @@ int readDirectoryDB();
void updateMp3Directory(); void updateMp3Directory();
Song * getSongFromDB(char * file); Song *getSongFromDB(char *file);
time_t getDbModTime(); time_t getDbModTime();
int traverseAllIn(FILE * fp, char * name, int traverseAllIn(FILE * fp, char *name,
int (*forEachSong)(FILE *, Song *, void *), int (*forEachSong) (FILE *, Song *, void *),
int (*forEachDir)(FILE *, Directory *, void *), int (*forEachDir) (FILE *, Directory *, void *), void *data);
void * data);
#define getDirectoryPath(dir) ((dir && dir->path) ? dir->path : "") #define getDirectoryPath(dir) ((dir && dir->path) ? dir->path : "")
......
...@@ -24,47 +24,59 @@ ...@@ -24,47 +24,59 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
static List * inputPlugin_list = NULL; static List *inputPlugin_list = NULL;
void loadInputPlugin(InputPlugin * inputPlugin) { void loadInputPlugin(InputPlugin * inputPlugin)
if(!inputPlugin) return; {
if(!inputPlugin->name) return; if (!inputPlugin)
return;
if (!inputPlugin->name)
return;
if(inputPlugin->initFunc && inputPlugin->initFunc() < 0) return; if (inputPlugin->initFunc && inputPlugin->initFunc() < 0)
return;
insertInList(inputPlugin_list, inputPlugin->name, (void *)inputPlugin); insertInList(inputPlugin_list, inputPlugin->name, (void *)inputPlugin);
} }
void unloadInputPlugin(InputPlugin * inputPlugin) { void unloadInputPlugin(InputPlugin * inputPlugin)
if(inputPlugin->finishFunc) inputPlugin->finishFunc(); {
if (inputPlugin->finishFunc)
inputPlugin->finishFunc();
deleteFromList(inputPlugin_list, inputPlugin->name); deleteFromList(inputPlugin_list, inputPlugin->name);
} }
static int stringFoundInStringArray(char ** array, char * suffix) { static int stringFoundInStringArray(char **array, char *suffix)
while(array && *array) { {
if(strcasecmp(*array, suffix) == 0) return 1; while (array && *array) {
if (strcasecmp(*array, suffix) == 0)
return 1;
array++; array++;
} }
return 0; return 0;
} }
InputPlugin * getInputPluginFromSuffix(char * suffix, unsigned int next) { InputPlugin *getInputPluginFromSuffix(char *suffix, unsigned int next)
static ListNode * pos = NULL; {
ListNode * node; static ListNode *pos = NULL;
InputPlugin * plugin; ListNode *node;
InputPlugin *plugin;
if(suffix == NULL) return NULL; if (suffix == NULL)
return NULL;
if (next) { if (next) {
if (pos) node = pos; if (pos)
else return NULL; node = pos;
else
return NULL;
} else } else
node = inputPlugin_list->firstNode; node = inputPlugin_list->firstNode;
while(node != NULL) { while (node != NULL) {
plugin = node->data; plugin = node->data;
if(stringFoundInStringArray(plugin->suffixes, suffix)) { if (stringFoundInStringArray(plugin->suffixes, suffix)) {
pos = node->nextNode; pos = node->nextNode;
return plugin; return plugin;
} }
...@@ -74,18 +86,20 @@ InputPlugin * getInputPluginFromSuffix(char * suffix, unsigned int next) { ...@@ -74,18 +86,20 @@ InputPlugin * getInputPluginFromSuffix(char * suffix, unsigned int next) {
return NULL; return NULL;
} }
InputPlugin * getInputPluginFromMimeType(char * mimeType, unsigned int next) { InputPlugin *getInputPluginFromMimeType(char *mimeType, unsigned int next)
static ListNode * pos = NULL; {
ListNode * node; static ListNode *pos = NULL;
InputPlugin * plugin; ListNode *node;
InputPlugin *plugin;
if(mimeType == NULL) return NULL; if (mimeType == NULL)
return NULL;
node = (next && pos) ? pos : inputPlugin_list->firstNode; node = (next && pos) ? pos : inputPlugin_list->firstNode;
while(node != NULL) { while (node != NULL) {
plugin = node->data; plugin = node->data;
if(stringFoundInStringArray(plugin->mimeTypes, mimeType)) { if (stringFoundInStringArray(plugin->mimeTypes, mimeType)) {
pos = node->nextNode; pos = node->nextNode;
return plugin; return plugin;
} }
...@@ -95,23 +109,25 @@ InputPlugin * getInputPluginFromMimeType(char * mimeType, unsigned int next) { ...@@ -95,23 +109,25 @@ InputPlugin * getInputPluginFromMimeType(char * mimeType, unsigned int next) {
return NULL; return NULL;
} }
InputPlugin * getInputPluginFromName(char * name) { InputPlugin *getInputPluginFromName(char *name)
void * plugin = NULL; {
void *plugin = NULL;
findInList(inputPlugin_list, name, &plugin); findInList(inputPlugin_list, name, &plugin);
return (InputPlugin *)plugin; return (InputPlugin *) plugin;
} }
void printAllInputPluginSuffixes(FILE * fp) { void printAllInputPluginSuffixes(FILE * fp)
ListNode * node = inputPlugin_list->firstNode; {
InputPlugin * plugin; ListNode *node = inputPlugin_list->firstNode;
char ** suffixes; InputPlugin *plugin;
char **suffixes;
while(node) { while (node) {
plugin = (InputPlugin *)node->data; plugin = (InputPlugin *) node->data;
suffixes = plugin->suffixes; suffixes = plugin->suffixes;
while(suffixes && *suffixes) { while (suffixes && *suffixes) {
myfprintf(fp, "%s ", *suffixes); myfprintf(fp, "%s ", *suffixes);
suffixes++; suffixes++;
} }
...@@ -130,7 +146,8 @@ extern InputPlugin mpcPlugin; ...@@ -130,7 +146,8 @@ extern InputPlugin mpcPlugin;
extern InputPlugin aacPlugin; extern InputPlugin aacPlugin;
extern InputPlugin modPlugin; extern InputPlugin modPlugin;
void initInputPlugins(void) { void initInputPlugins(void)
{
inputPlugin_list = makeList(NULL, 1); inputPlugin_list = makeList(NULL, 1);
/* load plugins here */ /* load plugins here */
...@@ -144,6 +161,7 @@ void initInputPlugins(void) { ...@@ -144,6 +161,7 @@ void initInputPlugins(void) {
loadInputPlugin(&modPlugin); loadInputPlugin(&modPlugin);
} }
void finishInputPlugins(void) { void finishInputPlugins(void)
{
freeList(inputPlugin_list); freeList(inputPlugin_list);
} }
...@@ -31,20 +31,20 @@ ...@@ -31,20 +31,20 @@
/* optional, set this to NULL if the InputPlugin doesn't have/need one /* optional, set this to NULL if the InputPlugin doesn't have/need one
* this must return < 0 if there is an error and >= 0 otherwise */ * this must return < 0 if there is an error and >= 0 otherwise */
typedef int (* InputPlugin_initFunc) (); typedef int (*InputPlugin_initFunc) ();
/* optional, set this to NULL if the InputPlugin doesn't have/need one */ /* optional, set this to NULL if the InputPlugin doesn't have/need one */
typedef void (* InputPlugin_finishFunc) (); typedef void (*InputPlugin_finishFunc) ();
/* boolean return value, returns 1 if the InputStream is decodable by /* boolean return value, returns 1 if the InputStream is decodable by
* the InputPlugin, 0 if not */ * the InputPlugin, 0 if not */
typedef unsigned int (* InputPlugin_tryDecodeFunc) (InputStream *); typedef unsigned int (*InputPlugin_tryDecodeFunc) (InputStream *);
/* this will be used to decode InputStreams, and is recommended for files /* this will be used to decode InputStreams, and is recommended for files
* and networked (HTTP) connections. * and networked (HTTP) connections.
* *
* returns -1 on error, 0 on success */ * returns -1 on error, 0 on success */
typedef int (* InputPlugin_streamDecodeFunc) (OutputBuffer *, DecoderControl *, typedef int (*InputPlugin_streamDecodeFunc) (OutputBuffer *, DecoderControl *,
InputStream *); InputStream *);
/* use this if and only if your InputPlugin can only be passed a filename or /* use this if and only if your InputPlugin can only be passed a filename or
...@@ -52,15 +52,15 @@ typedef int (* InputPlugin_streamDecodeFunc) (OutputBuffer *, DecoderControl *, ...@@ -52,15 +52,15 @@ typedef int (* InputPlugin_streamDecodeFunc) (OutputBuffer *, DecoderControl *,
* and FLAC libraries allow) * and FLAC libraries allow)
* *
* returns -1 on error, 0 on success */ * returns -1 on error, 0 on success */
typedef int (* InputPlugin_fileDecodeFunc) (OutputBuffer *, DecoderControl *, typedef int (*InputPlugin_fileDecodeFunc) (OutputBuffer *, DecoderControl *,
char * path); char *path);
/* file should be the full path! Returns NULL if a tag cannot be found /* file should be the full path! Returns NULL if a tag cannot be found
* or read */ * or read */
typedef MpdTag * (* InputPlugin_tagDupFunc) (char * file); typedef MpdTag *(*InputPlugin_tagDupFunc) (char *file);
typedef struct _InputPlugin { typedef struct _InputPlugin {
char * name; char *name;
InputPlugin_initFunc initFunc; InputPlugin_initFunc initFunc;
InputPlugin_finishFunc finishFunc; InputPlugin_finishFunc finishFunc;
InputPlugin_tryDecodeFunc tryDecodeFunc; InputPlugin_tryDecodeFunc tryDecodeFunc;
...@@ -72,8 +72,8 @@ typedef struct _InputPlugin { ...@@ -72,8 +72,8 @@ typedef struct _InputPlugin {
unsigned char streamTypes; unsigned char streamTypes;
/* last element in these arrays must always be a NULL: */ /* last element in these arrays must always be a NULL: */
char ** suffixes; char **suffixes;
char ** mimeTypes; char **mimeTypes;
} InputPlugin; } InputPlugin;
/* individual functions to load/unload plugins */ /* individual functions to load/unload plugins */
...@@ -82,11 +82,11 @@ void unloadInputPlugin(InputPlugin * inputPlugin); ...@@ -82,11 +82,11 @@ void unloadInputPlugin(InputPlugin * inputPlugin);
/* interface for using plugins */ /* interface for using plugins */
InputPlugin * getInputPluginFromSuffix(char * suffix, unsigned int next); InputPlugin *getInputPluginFromSuffix(char *suffix, unsigned int next);
InputPlugin * getInputPluginFromMimeType(char * mimeType, unsigned int next); InputPlugin *getInputPluginFromMimeType(char *mimeType, unsigned int next);
InputPlugin * getInputPluginFromName(char * name); InputPlugin *getInputPluginFromName(char *name);
void printAllInputPluginSuffixes(FILE * fp); void printAllInputPluginSuffixes(FILE * fp);
......
...@@ -38,7 +38,7 @@ ...@@ -38,7 +38,7 @@
#include <FLAC/format.h> #include <FLAC/format.h>
#include <FLAC/metadata.h> #include <FLAC/metadata.h>
void init_FlacData (FlacData * data, OutputBuffer * cb, void init_FlacData(FlacData * data, OutputBuffer * cb,
DecoderControl * dc, InputStream * inStream) DecoderControl * dc, InputStream * inStream)
{ {
data->chunk_length = 0; data->chunk_length = 0;
...@@ -53,18 +53,18 @@ void init_FlacData (FlacData * data, OutputBuffer * cb, ...@@ -53,18 +53,18 @@ void init_FlacData (FlacData * data, OutputBuffer * cb,
} }
static int flacFindVorbisCommentFloat(const FLAC__StreamMetadata * block, static int flacFindVorbisCommentFloat(const FLAC__StreamMetadata * block,
char * cmnt, float * fl) char *cmnt, float *fl)
{ {
int offset = FLAC__metadata_object_vorbiscomment_find_entry_from( int offset =
block,0,cmnt); FLAC__metadata_object_vorbiscomment_find_entry_from(block, 0, cmnt);
if(offset >= 0) { if (offset >= 0) {
size_t pos = strlen(cmnt)+1; /* 1 is for '=' */ size_t pos = strlen(cmnt) + 1; /* 1 is for '=' */
int len = block->data.vorbis_comment.comments[offset].length int len = block->data.vorbis_comment.comments[offset].length
-pos; - pos;
if(len > 0) { if (len > 0) {
unsigned char tmp; unsigned char tmp;
unsigned char * dup = &(block->data.vorbis_comment. unsigned char *dup = &(block->data.vorbis_comment.
comments[offset].entry[pos]); comments[offset].entry[pos]);
tmp = dup[len]; tmp = dup[len];
dup[len] = '\0'; dup[len] = '\0';
...@@ -79,8 +79,9 @@ static int flacFindVorbisCommentFloat(const FLAC__StreamMetadata * block, ...@@ -79,8 +79,9 @@ static int flacFindVorbisCommentFloat(const FLAC__StreamMetadata * block,
} }
/* replaygain stuff by AliasMrJones */ /* replaygain stuff by AliasMrJones */
static void flacParseReplayGain(const FLAC__StreamMetadata *block, static void flacParseReplayGain(const FLAC__StreamMetadata * block,
FlacData * data) { FlacData * data)
{
unsigned int found = 0; unsigned int found = 0;
if (data->replayGainInfo) if (data->replayGainInfo)
...@@ -88,13 +89,13 @@ static void flacParseReplayGain(const FLAC__StreamMetadata *block, ...@@ -88,13 +89,13 @@ static void flacParseReplayGain(const FLAC__StreamMetadata *block,
data->replayGainInfo = newReplayGainInfo(); data->replayGainInfo = newReplayGainInfo();
found &= flacFindVorbisCommentFloat(block,"replaygain_album_gain", found &= flacFindVorbisCommentFloat(block, "replaygain_album_gain",
&data->replayGainInfo->albumGain); &data->replayGainInfo->albumGain);
found &= flacFindVorbisCommentFloat(block,"replaygain_album_peak", found &= flacFindVorbisCommentFloat(block, "replaygain_album_peak",
&data->replayGainInfo->albumPeak); &data->replayGainInfo->albumPeak);
found &= flacFindVorbisCommentFloat(block,"replaygain_track_gain", found &= flacFindVorbisCommentFloat(block, "replaygain_track_gain",
&data->replayGainInfo->trackGain); &data->replayGainInfo->trackGain);
found &= flacFindVorbisCommentFloat(block,"replaygain_track_peak", found &= flacFindVorbisCommentFloat(block, "replaygain_track_peak",
&data->replayGainInfo->trackPeak); &data->replayGainInfo->trackPeak);
if (!found) { if (!found) {
...@@ -105,33 +106,38 @@ static void flacParseReplayGain(const FLAC__StreamMetadata *block, ...@@ -105,33 +106,38 @@ static void flacParseReplayGain(const FLAC__StreamMetadata *block,
/* tracknumber is used in VCs, MPD uses "track" ..., all the other /* tracknumber is used in VCs, MPD uses "track" ..., all the other
* tag names match */ * tag names match */
static const char * VORBIS_COMMENT_TRACK_KEY = "tracknumber"; static const char *VORBIS_COMMENT_TRACK_KEY = "tracknumber";
static const char * VORBIS_COMMENT_DISC_KEY = "discnumber"; static const char *VORBIS_COMMENT_DISC_KEY = "discnumber";
static unsigned int commentMatchesAddToTag( static unsigned int commentMatchesAddToTag(const
const FLAC__StreamMetadata_VorbisComment_Entry * entry, FLAC__StreamMetadata_VorbisComment_Entry
unsigned int itemType, * entry, unsigned int itemType,
MpdTag ** tag) MpdTag ** tag)
{ {
const char * str; const char *str;
size_t slen; size_t slen;
int vlen; int vlen;
switch (itemType) { switch (itemType) {
case TAG_ITEM_TRACK: str = VORBIS_COMMENT_TRACK_KEY; break; case TAG_ITEM_TRACK:
case TAG_ITEM_DISC: str = VORBIS_COMMENT_DISC_KEY; break; str = VORBIS_COMMENT_TRACK_KEY;
default: str = mpdTagItemKeys[itemType]; break;
case TAG_ITEM_DISC:
str = VORBIS_COMMENT_DISC_KEY;
break;
default:
str = mpdTagItemKeys[itemType];
} }
slen = strlen(str); slen = strlen(str);
vlen = entry->length - slen - 1; vlen = entry->length - slen - 1;
if ((vlen > 0) && (0 == strncasecmp(str,(char *)entry->entry, slen)) if ((vlen > 0) && (0 == strncasecmp(str, (char *)entry->entry, slen))
&& (*(entry->entry + slen) == '=')) { && (*(entry->entry + slen) == '=')) {
if (!*tag) if (!*tag)
*tag = newMpdTag(); *tag = newMpdTag();
addItemToMpdTagWithLen(*tag, itemType, addItemToMpdTagWithLen(*tag, itemType,
(char *)(entry->entry+slen + 1), vlen); (char *)(entry->entry + slen + 1), vlen);
return 1; return 1;
} }
...@@ -139,7 +145,7 @@ static unsigned int commentMatchesAddToTag( ...@@ -139,7 +145,7 @@ static unsigned int commentMatchesAddToTag(
return 0; return 0;
} }
MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block, MpdTag *copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
MpdTag * tag) MpdTag * tag)
{ {
unsigned int i, j; unsigned int i, j;
...@@ -148,7 +154,7 @@ MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block, ...@@ -148,7 +154,7 @@ MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
comments = block->data.vorbis_comment.comments; comments = block->data.vorbis_comment.comments;
for (i = block->data.vorbis_comment.num_comments; i != 0; --i) { for (i = block->data.vorbis_comment.num_comments; i != 0; --i) {
for (j = TAG_NUM_OF_ITEM_TYPES; j--; ) { for (j = TAG_NUM_OF_ITEM_TYPES; j--;) {
if (commentMatchesAddToTag(comments, j, &tag)) if (commentMatchesAddToTag(comments, j, &tag))
break; break;
} }
...@@ -158,12 +164,13 @@ MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block, ...@@ -158,12 +164,13 @@ MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
return tag; return tag;
} }
void flac_metadata_common_cb(const FLAC__StreamMetadata *block, FlacData *data) void flac_metadata_common_cb(const FLAC__StreamMetadata * block,
FlacData * data)
{ {
DecoderControl *dc = data->dc; DecoderControl *dc = data->dc;
const FLAC__StreamMetadata_StreamInfo *si = &(block->data.stream_info); const FLAC__StreamMetadata_StreamInfo *si = &(block->data.stream_info);
switch(block->type) { switch (block->type) {
case FLAC__METADATA_TYPE_STREAMINFO: case FLAC__METADATA_TYPE_STREAMINFO:
dc->audioFormat.bits = si->bits_per_sample; dc->audioFormat.bits = si->bits_per_sample;
dc->audioFormat.sampleRate = si->sample_rate; dc->audioFormat.sampleRate = si->sample_rate;
...@@ -173,19 +180,20 @@ void flac_metadata_common_cb(const FLAC__StreamMetadata *block, FlacData *data) ...@@ -173,19 +180,20 @@ void flac_metadata_common_cb(const FLAC__StreamMetadata *block, FlacData *data)
&(data->cb->audioFormat)); &(data->cb->audioFormat));
break; break;
case FLAC__METADATA_TYPE_VORBIS_COMMENT: case FLAC__METADATA_TYPE_VORBIS_COMMENT:
flacParseReplayGain(block,data); flacParseReplayGain(block, data);
default: default:
break; break;
} }
} }
void flac_error_common_cb( const char * plugin, void flac_error_common_cb(const char *plugin,
const FLAC__StreamDecoderErrorStatus status, const FLAC__StreamDecoderErrorStatus status,
FlacData *data) FlacData * data)
{ {
if(data->dc->stop) return; if (data->dc->stop)
return;
switch(status) { switch (status) {
case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC: case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC:
ERROR("%s lost sync\n", plugin); ERROR("%s lost sync\n", plugin);
break; break;
...@@ -196,7 +204,7 @@ void flac_error_common_cb( const char * plugin, ...@@ -196,7 +204,7 @@ void flac_error_common_cb( const char * plugin,
ERROR("%s crc mismatch\n", plugin); ERROR("%s crc mismatch\n", plugin);
break; break;
default: default:
ERROR("unknown %s error\n",plugin); ERROR("unknown %s error\n", plugin);
} }
} }
......
...@@ -41,38 +41,38 @@ typedef struct { ...@@ -41,38 +41,38 @@ typedef struct {
float time; float time;
int bitRate; int bitRate;
FLAC__uint64 position; FLAC__uint64 position;
OutputBuffer * cb; OutputBuffer *cb;
DecoderControl * dc; DecoderControl *dc;
InputStream * inStream; InputStream *inStream;
ReplayGainInfo * replayGainInfo; ReplayGainInfo *replayGainInfo;
MpdTag * tag; MpdTag *tag;
} FlacData; } FlacData;
/* initializes a given FlacData struct */ /* initializes a given FlacData struct */
void init_FlacData (FlacData * data, OutputBuffer * cb, void init_FlacData(FlacData * data, OutputBuffer * cb,
DecoderControl * dc, InputStream * inStream); DecoderControl * dc, InputStream * inStream);
void flac_metadata_common_cb( const FLAC__StreamMetadata *block, void flac_metadata_common_cb(const FLAC__StreamMetadata * block,
FlacData *data); FlacData * data);
void flac_error_common_cb( const char * plugin, void flac_error_common_cb(const char *plugin,
FLAC__StreamDecoderErrorStatus status, FLAC__StreamDecoderErrorStatus status,
FlacData *data); FlacData * data);
MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block, MpdTag *copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
MpdTag * tag); MpdTag * tag);
/* keep this inlined, this is just macro but prettier :) */ /* keep this inlined, this is just macro but prettier :) */
static inline int flacSendChunk(FlacData * data) static inline int flacSendChunk(FlacData * data)
{ {
if (sendDataToOutputBuffer(data->cb, NULL, data->dc, 1, data->chunk, if (sendDataToOutputBuffer(data->cb, NULL, data->dc, 1, data->chunk,
data->chunk_length, data->time, data->bitRate, data->chunk_length, data->time,
data->replayGainInfo) == OUTPUT_BUFFER_DC_STOP) data->bitRate,
data->replayGainInfo) ==
OUTPUT_BUFFER_DC_STOP)
return -1; return -1;
return 0; return 0;
} }
#endif /* HAVE_FLAC || HAVE_OGGFLAC */ #endif /* HAVE_FLAC || HAVE_OGGFLAC */
#endif /* _FLAC_COMMON_H */ #endif /* _FLAC_COMMON_H */
...@@ -51,15 +51,23 @@ ogg_stream_type ogg_stream_type_detect(InputStream * inStream) ...@@ -51,15 +51,23 @@ ogg_stream_type ogg_stream_type_detect(InputStream * inStream)
seekInputStream(inStream, 0, SEEK_SET); seekInputStream(inStream, 0, SEEK_SET);
if (r >= 32 && memcmp(buf, "OggS", 4) == 0 && ( if (r >= 32 && memcmp(buf, "OggS", 4) == 0 && ((memcmp
(memcmp(buf+29, "FLAC", 4) == 0 (buf + 29, "FLAC",
&& memcmp(buf+37, "fLaC", 4) == 0) 4) == 0
|| (memcmp(buf+28, "FLAC", 4) == 0) && memcmp(buf + 37,
|| (memcmp(buf+28, "fLaC", 4) == 0))) { "fLaC",
4) == 0)
||
(memcmp
(buf + 28, "FLAC",
4) == 0)
||
(memcmp
(buf + 28, "fLaC",
4) == 0))) {
return FLAC; return FLAC;
} }
return VORBIS; return VORBIS;
} }
#endif /* defined(HAVE_OGGFLAC || defined(HAVE_OGGVORBIS) */ #endif /* defined(HAVE_OGGFLAC || defined(HAVE_OGGVORBIS) */
...@@ -37,34 +37,35 @@ ...@@ -37,34 +37,35 @@
#include <unistd.h> #include <unistd.h>
#include <audiofile.h> #include <audiofile.h>
static int getAudiofileTotalTime(char * file) static int getAudiofileTotalTime(char *file)
{ {
int time; int time;
AFfilehandle af_fp = afOpenFile(file, "r", NULL); AFfilehandle af_fp = afOpenFile(file, "r", NULL);
if(af_fp == AF_NULL_FILEHANDLE) { if (af_fp == AF_NULL_FILEHANDLE) {
return -1; return -1;
} }
time = (int) time = (int)
((double)afGetFrameCount(af_fp,AF_DEFAULT_TRACK) ((double)afGetFrameCount(af_fp, AF_DEFAULT_TRACK)
/afGetRate(af_fp,AF_DEFAULT_TRACK)); / afGetRate(af_fp, AF_DEFAULT_TRACK));
afCloseFile(af_fp); afCloseFile(af_fp);
return time; return time;
} }
static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path) { static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char *path)
{
int fs, frame_count; int fs, frame_count;
AFfilehandle af_fp; AFfilehandle af_fp;
int bits; int bits;
mpd_uint16 bitRate; mpd_uint16 bitRate;
struct stat st; struct stat st;
if(stat(path, &st) < 0) { if (stat(path, &st) < 0) {
ERROR("failed to stat: %s\n", path); ERROR("failed to stat: %s\n", path);
return -1; return -1;
} }
af_fp = afOpenFile(path, "r", NULL); af_fp = afOpenFile(path, "r", NULL);
if(af_fp == AF_NULL_FILEHANDLE) { if (af_fp == AF_NULL_FILEHANDLE) {
ERROR("failed to open: %s\n", path); ERROR("failed to open: %s\n", path);
return -1; return -1;
} }
...@@ -72,14 +73,15 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path) ...@@ -72,14 +73,15 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path)
afGetSampleFormat(af_fp, AF_DEFAULT_TRACK, &fs, &bits); afGetSampleFormat(af_fp, AF_DEFAULT_TRACK, &fs, &bits);
dc->audioFormat.bits = bits; dc->audioFormat.bits = bits;
dc->audioFormat.sampleRate = afGetRate(af_fp, AF_DEFAULT_TRACK); dc->audioFormat.sampleRate = afGetRate(af_fp, AF_DEFAULT_TRACK);
dc->audioFormat.channels = afGetChannels(af_fp,AF_DEFAULT_TRACK); dc->audioFormat.channels = afGetChannels(af_fp, AF_DEFAULT_TRACK);
getOutputAudioFormat(&(dc->audioFormat),&(cb->audioFormat)); getOutputAudioFormat(&(dc->audioFormat), &(cb->audioFormat));
frame_count = afGetFrameCount(af_fp,AF_DEFAULT_TRACK); frame_count = afGetFrameCount(af_fp, AF_DEFAULT_TRACK);
dc->totalTime = ((float)frame_count/(float)dc->audioFormat.sampleRate); dc->totalTime =
((float)frame_count / (float)dc->audioFormat.sampleRate);
bitRate = st.st_size*8.0/dc->totalTime/1000.0+0.5; bitRate = st.st_size * 8.0 / dc->totalTime / 1000.0 + 0.5;
if (dc->audioFormat.bits != 8 && dc->audioFormat.bits != 16) { if (dc->audioFormat.bits != 8 && dc->audioFormat.bits != 16) {
ERROR("Only 8 and 16-bit files are supported. %s is %i-bit\n", ERROR("Only 8 and 16-bit files are supported. %s is %i-bit\n",
...@@ -88,24 +90,27 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path) ...@@ -88,24 +90,27 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path)
return -1; return -1;
} }
fs = (int)afGetFrameSize(af_fp, AF_DEFAULT_TRACK,1); fs = (int)afGetFrameSize(af_fp, AF_DEFAULT_TRACK, 1);
dc->state = DECODE_STATE_DECODE; dc->state = DECODE_STATE_DECODE;
{ {
int ret, eof = 0, current = 0; int ret, eof = 0, current = 0;
char chunk[CHUNK_SIZE]; char chunk[CHUNK_SIZE];
while(!eof) { while (!eof) {
if(dc->seek) { if (dc->seek) {
clearOutputBuffer(cb); clearOutputBuffer(cb);
current = dc->seekWhere * current = dc->seekWhere *
dc->audioFormat.sampleRate; dc->audioFormat.sampleRate;
afSeekFrame(af_fp, AF_DEFAULT_TRACK,current); afSeekFrame(af_fp, AF_DEFAULT_TRACK, current);
dc->seek = 0; dc->seek = 0;
} }
ret = afReadFrames(af_fp, AF_DEFAULT_TRACK, chunk, CHUNK_SIZE/fs); ret =
if(ret<=0) eof = 1; afReadFrames(af_fp, AF_DEFAULT_TRACK, chunk,
CHUNK_SIZE / fs);
if (ret <= 0)
eof = 1;
else { else {
current += ret; current += ret;
sendDataToOutputBuffer(cb, sendDataToOutputBuffer(cb,
...@@ -113,12 +118,13 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path) ...@@ -113,12 +118,13 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path)
dc, dc,
1, 1,
chunk, chunk,
ret*fs, ret * fs,
(float)current / (float)current /
(float)dc->audioFormat.sampleRate, (float)dc->audioFormat.
bitRate, sampleRate, bitRate,
NULL); NULL);
if(dc->stop) break; if (dc->stop)
break;
} }
} }
...@@ -127,38 +133,40 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path) ...@@ -127,38 +133,40 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path)
/*if(dc->seek) { /*if(dc->seek) {
dc->seekError = 1; dc->seekError = 1;
dc->seek = 0; dc->seek = 0;
}*/ } */
if(dc->stop) { if (dc->stop) {
dc->state = DECODE_STATE_STOP; dc->state = DECODE_STATE_STOP;
dc->stop = 0; dc->stop = 0;
} } else
else dc->state = DECODE_STATE_STOP; dc->state = DECODE_STATE_STOP;
} }
afCloseFile(af_fp); afCloseFile(af_fp);
return 0; return 0;
} }
static MpdTag * audiofileTagDup(char * file) { static MpdTag *audiofileTagDup(char *file)
MpdTag * ret = NULL; {
MpdTag *ret = NULL;
int time = getAudiofileTotalTime(file); int time = getAudiofileTotalTime(file);
if (time>=0) { if (time >= 0) {
if(!ret) ret = newMpdTag(); if (!ret)
ret = newMpdTag();
ret->time = time; ret->time = time;
} } else {
else { DEBUG
DEBUG("audiofileTagDup: Failed to get total song time from: %s\n", file); ("audiofileTagDup: Failed to get total song time from: %s\n",
file);
} }
return ret; return ret;
} }
static char * audiofileSuffixes[] = {"wav", "au", "aiff", "aif", NULL}; static char *audiofileSuffixes[] = { "wav", "au", "aiff", "aif", NULL };
InputPlugin audiofilePlugin = InputPlugin audiofilePlugin = {
{
"audiofile", "audiofile",
NULL, NULL,
NULL, NULL,
...@@ -173,8 +181,7 @@ InputPlugin audiofilePlugin = ...@@ -173,8 +181,7 @@ InputPlugin audiofilePlugin =
#else #else
InputPlugin audiofilePlugin = InputPlugin audiofilePlugin = {
{
NULL, NULL,
NULL, NULL,
NULL, NULL,
......
...@@ -39,23 +39,26 @@ ...@@ -39,23 +39,26 @@
#define MIKMOD_FRAME_SIZE 4096 #define MIKMOD_FRAME_SIZE 4096
static BOOL mod_mpd_Init(void) { static BOOL mod_mpd_Init(void)
{
return VC_Init(); return VC_Init();
} }
static void mod_mpd_Exit(void) { static void mod_mpd_Exit(void)
{
VC_Exit(); VC_Exit();
} }
static void mod_mpd_Update(void) { static void mod_mpd_Update(void)
{
} }
static BOOL mod_mpd_IsThere(void) { static BOOL mod_mpd_IsThere(void)
{
return 1; return 1;
} }
static MDRIVER drv_mpd = static MDRIVER drv_mpd = {
{
NULL, NULL,
"MPD", "MPD",
"MPD Output Driver v0.1", "MPD Output Driver v0.1",
...@@ -92,10 +95,12 @@ static MDRIVER drv_mpd = ...@@ -92,10 +95,12 @@ static MDRIVER drv_mpd =
static int mod_mikModInitiated = 0; static int mod_mikModInitiated = 0;
static int mod_mikModInitError = 0; static int mod_mikModInitError = 0;
static int mod_initMikMod(void) { static int mod_initMikMod(void)
if(mod_mikModInitError) return -1; {
if (mod_mikModInitError)
return -1;
if(!mod_mikModInitiated) { if (!mod_mikModInitiated) {
mod_mikModInitiated = 1; mod_mikModInitiated = 1;
md_device = 0; md_device = 0;
...@@ -110,7 +115,7 @@ static int mod_initMikMod(void) { ...@@ -110,7 +115,7 @@ static int mod_initMikMod(void) {
md_mode = (DMODE_SOFT_MUSIC | DMODE_INTERP | DMODE_STEREO | md_mode = (DMODE_SOFT_MUSIC | DMODE_INTERP | DMODE_STEREO |
DMODE_16BITS); DMODE_16BITS);
if(MikMod_Init("")) { if (MikMod_Init("")) {
ERROR("Could not init MikMod: %s\n", ERROR("Could not init MikMod: %s\n",
MikMod_strerror(MikMod_errno)); MikMod_strerror(MikMod_errno));
mod_mikModInitError = 1; mod_mikModInitError = 1;
...@@ -120,20 +125,23 @@ static int mod_initMikMod(void) { ...@@ -120,20 +125,23 @@ static int mod_initMikMod(void) {
return 0; return 0;
} }
static void mod_finishMikMod(void) { static void mod_finishMikMod(void)
{
MikMod_Exit(); MikMod_Exit();
} }
typedef struct _mod_Data { typedef struct _mod_Data {
MODULE * moduleHandle; MODULE *moduleHandle;
SBYTE * audio_buffer; SBYTE *audio_buffer;
} mod_Data; } mod_Data;
static mod_Data * mod_open(char * path) { static mod_Data *mod_open(char *path)
MODULE * moduleHandle; {
mod_Data * data; MODULE *moduleHandle;
mod_Data *data;
if(!(moduleHandle = Player_Load(path, 128, 0))) return NULL; if (!(moduleHandle = Player_Load(path, 128, 0)))
return NULL;
data = malloc(sizeof(mod_Data)); data = malloc(sizeof(mod_Data));
...@@ -145,22 +153,25 @@ static mod_Data * mod_open(char * path) { ...@@ -145,22 +153,25 @@ static mod_Data * mod_open(char * path) {
return data; return data;
} }
static void mod_close(mod_Data * data) { static void mod_close(mod_Data * data)
{
Player_Stop(); Player_Stop();
Player_Free(data->moduleHandle); Player_Free(data->moduleHandle);
free(data->audio_buffer); free(data->audio_buffer);
free(data); free(data);
} }
static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char * path) { static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char *path)
mod_Data * data; {
mod_Data *data;
float time = 0.0; float time = 0.0;
int ret; int ret;
float secPerByte; float secPerByte;
if(mod_initMikMod() < 0) return -1; if (mod_initMikMod() < 0)
return -1;
if(!(data = mod_open(path))) { if (!(data = mod_open(path))) {
ERROR("failed to open mod: %s\n", path); ERROR("failed to open mod: %s\n", path);
MikMod_Exit(); MikMod_Exit();
return -1; return -1;
...@@ -169,24 +180,27 @@ static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char * path) { ...@@ -169,24 +180,27 @@ static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
dc->audioFormat.bits = 16; dc->audioFormat.bits = 16;
dc->audioFormat.sampleRate = 44100; dc->audioFormat.sampleRate = 44100;
dc->audioFormat.channels = 2; dc->audioFormat.channels = 2;
getOutputAudioFormat(&(dc->audioFormat),&(cb->audioFormat)); getOutputAudioFormat(&(dc->audioFormat), &(cb->audioFormat));
secPerByte = 1.0/((dc->audioFormat.bits*dc->audioFormat.channels/8.0)* secPerByte =
1.0 / ((dc->audioFormat.bits * dc->audioFormat.channels / 8.0) *
(float)dc->audioFormat.sampleRate); (float)dc->audioFormat.sampleRate);
dc->state = DECODE_STATE_DECODE; dc->state = DECODE_STATE_DECODE;
while(1) { while (1) {
if(dc->seek) { if (dc->seek) {
dc->seekError = 1; dc->seekError = 1;
dc->seek = 0; dc->seek = 0;
} }
if(dc->stop) break; if (dc->stop)
break;
if(!Player_Active()) break; if (!Player_Active())
break;
ret = VC_WriteBytes(data->audio_buffer, MIKMOD_FRAME_SIZE); ret = VC_WriteBytes(data->audio_buffer, MIKMOD_FRAME_SIZE);
time += ret*secPerByte; time += ret * secPerByte;
sendDataToOutputBuffer(cb, NULL, dc, 0, sendDataToOutputBuffer(cb, NULL, dc, 0,
(char *)data->audio_buffer, ret, time, (char *)data->audio_buffer, ret, time,
0, NULL); 0, NULL);
...@@ -198,27 +212,28 @@ static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char * path) { ...@@ -198,27 +212,28 @@ static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
MikMod_Exit(); MikMod_Exit();
if(dc->stop) { if (dc->stop) {
dc->state = DECODE_STATE_STOP; dc->state = DECODE_STATE_STOP;
dc->stop = 0; dc->stop = 0;
} } else
else dc->state = DECODE_STATE_STOP; dc->state = DECODE_STATE_STOP;
return 0; return 0;
} }
static MpdTag * modTagDup(char * file) { static MpdTag *modTagDup(char *file)
MpdTag * ret = NULL; {
MODULE * moduleHandle; MpdTag *ret = NULL;
char * title; MODULE *moduleHandle;
char *title;
if(mod_initMikMod() < 0) { if (mod_initMikMod() < 0) {
DEBUG("modTagDup: Failed to initialize MikMod\n"); DEBUG("modTagDup: Failed to initialize MikMod\n");
return NULL; return NULL;
} }
if(!(moduleHandle = Player_Load(file, 128, 0))) { if (!(moduleHandle = Player_Load(file, 128, 0))) {
DEBUG("modTagDup: Failed to open file: %s\n",file); DEBUG("modTagDup: Failed to open file: %s\n", file);
MikMod_Exit(); MikMod_Exit();
return NULL; return NULL;
...@@ -229,14 +244,15 @@ static MpdTag * modTagDup(char * file) { ...@@ -229,14 +244,15 @@ static MpdTag * modTagDup(char * file) {
ret->time = 0; ret->time = 0;
title = strdup(Player_LoadTitle(file)); title = strdup(Player_LoadTitle(file));
if(title) addItemToMpdTag(ret, TAG_ITEM_TITLE, title); if (title)
addItemToMpdTag(ret, TAG_ITEM_TITLE, title);
MikMod_Exit(); MikMod_Exit();
return ret; return ret;
} }
static char * modSuffixes[] = {"amf", static char *modSuffixes[] = { "amf",
"dsm", "dsm",
"far", "far",
"gdm", "gdm",
...@@ -251,10 +267,10 @@ static char * modSuffixes[] = {"amf", ...@@ -251,10 +267,10 @@ static char * modSuffixes[] = {"amf",
"ult", "ult",
"uni", "uni",
"xm", "xm",
NULL}; NULL
};
InputPlugin modPlugin = InputPlugin modPlugin = {
{
"mod", "mod",
NULL, NULL,
mod_finishMikMod, mod_finishMikMod,
...@@ -269,8 +285,7 @@ InputPlugin modPlugin = ...@@ -269,8 +285,7 @@ InputPlugin modPlugin =
#else #else
InputPlugin modPlugin = InputPlugin modPlugin = {
{
NULL, NULL,
NULL, NULL,
NULL, NULL,
......
...@@ -37,53 +37,58 @@ ...@@ -37,53 +37,58 @@
#include <math.h> #include <math.h>
typedef struct _MpcCallbackData { typedef struct _MpcCallbackData {
InputStream * inStream; InputStream *inStream;
DecoderControl * dc; DecoderControl *dc;
} MpcCallbackData; } MpcCallbackData;
static mpc_int32_t mpc_read_cb(void * vdata, void * ptr, mpc_int32_t size) { static mpc_int32_t mpc_read_cb(void *vdata, void *ptr, mpc_int32_t size)
{
mpc_int32_t ret = 0; mpc_int32_t ret = 0;
MpcCallbackData * data = (MpcCallbackData *)vdata; MpcCallbackData *data = (MpcCallbackData *) vdata;
while(1) { while (1) {
ret = readFromInputStream(data->inStream, ptr, 1, size); ret = readFromInputStream(data->inStream, ptr, 1, size);
if(ret == 0 && !inputStreamAtEOF(data->inStream) && if (ret == 0 && !inputStreamAtEOF(data->inStream) &&
(data->dc && !data->dc->stop)) (data->dc && !data->dc->stop)) {
{
my_usleep(10000); my_usleep(10000);
} } else
else break; break;
} }
return ret; return ret;
} }
static mpc_bool_t mpc_seek_cb(void * vdata, mpc_int32_t offset) { static mpc_bool_t mpc_seek_cb(void *vdata, mpc_int32_t offset)
MpcCallbackData * data = (MpcCallbackData *)vdata; {
MpcCallbackData *data = (MpcCallbackData *) vdata;
return seekInputStream(data->inStream , offset, SEEK_SET) < 0 ? 0 : 1; return seekInputStream(data->inStream, offset, SEEK_SET) < 0 ? 0 : 1;
} }
static mpc_int32_t mpc_tell_cb(void * vdata) { static mpc_int32_t mpc_tell_cb(void *vdata)
MpcCallbackData * data = (MpcCallbackData *)vdata; {
MpcCallbackData *data = (MpcCallbackData *) vdata;
return (long)(data->inStream->offset); return (long)(data->inStream->offset);
} }
static mpc_bool_t mpc_canseek_cb(void * vdata) { static mpc_bool_t mpc_canseek_cb(void *vdata)
MpcCallbackData * data = (MpcCallbackData *)vdata; {
MpcCallbackData *data = (MpcCallbackData *) vdata;
return data->inStream->seekable; return data->inStream->seekable;
} }
static mpc_int32_t mpc_getsize_cb(void * vdata) { static mpc_int32_t mpc_getsize_cb(void *vdata)
MpcCallbackData * data = (MpcCallbackData *)vdata; {
MpcCallbackData *data = (MpcCallbackData *) vdata;
return data->inStream->size; return data->inStream->size;
} }
/* this _looks_ performance-critical, don't de-inline -- eric */ /* this _looks_ performance-critical, don't de-inline -- eric */
static inline mpd_sint16 convertSample(MPC_SAMPLE_FORMAT sample) { static inline mpd_sint16 convertSample(MPC_SAMPLE_FORMAT sample)
{
/* only doing 16-bit audio for now */ /* only doing 16-bit audio for now */
mpd_sint32 val; mpd_sint32 val;
...@@ -93,10 +98,9 @@ static inline mpd_sint16 convertSample(MPC_SAMPLE_FORMAT sample) { ...@@ -93,10 +98,9 @@ static inline mpd_sint16 convertSample(MPC_SAMPLE_FORMAT sample) {
#ifdef MPC_FIXED_POINT #ifdef MPC_FIXED_POINT
const int shift = 16 - MPC_FIXED_POINT_SCALE_SHIFT; const int shift = 16 - MPC_FIXED_POINT_SCALE_SHIFT;
if( ssample > 0 ) { if (ssample > 0) {
sample <<= shift; sample <<= shift;
} } else if (shift < 0) {
else if ( shift < 0 ) {
sample >>= -shift; sample >>= -shift;
} }
val = sample; val = sample;
...@@ -106,8 +110,10 @@ static inline mpd_sint16 convertSample(MPC_SAMPLE_FORMAT sample) { ...@@ -106,8 +110,10 @@ static inline mpd_sint16 convertSample(MPC_SAMPLE_FORMAT sample) {
val = sample * float_scale; val = sample * float_scale;
#endif #endif
if( val < clip_min) val = clip_min; if (val < clip_min)
else if ( val > clip_max ) val = clip_max; val = clip_min;
else if (val > clip_max)
val = clip_max;
return val; return val;
} }
...@@ -129,13 +135,13 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc, ...@@ -129,13 +135,13 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
char chunk[MPC_CHUNK_SIZE]; char chunk[MPC_CHUNK_SIZE];
int chunkpos = 0; int chunkpos = 0;
long bitRate = 0; long bitRate = 0;
mpd_sint16 * s16 = (mpd_sint16 *) chunk; mpd_sint16 *s16 = (mpd_sint16 *) chunk;
unsigned long samplePos = 0; unsigned long samplePos = 0;
mpc_uint32_t vbrUpdateAcc; mpc_uint32_t vbrUpdateAcc;
mpc_uint32_t vbrUpdateBits; mpc_uint32_t vbrUpdateBits;
float time; float time;
int i; int i;
ReplayGainInfo * replayGainInfo = NULL; ReplayGainInfo *replayGainInfo = NULL;
data.inStream = inStream; data.inStream = inStream;
data.dc = dc; data.dc = dc;
...@@ -149,13 +155,12 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc, ...@@ -149,13 +155,12 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
mpc_streaminfo_init(&info); mpc_streaminfo_init(&info);
if((ret = mpc_streaminfo_read(&info, &reader)) != ERROR_CODE_OK) { if ((ret = mpc_streaminfo_read(&info, &reader)) != ERROR_CODE_OK) {
closeInputStream(inStream); closeInputStream(inStream);
if(!dc->stop) { if (!dc->stop) {
ERROR("Not a valid musepack stream"); ERROR("Not a valid musepack stream");
return -1; return -1;
} } else {
else {
dc->state = DECODE_STATE_STOP; dc->state = DECODE_STATE_STOP;
dc->stop = 0; dc->stop = 0;
} }
...@@ -164,12 +169,11 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc, ...@@ -164,12 +169,11 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
mpc_decoder_setup(&decoder, &reader); mpc_decoder_setup(&decoder, &reader);
if(!mpc_decoder_initialize(&decoder, &info)) { if (!mpc_decoder_initialize(&decoder, &info)) {
closeInputStream(inStream); closeInputStream(inStream);
if(!dc->stop) { if (!dc->stop) {
ERROR("Not a valid musepack stream"); ERROR("Not a valid musepack stream");
} } else {
else {
dc->state = DECODE_STATE_STOP; dc->state = DECODE_STATE_STOP;
dc->stop = 0; dc->stop = 0;
} }
...@@ -191,14 +195,14 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc, ...@@ -191,14 +195,14 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
dc->state = DECODE_STATE_DECODE; dc->state = DECODE_STATE_DECODE;
while(!eof) { while (!eof) {
if(dc->seek) { if (dc->seek) {
samplePos = dc->seekWhere * dc->audioFormat.sampleRate; samplePos = dc->seekWhere * dc->audioFormat.sampleRate;
if(mpc_decoder_seek_sample(&decoder, samplePos)) { if (mpc_decoder_seek_sample(&decoder, samplePos)) {
clearOutputBuffer(cb); clearOutputBuffer(cb);
chunkpos = 0; chunkpos = 0;
} } else
else dc->seekError = 1; dc->seekError = 1;
dc->seek = 0; dc->seek = 0;
} }
...@@ -207,7 +211,7 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc, ...@@ -207,7 +211,7 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
ret = mpc_decoder_decode(&decoder, sample_buffer, ret = mpc_decoder_decode(&decoder, sample_buffer,
&vbrUpdateAcc, &vbrUpdateBits); &vbrUpdateAcc, &vbrUpdateBits);
if(ret <= 0 || dc->stop ) { if (ret <= 0 || dc->stop) {
eof = 1; eof = 1;
break; break;
} }
...@@ -217,30 +221,28 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc, ...@@ -217,30 +221,28 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
/* ret is in samples, and we have stereo */ /* ret is in samples, and we have stereo */
ret *= 2; ret *= 2;
for(i = 0; i < ret; i++) { for (i = 0; i < ret; i++) {
/* 16 bit audio again */ /* 16 bit audio again */
*s16 = convertSample(sample_buffer[i]); *s16 = convertSample(sample_buffer[i]);
chunkpos += 2; chunkpos += 2;
s16++; s16++;
if(chunkpos >= MPC_CHUNK_SIZE) { if (chunkpos >= MPC_CHUNK_SIZE) {
time = ((float)samplePos) / time = ((float)samplePos) /
dc->audioFormat.sampleRate; dc->audioFormat.sampleRate;
bitRate = vbrUpdateBits * bitRate = vbrUpdateBits *
dc->audioFormat.sampleRate / dc->audioFormat.sampleRate / 1152 / 1000;
1152 / 1000;
sendDataToOutputBuffer(cb, inStream, dc, sendDataToOutputBuffer(cb, inStream, dc,
inStream->seekable, inStream->seekable,
chunk, chunkpos, chunk, chunkpos,
time, time,
bitRate, bitRate, replayGainInfo);
replayGainInfo);
chunkpos = 0; chunkpos = 0;
s16 = (mpd_sint16 *)chunk; s16 = (mpd_sint16 *) chunk;
if(dc->stop) { if (dc->stop) {
eof = 1; eof = 1;
break; break;
} }
...@@ -248,10 +250,11 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc, ...@@ -248,10 +250,11 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
} }
} }
if(!dc->stop && chunkpos > 0) { if (!dc->stop && chunkpos > 0) {
time = ((float)samplePos) / dc->audioFormat.sampleRate; time = ((float)samplePos) / dc->audioFormat.sampleRate;
bitRate = vbrUpdateBits * dc->audioFormat.sampleRate / 1152 / 1000; bitRate =
vbrUpdateBits * dc->audioFormat.sampleRate / 1152 / 1000;
sendDataToOutputBuffer(cb, NULL, dc, inStream->seekable, sendDataToOutputBuffer(cb, NULL, dc, inStream->seekable,
chunk, chunkpos, time, bitRate, chunk, chunkpos, time, bitRate,
...@@ -264,18 +267,18 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc, ...@@ -264,18 +267,18 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
freeReplayGainInfo(replayGainInfo); freeReplayGainInfo(replayGainInfo);
if(dc->stop) { if (dc->stop) {
dc->state = DECODE_STATE_STOP; dc->state = DECODE_STATE_STOP;
dc->stop = 0; dc->stop = 0;
} } else {
else {
dc->state = DECODE_STATE_STOP; dc->state = DECODE_STATE_STOP;
} }
return 0; return 0;
} }
static float mpcGetTime(char * file) { static float mpcGetTime(char *file)
{
InputStream inStream; InputStream inStream;
float time = -1; float time = -1;
...@@ -295,12 +298,12 @@ static float mpcGetTime(char * file) { ...@@ -295,12 +298,12 @@ static float mpcGetTime(char * file) {
mpc_streaminfo_init(&info); mpc_streaminfo_init(&info);
if(openInputStream(&inStream, file) < 0) { if (openInputStream(&inStream, file) < 0) {
DEBUG("mpcGetTime: Failed to open file: %s\n", file); DEBUG("mpcGetTime: Failed to open file: %s\n", file);
return -1; return -1;
} }
if(mpc_streaminfo_read(&info, &reader) != ERROR_CODE_OK) { if (mpc_streaminfo_read(&info, &reader) != ERROR_CODE_OK) {
closeInputStream(&inStream); closeInputStream(&inStream);
return -1; return -1;
} }
...@@ -312,28 +315,31 @@ static float mpcGetTime(char * file) { ...@@ -312,28 +315,31 @@ static float mpcGetTime(char * file) {
return time; return time;
} }
static MpdTag * mpcTagDup(char * file) { static MpdTag *mpcTagDup(char *file)
MpdTag * ret = NULL; {
MpdTag *ret = NULL;
float time = mpcGetTime(file); float time = mpcGetTime(file);
if(time < 0) { if (time < 0) {
DEBUG("mpcTagDup: Failed to get Songlength of file: %s\n",file); DEBUG("mpcTagDup: Failed to get Songlength of file: %s\n",
file);
return NULL; return NULL;
} }
ret = apeDup(file); ret = apeDup(file);
if(!ret) ret = id3Dup(file); if (!ret)
if(!ret) ret = newMpdTag(); ret = id3Dup(file);
if (!ret)
ret = newMpdTag();
ret->time = time; ret->time = time;
return ret; return ret;
} }
static char * mpcSuffixes[] = {"mpc", NULL}; static char *mpcSuffixes[] = { "mpc", NULL };
static char * mpcMimeTypes[] = {NULL}; static char *mpcMimeTypes[] = { NULL };
InputPlugin mpcPlugin = InputPlugin mpcPlugin = {
{
"mpc", "mpc",
NULL, NULL,
NULL, NULL,
...@@ -348,8 +354,7 @@ InputPlugin mpcPlugin = ...@@ -348,8 +354,7 @@ InputPlugin mpcPlugin =
#else #else
InputPlugin mpcPlugin = InputPlugin mpcPlugin = {
{
NULL, NULL,
NULL, NULL,
NULL, NULL,
......
...@@ -25,12 +25,14 @@ ...@@ -25,12 +25,14 @@
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
void initInputStream(void) { void initInputStream(void)
{
inputStream_initFile(); inputStream_initFile();
inputStream_initHttp(); inputStream_initHttp();
} }
int openInputStream(InputStream * inStream, char * url) { int openInputStream(InputStream * inStream, char *url)
{
inStream->offset = 0; inStream->offset = 0;
inStream->size = 0; inStream->size = 0;
inStream->error = 0; inStream->error = 0;
...@@ -39,34 +41,43 @@ int openInputStream(InputStream * inStream, char * url) { ...@@ -39,34 +41,43 @@ int openInputStream(InputStream * inStream, char * url) {
inStream->metaName = NULL; inStream->metaName = NULL;
inStream->metaTitle = NULL; inStream->metaTitle = NULL;
if(inputStream_fileOpen(inStream,url) == 0) return 0; if (inputStream_fileOpen(inStream, url) == 0)
if(inputStream_httpOpen(inStream,url) == 0) return 0; return 0;
if (inputStream_httpOpen(inStream, url) == 0)
return 0;
return -1; return -1;
} }
int seekInputStream(InputStream * inStream, long offset, int whence) { int seekInputStream(InputStream * inStream, long offset, int whence)
return inStream->seekFunc(inStream,offset,whence); {
return inStream->seekFunc(inStream, offset, whence);
} }
size_t readFromInputStream(InputStream * inStream, void * ptr, size_t size, size_t readFromInputStream(InputStream * inStream, void *ptr, size_t size,
size_t nmemb) size_t nmemb)
{ {
return inStream->readFunc(inStream,ptr,size,nmemb); return inStream->readFunc(inStream, ptr, size, nmemb);
} }
int closeInputStream(InputStream * inStream) { int closeInputStream(InputStream * inStream)
if(inStream->mime) free(inStream->mime); {
if(inStream->metaName) free(inStream->metaName); if (inStream->mime)
if(inStream->metaTitle) free(inStream->metaTitle); free(inStream->mime);
if (inStream->metaName)
free(inStream->metaName);
if (inStream->metaTitle)
free(inStream->metaTitle);
return inStream->closeFunc(inStream); return inStream->closeFunc(inStream);
} }
int inputStreamAtEOF(InputStream * inStream) { int inputStreamAtEOF(InputStream * inStream)
{
return inStream->atEOFFunc(inStream); return inStream->atEOFFunc(inStream);
} }
int bufferInputStream(InputStream * inStream) { int bufferInputStream(InputStream * inStream)
{
return inStream->bufferFunc(inStream); return inStream->bufferFunc(inStream);
} }
...@@ -23,19 +23,19 @@ ...@@ -23,19 +23,19 @@
typedef struct _InputStream InputStream; typedef struct _InputStream InputStream;
typedef int (* InputStreamSeekFunc) (InputStream * inStream, long offset, typedef int (*InputStreamSeekFunc) (InputStream * inStream, long offset,
int whence); int whence);
typedef size_t (* InputStreamReadFunc) (InputStream * inStream, void * ptr, size_t size, typedef size_t(*InputStreamReadFunc) (InputStream * inStream, void *ptr,
size_t nmemb); size_t size, size_t nmemb);
typedef int (* InputStreamCloseFunc) (InputStream * inStream); typedef int (*InputStreamCloseFunc) (InputStream * inStream);
typedef int (* InputStreamAtEOFFunc) (InputStream * inStream); typedef int (*InputStreamAtEOFFunc) (InputStream * inStream);
typedef int (* InputStreamBufferFunc) (InputStream * inStream); typedef int (*InputStreamBufferFunc) (InputStream * inStream);
struct _InputStream { struct _InputStream {
int error; int error;
long offset; long offset;
size_t size; size_t size;
char * mime; char *mime;
int seekable; int seekable;
/* don't touc this stuff */ /* don't touc this stuff */
...@@ -44,18 +44,18 @@ struct _InputStream { ...@@ -44,18 +44,18 @@ struct _InputStream {
InputStreamCloseFunc closeFunc; InputStreamCloseFunc closeFunc;
InputStreamAtEOFFunc atEOFFunc; InputStreamAtEOFFunc atEOFFunc;
InputStreamBufferFunc bufferFunc; InputStreamBufferFunc bufferFunc;
void * data; void *data;
char * metaName; char *metaName;
char * metaTitle; char *metaTitle;
}; };
void initInputStream(); void initInputStream();
int isUrlSaneForInputStream(char * url); int isUrlSaneForInputStream(char *url);
/* if an error occurs for these 3 functions, then -1 is returned and errno /* if an error occurs for these 3 functions, then -1 is returned and errno
for the input stream is set */ for the input stream is set */
int openInputStream(InputStream * inStream, char * url); int openInputStream(InputStream * inStream, char *url);
int seekInputStream(InputStream * inStream, long offset, int whence); int seekInputStream(InputStream * inStream, long offset, int whence);
int closeInputStream(InputStream * inStream); int closeInputStream(InputStream * inStream);
int inputStreamAtEOF(InputStream * inStream); int inputStreamAtEOF(InputStream * inStream);
...@@ -64,7 +64,7 @@ int inputStreamAtEOF(InputStream * inStream); ...@@ -64,7 +64,7 @@ int inputStreamAtEOF(InputStream * inStream);
was buffered */ was buffered */
int bufferInputStream(InputStream * inStream); int bufferInputStream(InputStream * inStream);
size_t readFromInputStream(InputStream * inStream, void * ptr, size_t size, size_t readFromInputStream(InputStream * inStream, void *ptr, size_t size,
size_t nmemb); size_t nmemb);
#endif #endif
...@@ -26,23 +26,25 @@ ...@@ -26,23 +26,25 @@
#include <unistd.h> #include <unistd.h>
#include <errno.h> #include <errno.h>
void inputStream_initFile(void) { void inputStream_initFile(void)
{
} }
int inputStream_fileOpen(InputStream * inStream, char * filename) { int inputStream_fileOpen(InputStream * inStream, char *filename)
FILE * fp; {
FILE *fp;
fp = fopen(filename,"r"); fp = fopen(filename, "r");
if(!fp) { if (!fp) {
inStream->error = errno; inStream->error = errno;
return -1; return -1;
} }
inStream->seekable = 1; inStream->seekable = 1;
fseek(fp,0,SEEK_END); fseek(fp, 0, SEEK_END);
inStream->size = ftell(fp); inStream->size = ftell(fp);
fseek(fp,0,SEEK_SET); fseek(fp, 0, SEEK_SET);
inStream->data = fp; inStream->data = fp;
inStream->seekFunc = inputStream_fileSeek; inStream->seekFunc = inputStream_fileSeek;
...@@ -54,11 +56,11 @@ int inputStream_fileOpen(InputStream * inStream, char * filename) { ...@@ -54,11 +56,11 @@ int inputStream_fileOpen(InputStream * inStream, char * filename) {
return 0; return 0;
} }
int inputStream_fileSeek(InputStream * inStream, long offset, int whence) { int inputStream_fileSeek(InputStream * inStream, long offset, int whence)
if(fseek((FILE *)inStream->data,offset,whence)==0) { {
inStream->offset = ftell((FILE *)inStream->data); if (fseek((FILE *) inStream->data, offset, whence) == 0) {
} inStream->offset = ftell((FILE *) inStream->data);
else { } else {
inStream->error = errno; inStream->error = errno;
return -1; return -1;
} }
...@@ -66,25 +68,26 @@ int inputStream_fileSeek(InputStream * inStream, long offset, int whence) { ...@@ -66,25 +68,26 @@ int inputStream_fileSeek(InputStream * inStream, long offset, int whence) {
return 0; return 0;
} }
size_t inputStream_fileRead(InputStream * inStream, void * ptr, size_t size, size_t inputStream_fileRead(InputStream * inStream, void *ptr, size_t size,
size_t nmemb) size_t nmemb)
{ {
size_t readSize; size_t readSize;
readSize = fread(ptr,size,nmemb,(FILE *)inStream->data); readSize = fread(ptr, size, nmemb, (FILE *) inStream->data);
if(readSize <=0 && ferror((FILE *)inStream->data)) { if (readSize <= 0 && ferror((FILE *) inStream->data)) {
inStream->error = errno; inStream->error = errno;
DEBUG("inputStream_fileRead: error reading: %s\n", DEBUG("inputStream_fileRead: error reading: %s\n",
strerror(inStream->error)); strerror(inStream->error));
} }
inStream->offset = ftell((FILE *)inStream->data); inStream->offset = ftell((FILE *) inStream->data);
return readSize; return readSize;
} }
int inputStream_fileClose(InputStream * inStream) { int inputStream_fileClose(InputStream * inStream)
if(fclose((FILE *)inStream->data)<0) { {
if (fclose((FILE *) inStream->data) < 0) {
inStream->error = errno; inStream->error = errno;
return -1; return -1;
} }
...@@ -92,16 +95,19 @@ int inputStream_fileClose(InputStream * inStream) { ...@@ -92,16 +95,19 @@ int inputStream_fileClose(InputStream * inStream) {
return 0; return 0;
} }
int inputStream_fileAtEOF(InputStream * inStream) { int inputStream_fileAtEOF(InputStream * inStream)
if(feof((FILE *)inStream->data)) return 1; {
if (feof((FILE *) inStream->data))
return 1;
if(ferror((FILE *)inStream->data) && inStream->error != EINTR) { if (ferror((FILE *) inStream->data) && inStream->error != EINTR) {
return 1; return 1;
} }
return 0; return 0;
} }
int inputStream_fileBuffer(InputStream * inStream) { int inputStream_fileBuffer(InputStream * inStream)
{
return 0; return 0;
} }
...@@ -23,11 +23,11 @@ ...@@ -23,11 +23,11 @@
void inputStream_initFile(); void inputStream_initFile();
int inputStream_fileOpen(InputStream * inStream, char * filename); int inputStream_fileOpen(InputStream * inStream, char *filename);
int inputStream_fileSeek(InputStream * inStream, long offset, int whence); int inputStream_fileSeek(InputStream * inStream, long offset, int whence);
size_t inputStream_fileRead(InputStream * inStream, void * ptr, size_t size, size_t inputStream_fileRead(InputStream * inStream, void *ptr, size_t size,
size_t nmemb); size_t nmemb);
int inputStream_fileClose(InputStream * inStream); int inputStream_fileClose(InputStream * inStream);
......
...@@ -23,11 +23,11 @@ ...@@ -23,11 +23,11 @@
void inputStream_initHttp(); void inputStream_initHttp();
int inputStream_httpOpen(InputStream * inStream, char * filename); int inputStream_httpOpen(InputStream * inStream, char *filename);
int inputStream_httpSeek(InputStream * inStream, long offset, int whence); int inputStream_httpSeek(InputStream * inStream, long offset, int whence);
size_t inputStream_httpRead(InputStream * inStream, void * ptr, size_t size, size_t inputStream_httpRead(InputStream * inStream, void *ptr, size_t size,
size_t nmemb); size_t nmemb);
int inputStream_httpClose(InputStream * inStream); int inputStream_httpClose(InputStream * inStream);
......
...@@ -27,10 +27,10 @@ ...@@ -27,10 +27,10 @@
#include <sys/socket.h> #include <sys/socket.h>
void initInterfaces(); void initInterfaces();
void openAInterface(int fd, struct sockaddr * addr); void openAInterface(int fd, struct sockaddr *addr);
void freeAllInterfaces(); void freeAllInterfaces();
void closeOldInterfaces(); void closeOldInterfaces();
int interfacePrintWithFD(int fd, char * buffer, int len); int interfacePrintWithFD(int fd, char *buffer, int len);
int doIOForInterfaces(); int doIOForInterfaces();
......
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/ */
#ifndef LIST_H #ifndef LIST_H
#define LIST_H #define LIST_H
...@@ -32,26 +31,26 @@ typedef void ListFreeDataFunc(void *); ...@@ -32,26 +31,26 @@ typedef void ListFreeDataFunc(void *);
typedef struct _ListNode { typedef struct _ListNode {
/* used to identify node (ie. when using findInList) */ /* used to identify node (ie. when using findInList) */
char * key; char *key;
/* data store in node */ /* data store in node */
void * data; void *data;
/* next node in list */ /* next node in list */
struct _ListNode * nextNode; struct _ListNode *nextNode;
/* previous node in list */ /* previous node in list */
struct _ListNode * prevNode; struct _ListNode *prevNode;
} ListNode; } ListNode;
typedef struct _List { typedef struct _List {
/* first node in list */ /* first node in list */
ListNode * firstNode; ListNode *firstNode;
/* last node in list */ /* last node in list */
ListNode * lastNode; ListNode *lastNode;
/* function used to free data stored in nodes of the list */ /* function used to free data stored in nodes of the list */
ListFreeDataFunc * freeDataFunc; ListFreeDataFunc *freeDataFunc;
/* number of nodes */ /* number of nodes */
long numberOfNodes; long numberOfNodes;
/* array for searching when list is sorted */ /* array for searching when list is sorted */
ListNode ** nodesArray; ListNode **nodesArray;
/* sorted */ /* sorted */
int sorted; int sorted;
/* weather to strdup() key's on insertion */ /* weather to strdup() key's on insertion */
...@@ -63,7 +62,7 @@ typedef struct _List { ...@@ -63,7 +62,7 @@ typedef struct _List {
* DEFAULT_FREE_DATAFUNC to use free() * DEFAULT_FREE_DATAFUNC to use free()
* returns pointer to new list if successful, NULL otherwise * returns pointer to new list if successful, NULL otherwise
*/ */
List * makeList(ListFreeDataFunc * freeDataFunc, int strdupKeys); List *makeList(ListFreeDataFunc * freeDataFunc, int strdupKeys);
/* inserts a node into _list_ with _key_ and _data_ /* inserts a node into _list_ with _key_ and _data_
* _list_ -> list the data will be inserted in * _list_ -> list the data will be inserted in
...@@ -71,21 +70,21 @@ List * makeList(ListFreeDataFunc * freeDataFunc, int strdupKeys); ...@@ -71,21 +70,21 @@ List * makeList(ListFreeDataFunc * freeDataFunc, int strdupKeys);
* _data_ -> data to be inserted in list * _data_ -> data to be inserted in list
* returns 1 if successful, 0 otherwise * returns 1 if successful, 0 otherwise
*/ */
ListNode * insertInList(List * list,char * key,void * data); ListNode *insertInList(List * list, char *key, void *data);
ListNode * insertInListBeforeNode(List * list, ListNode * beforeNode, ListNode *insertInListBeforeNode(List * list, ListNode * beforeNode,
int pos, char * key, void * data); int pos, char *key, void *data);
int insertInListWithoutKey(List * list,void * data); int insertInListWithoutKey(List * list, void *data);
/* deletes the first node in the list with the key _key_ /* deletes the first node in the list with the key _key_
* _list_ -> list the node will be deleted from * _list_ -> list the node will be deleted from
* _key_ -> key used to identify node to delete * _key_ -> key used to identify node to delete
* returns 1 if node is found and deleted, 0 otherwise * returns 1 if node is found and deleted, 0 otherwise
*/ */
int deleteFromList(List * list,char * key); int deleteFromList(List * list, char *key);
void deleteNodeFromList(List * list,ListNode * node); void deleteNodeFromList(List * list, ListNode * node);
/* finds data in a list based on key /* finds data in a list based on key
* _list_ -> list to search for _key_ in * _list_ -> list to search for _key_ in
...@@ -95,16 +94,16 @@ void deleteNodeFromList(List * list,ListNode * node); ...@@ -95,16 +94,16 @@ void deleteNodeFromList(List * list,ListNode * node);
* _data_ can be NULL * _data_ can be NULL
* returns 1 if successful, 0 otherwise * returns 1 if successful, 0 otherwise
*/ */
int findInList(List * list, char * key, void ** data); int findInList(List * list, char *key, void **data);
/* if _key_ is not found, *_node_ is assigned to the node before which /* if _key_ is not found, *_node_ is assigned to the node before which
the info would be found */ the info would be found */
int findNodeInList(List * list, char * key, ListNode ** node, int * pos); int findNodeInList(List * list, char *key, ListNode ** node, int *pos);
/* frees memory malloc'd for list and its nodes /* frees memory malloc'd for list and its nodes
* _list_ -> List to be free'd * _list_ -> List to be free'd
*/ */
void freeList(void * list); void freeList(void *list);
void sortList(List * list); void sortList(List * list);
......
...@@ -40,18 +40,17 @@ ...@@ -40,18 +40,17 @@
#define DEFAULT_PORT 6600 #define DEFAULT_PORT 6600
int * listenSockets = NULL; int *listenSockets = NULL;
int numberOfListenSockets = 0; int numberOfListenSockets = 0;
static void establishListen(unsigned int port, static void establishListen(unsigned int port,
struct sockaddr * addrp, struct sockaddr *addrp, socklen_t addrlen)
socklen_t addrlen)
{ {
int pf; int pf;
int sock; int sock;
int allowReuse = ALLOW_REUSE; int allowReuse = ALLOW_REUSE;
switch(addrp->sa_family) { switch (addrp->sa_family) {
case AF_INET: case AF_INET:
pf = PF_INET; pf = PF_INET;
break; break;
...@@ -64,49 +63,49 @@ static void establishListen(unsigned int port, ...@@ -64,49 +63,49 @@ static void establishListen(unsigned int port,
pf = PF_UNIX; pf = PF_UNIX;
break; break;
default: default:
ERROR("unknown address family: %i\n",addrp->sa_family); ERROR("unknown address family: %i\n", addrp->sa_family);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if((sock = socket(pf,SOCK_STREAM,0)) < 0) { if ((sock = socket(pf, SOCK_STREAM, 0)) < 0) {
ERROR("socket < 0\n"); ERROR("socket < 0\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if(fcntl(sock, F_SETFL ,fcntl(sock, F_GETFL) | O_NONBLOCK) < 0) { if (fcntl(sock, F_SETFL, fcntl(sock, F_GETFL) | O_NONBLOCK) < 0) {
ERROR("problems setting nonblocking on listen socket: %s\n", ERROR("problems setting nonblocking on listen socket: %s\n",
strerror(errno)); strerror(errno));
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&allowReuse, if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&allowReuse,
sizeof(allowReuse))<0) sizeof(allowReuse)) < 0) {
{
ERROR("problems setsockopt'ing: %s\n", strerror(errno)); ERROR("problems setsockopt'ing: %s\n", strerror(errno));
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if(bind(sock,addrp,addrlen)<0) { if (bind(sock, addrp, addrlen) < 0) {
ERROR("unable to bind port %u", port); ERROR("unable to bind port %u", port);
ERROR(": %s\n", strerror(errno)); ERROR(": %s\n", strerror(errno));
ERROR("maybe MPD is still running?\n"); ERROR("maybe MPD is still running?\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
if(listen(sock,5)<0) { if (listen(sock, 5) < 0) {
ERROR("problems listen'ing: %s\n", strerror(errno)); ERROR("problems listen'ing: %s\n", strerror(errno));
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
numberOfListenSockets++; numberOfListenSockets++;
listenSockets = listenSockets =
realloc(listenSockets,sizeof(int)*numberOfListenSockets); realloc(listenSockets, sizeof(int) * numberOfListenSockets);
listenSockets[numberOfListenSockets-1] = sock; listenSockets[numberOfListenSockets - 1] = sock;
} }
static void parseListenConfigParam(unsigned int port, ConfigParam * param) { static void parseListenConfigParam(unsigned int port, ConfigParam * param)
struct sockaddr * addrp; {
struct sockaddr *addrp;
socklen_t addrlen; socklen_t addrlen;
struct sockaddr_in sin; struct sockaddr_in sin;
#ifdef HAVE_IPV6 #ifdef HAVE_IPV6
...@@ -120,54 +119,52 @@ static void parseListenConfigParam(unsigned int port, ConfigParam * param) { ...@@ -120,54 +119,52 @@ static void parseListenConfigParam(unsigned int port, ConfigParam * param) {
sin.sin_port = htons(port); sin.sin_port = htons(port);
sin.sin_family = AF_INET; sin.sin_family = AF_INET;
if(!param || 0==strcmp(param->value, "any")) { if (!param || 0 == strcmp(param->value, "any")) {
DEBUG("binding to any address\n"); DEBUG("binding to any address\n");
#ifdef HAVE_IPV6 #ifdef HAVE_IPV6
if(ipv6Supported()) { if (ipv6Supported()) {
sin6.sin6_addr = in6addr_any; sin6.sin6_addr = in6addr_any;
addrp = (struct sockaddr *) &sin6; addrp = (struct sockaddr *)&sin6;
addrlen = sizeof(struct sockaddr_in6); addrlen = sizeof(struct sockaddr_in6);
establishListen(port, addrp, addrlen); establishListen(port, addrp, addrlen);
} }
#endif #endif
sin.sin_addr.s_addr = INADDR_ANY; sin.sin_addr.s_addr = INADDR_ANY;
addrp = (struct sockaddr *) &sin; addrp = (struct sockaddr *)&sin;
addrlen = sizeof(struct sockaddr_in); addrlen = sizeof(struct sockaddr_in);
establishListen(port, addrp, addrlen); establishListen(port, addrp, addrlen);
} } else {
else { struct hostent *he;
struct hostent * he;
DEBUG("binding to address for %s\n", param->value); DEBUG("binding to address for %s\n", param->value);
if(!(he = gethostbyname(param->value))) { if (!(he = gethostbyname(param->value))) {
ERROR("can't lookup host \"%s\" at line %i\n", ERROR("can't lookup host \"%s\" at line %i\n",
param->value, param->line); param->value, param->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
switch(he->h_addrtype) { switch (he->h_addrtype) {
#ifdef HAVE_IPV6 #ifdef HAVE_IPV6
case AF_INET6: case AF_INET6:
if(!ipv6Supported()) { if (!ipv6Supported()) {
ERROR("no IPv6 support, but a IPv6 address " ERROR("no IPv6 support, but a IPv6 address "
"found for \"%s\" at line %i\n", "found for \"%s\" at line %i\n",
param->value, param->line); param->value, param->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
bcopy((char *)he->h_addr,(char *) bcopy((char *)he->h_addr, (char *)
&sin6.sin6_addr.s6_addr,he->h_length); &sin6.sin6_addr.s6_addr, he->h_length);
addrp = (struct sockaddr *) &sin6; addrp = (struct sockaddr *)&sin6;
addrlen = sizeof(struct sockaddr_in6); addrlen = sizeof(struct sockaddr_in6);
break; break;
#endif #endif
case AF_INET: case AF_INET:
bcopy((char *)he->h_addr,(char *)&sin.sin_addr.s_addr, bcopy((char *)he->h_addr, (char *)&sin.sin_addr.s_addr,
he->h_length); he->h_length);
addrp = (struct sockaddr *) &sin; addrp = (struct sockaddr *)&sin;
addrlen = sizeof(struct sockaddr_in); addrlen = sizeof(struct sockaddr_in);
break; break;
default: default:
ERROR("address type for \"%s\" is not IPv4 or IPv6 " ERROR("address type for \"%s\" is not IPv4 or IPv6 "
"at line %i\n", "at line %i\n", param->value, param->line);
param->value, param->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
...@@ -175,21 +172,21 @@ static void parseListenConfigParam(unsigned int port, ConfigParam * param) { ...@@ -175,21 +172,21 @@ static void parseListenConfigParam(unsigned int port, ConfigParam * param) {
} }
} }
void listenOnPort(void) { void listenOnPort(void)
{
int port = DEFAULT_PORT; int port = DEFAULT_PORT;
ConfigParam * param = getNextConfigParam(CONF_BIND_TO_ADDRESS,NULL); ConfigParam *param = getNextConfigParam(CONF_BIND_TO_ADDRESS, NULL);
{ {
ConfigParam * portParam = getConfigParam(CONF_PORT); ConfigParam *portParam = getConfigParam(CONF_PORT);
if(portParam) { if (portParam) {
char * test; char *test;
port = strtol(portParam->value, &test, 10); port = strtol(portParam->value, &test, 10);
if(port <= 0 || *test != '\0') { if (port <= 0 || *test != '\0') {
ERROR("%s \"%s\" specified at line %i is not a " ERROR("%s \"%s\" specified at line %i is not a "
"positive integer", CONF_PORT, "positive integer", CONF_PORT,
portParam->value, portParam->value, portParam->line);
portParam->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
} }
...@@ -200,47 +197,51 @@ void listenOnPort(void) { ...@@ -200,47 +197,51 @@ void listenOnPort(void) {
} while ((param = getNextConfigParam(CONF_BIND_TO_ADDRESS, param))); } while ((param = getNextConfigParam(CONF_BIND_TO_ADDRESS, param)));
} }
void addListenSocketsToFdSet(fd_set * fds, int * fdmax) { void addListenSocketsToFdSet(fd_set * fds, int *fdmax)
{
int i; int i;
for(i=0; i<numberOfListenSockets; i++) { for (i = 0; i < numberOfListenSockets; i++) {
FD_SET(listenSockets[i], fds); FD_SET(listenSockets[i], fds);
if(listenSockets[i] > *fdmax) *fdmax = listenSockets[i]; if (listenSockets[i] > *fdmax)
*fdmax = listenSockets[i];
} }
} }
void closeAllListenSockets(void) { void closeAllListenSockets(void)
{
int i; int i;
DEBUG("closeAllListenSockets called\n"); DEBUG("closeAllListenSockets called\n");
for(i=0; i<numberOfListenSockets; i++) { for (i = 0; i < numberOfListenSockets; i++) {
DEBUG("closing listen socket %i\n", i); DEBUG("closing listen socket %i\n", i);
while(close(listenSockets[i]) < 0 && errno==EINTR); while (close(listenSockets[i]) < 0 && errno == EINTR) ;
} }
freeAllListenSockets(); freeAllListenSockets();
} }
void freeAllListenSockets(void) { void freeAllListenSockets(void)
{
numberOfListenSockets = 0; numberOfListenSockets = 0;
free(listenSockets); free(listenSockets);
listenSockets = NULL; listenSockets = NULL;
} }
void getConnections(fd_set * fds) { void getConnections(fd_set * fds)
{
int i; int i;
int fd = 0; int fd = 0;
struct sockaddr sockAddr; struct sockaddr sockAddr;
socklen_t socklen = sizeof(sockAddr); socklen_t socklen = sizeof(sockAddr);
for(i=0; i<numberOfListenSockets; i++) { for (i = 0; i < numberOfListenSockets; i++) {
if(FD_ISSET(listenSockets[i], fds)) { if (FD_ISSET(listenSockets[i], fds)) {
if((fd = accept(listenSockets[i], &sockAddr, &socklen)) if ((fd = accept(listenSockets[i], &sockAddr, &socklen))
>= 0) >= 0) {
{ openAInterface(fd, &sockAddr);
openAInterface(fd,&sockAddr); } else if (fd < 0
} && (errno != EAGAIN && errno != EINTR)) {
else if(fd<0 && (errno!=EAGAIN && errno!=EINTR)) {
ERROR("Problems accept()'ing\n"); ERROR("Problems accept()'ing\n");
} }
} }
......
...@@ -34,6 +34,6 @@ void closeAllListenSockets(); ...@@ -34,6 +34,6 @@ void closeAllListenSockets();
void freeAllListenSockets(); void freeAllListenSockets();
/* fdmax should be initialized to something */ /* fdmax should be initialized to something */
void addListenSocketsToFdSet(fd_set * fds, int * fdmax); void addListenSocketsToFdSet(fd_set * fds, int *fdmax);
#endif #endif
...@@ -29,23 +29,25 @@ ...@@ -29,23 +29,25 @@
int logLevel = LOG_LEVEL_LOW; int logLevel = LOG_LEVEL_LOW;
short warningFlushed = 0; short warningFlushed = 0;
static char * warningBuffer = NULL; static char *warningBuffer = NULL;
void initLog(void) { void initLog(void)
ConfigParam * param = getConfigParam(CONF_LOG_LEVEL); {
ConfigParam *param = getConfigParam(CONF_LOG_LEVEL);
if(!param) return;
if (!param)
if(0 == strcmp(param->value, "default")) { return;
if(logLevel<LOG_LEVEL_LOW) logLevel = LOG_LEVEL_LOW;
} if (0 == strcmp(param->value, "default")) {
else if(0 == strcmp(param->value, "secure")) { if (logLevel < LOG_LEVEL_LOW)
if(logLevel<LOG_LEVEL_SECURE) logLevel = LOG_LEVEL_SECURE; logLevel = LOG_LEVEL_LOW;
} } else if (0 == strcmp(param->value, "secure")) {
else if(0 == strcmp(param->value, "verbose")) { if (logLevel < LOG_LEVEL_SECURE)
if(logLevel<LOG_LEVEL_DEBUG) logLevel = LOG_LEVEL_DEBUG; logLevel = LOG_LEVEL_SECURE;
} } else if (0 == strcmp(param->value, "verbose")) {
else { if (logLevel < LOG_LEVEL_DEBUG)
logLevel = LOG_LEVEL_DEBUG;
} else {
ERROR("unknown log level \"%s\" at line %i\n", ERROR("unknown log level \"%s\" at line %i\n",
param->value, param->line); param->value, param->line);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
...@@ -54,11 +56,12 @@ void initLog(void) { ...@@ -54,11 +56,12 @@ void initLog(void) {
#define BUFFER_LENGTH 4096 #define BUFFER_LENGTH 4096
void bufferWarning(char * format, ... ) { void bufferWarning(char *format, ...)
{
va_list arglist; va_list arglist;
char temp[BUFFER_LENGTH+1]; char temp[BUFFER_LENGTH + 1];
memset(temp, 0, BUFFER_LENGTH+1); memset(temp, 0, BUFFER_LENGTH + 1);
va_start(arglist, format); va_start(arglist, format);
...@@ -69,15 +72,17 @@ void bufferWarning(char * format, ... ) { ...@@ -69,15 +72,17 @@ void bufferWarning(char * format, ... ) {
va_end(arglist); va_end(arglist);
} }
void flushWarningLog(void) { void flushWarningLog(void)
char * s; {
char *s;
DEBUG("flushing warning messages\n"); DEBUG("flushing warning messages\n");
if(warningBuffer == NULL) return; if (warningBuffer == NULL)
return;
s = strtok(warningBuffer, "\n"); s = strtok(warningBuffer, "\n");
while ( s != NULL ) { while (s != NULL) {
myfprintf(stderr, "%s\n", s); myfprintf(stderr, "%s\n", s);
s = strtok(NULL, "\n"); s = strtok(NULL, "\n");
......
...@@ -37,7 +37,6 @@ extern short warningFlushed; ...@@ -37,7 +37,6 @@ extern short warningFlushed;
#define SECURE(...) if(logLevel>=LOG_LEVEL_SECURE) \ #define SECURE(...) if(logLevel>=LOG_LEVEL_SECURE) \
myfprintf(stdout, __VA_ARGS__) myfprintf(stdout, __VA_ARGS__)
#define DEBUG(...) if(logLevel>=LOG_LEVEL_DEBUG) \ #define DEBUG(...) if(logLevel>=LOG_LEVEL_DEBUG) \
myfprintf(stdout, __VA_ARGS__) myfprintf(stdout, __VA_ARGS__)
...@@ -48,7 +47,7 @@ extern short warningFlushed; ...@@ -48,7 +47,7 @@ extern short warningFlushed;
void initLog(); void initLog();
void bufferWarning(char * format, ... ); void bufferWarning(char *format, ...);
void flushWarningLog(); void flushWarningLog();
......
...@@ -27,33 +27,34 @@ ...@@ -27,33 +27,34 @@
#include <stdio.h> #include <stdio.h>
#include <errno.h> #include <errno.h>
static char * remoteUrlPrefixes[] = static char *remoteUrlPrefixes[] = {
{
"http://", "http://",
NULL NULL
}; };
int printRemoteUrlHandlers(FILE * fp) { int printRemoteUrlHandlers(FILE * fp)
char ** prefixes = remoteUrlPrefixes; {
char **prefixes = remoteUrlPrefixes;
while (*prefixes) { while (*prefixes) {
myfprintf(fp,"handler: %s\n", *prefixes); myfprintf(fp, "handler: %s\n", *prefixes);
prefixes++; prefixes++;
} }
return 0; return 0;
} }
int isValidRemoteUtf8Url(char * utf8url) { int isValidRemoteUtf8Url(char *utf8url)
{
int ret = 0; int ret = 0;
char * temp; char *temp;
switch(isRemoteUrl(utf8url)) { switch (isRemoteUrl(utf8url)) {
case 1: case 1:
ret = 1; ret = 1;
temp = utf8url; temp = utf8url;
while(*temp) { while (*temp) {
if((*temp >= 'a' && *temp <= 'z') || if ((*temp >= 'a' && *temp <= 'z') ||
(*temp >= 'A' && *temp <= 'Z') || (*temp >= 'A' && *temp <= 'Z') ||
(*temp >= '0' && *temp <= '9') || (*temp >= '0' && *temp <= '9') ||
*temp == '$' || *temp == '$' ||
...@@ -70,12 +71,8 @@ int isValidRemoteUtf8Url(char * utf8url) { ...@@ -70,12 +71,8 @@ int isValidRemoteUtf8Url(char * utf8url) {
*temp == '/' || *temp == '/' ||
*temp == ':' || *temp == ':' ||
*temp == '?' || *temp == '?' ||
*temp == ';' || *temp == ';' || *temp == '&' || *temp == '=') {
*temp == '&' || } else {
*temp == '=')
{
}
else {
ret = 1; ret = 1;
break; break;
} }
...@@ -87,13 +84,14 @@ int isValidRemoteUtf8Url(char * utf8url) { ...@@ -87,13 +84,14 @@ int isValidRemoteUtf8Url(char * utf8url) {
return ret; return ret;
} }
int isRemoteUrl(char * url) { int isRemoteUrl(char *url)
{
int count = 0; int count = 0;
char ** urlPrefixes = remoteUrlPrefixes; char **urlPrefixes = remoteUrlPrefixes;
while(*urlPrefixes) { while (*urlPrefixes) {
count++; count++;
if(strncmp(*urlPrefixes,url,strlen(*urlPrefixes)) == 0) { if (strncmp(*urlPrefixes, url, strlen(*urlPrefixes)) == 0) {
return count; return count;
} }
urlPrefixes++; urlPrefixes++;
...@@ -102,46 +100,47 @@ int isRemoteUrl(char * url) { ...@@ -102,46 +100,47 @@ int isRemoteUrl(char * url) {
return 0; return 0;
} }
int lsPlaylists(FILE * fp, char * utf8path) { int lsPlaylists(FILE * fp, char *utf8path)
DIR * dir; {
DIR *dir;
struct stat st; struct stat st;
struct dirent * ent; struct dirent *ent;
char * dup; char *dup;
char * utf8; char *utf8;
char s[MAXPATHLEN+1]; char s[MAXPATHLEN + 1];
List * list = NULL; List *list = NULL;
ListNode * node = NULL; ListNode *node = NULL;
char * path = utf8ToFsCharset(utf8path); char *path = utf8ToFsCharset(utf8path);
char * actualPath = rpp2app(path); char *actualPath = rpp2app(path);
int actlen = strlen(actualPath)+1; int actlen = strlen(actualPath) + 1;
int maxlen = MAXPATHLEN-actlen; int maxlen = MAXPATHLEN - actlen;
int suflen = strlen(PLAYLIST_FILE_SUFFIX)+1; int suflen = strlen(PLAYLIST_FILE_SUFFIX) + 1;
int suff; int suff;
if(actlen>MAXPATHLEN-1 || (dir = opendir(actualPath))==NULL) { if (actlen > MAXPATHLEN - 1 || (dir = opendir(actualPath)) == NULL) {
free(path); free(path);
return 0; return 0;
} }
s[MAXPATHLEN] = '\0'; s[MAXPATHLEN] = '\0';
/* this is safe, notice actlen > MAXPATHLEN-1 above */ /* this is safe, notice actlen > MAXPATHLEN-1 above */
strcpy(s,actualPath); strcpy(s, actualPath);
strcat(s,"/"); strcat(s, "/");
while((ent = readdir(dir))) { while ((ent = readdir(dir))) {
dup = ent->d_name; dup = ent->d_name;
if(dup[0]!='.' && if (dup[0] != '.' &&
(suff=strlen(dup)-suflen)>0 && (suff = strlen(dup) - suflen) > 0 &&
dup[suff]=='.' && dup[suff] == '.' &&
strcmp(dup+suff+1,PLAYLIST_FILE_SUFFIX)==0) strcmp(dup + suff + 1, PLAYLIST_FILE_SUFFIX) == 0) {
{ strncpy(s + actlen, ent->d_name, maxlen);
strncpy(s+actlen,ent->d_name,maxlen); if (stat(s, &st) == 0) {
if(stat(s,&st)==0) { if (S_ISREG(st.st_mode)) {
if(S_ISREG(st.st_mode)) { if (list == NULL)
if(list==NULL) list = makeList(NULL, 1); list = makeList(NULL, 1);
dup[suff] = '\0'; dup[suff] = '\0';
if((utf8 = fsCharsetToUtf8(dup))) { if ((utf8 = fsCharsetToUtf8(dup))) {
insertInList(list,utf8,NULL); insertInList(list, utf8, NULL);
free(utf8); free(utf8);
} }
} }
...@@ -152,21 +151,23 @@ int lsPlaylists(FILE * fp, char * utf8path) { ...@@ -152,21 +151,23 @@ int lsPlaylists(FILE * fp, char * utf8path) {
closedir(dir); closedir(dir);
free(path); free(path);
if(list) { if (list) {
int i; int i;
sortList(list); sortList(list);
dup = malloc(strlen(utf8path)+2); dup = malloc(strlen(utf8path) + 2);
strcpy(dup,utf8path); strcpy(dup, utf8path);
for(i = strlen(dup)-1; i >= 0 && dup[i]=='/'; i--) { for (i = strlen(dup) - 1; i >= 0 && dup[i] == '/'; i--) {
dup[i] = '\0'; dup[i] = '\0';
} }
if(strlen(dup)) strcat(dup,"/"); if (strlen(dup))
strcat(dup, "/");
node = list->firstNode; node = list->firstNode;
while(node!=NULL) { while (node != NULL) {
if(!strchr(node->key, '\n')) { if (!strchr(node->key, '\n')) {
myfprintf(fp,"playlist: %s%s\n",dup,node->key); myfprintf(fp, "playlist: %s%s\n", dup,
node->key);
} }
node = node->nextNode; node = node->nextNode;
} }
...@@ -178,71 +179,79 @@ int lsPlaylists(FILE * fp, char * utf8path) { ...@@ -178,71 +179,79 @@ int lsPlaylists(FILE * fp, char * utf8path) {
return 0; return 0;
} }
int myStat(char * utf8file, struct stat * st) { int myStat(char *utf8file, struct stat *st)
char * file = utf8ToFsCharset(utf8file); {
char * actualFile = file; char *file = utf8ToFsCharset(utf8file);
char *actualFile = file;
int ret; int ret;
if(actualFile[0]!='/') actualFile = rmp2amp(file); if (actualFile[0] != '/')
actualFile = rmp2amp(file);
ret = stat(actualFile,st); ret = stat(actualFile, st);
free(file); free(file);
return ret; return ret;
} }
static int isFile(char * utf8file, time_t * mtime) { static int isFile(char *utf8file, time_t * mtime)
{
struct stat st; struct stat st;
if(myStat(utf8file,&st)==0) { if (myStat(utf8file, &st) == 0) {
if(S_ISREG(st.st_mode)) { if (S_ISREG(st.st_mode)) {
if(mtime) *mtime = st.st_mtime; if (mtime)
*mtime = st.st_mtime;
return 1; return 1;
} } else {
else DEBUG("isFile: %s is not a regular file\n", utf8file);
{
DEBUG("isFile: %s is not a regular file\n",utf8file);
return 0; return 0;
} }
} } else {
else { DEBUG("isFile: failed to stat: %s: %s\n", utf8file,
DEBUG("isFile: failed to stat: %s: %s\n", utf8file, strerror(errno)); strerror(errno));
} }
return 0; return 0;
} }
/* suffixes should be ascii only characters */ /* suffixes should be ascii only characters */
char * getSuffix(char * utf8file) { char *getSuffix(char *utf8file)
char * ret = NULL; {
char *ret = NULL;
while(*utf8file) { while (*utf8file) {
if(*utf8file == '.') ret = utf8file+1; if (*utf8file == '.')
ret = utf8file + 1;
utf8file++; utf8file++;
} }
return ret; return ret;
} }
int hasSuffix(char * utf8file, char * suffix) { int hasSuffix(char *utf8file, char *suffix)
char * s = getSuffix(utf8file); {
if(s && 0==strcmp(s,suffix)) return 1; char *s = getSuffix(utf8file);
if (s && 0 == strcmp(s, suffix))
return 1;
return 0; return 0;
} }
int isPlaylist(char * utf8file) { int isPlaylist(char *utf8file)
if(isFile(utf8file,NULL)) { {
return hasSuffix(utf8file,PLAYLIST_FILE_SUFFIX); if (isFile(utf8file, NULL)) {
return hasSuffix(utf8file, PLAYLIST_FILE_SUFFIX);
} }
return 0; return 0;
} }
int isDir(char * utf8name) { int isDir(char *utf8name)
{
struct stat st; struct stat st;
if(myStat(utf8name,&st)==0) { if (myStat(utf8name, &st) == 0) {
if(S_ISDIR(st.st_mode)) { if (S_ISDIR(st.st_mode)) {
return 1; return 1;
} }
} }
...@@ -250,26 +259,28 @@ int isDir(char * utf8name) { ...@@ -250,26 +259,28 @@ int isDir(char * utf8name) {
return 0; return 0;
} }
InputPlugin * hasMusicSuffix(char * utf8file, unsigned int next) { InputPlugin *hasMusicSuffix(char *utf8file, unsigned int next)
InputPlugin * ret = NULL; {
InputPlugin *ret = NULL;
char * s = getSuffix(utf8file); char *s = getSuffix(utf8file);
if(s) { if (s) {
ret = getInputPluginFromSuffix(s, next); ret = getInputPluginFromSuffix(s, next);
} } else {
else { DEBUG("hasMusicSuffix: The file: %s has no valid suffix\n",
DEBUG("hasMusicSuffix: The file: %s has no valid suffix\n",utf8file); utf8file);
} }
return ret; return ret;
} }
InputPlugin * isMusic(char * utf8file, time_t * mtime, unsigned int next) { InputPlugin *isMusic(char *utf8file, time_t * mtime, unsigned int next)
if(isFile(utf8file,mtime)) { {
InputPlugin * plugin = hasMusicSuffix(utf8file, next); if (isFile(utf8file, mtime)) {
InputPlugin *plugin = hasMusicSuffix(utf8file, next);
if (plugin != NULL) if (plugin != NULL)
return plugin; return plugin;
} }
DEBUG("isMusic: %s is not a valid file\n",utf8file); DEBUG("isMusic: %s is not a valid file\n", utf8file);
return NULL; return NULL;
} }
...@@ -29,23 +29,23 @@ ...@@ -29,23 +29,23 @@
#include <unistd.h> #include <unistd.h>
#include <time.h> #include <time.h>
int lsPlaylists(FILE * fp, char * utf8path); int lsPlaylists(FILE * fp, char *utf8path);
char * getSuffix(char * utf8file); char *getSuffix(char *utf8file);
int isValidRemoteUtf8Url(char * utf8url); int isValidRemoteUtf8Url(char *utf8url);
int isRemoteUrl(char * url); int isRemoteUrl(char *url);
int myStat(char * utf8file, struct stat * st); int myStat(char *utf8file, struct stat *st);
int isDir(char * utf8name); int isDir(char *utf8name);
int isPlaylist(char * utf8file); int isPlaylist(char *utf8file);
InputPlugin * hasMusicSuffix(char * utf8file, unsigned int next); InputPlugin *hasMusicSuffix(char *utf8file, unsigned int next);
InputPlugin * isMusic(char * utf8file, time_t * mtime, unsigned int next); InputPlugin *isMusic(char *utf8file, time_t * mtime, unsigned int next);
int printRemoteUrlHandlers(FILE * fp); int printRemoteUrlHandlers(FILE * fp);
......
...@@ -20,7 +20,8 @@ ...@@ -20,7 +20,8 @@
#include <string.h> #include <string.h>
static void initMetadataChunk(MetadataChunk * chunk) { static void initMetadataChunk(MetadataChunk * chunk)
{
memset(chunk, 0, sizeof(MetadataChunk)); memset(chunk, 0, sizeof(MetadataChunk));
chunk->name = -1; chunk->name = -1;
...@@ -35,10 +36,11 @@ static void initMetadataChunk(MetadataChunk * chunk) { ...@@ -35,10 +36,11 @@ static void initMetadataChunk(MetadataChunk * chunk) {
} \ } \
} }
MpdTag * metadataChunkToMpdTagDup(MetadataChunk * chunk) { MpdTag *metadataChunkToMpdTagDup(MetadataChunk * chunk)
MpdTag * ret = newMpdTag(); {
MpdTag *ret = newMpdTag();
chunk->buffer[METADATA_BUFFER_LENGTH-1] = '\0'; chunk->buffer[METADATA_BUFFER_LENGTH - 1] = '\0';
dupElementToTag(TAG_ITEM_NAME, chunk->name); dupElementToTag(TAG_ITEM_NAME, chunk->name);
dupElementToTag(TAG_ITEM_TITLE, chunk->title); dupElementToTag(TAG_ITEM_TITLE, chunk->title);
...@@ -59,17 +61,19 @@ MpdTag * metadataChunkToMpdTagDup(MetadataChunk * chunk) { ...@@ -59,17 +61,19 @@ MpdTag * metadataChunkToMpdTagDup(MetadataChunk * chunk) {
} \ } \
} }
void copyMpdTagToMetadataChunk(MpdTag * tag, MetadataChunk * chunk) { void copyMpdTagToMetadataChunk(MpdTag * tag, MetadataChunk * chunk)
{
int pos = 0; int pos = 0;
int slen; int slen;
int i; int i;
initMetadataChunk(chunk); initMetadataChunk(chunk);
if(!tag) return; if (!tag)
return;
for(i = 0; i < tag->numOfItems; i++) { for (i = 0; i < tag->numOfItems; i++) {
switch(tag->items[i].type) { switch (tag->items[i].type) {
case TAG_ITEM_NAME: case TAG_ITEM_NAME:
copyStringToChunk(tag->items[i].value, chunk->name); copyStringToChunk(tag->items[i].value, chunk->name);
break; break;
......
...@@ -31,7 +31,7 @@ typedef struct _MetadataChunk { ...@@ -31,7 +31,7 @@ typedef struct _MetadataChunk {
char buffer[METADATA_BUFFER_LENGTH]; char buffer[METADATA_BUFFER_LENGTH];
} MetadataChunk; } MetadataChunk;
MpdTag * metadataChunkToMpdTagDup(MetadataChunk * chunk); MpdTag *metadataChunkToMpdTagDup(MetadataChunk * chunk);
void copyMpdTagToMetadataChunk(MpdTag * tag, MetadataChunk * chunk); void copyMpdTagToMetadataChunk(MpdTag * tag, MetadataChunk * chunk);
......
...@@ -33,19 +33,21 @@ ...@@ -33,19 +33,21 @@
#define BUFFER_LENGTH MAXPATHLEN+1024 #define BUFFER_LENGTH MAXPATHLEN+1024
static int myfprintf_stdLogMode = 0; static int myfprintf_stdLogMode = 0;
static FILE * myfprintf_out; static FILE *myfprintf_out;
static FILE * myfprintf_err; static FILE *myfprintf_err;
static char * myfprintf_outFilename; static char *myfprintf_outFilename;
static char * myfprintf_errFilename; static char *myfprintf_errFilename;
static void blockingWrite(int fd, char * string, int len) { static void blockingWrite(int fd, char *string, int len)
{
int ret; int ret;
while(len) { while (len) {
ret = write(fd,string,len); ret = write(fd, string, len);
if(ret==0) return; if (ret == 0)
if(ret<0) { return;
switch(errno) { if (ret < 0) {
switch (errno) {
case EAGAIN: case EAGAIN:
case EINTR: case EINTR:
continue; continue;
...@@ -53,12 +55,13 @@ static void blockingWrite(int fd, char * string, int len) { ...@@ -53,12 +55,13 @@ static void blockingWrite(int fd, char * string, int len) {
return; return;
} }
} }
len-= ret; len -= ret;
string+= ret; string += ret;
} }
} }
void myfprintfStdLogMode(FILE * out, FILE * err) { void myfprintfStdLogMode(FILE * out, FILE * err)
{
myfprintf_stdLogMode = 1; myfprintf_stdLogMode = 1;
myfprintf_out = out; myfprintf_out = out;
myfprintf_err = err; myfprintf_err = err;
...@@ -66,64 +69,68 @@ void myfprintfStdLogMode(FILE * out, FILE * err) { ...@@ -66,64 +69,68 @@ void myfprintfStdLogMode(FILE * out, FILE * err) {
myfprintf_errFilename = getConfigParamValue(CONF_ERROR_FILE); myfprintf_errFilename = getConfigParamValue(CONF_ERROR_FILE);
} }
void myfprintf(FILE * fp, char * format, ... ) { void myfprintf(FILE * fp, char *format, ...)
static char buffer[BUFFER_LENGTH+1]; {
static char buffer[BUFFER_LENGTH + 1];
va_list arglist; va_list arglist;
int fd = fileno(fp); int fd = fileno(fp);
va_start(arglist,format); va_start(arglist, format);
if(fd==1 || fd==2) { if (fd == 1 || fd == 2) {
if(myfprintf_stdLogMode) { if (myfprintf_stdLogMode) {
time_t t = time(NULL); time_t t = time(NULL);
if(fd==1) fp = myfprintf_out; if (fd == 1)
else fp = myfprintf_err; fp = myfprintf_out;
strftime(buffer,14,"%b %e %R",localtime(&t)); else
blockingWrite(fd,buffer,strlen(buffer)); fp = myfprintf_err;
blockingWrite(fd," : ",3); strftime(buffer, 14, "%b %e %R", localtime(&t));
} blockingWrite(fd, buffer, strlen(buffer));
vsnprintf(buffer,BUFFER_LENGTH,format,arglist); blockingWrite(fd, " : ", 3);
blockingWrite(fd,buffer,strlen(buffer));
} }
else { vsnprintf(buffer, BUFFER_LENGTH, format, arglist);
blockingWrite(fd, buffer, strlen(buffer));
} else {
int len; int len;
vsnprintf(buffer,BUFFER_LENGTH,format,arglist); vsnprintf(buffer, BUFFER_LENGTH, format, arglist);
len = strlen(buffer); len = strlen(buffer);
if(interfacePrintWithFD(fd,buffer,len)<0) { if (interfacePrintWithFD(fd, buffer, len) < 0) {
blockingWrite(fd,buffer,len); blockingWrite(fd, buffer, len);
} }
} }
va_end(arglist); va_end(arglist);
} }
int myfprintfCloseAndOpenLogFile(void) { int myfprintfCloseAndOpenLogFile(void)
if(myfprintf_stdLogMode) { {
while(fclose(myfprintf_out)<0 && errno==EINTR); if (myfprintf_stdLogMode) {
while(fclose(myfprintf_err)<0 && errno==EINTR); while (fclose(myfprintf_out) < 0 && errno == EINTR) ;
while((myfprintf_out = fopen(myfprintf_outFilename,"a+"))==NULL while (fclose(myfprintf_err) < 0 && errno == EINTR) ;
&& errno==EINTR); while ((myfprintf_out =
if(!myfprintf_out) { fopen(myfprintf_outFilename, "a+")) == NULL
ERROR("error re-opening log file: %s\n", && errno == EINTR) ;
myfprintf_out); if (!myfprintf_out) {
ERROR("error re-opening log file: %s\n", myfprintf_out);
return -1; return -1;
} }
while((myfprintf_err = fopen(myfprintf_errFilename,"a+"))==NULL while ((myfprintf_err =
&& errno==EINTR); fopen(myfprintf_errFilename, "a+")) == NULL
if(!myfprintf_out) { && errno == EINTR) ;
ERROR("error re-opening log file: %s\n", if (!myfprintf_out) {
myfprintf_out); ERROR("error re-opening log file: %s\n", myfprintf_out);
return -1; return -1;
} }
while(dup2(fileno(myfprintf_out),1)<0 && errno==EINTR); while (dup2(fileno(myfprintf_out), 1) < 0 && errno == EINTR) ;
while(dup2(fileno(myfprintf_err),2)<0 && errno==EINTR); while (dup2(fileno(myfprintf_err), 2) < 0 && errno == EINTR) ;
} }
return 0; return 0;
} }
void myfprintfCloseLogFile(void) { void myfprintfCloseLogFile(void)
if(myfprintf_stdLogMode) { {
while(fclose(myfprintf_out)<0 && errno==EINTR); if (myfprintf_stdLogMode) {
while(fclose(myfprintf_err)<0 && errno==EINTR); while (fclose(myfprintf_out) < 0 && errno == EINTR) ;
while (fclose(myfprintf_err) < 0 && errno == EINTR) ;
} }
} }
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
void myfprintfStdLogMode(FILE * out, FILE * err); void myfprintfStdLogMode(FILE * out, FILE * err);
void myfprintf(FILE * fp, char * format, ... ); void myfprintf(FILE * fp, char *format, ...);
int myfprintfCloseAndOpenLogFile(); int myfprintfCloseAndOpenLogFile();
......
...@@ -30,11 +30,13 @@ static mpd_sint16 currentChunk = -1; ...@@ -30,11 +30,13 @@ static mpd_sint16 currentChunk = -1;
static mpd_sint8 currentMetaChunk = -1; static mpd_sint8 currentMetaChunk = -1;
static mpd_sint8 sendMetaChunk = 0; static mpd_sint8 sendMetaChunk = 0;
void clearAllMetaChunkSets(OutputBuffer * cb) { void clearAllMetaChunkSets(OutputBuffer * cb)
{
memset(cb->metaChunkSet, 0, BUFFERED_METACHUNKS); memset(cb->metaChunkSet, 0, BUFFERED_METACHUNKS);
} }
void clearOutputBuffer(OutputBuffer * cb) { void clearOutputBuffer(OutputBuffer * cb)
{
int currentSet = 1; int currentSet = 1;
currentChunk = -1; currentChunk = -1;
...@@ -42,19 +44,20 @@ void clearOutputBuffer(OutputBuffer * cb) { ...@@ -42,19 +44,20 @@ void clearOutputBuffer(OutputBuffer * cb) {
/* be sure to reset metaChunkSets cause we are skipping over audio /* be sure to reset metaChunkSets cause we are skipping over audio
* audio chunks, and thus skipping over metadata */ * audio chunks, and thus skipping over metadata */
if(sendMetaChunk == 0 && currentMetaChunk >= 0) { if (sendMetaChunk == 0 && currentMetaChunk >= 0) {
currentSet = cb->metaChunkSet[currentChunk]; currentSet = cb->metaChunkSet[currentChunk];
} }
clearAllMetaChunkSets(cb); clearAllMetaChunkSets(cb);
if(sendMetaChunk == 0 && currentMetaChunk >= 0) { if (sendMetaChunk == 0 && currentMetaChunk >= 0) {
cb->metaChunkSet[currentChunk] = currentSet; cb->metaChunkSet[currentChunk] = currentSet;
} }
} }
void flushOutputBuffer(OutputBuffer * cb) { void flushOutputBuffer(OutputBuffer * cb)
if(currentChunk == cb->end) { {
int next = cb->end+1; if (currentChunk == cb->end) {
if(next>=buffered_chunks) { int next = cb->end + 1;
if (next >= buffered_chunks) {
next = 0; next = 0;
} }
cb->end = next; cb->end = next;
...@@ -63,85 +66,85 @@ void flushOutputBuffer(OutputBuffer * cb) { ...@@ -63,85 +66,85 @@ void flushOutputBuffer(OutputBuffer * cb) {
} }
int sendDataToOutputBuffer(OutputBuffer * cb, InputStream * inStream, int sendDataToOutputBuffer(OutputBuffer * cb, InputStream * inStream,
DecoderControl * dc, int seekable, void * dataIn, DecoderControl * dc, int seekable, void *dataIn,
long dataInLen, float time, mpd_uint16 bitRate, long dataInLen, float time, mpd_uint16 bitRate,
ReplayGainInfo * replayGainInfo) ReplayGainInfo * replayGainInfo)
{ {
mpd_uint16 dataToSend; mpd_uint16 dataToSend;
mpd_uint16 chunkLeft; mpd_uint16 chunkLeft;
char * data; char *data;
size_t datalen; size_t datalen;
static char * convBuffer = NULL; static char *convBuffer = NULL;
static long convBufferLen = 0; static long convBufferLen = 0;
if(cmpAudioFormat(&(cb->audioFormat),&(dc->audioFormat))==0) if (cmpAudioFormat(&(cb->audioFormat), &(dc->audioFormat)) == 0) {
{
data = dataIn; data = dataIn;
datalen = dataInLen; datalen = dataInLen;
} } else {
else { datalen =
datalen = pcm_sizeOfOutputBufferForAudioFormatConversion( pcm_sizeOfOutputBufferForAudioFormatConversion(&
&(dc->audioFormat), dataInLen, (dc->
&(cb->audioFormat)); audioFormat),
if(datalen > convBufferLen) { dataInLen,
convBuffer = realloc(convBuffer,datalen); &(cb->
audioFormat));
if (datalen > convBufferLen) {
convBuffer = realloc(convBuffer, datalen);
convBufferLen = datalen; convBufferLen = datalen;
} }
data = convBuffer; data = convBuffer;
pcm_convertAudioFormat(&(dc->audioFormat), dataIn, dataInLen, pcm_convertAudioFormat(&(dc->audioFormat), dataIn, dataInLen,
&(cb->audioFormat),data); &(cb->audioFormat), data);
} }
if(replayGainInfo) { if (replayGainInfo) {
doReplayGain(replayGainInfo, data, datalen, &cb->audioFormat); doReplayGain(replayGainInfo, data, datalen, &cb->audioFormat);
} }
while(datalen) { while (datalen) {
if(currentChunk != cb->end) { if (currentChunk != cb->end) {
int next = cb->end+1; int next = cb->end + 1;
if(next>=buffered_chunks) { if (next >= buffered_chunks) {
next = 0; next = 0;
} }
while(cb->begin==next && !dc->stop) { while (cb->begin == next && !dc->stop) {
if(dc->seek) { if (dc->seek) {
if(seekable) { if (seekable) {
return OUTPUT_BUFFER_DC_SEEK; return OUTPUT_BUFFER_DC_SEEK;
} } else {
else {
dc->seekError = 1; dc->seekError = 1;
dc->seek = 0; dc->seek = 0;
} }
} }
if(!inStream || if (!inStream ||
bufferInputStream(inStream) <= 0) bufferInputStream(inStream) <= 0) {
{
my_usleep(10000); my_usleep(10000);
} }
} }
if(dc->stop) return OUTPUT_BUFFER_DC_STOP; if (dc->stop)
return OUTPUT_BUFFER_DC_STOP;
currentChunk = cb->end; currentChunk = cb->end;
cb->chunkSize[currentChunk] = 0; cb->chunkSize[currentChunk] = 0;
if(sendMetaChunk) { if (sendMetaChunk) {
cb->metaChunk[currentChunk] = currentMetaChunk; cb->metaChunk[currentChunk] = currentMetaChunk;
} } else
else cb->metaChunk[currentChunk] = -1; cb->metaChunk[currentChunk] = -1;
cb->bitRate[currentChunk] = bitRate; cb->bitRate[currentChunk] = bitRate;
cb->times[currentChunk] = time; cb->times[currentChunk] = time;
} }
chunkLeft = CHUNK_SIZE-cb->chunkSize[currentChunk]; chunkLeft = CHUNK_SIZE - cb->chunkSize[currentChunk];
dataToSend = datalen > chunkLeft ? chunkLeft : datalen; dataToSend = datalen > chunkLeft ? chunkLeft : datalen;
memcpy(cb->chunks+currentChunk*CHUNK_SIZE+ memcpy(cb->chunks + currentChunk * CHUNK_SIZE +
cb->chunkSize[currentChunk], cb->chunkSize[currentChunk], data, dataToSend);
data, dataToSend); cb->chunkSize[currentChunk] += dataToSend;
cb->chunkSize[currentChunk]+= dataToSend; datalen -= dataToSend;
datalen-= dataToSend; data += dataToSend;
data+= dataToSend;
if(cb->chunkSize[currentChunk] == CHUNK_SIZE) { if (cb->chunkSize[currentChunk] == CHUNK_SIZE) {
flushOutputBuffer(cb); flushOutputBuffer(cb);
} }
} }
...@@ -149,30 +152,34 @@ int sendDataToOutputBuffer(OutputBuffer * cb, InputStream * inStream, ...@@ -149,30 +152,34 @@ int sendDataToOutputBuffer(OutputBuffer * cb, InputStream * inStream,
return 0; return 0;
} }
int copyMpdTagToOutputBuffer(OutputBuffer * cb, MpdTag * tag) { int copyMpdTagToOutputBuffer(OutputBuffer * cb, MpdTag * tag)
{
int nextChunk; int nextChunk;
static MpdTag * last = NULL; static MpdTag *last = NULL;
if(!cb->acceptMetadata || !tag) { if (!cb->acceptMetadata || !tag) {
sendMetaChunk = 0; sendMetaChunk = 0;
if(last) freeMpdTag(last); if (last)
freeMpdTag(last);
last = NULL; last = NULL;
DEBUG("copyMpdTagToOB: !acceptMetadata || !tag\n"); DEBUG("copyMpdTagToOB: !acceptMetadata || !tag\n");
return 0; return 0;
} }
if(last && mpdTagsAreEqual(last, tag)) { if (last && mpdTagsAreEqual(last, tag)) {
DEBUG("copyMpdTagToOB: same as last\n"); DEBUG("copyMpdTagToOB: same as last\n");
return 0; return 0;
} }
if(last) freeMpdTag(last); if (last)
freeMpdTag(last);
last = NULL; last = NULL;
nextChunk = currentMetaChunk+1; nextChunk = currentMetaChunk + 1;
if(nextChunk >= BUFFERED_METACHUNKS) nextChunk = 0; if (nextChunk >= BUFFERED_METACHUNKS)
nextChunk = 0;
if(cb->metaChunkSet[nextChunk]) { if (cb->metaChunkSet[nextChunk]) {
sendMetaChunk = 0; sendMetaChunk = 0;
DEBUG("copyMpdTagToOB: metachunk in use!\n"); DEBUG("copyMpdTagToOB: metachunk in use!\n");
return -1; return -1;
......
...@@ -32,16 +32,16 @@ ...@@ -32,16 +32,16 @@
#define BUFFERED_METACHUNKS 25 #define BUFFERED_METACHUNKS 25
typedef struct _OutputBuffer { typedef struct _OutputBuffer {
char * volatile chunks; char *volatile chunks;
mpd_uint16 * volatile chunkSize; mpd_uint16 *volatile chunkSize;
mpd_uint16 * volatile bitRate; mpd_uint16 *volatile bitRate;
float * volatile times; float *volatile times;
mpd_sint16 volatile begin; mpd_sint16 volatile begin;
mpd_sint16 volatile end; mpd_sint16 volatile end;
AudioFormat audioFormat; AudioFormat audioFormat;
MetadataChunk metadataChunks[BUFFERED_METACHUNKS]; MetadataChunk metadataChunks[BUFFERED_METACHUNKS];
mpd_sint8 metaChunkSet[BUFFERED_METACHUNKS]; mpd_sint8 metaChunkSet[BUFFERED_METACHUNKS];
mpd_sint8 * volatile metaChunk; mpd_sint8 *volatile metaChunk;
volatile mpd_sint8 acceptMetadata; volatile mpd_sint8 acceptMetadata;
} OutputBuffer; } OutputBuffer;
...@@ -51,16 +51,14 @@ void flushOutputBuffer(OutputBuffer * cb); ...@@ -51,16 +51,14 @@ void flushOutputBuffer(OutputBuffer * cb);
/* we send inStream for buffering the inputStream while waiting to /* we send inStream for buffering the inputStream while waiting to
send the next chunk */ send the next chunk */
int sendDataToOutputBuffer( int sendDataToOutputBuffer(OutputBuffer * cb,
OutputBuffer * cb,
InputStream * inStream, InputStream * inStream,
DecoderControl * dc, DecoderControl * dc,
int seekable, int seekable,
void * data, void *data,
long datalen, long datalen,
float time, float time,
mpd_uint16 bitRate, mpd_uint16 bitRate, ReplayGainInfo * replayGainInfo);
ReplayGainInfo * replayGainInfo);
int copyMpdTagToOutputBuffer(OutputBuffer * cb, MpdTag * tag); int copyMpdTagToOutputBuffer(OutputBuffer * cb, MpdTag * tag);
......
...@@ -37,23 +37,25 @@ ...@@ -37,23 +37,25 @@
#endif #endif
#endif #endif
char * musicDir; char *musicDir;
char * playlistDir; char *playlistDir;
char * fsCharset = NULL; char *fsCharset = NULL;
static char * pathConvCharset(char * to, char * from, char * str) { static char *pathConvCharset(char *to, char *from, char *str)
if(setCharSetConversion(to,from)==0) { {
if (setCharSetConversion(to, from) == 0) {
return convStrDup(str); return convStrDup(str);
} }
return NULL; return NULL;
} }
char * fsCharsetToUtf8(char * str) { char *fsCharsetToUtf8(char *str)
char * ret = pathConvCharset("UTF-8",fsCharset,str); {
char *ret = pathConvCharset("UTF-8", fsCharset, str);
if(ret && !validUtf8String(ret)) { if (ret && !validUtf8String(ret)) {
free(ret); free(ret);
ret = NULL; ret = NULL;
} }
...@@ -61,54 +63,60 @@ char * fsCharsetToUtf8(char * str) { ...@@ -61,54 +63,60 @@ char * fsCharsetToUtf8(char * str) {
return ret; return ret;
} }
char * utf8ToFsCharset(char * str) { char *utf8ToFsCharset(char *str)
char * ret = pathConvCharset(fsCharset,"UTF-8",str); {
char *ret = pathConvCharset(fsCharset, "UTF-8", str);
if(!ret) ret = strdup(str); if (!ret)
ret = strdup(str);
return ret; return ret;
} }
void setFsCharset(char * charset) { void setFsCharset(char *charset)
{
int error = 0; int error = 0;
if(fsCharset) free(fsCharset); if (fsCharset)
free(fsCharset);
fsCharset = strdup(charset); fsCharset = strdup(charset);
DEBUG("setFsCharset: fs charset is: %s\n",fsCharset); DEBUG("setFsCharset: fs charset is: %s\n", fsCharset);
if(setCharSetConversion("UTF-8",fsCharset)!=0) { if (setCharSetConversion("UTF-8", fsCharset) != 0) {
WARNING("fs charset conversion problem: " WARNING("fs charset conversion problem: "
"not able to convert from \"%s\" to \"%s\"\n", "not able to convert from \"%s\" to \"%s\"\n",
fsCharset,"UTF-8"); fsCharset, "UTF-8");
error = 1; error = 1;
} }
if(setCharSetConversion(fsCharset,"UTF-8")!=0) { if (setCharSetConversion(fsCharset, "UTF-8") != 0) {
WARNING("fs charset conversion problem: " WARNING("fs charset conversion problem: "
"not able to convert from \"%s\" to \"%s\"\n", "not able to convert from \"%s\" to \"%s\"\n",
"UTF-8",fsCharset); "UTF-8", fsCharset);
error = 1; error = 1;
} }
if(error) { if (error) {
free(fsCharset); free(fsCharset);
WARNING("setting fs charset to ISO-8859-1!\n"); WARNING("setting fs charset to ISO-8859-1!\n");
fsCharset = strdup("ISO-8859-1"); fsCharset = strdup("ISO-8859-1");
} }
} }
char * getFsCharset(void) { char *getFsCharset(void)
{
return fsCharset; return fsCharset;
} }
static char * appendSlash(char ** path) { static char *appendSlash(char **path)
char * temp = *path; {
char *temp = *path;
int len = strlen(temp); int len = strlen(temp);
if(temp[len-1] != '/') { if (temp[len - 1] != '/') {
temp = malloc(len+2); temp = malloc(len + 2);
memset(temp, 0, len+2); memset(temp, 0, len + 2);
memcpy(temp, *path, len); memcpy(temp, *path, len);
temp[len] = '/'; temp[len] = '/';
free(*path); free(*path);
...@@ -118,19 +126,20 @@ static char * appendSlash(char ** path) { ...@@ -118,19 +126,20 @@ static char * appendSlash(char ** path) {
return temp; return temp;
} }
void initPaths(void) { void initPaths(void)
ConfigParam * musicParam = parseConfigFilePath(CONF_MUSIC_DIR, 1); {
ConfigParam * playlistParam = parseConfigFilePath(CONF_PLAYLIST_DIR, 1); ConfigParam *musicParam = parseConfigFilePath(CONF_MUSIC_DIR, 1);
ConfigParam * fsCharsetParam = getConfigParam(CONF_FS_CHARSET); ConfigParam *playlistParam = parseConfigFilePath(CONF_PLAYLIST_DIR, 1);
ConfigParam *fsCharsetParam = getConfigParam(CONF_FS_CHARSET);
char * charset = NULL; char *charset = NULL;
char * originalLocale; char *originalLocale;
DIR * dir; DIR *dir;
musicDir = appendSlash(&(musicParam->value)); musicDir = appendSlash(&(musicParam->value));
playlistDir = appendSlash(&(playlistParam->value)); playlistDir = appendSlash(&(playlistParam->value));
if((dir = opendir(playlistDir)) == NULL) { if ((dir = opendir(playlistDir)) == NULL) {
ERROR("cannot open %s \"%s\" (config line %i): %s\n", ERROR("cannot open %s \"%s\" (config line %i): %s\n",
CONF_PLAYLIST_DIR, playlistParam->value, CONF_PLAYLIST_DIR, playlistParam->value,
playlistParam->line, strerror(errno)); playlistParam->line, strerror(errno));
...@@ -138,7 +147,7 @@ void initPaths(void) { ...@@ -138,7 +147,7 @@ void initPaths(void) {
} }
closedir(dir); closedir(dir);
if((dir = opendir(musicDir)) == NULL) { if ((dir = opendir(musicDir)) == NULL) {
ERROR("cannot open %s \"%s\" (config line %i): %s\n", ERROR("cannot open %s \"%s\" (config line %i): %s\n",
CONF_MUSIC_DIR, musicParam->value, CONF_MUSIC_DIR, musicParam->value,
musicParam->line, strerror(errno)); musicParam->line, strerror(errno));
...@@ -146,132 +155,136 @@ void initPaths(void) { ...@@ -146,132 +155,136 @@ void initPaths(void) {
} }
closedir(dir); closedir(dir);
if(fsCharsetParam) { if (fsCharsetParam) {
charset = strdup(fsCharsetParam->value); charset = strdup(fsCharsetParam->value);
} }
#ifdef HAVE_LOCALE #ifdef HAVE_LOCALE
#ifdef HAVE_LANGINFO_CODESET #ifdef HAVE_LANGINFO_CODESET
else if((originalLocale = setlocale(LC_CTYPE,NULL))) { else if ((originalLocale = setlocale(LC_CTYPE, NULL))) {
char * temp; char *temp;
char * currentLocale; char *currentLocale;
originalLocale = strdup(originalLocale); originalLocale = strdup(originalLocale);
if(!(currentLocale = setlocale(LC_CTYPE,""))) { if (!(currentLocale = setlocale(LC_CTYPE, ""))) {
WARNING("problems setting current locale with " WARNING("problems setting current locale with "
"setlocale()\n"); "setlocale()\n");
} } else {
else { if (strcmp(currentLocale, "C") == 0 ||
if(strcmp(currentLocale,"C")==0 || strcmp(currentLocale, "POSIX") == 0) {
strcmp(currentLocale,"POSIX")==0)
{
WARNING("current locale is \"%s\"\n", WARNING("current locale is \"%s\"\n",
currentLocale); currentLocale);
} } else if ((temp = nl_langinfo(CODESET))) {
else if((temp = nl_langinfo(CODESET))) {
charset = strdup(temp); charset = strdup(temp);
} } else
else WARNING("problems getting charset for locale\n"); WARNING
if(!setlocale(LC_CTYPE,originalLocale)) { ("problems getting charset for locale\n");
WARNING("problems resetting locale with setlocale()\n"); if (!setlocale(LC_CTYPE, originalLocale)) {
WARNING
("problems resetting locale with setlocale()\n");
} }
} }
free(originalLocale); free(originalLocale);
} } else
else WARNING("problems getting locale with setlocale()\n"); WARNING("problems getting locale with setlocale()\n");
#endif #endif
#endif #endif
if(charset) { if (charset) {
setFsCharset(charset); setFsCharset(charset);
free(charset); free(charset);
} } else {
else {
WARNING("setting filesystem charset to ISO-8859-1\n"); WARNING("setting filesystem charset to ISO-8859-1\n");
setFsCharset("ISO-8859-1"); setFsCharset("ISO-8859-1");
} }
} }
void finishPaths(void) { void finishPaths(void)
{
free(fsCharset); free(fsCharset);
fsCharset = NULL; fsCharset = NULL;
} }
char * rmp2amp(char * relativePath) { char *rmp2amp(char *relativePath)
static char absolutePath[MAXPATHLEN+1]; {
static char absolutePath[MAXPATHLEN + 1];
memset(absolutePath,0,MAXPATHLEN+1); memset(absolutePath, 0, MAXPATHLEN + 1);
strncpy(absolutePath,musicDir,MAXPATHLEN); strncpy(absolutePath, musicDir, MAXPATHLEN);
strncat(absolutePath,relativePath,MAXPATHLEN-strlen(musicDir)); strncat(absolutePath, relativePath, MAXPATHLEN - strlen(musicDir));
return absolutePath; return absolutePath;
} }
char * rpp2app(char * relativePath) { char *rpp2app(char *relativePath)
static char absolutePath[MAXPATHLEN+1]; {
static char absolutePath[MAXPATHLEN + 1];
memset(absolutePath,0,MAXPATHLEN+1); memset(absolutePath, 0, MAXPATHLEN + 1);
strncpy(absolutePath,playlistDir,MAXPATHLEN); strncpy(absolutePath, playlistDir, MAXPATHLEN);
strncat(absolutePath,relativePath,MAXPATHLEN-strlen(musicDir)); strncat(absolutePath, relativePath, MAXPATHLEN - strlen(musicDir));
return absolutePath; return absolutePath;
} }
char * parentPath(char * path) { char *parentPath(char *path)
static char parentPath[MAXPATHLEN+1]; {
char * c; static char parentPath[MAXPATHLEN + 1];
char *c;
memset(parentPath,0,MAXPATHLEN+1); memset(parentPath, 0, MAXPATHLEN + 1);
strncpy(parentPath,path,MAXPATHLEN); strncpy(parentPath, path, MAXPATHLEN);
c = strrchr(parentPath,'/'); c = strrchr(parentPath, '/');
if (c == NULL) if (c == NULL)
parentPath[0] = '\0'; parentPath[0] = '\0';
else { else {
while ((parentPath <= c) && *(--c) == '/') /* nothing */; while ((parentPath <= c) && *(--c) == '/') /* nothing */
;
c[1] = '\0'; c[1] = '\0';
} }
return parentPath; return parentPath;
} }
char * sanitizePathDup(char * path) { char *sanitizePathDup(char *path)
int len = strlen(path)+1; {
char * ret = malloc(len); int len = strlen(path) + 1;
char * cp = ret; char *ret = malloc(len);
char *cp = ret;
memset(ret,0,len); memset(ret, 0, len);
len = 0; len = 0;
/* illeminate more than one '/' in a row, like "///" */ /* illeminate more than one '/' in a row, like "///" */
while(*path) { while (*path) {
while(*path=='/') path++; while (*path == '/')
if(*path=='.') { path++;
if (*path == '.') {
/* we dont want to have hidden directoires, or '.' or /* we dont want to have hidden directoires, or '.' or
".." in our path */ ".." in our path */
free(ret); free(ret);
return NULL; return NULL;
} }
while(*path && *path!='/') { while (*path && *path != '/') {
*(cp++) = *(path++); *(cp++) = *(path++);
len++; len++;
} }
if(*path=='/') { if (*path == '/') {
*(cp++) = *(path++); *(cp++) = *(path++);
len++; len++;
} }
} }
if(len && ret[len-1]=='/') { if (len && ret[len - 1] == '/') {
len--; len--;
ret[len] = '\0'; ret[len] = '\0';
} }
DEBUG("sanitized: %s\n", ret); DEBUG("sanitized: %s\n", ret);
return realloc(ret,len+1); return realloc(ret, len + 1);
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment