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
......@@ -41,23 +41,25 @@
static AudioFormat audio_format;
static AudioFormat * audio_configFormat = NULL;
static AudioFormat *audio_configFormat = NULL;
static AudioOutput ** audioOutputArray = NULL;
static AudioOutput **audioOutputArray = NULL;
static mpd_uint8 audioOutputArraySize = 0;
/* the audioEnabledArray should be stuck into shared memory, and then disable
and enable in playAudio() routine */
static mpd_sint8 * pdAudioDevicesEnabled = NULL;
static mpd_sint8 *pdAudioDevicesEnabled = NULL;
static mpd_sint8 myAudioDevicesEnabled[AUDIO_MAX_DEVICES];
static mpd_uint8 audioOpened = 0;
static mpd_sint32 audioBufferSize = 0;
static char * audioBuffer = NULL;
static char *audioBuffer = NULL;
static mpd_sint32 audioBufferPos = 0;
void copyAudioFormat(AudioFormat * dest, AudioFormat * src) {
if(!src) return;
void copyAudioFormat(AudioFormat * dest, AudioFormat * src)
{
if (!src)
return;
memcpy(dest, src, sizeof(AudioFormat));
}
......@@ -65,8 +67,7 @@ void copyAudioFormat(AudioFormat * dest, AudioFormat * src) {
int cmpAudioFormat(AudioFormat * f1, AudioFormat * f2)
{
if (f1 && f2 && (f1->sampleRate == f2->sampleRate) &&
(f1->bits == f2->bits) &&
(f1->channels == f2->channels))
(f1->bits == f2->bits) && (f1->channels == f2->channels))
return 0;
return 1;
}
......@@ -79,8 +80,8 @@ extern AudioOutputPlugin pulsePlugin;
extern AudioOutputPlugin mvpPlugin;
extern AudioOutputPlugin shoutPlugin;
void loadAudioDrivers(void) {
void loadAudioDrivers(void)
{
initAudioOutputPlugins();
loadAudioOutputPlugin(&alsaPlugin);
loadAudioOutputPlugin(&aoPlugin);
......@@ -92,15 +93,16 @@ void loadAudioDrivers(void) {
}
/* make sure initPlayerData is called before this function!! */
void initAudioDriver(void) {
ConfigParam * param = NULL;
void initAudioDriver(void)
{
ConfigParam *param = NULL;
int i;
loadAudioDrivers();
pdAudioDevicesEnabled = (getPlayerData())->audioDeviceEnabled;
for(i = 0; i < AUDIO_MAX_DEVICES; i++) {
for (i = 0; i < AUDIO_MAX_DEVICES; i++) {
pdAudioDevicesEnabled[i] = 1;
myAudioDevicesEnabled[i] = 1;
}
......@@ -111,7 +113,7 @@ void initAudioDriver(void) {
AudioOutput *output;
int j;
if(audioOutputArraySize == AUDIO_MAX_DEVICES) {
if (audioOutputArraySize == AUDIO_MAX_DEVICES) {
ERROR("only up to 255 audio output devices are "
"supported");
exit(EXIT_FAILURE);
......@@ -120,10 +122,11 @@ void initAudioDriver(void) {
i = audioOutputArraySize++;
audioOutputArray = realloc(audioOutputArray,
audioOutputArraySize*sizeof(AudioOutput *));
audioOutputArraySize *
sizeof(AudioOutput *));
output = newAudioOutput(param);
if(!output && param) {
if (!output && param) {
ERROR("problems configuring output device defined at "
"line %i\n", param->line);
exit(EXIT_FAILURE);
......@@ -131,50 +134,51 @@ void initAudioDriver(void) {
/* require output names to be unique: */
for (j = i - 1; j >= 0; --j) {
if ( !strcmp( output->name,
audioOutputArray[j]->name) ) {
if (!strcmp(output->name, audioOutputArray[j]->name)) {
ERROR("output devices with identical "
"names: %s\n",
output->name);
"names: %s\n", output->name);
exit(EXIT_FAILURE);
}
}
audioOutputArray[i] = output;
} while((param = getNextConfigParam(CONF_AUDIO_OUTPUT, param)));
} while ((param = getNextConfigParam(CONF_AUDIO_OUTPUT, param)));
}
void getOutputAudioFormat(AudioFormat * inAudioFormat,
AudioFormat * outAudioFormat)
{
if(audio_configFormat) {
copyAudioFormat(outAudioFormat,audio_configFormat);
}
else copyAudioFormat(outAudioFormat,inAudioFormat);
if (audio_configFormat) {
copyAudioFormat(outAudioFormat, audio_configFormat);
} else
copyAudioFormat(outAudioFormat, inAudioFormat);
}
void initAudioConfig(void) {
ConfigParam * param = getConfigParam(CONF_AUDIO_OUTPUT_FORMAT);
void initAudioConfig(void)
{
ConfigParam *param = getConfigParam(CONF_AUDIO_OUTPUT_FORMAT);
if(NULL == param || NULL == param->value) return;
if (NULL == param || NULL == param->value)
return;
audio_configFormat = malloc(sizeof(AudioFormat));
if(0 != parseAudioConfig(audio_configFormat, param->value)) {
if (0 != parseAudioConfig(audio_configFormat, param->value)) {
ERROR("error parsing \"%s\" at line %i\n",
CONF_AUDIO_OUTPUT_FORMAT, param->line);
exit(EXIT_FAILURE);
}
}
int parseAudioConfig(AudioFormat * audioFormat, char * conf) {
char * test;
int parseAudioConfig(AudioFormat * audioFormat, char *conf)
{
char *test;
memset(audioFormat,0,sizeof(AudioFormat));
memset(audioFormat, 0, sizeof(AudioFormat));
audioFormat->sampleRate = strtol(conf,&test,10);
audioFormat->sampleRate = strtol(conf, &test, 10);
if(*test!=':') {
ERROR("error parsing audio output format: %s\n",conf);
if (*test != ':') {
ERROR("error parsing audio output format: %s\n", conf);
return -1;
}
......@@ -188,22 +192,22 @@ int parseAudioConfig(AudioFormat * audioFormat, char * conf) {
ERROR("sample rate %i can not be used for audio output\n",
(int)audioFormat->sampleRate);
return -1
}*/
} */
if(audioFormat->sampleRate <= 0) {
if (audioFormat->sampleRate <= 0) {
ERROR("sample rate %i is not >= 0\n",
(int)audioFormat->sampleRate);
return -1;
}
audioFormat->bits = strtol(test+1,&test,10);
audioFormat->bits = strtol(test + 1, &test, 10);
if(*test!=':') {
ERROR("error parsing audio output format: %s\n",conf);
if (*test != ':') {
ERROR("error parsing audio output format: %s\n", conf);
return -1;
}
switch(audioFormat->bits) {
switch (audioFormat->bits) {
case 16:
break;
default:
......@@ -212,14 +216,14 @@ int parseAudioConfig(AudioFormat * audioFormat, char * conf) {
return -1;
}
audioFormat->channels = strtol(test+1,&test,10);
audioFormat->channels = strtol(test + 1, &test, 10);
if(*test!='\0') {
ERROR("error parsing audio output format: %s\n",conf);
if (*test != '\0') {
ERROR("error parsing audio output format: %s\n", conf);
return -1;
}
switch(audioFormat->channels) {
switch (audioFormat->channels) {
case 1:
case 2:
break;
......@@ -232,14 +236,17 @@ int parseAudioConfig(AudioFormat * audioFormat, char * conf) {
return 0;
}
void finishAudioConfig(void) {
if(audio_configFormat) free(audio_configFormat);
void finishAudioConfig(void)
{
if (audio_configFormat)
free(audio_configFormat);
}
void finishAudioDriver(void) {
void finishAudioDriver(void)
{
int i;
for(i = 0; i < audioOutputArraySize; i++) {
for (i = 0; i < audioOutputArraySize; i++) {
finishAudioOutput(audioOutputArray[i]);
}
......@@ -248,44 +255,49 @@ void finishAudioDriver(void) {
audioOutputArraySize = 0;
}
int isCurrentAudioFormat(AudioFormat * audioFormat) {
if(!audioFormat) return 1;
int isCurrentAudioFormat(AudioFormat * audioFormat)
{
if (!audioFormat)
return 1;
if(cmpAudioFormat(audioFormat, &audio_format) != 0) return 0;
if (cmpAudioFormat(audioFormat, &audio_format) != 0)
return 0;
return 1;
}
static void syncAudioDevicesEnabledArrays(void) {
static void syncAudioDevicesEnabledArrays(void)
{
int i;
memcpy(myAudioDevicesEnabled, pdAudioDevicesEnabled,AUDIO_MAX_DEVICES);
memcpy(myAudioDevicesEnabled, pdAudioDevicesEnabled, AUDIO_MAX_DEVICES);
for(i = 0; i < audioOutputArraySize; i++) {
if(myAudioDevicesEnabled[i]) {
for (i = 0; i < audioOutputArraySize; i++) {
if (myAudioDevicesEnabled[i]) {
openAudioOutput(audioOutputArray[i], &audio_format);
}
else {
} else {
dropBufferedAudioOutput(audioOutputArray[i]);
closeAudioOutput(audioOutputArray[i]);
}
}
}
static int flushAudioBuffer(void) {
static int flushAudioBuffer(void)
{
int ret = -1;
int i, err;
if(audioBufferPos == 0) return 0;
if (audioBufferPos == 0)
return 0;
if(0 != memcmp(pdAudioDevicesEnabled, myAudioDevicesEnabled,
AUDIO_MAX_DEVICES))
{
if (0 != memcmp(pdAudioDevicesEnabled, myAudioDevicesEnabled,
AUDIO_MAX_DEVICES)) {
syncAudioDevicesEnabledArrays();
}
for(i = 0; i < audioOutputArraySize; i++) {
if(!myAudioDevicesEnabled[i]) continue;
for (i = 0; i < audioOutputArraySize; i++) {
if (!myAudioDevicesEnabled[i])
continue;
err = playAudioOutput(audioOutputArray[i], audioBuffer,
audioBufferPos);
if (!err)
......@@ -301,32 +313,36 @@ static int flushAudioBuffer(void) {
return ret;
}
int openAudioDevice(AudioFormat * audioFormat) {
int openAudioDevice(AudioFormat * audioFormat)
{
int isCurrentFormat = isCurrentAudioFormat(audioFormat);
int ret = -1;
int i;
if(!audioOutputArray) return -1;
if (!audioOutputArray)
return -1;
if(!audioOpened || !isCurrentFormat) {
if (!audioOpened || !isCurrentFormat) {
flushAudioBuffer();
copyAudioFormat(&audio_format, audioFormat);
audioBufferSize = (audio_format.bits >> 3)*
audioBufferSize = (audio_format.bits >> 3) *
audio_format.channels;
audioBufferSize*= audio_format.sampleRate >> 5;
audioBufferSize *= audio_format.sampleRate >> 5;
audioBuffer = realloc(audioBuffer, audioBufferSize);
}
syncAudioDevicesEnabledArrays();
for(i = 0; i < audioOutputArraySize; i++) {
if(audioOutputArray[i]->open) ret = 0;
for (i = 0; i < audioOutputArraySize; i++) {
if (audioOutputArray[i]->open)
ret = 0;
}
if(ret == 0) audioOpened = 1;
if (ret == 0)
audioOpened = 1;
else {
/* close all devices if there was an error */
for(i = 0; i < audioOutputArraySize; i++) {
for (i = 0; i < audioOutputArraySize; i++) {
closeAudioOutput(audioOutputArray[i]);
}
......@@ -336,48 +352,53 @@ int openAudioDevice(AudioFormat * audioFormat) {
return ret;
}
int playAudio(char * playChunk, int size) {
int playAudio(char *playChunk, int size)
{
int send;
while(size > 0) {
send = audioBufferSize-audioBufferPos;
while (size > 0) {
send = audioBufferSize - audioBufferPos;
send = send < size ? send : size;
memcpy(audioBuffer+audioBufferPos, playChunk, send);
memcpy(audioBuffer + audioBufferPos, playChunk, send);
audioBufferPos += send;
size -= send;
playChunk+= send;
playChunk += send;
if(audioBufferPos == audioBufferSize) {
if( flushAudioBuffer() < 0 ) return -1;
if (audioBufferPos == audioBufferSize) {
if (flushAudioBuffer() < 0)
return -1;
}
}
return 0;
}
int isAudioDeviceOpen(void) {
int isAudioDeviceOpen(void)
{
return audioOpened;
}
void dropBufferedAudio(void) {
void dropBufferedAudio(void)
{
int i;
if(0 != memcmp(pdAudioDevicesEnabled, myAudioDevicesEnabled,
AUDIO_MAX_DEVICES))
{
if (0 != memcmp(pdAudioDevicesEnabled, myAudioDevicesEnabled,
AUDIO_MAX_DEVICES)) {
syncAudioDevicesEnabledArrays();
}
audioBufferPos = 0;
for(i = 0; i < audioOutputArraySize; i++) {
if(!myAudioDevicesEnabled[i]) continue;
for (i = 0; i < audioOutputArraySize; i++) {
if (!myAudioDevicesEnabled[i])
continue;
dropBufferedAudioOutput(audioOutputArray[i]);
}
}
void closeAudioDevice(void) {
void closeAudioDevice(void)
{
int i;
flushAudioBuffer();
......@@ -386,23 +407,25 @@ void closeAudioDevice(void) {
audioBuffer = NULL;
audioBufferSize = 0;
for(i = 0; i < audioOutputArraySize; i++) {
for (i = 0; i < audioOutputArraySize; i++) {
closeAudioOutput(audioOutputArray[i]);
}
audioOpened = 0;
}
void sendMetadataToAudioDevice(MpdTag * tag) {
void sendMetadataToAudioDevice(MpdTag * tag)
{
int i;
for(i = 0; i < audioOutputArraySize; i++) {
for (i = 0; i < audioOutputArraySize; i++) {
sendMetadataToAudioOutput(audioOutputArray[i], tag);
}
}
int enableAudioDevice(FILE * fp, int device) {
if(device < 0 || device >= audioOutputArraySize) {
int enableAudioDevice(FILE * fp, int device)
{
if (device < 0 || device >= audioOutputArraySize) {
commandError(fp, ACK_ERROR_ARG, "audio output device id %i "
"doesn't exist\n", device);
return -1;
......@@ -413,8 +436,9 @@ int enableAudioDevice(FILE * fp, int device) {
return 0;
}
int disableAudioDevice(FILE * fp, int device) {
if(device < 0 || device >= audioOutputArraySize) {
int disableAudioDevice(FILE * fp, int device)
{
if (device < 0 || device >= audioOutputArraySize) {
commandError(fp, ACK_ERROR_ARG, "audio output device id %i "
"doesn't exist\n", device);
return -1;
......@@ -425,10 +449,11 @@ int disableAudioDevice(FILE * fp, int device) {
return 0;
}
void printAudioDevices(FILE * fp) {
void printAudioDevices(FILE * fp)
{
int i;
for(i = 0; i < audioOutputArraySize; i++) {
for (i = 0; i < audioOutputArraySize; i++) {
myfprintf(fp, "outputid: %i\n", i);
myfprintf(fp, "outputname: %s\n", audioOutputArray[i]->name);
myfprintf(fp, "outputenabled: %i\n",
......@@ -436,7 +461,8 @@ void printAudioDevices(FILE * fp) {
}
}
void saveAudioDevicesState(void) {
void saveAudioDevicesState(void)
{
char *stateFile;
FILE *fp;
int i;
......@@ -444,8 +470,8 @@ void saveAudioDevicesState(void) {
if (!(stateFile = getStateFile()))
return;
while(!(fp = fopen(stateFile,"a")) && errno==EINTR);
if(!fp) {
while (!(fp = fopen(stateFile, "a")) && errno == EINTR) ;
if (!fp) {
ERROR("problems opening state file \"%s\" for "
"writing: %s\n", stateFile, strerror(errno));
return;
......@@ -457,27 +483,27 @@ void saveAudioDevicesState(void) {
(int)pdAudioDevicesEnabled[i],
audioOutputArray[i]->name);
}
while(fclose(fp) && errno==EINTR);
while (fclose(fp) && errno == EINTR) ;
}
static void parse_audio_device_state(FILE *fp)
static void parse_audio_device_state(FILE * fp)
{
char buffer[AUDIO_BUFFER_SIZE];
int i;
assert(audioOutputArraySize != 0);
while (myFgets(buffer,AUDIO_BUFFER_SIZE,fp)) {
while (myFgets(buffer, AUDIO_BUFFER_SIZE, fp)) {
char *c, *name;
if (strncmp(buffer,AUDIO_DEVICE_STATE,AUDIO_DEVICE_STATE_LEN))
if (strncmp(buffer, AUDIO_DEVICE_STATE, AUDIO_DEVICE_STATE_LEN))
continue;
c = strchr(buffer,':');
c = strchr(buffer, ':');
if (!c || !(++c))
goto errline;
name = strchr(c,':');
name = strchr(c, ':');
if (!name || !(++name))
goto errline;
......@@ -488,37 +514,35 @@ static void parse_audio_device_state(FILE *fp)
}
}
continue;
errline:
errline:
/* nonfatal */
ERROR("invalid line in state_file: %s\n", buffer);
}
}
void readAudioDevicesState(void) {
void readAudioDevicesState(void)
{
char *stateFile;
FILE *fp;
struct stat st;
if (!(stateFile = getStateFile()))
return;
if(stat(stateFile,&st)<0) {
if (stat(stateFile, &st) < 0) {
DEBUG("failed to stat state file\n");
return;
}
if(!S_ISREG(st.st_mode)) {
ERROR("state file \"%s\" is not a regular file\n",
stateFile);
if (!S_ISREG(st.st_mode)) {
ERROR("state file \"%s\" is not a regular file\n", stateFile);
exit(EXIT_FAILURE);
}
fp = fopen(stateFile,"r");
if(!fp) {
fp = fopen(stateFile, "r");
if (!fp) {
ERROR("problems opening state file \"%s\" for "
"reading: %s\n", stateFile,
strerror(errno));
"reading: %s\n", stateFile, strerror(errno));
exit(EXIT_FAILURE);
}
parse_audio_device_state(fp);
fclose(fp);
}
......@@ -42,7 +42,7 @@ int cmpAudioFormat(AudioFormat * dest, AudioFormat * src);
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!! */
void initAudioConfig();
......@@ -55,7 +55,7 @@ void finishAudioDriver();
int openAudioDevice(AudioFormat * audioFormat);
int playAudio(char * playChunk,int size);
int playAudio(char *playChunk, int size);
void dropBufferedAudio();
......
......@@ -28,24 +28,30 @@
#define AUDIO_OUTPUT_NAME "name"
#define AUDIO_OUTPUT_FORMAT "format"
static List * audioOutputPluginList;
static List *audioOutputPluginList;
void loadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin) {
if(!audioOutputPlugin->name) return;
void loadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin)
{
if (!audioOutputPlugin->name)
return;
insertInList(audioOutputPluginList, audioOutputPlugin->name,
audioOutputPlugin);
}
void unloadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin) {
if(!audioOutputPlugin->name) return;
void unloadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin)
{
if (!audioOutputPlugin->name)
return;
deleteFromList(audioOutputPluginList, audioOutputPlugin->name);
}
void initAudioOutputPlugins(void) {
void initAudioOutputPlugins(void)
{
audioOutputPluginList = makeList(NULL, 0);
}
void finishAudioOutputPlugins(void) {
void finishAudioOutputPlugins(void)
{
freeList(audioOutputPluginList);
}
......@@ -60,52 +66,50 @@ void finishAudioOutputPlugins(void) {
if(bp) str = bp->value; \
}
AudioOutput * newAudioOutput(ConfigParam * param) {
AudioOutput * ret = NULL;
void * data = NULL;
char * name = NULL;
char * format = NULL;
char * type = NULL;
BlockParam * bp = NULL;
AudioOutputPlugin * plugin = NULL;
if(param) {
AudioOutput *newAudioOutput(ConfigParam * param)
{
AudioOutput *ret = NULL;
void *data = NULL;
char *name = NULL;
char *format = NULL;
char *type = NULL;
BlockParam *bp = NULL;
AudioOutputPlugin *plugin = NULL;
if (param) {
getBlockParam(AUDIO_OUTPUT_NAME, name, 1);
getBlockParam(AUDIO_OUTPUT_TYPE, type, 1);
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 "
"\"%s\" at line %i\n", type,
param->line);
"\"%s\" at line %i\n", type, param->line);
exit(EXIT_FAILURE);
}
plugin = (AudioOutputPlugin *) data;
}
else {
ListNode * node = audioOutputPluginList->firstNode;
} else {
ListNode *node = audioOutputPluginList->firstNode;
WARNING("No \"%s\" defined in config file\n",
CONF_AUDIO_OUTPUT);
WARNING("Attempt to detect audio output device\n");
while(node) {
while (node) {
plugin = (AudioOutputPlugin *) node->data;
if(plugin->testDefaultDeviceFunc) {
if (plugin->testDefaultDeviceFunc) {
WARNING("Attempting to detect a %s audio "
"device\n", plugin->name);
if(plugin->testDefaultDeviceFunc() == 0) {
if (plugin->testDefaultDeviceFunc() == 0) {
WARNING("Successfully detected a %s "
"audio device\n",
plugin->name);
"audio device\n", plugin->name);
break;
}
}
node = node->nextNode;
}
if(!node) {
if (!node) {
WARNING("Unable to detect an audio device\n");
return NULL;
}
......@@ -134,20 +138,18 @@ AudioOutput * newAudioOutput(ConfigParam * param) {
memset(&ret->outAudioFormat, 0, sizeof(AudioFormat));
memset(&ret->reqAudioFormat, 0, sizeof(AudioFormat));
if(format) {
if (format) {
ret->convertAudioFormat = 1;
if(0 != parseAudioConfig(&ret->reqAudioFormat, format))
{
ERROR("error parsing format at line %i\n",
bp->line);
if (0 != parseAudioConfig(&ret->reqAudioFormat, format)) {
ERROR("error parsing format at line %i\n", bp->line);
exit(EXIT_FAILURE);
}
copyAudioFormat(&ret->outAudioFormat, &ret->reqAudioFormat);
}
if(plugin->initDriverFunc(ret, param) != 0) {
if (plugin->initDriverFunc(ret, param) != 0) {
free(ret);
ret = NULL;
}
......@@ -155,13 +157,13 @@ AudioOutput * newAudioOutput(ConfigParam * param) {
return ret;
}
int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat) {
int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat)
{
int ret;
if(audioOutput->open) {
if(cmpAudioFormat(audioFormat, &audioOutput->inAudioFormat)
== 0)
{
if (audioOutput->open) {
if (cmpAudioFormat(audioFormat, &audioOutput->inAudioFormat)
== 0) {
return 0;
}
closeAudioOutput(audioOutput);
......@@ -169,35 +171,36 @@ int openAudioOutput(AudioOutput * audioOutput, AudioFormat * audioFormat) {
copyAudioFormat(&audioOutput->inAudioFormat, audioFormat);
if(audioOutput->convertAudioFormat) {
if (audioOutput->convertAudioFormat) {
copyAudioFormat(&audioOutput->outAudioFormat,
&audioOutput->reqAudioFormat);
}
else {
} else {
copyAudioFormat(&audioOutput->outAudioFormat,
&audioOutput->inAudioFormat);
}
ret = audioOutput->openDeviceFunc(audioOutput);
if(cmpAudioFormat(&audioOutput->inAudioFormat,
&audioOutput->outAudioFormat) == 0)
{
if (cmpAudioFormat(&audioOutput->inAudioFormat,
&audioOutput->outAudioFormat) == 0) {
audioOutput->sameInAndOutFormats = 1;
}
else audioOutput->sameInAndOutFormats = 0;
} else
audioOutput->sameInAndOutFormats = 0;
return ret;
}
static void convertAudioFormat(AudioOutput * audioOutput, char ** chunkArgPtr,
int * sizeArgPtr)
static void convertAudioFormat(AudioOutput * audioOutput, char **chunkArgPtr,
int *sizeArgPtr)
{
int size = pcm_sizeOfOutputBufferForAudioFormatConversion(
&(audioOutput->inAudioFormat), *sizeArgPtr,
&(audioOutput->outAudioFormat));
if(size > audioOutput->convBufferLen) {
int size =
pcm_sizeOfOutputBufferForAudioFormatConversion(&
(audioOutput->
inAudioFormat),
*sizeArgPtr,
&(audioOutput->outAudioFormat));
if (size > audioOutput->convBufferLen) {
audioOutput->convBuffer =
realloc(audioOutput->convBuffer, size);
audioOutput->convBufferLen = size;
......@@ -211,49 +214,59 @@ static void convertAudioFormat(AudioOutput * audioOutput, char ** chunkArgPtr,
*chunkArgPtr = audioOutput->convBuffer;
}
int playAudioOutput(AudioOutput * audioOutput, char * playChunk, int size) {
int playAudioOutput(AudioOutput * audioOutput, char *playChunk, int size)
{
int ret;
if(!audioOutput->open) return -1;
if (!audioOutput->open)
return -1;
if(!audioOutput->sameInAndOutFormats) {
if (!audioOutput->sameInAndOutFormats) {
convertAudioFormat(audioOutput, &playChunk, &size);
}
ret = audioOutput->playFunc(audioOutput, playChunk, size);
return ret;
}
void dropBufferedAudioOutput(AudioOutput * audioOutput) {
if(audioOutput->open) audioOutput->dropBufferedAudioFunc(audioOutput);
void dropBufferedAudioOutput(AudioOutput * audioOutput)
{
if (audioOutput->open)
audioOutput->dropBufferedAudioFunc(audioOutput);
}
void closeAudioOutput(AudioOutput * audioOutput) {
if(audioOutput->open) audioOutput->closeDeviceFunc(audioOutput);
void closeAudioOutput(AudioOutput * audioOutput)
{
if (audioOutput->open)
audioOutput->closeDeviceFunc(audioOutput);
}
void finishAudioOutput(AudioOutput * audioOutput) {
void finishAudioOutput(AudioOutput * audioOutput)
{
closeAudioOutput(audioOutput);
audioOutput->finishDriverFunc(audioOutput);
if(audioOutput->convBuffer) free(audioOutput->convBuffer);
if (audioOutput->convBuffer)
free(audioOutput->convBuffer);
free(audioOutput->type);
free(audioOutput->name);
free(audioOutput);
}
void sendMetadataToAudioOutput(AudioOutput * audioOutput, MpdTag * tag) {
if(!audioOutput->sendMetdataFunc) return;
void sendMetadataToAudioOutput(AudioOutput * audioOutput, MpdTag * tag)
{
if (!audioOutput->sendMetdataFunc)
return;
audioOutput->sendMetdataFunc(audioOutput, tag);
}
void printAllOutputPluginTypes(FILE *fp) {
void printAllOutputPluginTypes(FILE * fp)
{
ListNode *node = audioOutputPluginList->firstNode;
AudioOutputPlugin *plugin;
while(node) {
plugin = (AudioOutputPlugin *)node->data;
while (node) {
plugin = (AudioOutputPlugin *) node->data;
myfprintf(fp, "%s ", plugin->name);
node = node->nextNode;
}
......
......@@ -40,29 +40,29 @@
typedef struct _AudioOutput AudioOutput;
typedef int (* AudioOutputTestDefaultDeviceFunc) ();
typedef int (*AudioOutputTestDefaultDeviceFunc) ();
typedef int (* AudioOutputInitDriverFunc) (AudioOutput * audioOutput,
typedef int (*AudioOutputInitDriverFunc) (AudioOutput * audioOutput,
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,
char * playChunk, int size);
typedef int (*AudioOutputPlayFunc) (AudioOutput * audioOutput,
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);
struct _AudioOutput {
int open;
char * name;
char * type;
char *name;
char *type;
AudioOutputFinishDriverFunc finishDriverFunc;
AudioOutputOpenDeviceFunc openDeviceFunc;
......@@ -75,15 +75,15 @@ struct _AudioOutput {
AudioFormat inAudioFormat;
AudioFormat outAudioFormat;
AudioFormat reqAudioFormat;
char * convBuffer;
char *convBuffer;
int convBufferLen;
int sameInAndOutFormats;
void * data;
void *data;
};
typedef struct _AudioOutputPlugin {
char * name;
char *name;
AudioOutputTestDefaultDeviceFunc testDefaultDeviceFunc;
AudioOutputInitDriverFunc initDriverFunc;
......@@ -101,14 +101,14 @@ void finishAudioOutputPlugins();
void loadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin);
void unloadAudioOutputPlugin(AudioOutputPlugin * audioOutputPlugin);
AudioOutput * newAudioOutput(ConfigParam * param);
AudioOutput *newAudioOutput(ConfigParam * param);
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 closeAudioOutput(AudioOutput * audioOutput);
void finishAudioOutput(AudioOutput * audioOutput);
int keepAudioOutputAlive(AudioOutput * audioOutput, int ms);
void sendMetadataToAudioOutput(AudioOutput * audioOutput, MpdTag * tag);
void printAllOutputPluginTypes(FILE *fp);
void printAllOutputPluginTypes(FILE * fp);
#endif
......@@ -39,13 +39,13 @@
#include <alsa/asoundlib.h>
typedef snd_pcm_sframes_t alsa_writei_t(snd_pcm_t *pcm, const void *buffer,
typedef snd_pcm_sframes_t alsa_writei_t(snd_pcm_t * pcm, const void *buffer,
snd_pcm_uframes_t size);
typedef struct _AlsaData {
char * device;
snd_pcm_t * pcmHandle;
alsa_writei_t * writei;
char *device;
snd_pcm_t *pcmHandle;
alsa_writei_t *writei;
unsigned int buffer_time;
unsigned int period_time;
int sampleSize;
......@@ -54,8 +54,9 @@ typedef struct _AlsaData {
int canResume;
} AlsaData;
static AlsaData * newAlsaData(void) {
AlsaData * ret = malloc(sizeof(AlsaData));
static AlsaData *newAlsaData(void)
{
AlsaData *ret = malloc(sizeof(AlsaData));
ret->device = NULL;
ret->pcmHandle = NULL;
......@@ -67,17 +68,20 @@ static AlsaData * newAlsaData(void) {
return ret;
}
static void freeAlsaData(AlsaData * ad) {
if(ad->device) free(ad->device);
static void freeAlsaData(AlsaData * ad)
{
if (ad->device)
free(ad->device);
free(ad);
}
static int alsa_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
AlsaData * ad = newAlsaData();
static int alsa_initDriver(AudioOutput * audioOutput, ConfigParam * param)
{
AlsaData *ad = newAlsaData();
if (param) {
BlockParam * bp = getBlockParam(param, "device");
BlockParam *bp = getBlockParam(param, "device");
ad->device = bp ? strdup(bp->value) : strdup("default");
if ((bp = getBlockParam(param, "use_mmap")) &&
......@@ -94,45 +98,46 @@ static int alsa_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
return 0;
}
static void alsa_finishDriver(AudioOutput * audioOutput) {
AlsaData * ad = audioOutput->data;
static void alsa_finishDriver(AudioOutput * audioOutput)
{
AlsaData *ad = audioOutput->data;
freeAlsaData(ad);
}
static int alsa_testDefault(void)
{
snd_pcm_t * handle;
snd_pcm_t *handle;
int ret = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK,
SND_PCM_NONBLOCK);
snd_config_update_free_global();
if(ret) {
if (ret) {
WARNING("Error opening default alsa device: %s\n",
snd_strerror(-ret));
return -1;
}
else snd_pcm_close(handle);
} else
snd_pcm_close(handle);
return 0;
}
static int alsa_openDevice(AudioOutput * audioOutput)
{
AlsaData * ad = audioOutput->data;
AudioFormat * audioFormat = &audioOutput->outAudioFormat;
AlsaData *ad = audioOutput->data;
AudioFormat *audioFormat = &audioOutput->outAudioFormat;
snd_pcm_format_t bitformat;
snd_pcm_hw_params_t * hwparams;
snd_pcm_sw_params_t * swparams;
snd_pcm_hw_params_t *hwparams;
snd_pcm_sw_params_t *swparams;
unsigned int sampleRate = audioFormat->sampleRate;
unsigned int channels = audioFormat->channels;
snd_pcm_uframes_t alsa_buffer_size;
snd_pcm_uframes_t alsa_period_size;
int err;
char * cmd = NULL;
char *cmd = NULL;
switch(audioFormat->bits) {
switch (audioFormat->bits) {
case 8:
bitformat = SND_PCM_FORMAT_S8;
break;
......@@ -154,54 +159,55 @@ static int alsa_openDevice(AudioOutput * audioOutput)
err = snd_pcm_open(&ad->pcmHandle, ad->device,
SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK);
snd_config_update_free_global();
if(err < 0) {
if (err < 0) {
ad->pcmHandle = NULL;
goto error;
}
cmd = "snd_pcm_nonblock";
err = snd_pcm_nonblock(ad->pcmHandle, 0);
if(err < 0) goto error;
if (err < 0)
goto error;
/* configure HW params */
snd_pcm_hw_params_alloca(&hwparams);
cmd = "snd_pcm_hw_params_any";
err = snd_pcm_hw_params_any(ad->pcmHandle, hwparams);
if(err < 0) goto error;
if (err < 0)
goto error;
if(ad->useMmap) {
if (ad->useMmap) {
err = snd_pcm_hw_params_set_access(ad->pcmHandle, hwparams,
SND_PCM_ACCESS_MMAP_INTERLEAVED);
if(err < 0) {
if (err < 0) {
ERROR("Cannot set mmap'ed mode on alsa device \"%s\": "
" %s\n", ad->device,
snd_strerror(-err));
" %s\n", ad->device, snd_strerror(-err));
ERROR("Falling back to direct write mode\n");
ad->useMmap = 0;
}
else ad->writei = snd_pcm_mmap_writei;
} else
ad->writei = snd_pcm_mmap_writei;
}
if(!ad->useMmap) {
if (!ad->useMmap) {
cmd = "snd_pcm_hw_params_set_access";
err = snd_pcm_hw_params_set_access(ad->pcmHandle, hwparams,
SND_PCM_ACCESS_RW_INTERLEAVED);
if(err < 0) goto error;
if (err < 0)
goto error;
ad->writei = snd_pcm_writei;
}
err = snd_pcm_hw_params_set_format(ad->pcmHandle, hwparams, bitformat);
if(err < 0) {
if (err < 0) {
ERROR("Alsa device \"%s\" does not support %i bit audio: "
"%s\n", ad->device, (int)bitformat,
snd_strerror(-err));
"%s\n", ad->device, (int)bitformat, snd_strerror(-err));
goto fail;
}
err = snd_pcm_hw_params_set_channels_near(ad->pcmHandle, hwparams,
&channels);
if(err < 0) {
if (err < 0) {
ERROR("Alsa device \"%s\" does not support %i channels: "
"%s\n", ad->device, (int)audioFormat->channels,
snd_strerror(-err));
......@@ -211,7 +217,7 @@ static int alsa_openDevice(AudioOutput * audioOutput)
err = snd_pcm_hw_params_set_rate_near(ad->pcmHandle, hwparams,
&sampleRate, NULL);
if(err < 0 || sampleRate == 0) {
if (err < 0 || sampleRate == 0) {
ERROR("Alsa device \"%s\" does not support %i Hz audio\n",
ad->device, (int)audioFormat->sampleRate);
goto fail;
......@@ -221,27 +227,32 @@ static int alsa_openDevice(AudioOutput * audioOutput)
cmd = "snd_pcm_hw_params_set_buffer_time_near";
err = snd_pcm_hw_params_set_buffer_time_near(ad->pcmHandle, hwparams,
&ad->buffer_time, NULL);
if(err < 0) goto error;
if (err < 0)
goto error;
if (!ad->period_time && sampleRate > 0)
ad->period_time = 1000000 * MPD_ALSA_SAMPLE_XFER / sampleRate;
cmd = "snd_pcm_hw_params_set_period_time_near";
err = snd_pcm_hw_params_set_period_time_near(ad->pcmHandle, hwparams,
&ad->period_time, NULL);
if(err < 0) goto error;
if (err < 0)
goto error;
cmd = "snd_pcm_hw_params";
err = snd_pcm_hw_params(ad->pcmHandle, hwparams);
if(err < 0) goto error;
if (err < 0)
goto error;
cmd = "snd_pcm_hw_params_get_buffer_size";
err = snd_pcm_hw_params_get_buffer_size(hwparams, &alsa_buffer_size);
if(err < 0) goto error;
if (err < 0)
goto error;
cmd = "snd_pcm_hw_params_get_period_size";
err = snd_pcm_hw_params_get_period_size(hwparams, &alsa_period_size,
NULL);
if(err < 0) goto error;
if (err < 0)
goto error;
ad->canPause = snd_pcm_hw_params_can_pause(hwparams);
ad->canResume = snd_pcm_hw_params_can_resume(hwparams);
......@@ -251,27 +262,33 @@ static int alsa_openDevice(AudioOutput * audioOutput)
cmd = "snd_pcm_sw_params_current";
err = snd_pcm_sw_params_current(ad->pcmHandle, swparams);
if(err < 0) goto error;
if (err < 0)
goto error;
cmd = "snd_pcm_sw_params_set_start_threshold";
err = snd_pcm_sw_params_set_start_threshold(ad->pcmHandle, swparams,
alsa_buffer_size - alsa_period_size);
if(err < 0) goto error;
alsa_buffer_size -
alsa_period_size);
if (err < 0)
goto error;
cmd = "snd_pcm_sw_params_set_avail_min";
err = snd_pcm_sw_params_set_avail_min(ad->pcmHandle, swparams,
alsa_period_size);
if(err < 0) goto error;
if (err < 0)
goto error;
cmd = "snd_pcm_sw_params_set_xfer_align";
err = snd_pcm_sw_params_set_xfer_align(ad->pcmHandle, swparams, 1);
if(err < 0) goto error;
if (err < 0)
goto error;
cmd = "snd_pcm_sw_params";
err = snd_pcm_sw_params(ad->pcmHandle, swparams);
if(err < 0) goto error;
if (err < 0)
goto error;
ad->sampleSize = (audioFormat->bits/8)*audioFormat->channels;
ad->sampleSize = (audioFormat->bits / 8) * audioFormat->channels;
audioOutput->open = 1;
......@@ -281,31 +298,31 @@ static int alsa_openDevice(AudioOutput * audioOutput)
return 0;
error:
if(cmd) {
error:
if (cmd) {
ERROR("Error opening alsa device \"%s\" (%s): %s\n",
ad->device, cmd, snd_strerror(-err));
}
else {
} else {
ERROR("Error opening alsa device \"%s\": %s\n", ad->device,
snd_strerror(-err));
}
fail:
if(ad->pcmHandle) snd_pcm_close(ad->pcmHandle);
fail:
if (ad->pcmHandle)
snd_pcm_close(ad->pcmHandle);
ad->pcmHandle = NULL;
audioOutput->open = 0;
return -1;
}
static int alsa_errorRecovery(AlsaData * ad, int err) {
if(err == -EPIPE) {
static int alsa_errorRecovery(AlsaData * ad, int err)
{
if (err == -EPIPE) {
DEBUG("Underrun on alsa device \"%s\"\n", ad->device);
}
else if(err == -ESTRPIPE) {
} else if (err == -ESTRPIPE) {
DEBUG("alsa device \"%s\" was suspended\n", ad->device);
}
switch(snd_pcm_state(ad->pcmHandle)) {
switch (snd_pcm_state(ad->pcmHandle)) {
case SND_PCM_STATE_PAUSED:
err = snd_pcm_pause(ad->pcmHandle, /* disable */ 0);
break;
......@@ -331,16 +348,18 @@ static int alsa_errorRecovery(AlsaData * ad, int err) {
return err;
}
static void alsa_dropBufferedAudio(AudioOutput * audioOutput) {
AlsaData * ad = audioOutput->data;
static void alsa_dropBufferedAudio(AudioOutput * audioOutput)
{
AlsaData *ad = audioOutput->data;
alsa_errorRecovery( ad, snd_pcm_drop(ad->pcmHandle) );
alsa_errorRecovery(ad, snd_pcm_drop(ad->pcmHandle));
}
static void alsa_closeDevice(AudioOutput * audioOutput) {
AlsaData * ad = audioOutput->data;
static void alsa_closeDevice(AudioOutput * audioOutput)
{
AlsaData *ad = audioOutput->data;
if(ad->pcmHandle) {
if (ad->pcmHandle) {
snd_pcm_drain(ad->pcmHandle);
snd_pcm_close(ad->pcmHandle);
ad->pcmHandle = NULL;
......@@ -349,10 +368,9 @@ static void alsa_closeDevice(AudioOutput * audioOutput) {
audioOutput->open = 0;
}
static int alsa_playAudio(AudioOutput * audioOutput, char * playChunk,
int size)
static int alsa_playAudio(AudioOutput * audioOutput, char *playChunk, int size)
{
AlsaData * ad = audioOutput->data;
AlsaData *ad = audioOutput->data;
int ret;
size /= ad->sampleSize;
......@@ -360,10 +378,11 @@ static int alsa_playAudio(AudioOutput * audioOutput, char * playChunk,
while (size > 0) {
ret = ad->writei(ad->pcmHandle, playChunk, size);
if(ret == -EAGAIN || ret == -EINTR) continue;
if (ret == -EAGAIN || ret == -EINTR)
continue;
if(ret < 0) {
if( alsa_errorRecovery(ad, ret) < 0) {
if (ret < 0) {
if (alsa_errorRecovery(ad, ret) < 0) {
ERROR("closing alsa device \"%s\" due to write "
"error: %s\n", ad->device,
snd_strerror(-errno));
......@@ -380,8 +399,7 @@ static int alsa_playAudio(AudioOutput * audioOutput, char * playChunk,
return 0;
}
AudioOutputPlugin alsaPlugin =
{
AudioOutputPlugin alsaPlugin = {
"alsa",
alsa_testDefault,
alsa_initDriver,
......@@ -396,5 +414,4 @@ AudioOutputPlugin alsaPlugin =
#else /* HAVE ALSA */
DISABLED_AUDIO_OUTPUT_PLUGIN(alsaPlugin)
#endif /* HAVE_ALSA */
......@@ -34,26 +34,26 @@ static int driverInitCount = 0;
typedef struct _AoData {
int writeSize;
int driverId;
ao_option * options;
ao_device * device;
ao_option *options;
ao_device *device;
} AoData;
static AoData * newAoData() {
AoData * ret = malloc(sizeof(AoData));
static AoData *newAoData()
{
AoData *ret = malloc(sizeof(AoData));
ret->device = NULL;
ret->options = NULL;
return ret;
}
static void audioOutputAo_error() {
if(errno==AO_ENOTLIVE) {
static void audioOutputAo_error()
{
if (errno == AO_ENOTLIVE) {
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");
}
else if(errno==AO_EBADOPTION) {
} else if (errno == AO_EBADOPTION) {
ERROR("bad driver option\n");
}
}
......@@ -61,47 +61,45 @@ static void audioOutputAo_error() {
static int audioOutputAo_initDriver(AudioOutput * audioOutput,
ConfigParam * param)
{
ao_info * ai;
char * dup;
char * stk1;
char * stk2;
char * n1;
char * key;
char * value;
char * test;
AoData * ad = newAoData();
BlockParam * blockParam;
ao_info *ai;
char *dup;
char *stk1;
char *stk2;
char *n1;
char *key;
char *value;
char *test;
AoData *ad = newAoData();
BlockParam *blockParam;
audioOutput->data = ad;
if((blockParam = getBlockParam(param, "write_size"))) {
if ((blockParam = getBlockParam(param, "write_size"))) {
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",
blockParam->value, blockParam->line);
exit(EXIT_FAILURE);
}
}
else ad->writeSize = 1024;
} else
ad->writeSize = 1024;
if(driverInitCount == 0) {
if (driverInitCount == 0) {
ao_initialize();
}
driverInitCount++;
blockParam = getBlockParam(param, "driver");
if(!blockParam || 0 == strcmp(blockParam->value,"default")) {
if (!blockParam || 0 == strcmp(blockParam->value, "default")) {
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",
blockParam->value, blockParam->line);
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 "
"line %i\n", param->line);
ERROR("you may not have permission to the audio device\n");
......@@ -113,18 +111,18 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput,
blockParam = getBlockParam(param, "options");
if(blockParam) {
if (blockParam) {
dup = strdup(blockParam->value);
}
else dup = strdup("");
} else
dup = strdup("");
if(strlen(dup)) {
if (strlen(dup)) {
stk1 = NULL;
n1 = strtok_r(dup,";",&stk1);
while(n1) {
n1 = strtok_r(dup, ";", &stk1);
while (n1) {
stk2 = NULL;
key = strtok_r(n1,"=",&stk2);
if(!key) {
key = strtok_r(n1, "=", &stk2);
if (!key) {
ERROR("problems parsing "
"ao_driver_options \"%s\"\n", n1);
exit(EXIT_FAILURE);
......@@ -141,15 +139,15 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput,
"\"%s\" ao driver\n",key,
ai->short_name);
exit(EXIT_FAILURE);
}*/
value = strtok_r(NULL,"",&stk2);
if(!value) {
} */
value = strtok_r(NULL, "", &stk2);
if (!value) {
ERROR("problems parsing "
"ao_driver_options \"%s\"\n", n1);
exit(EXIT_FAILURE);
}
ao_append_option(&ad->options,key,value);
n1 = strtok_r(NULL,";",&stk1);
ao_append_option(&ad->options, key, value);
n1 = strtok_r(NULL, ";", &stk1);
}
}
free(dup);
......@@ -157,28 +155,33 @@ static int audioOutputAo_initDriver(AudioOutput * audioOutput,
return 0;
}
static void freeAoData(AoData * ad) {
static void freeAoData(AoData * ad)
{
ao_free_options(ad->options);
free(ad);
}
static void audioOutputAo_finishDriver(AudioOutput * audioOutput) {
AoData * ad = (AoData *)audioOutput->data;
static void audioOutputAo_finishDriver(AudioOutput * audioOutput)
{
AoData *ad = (AoData *) audioOutput->data;
freeAoData(ad);
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 */
}
static void audioOutputAo_closeDevice(AudioOutput * audioOutput) {
AoData * ad = (AoData *) audioOutput->data;
static void audioOutputAo_closeDevice(AudioOutput * audioOutput)
{
AoData *ad = (AoData *) audioOutput->data;
if(ad->device) {
if (ad->device) {
ao_close(ad->device);
ad->device = NULL;
}
......@@ -186,11 +189,12 @@ static void audioOutputAo_closeDevice(AudioOutput * audioOutput) {
audioOutput->open = 0;
}
static int audioOutputAo_openDevice(AudioOutput * audioOutput) {
static int audioOutputAo_openDevice(AudioOutput * audioOutput)
{
ao_sample_format format;
AoData * ad = (AoData *)audioOutput->data;
AoData *ad = (AoData *) audioOutput->data;
if(ad->device) {
if (ad->device) {
audioOutputAo_closeDevice(audioOutput);
}
......@@ -201,41 +205,41 @@ static int audioOutputAo_openDevice(AudioOutput * audioOutput) {
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;
return 0;
}
static int audioOutputAo_play(AudioOutput * audioOutput, char * playChunk,
static int audioOutputAo_play(AudioOutput * audioOutput, char *playChunk,
int size)
{
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;
if(ao_play(ad->device, playChunk, send)==0) {
if (ao_play(ad->device, playChunk, send) == 0) {
audioOutputAo_error();
ERROR("closing audio device due to write error\n");
audioOutputAo_closeDevice(audioOutput);
return -1;
}
playChunk+=send;
size-=send;
playChunk += send;
size -= send;
}
return 0;
}
AudioOutputPlugin aoPlugin =
{
AudioOutputPlugin aoPlugin = {
"ao",
NULL,
audioOutputAo_initDriver,
......@@ -252,5 +256,4 @@ AudioOutputPlugin aoPlugin =
#include <stdio.h>
DISABLED_AUDIO_OUTPUT_PLUGIN(aoPlugin)
#endif
......@@ -54,14 +54,14 @@
typedef struct _OssData {
int fd;
char * device;
char *device;
int channels;
int sampleRate;
int bitFormat;
int bits;
int * supported[3];
int *supported[3];
int numSupported[3];
int * unsupported[3];
int *unsupported[3];
int numUnsupported[3];
} OssData;
......@@ -73,10 +73,11 @@ typedef struct _OssData {
#define OSS_CHANNELS 1
#define OSS_BITS 2
static int getIndexForParam(int param) {
static int getIndexForParam(int param)
{
int index = 0;
switch(param) {
switch (param) {
case SNDCTL_DSP_SPEED:
index = OSS_RATE;
break;
......@@ -91,42 +92,49 @@ static int getIndexForParam(int param) {
return index;
}
static int findSupportedParam(OssData * od, int param, int val) {
static int findSupportedParam(OssData * od, int param, int val)
{
int i;
int index = getIndexForParam(param);
for(i = 0; i < od->numSupported[index]; i++) {
if(od->supported[index][i] == val) return 1;
for (i = 0; i < od->numSupported[index]; i++) {
if (od->supported[index][i] == val)
return 1;
}
return 0;
}
static int canConvert(int index, int val) {
switch(index) {
static int canConvert(int index, int val)
{
switch (index) {
case OSS_BITS:
if(val!=16) return 0;
if (val != 16)
return 0;
break;
case OSS_CHANNELS:
if(val!=2) return 0;
if (val != 2)
return 0;
break;
}
return 1;
}
static int getSupportedParam(OssData * od, int param, int val) {
static int getSupportedParam(OssData * od, int param, int val)
{
int i;
int index = getIndexForParam(param);
int ret = -1;
int least = val;
int diff;
for(i = 0; i < od->numSupported[index]; i++) {
diff = od->supported[index][i]-val;
if(diff < 0) diff = -diff;
if(diff < least) {
if(!canConvert(index, od->supported[index][i])) {
for (i = 0; i < od->numSupported[index]; i++) {
diff = od->supported[index][i] - val;
if (diff < 0)
diff = -diff;
if (diff < least) {
if (!canConvert(index, od->supported[index][i])) {
continue;
}
least = diff;
......@@ -137,97 +145,115 @@ static int getSupportedParam(OssData * od, int param, int val) {
return ret;
}
static int findUnsupportedParam(OssData * od, int param, int val) {
static int findUnsupportedParam(OssData * od, int param, int val)
{
int i;
int index = getIndexForParam(param);
for(i = 0; i < od->numUnsupported[index]; i++) {
if(od->unsupported[index][i] == val) return 1;
for (i = 0; i < od->numUnsupported[index]; i++) {
if (od->unsupported[index][i] == val)
return 1;
}
return 0;
}
static void addSupportedParam(OssData * od, int param, int val) {
static void addSupportedParam(OssData * od, int param, int val)
{
int index = getIndexForParam(param);
od->numSupported[index]++;
od->supported[index] = realloc(od->supported[index],
od->numSupported[index]*sizeof(int));
od->supported[index][od->numSupported[index]-1] = val;
od->numSupported[index] * sizeof(int));
od->supported[index][od->numSupported[index] - 1] = val;
}
static void addUnsupportedParam(OssData * od, int param, int val) {
static void addUnsupportedParam(OssData * od, int param, int val)
{
int index = getIndexForParam(param);
od->numUnsupported[index]++;
od->unsupported[index] = realloc(od->unsupported[index],
od->numUnsupported[index]*sizeof(int));
od->unsupported[index][od->numUnsupported[index]-1] = val;
od->numUnsupported[index] *
sizeof(int));
od->unsupported[index][od->numUnsupported[index] - 1] = val;
}
static void removeSupportedParam(OssData * od, int param, int val) {
static void removeSupportedParam(OssData * od, int param, int val)
{
int i = 0;
int j = 0;
int index = getIndexForParam(param);
for(i = 0; i < od->numSupported[index]-1; i++) {
if(od->supported[index][i] == val) j = 1;
od->supported[index][i] = od->supported[index][i+j];
for (i = 0; i < od->numSupported[index] - 1; i++) {
if (od->supported[index][i] == val)
j = 1;
od->supported[index][i] = od->supported[index][i + j];
}
od->numSupported[index]--;
od->supported[index] = realloc(od->supported[index],
od->numSupported[index]*sizeof(int));
od->numSupported[index] * sizeof(int));
}
static void removeUnsupportedParam(OssData * od, int param, int val) {
static void removeUnsupportedParam(OssData * od, int param, int val)
{
int i = 0;
int j = 0;
int index = getIndexForParam(param);
for(i = 0; i < od->numUnsupported[index]-1; i++) {
if(od->unsupported[index][i] == val) j = 1;
od->unsupported[index][i] = od->unsupported[index][i+j];
for (i = 0; i < od->numUnsupported[index] - 1; i++) {
if (od->unsupported[index][i] == val)
j = 1;
od->unsupported[index][i] = od->unsupported[index][i + j];
}
od->numUnsupported[index]--;
od->unsupported[index] = realloc(od->unsupported[index],
od->numUnsupported[index]*sizeof(int));
od->numUnsupported[index] *
sizeof(int));
}
static int isSupportedParam(OssData * od, int param, int val) {
if(findSupportedParam(od, param, val)) return OSS_SUPPORTED;
if(findUnsupportedParam(od, param, val)) return OSS_UNSUPPORTED;
static int isSupportedParam(OssData * od, int param, int val)
{
if (findSupportedParam(od, param, val))
return OSS_SUPPORTED;
if (findUnsupportedParam(od, param, val))
return OSS_UNSUPPORTED;
return OSS_UNKNOWN;
}
static void supportParam(OssData * od, int param, int val) {
static void supportParam(OssData * od, int param, int val)
{
int supported = isSupportedParam(od, param, val);
if(supported == OSS_SUPPORTED) return;
if (supported == OSS_SUPPORTED)
return;
if(supported == OSS_UNSUPPORTED) {
if (supported == OSS_UNSUPPORTED) {
removeUnsupportedParam(od, param, val);
}
addSupportedParam(od, param, val);
}
static void unsupportParam(OssData * od, int param, int val) {
static void unsupportParam(OssData * od, int param, int val)
{
int supported = isSupportedParam(od, param, val);
if(supported == OSS_UNSUPPORTED) return;
if (supported == OSS_UNSUPPORTED)
return;
if(supported == OSS_SUPPORTED) {
if (supported == OSS_SUPPORTED) {
removeSupportedParam(od, param, val);
}
addUnsupportedParam(od, param, val);
}
static OssData * newOssData(void) {
OssData * ret = malloc(sizeof(OssData));
static OssData *newOssData(void)
{
OssData *ret = malloc(sizeof(OssData));
ret->device = NULL;
ret->fd = -1;
......@@ -254,15 +280,23 @@ static OssData * newOssData(void) {
return ret;
}
static void freeOssData(OssData * od) {
if(od->device) free(od->device);
if(od->supported[OSS_RATE]) free(od->supported[OSS_RATE]);
if(od->supported[OSS_CHANNELS]) free(od->supported[OSS_CHANNELS]);
if(od->supported[OSS_BITS]) free(od->supported[OSS_BITS]);
if(od->unsupported[OSS_RATE]) free(od->unsupported[OSS_RATE]);
if(od->unsupported[OSS_CHANNELS]) free(od->unsupported[OSS_CHANNELS]);
if(od->unsupported[OSS_BITS]) free(od->unsupported[OSS_BITS]);
static void freeOssData(OssData * od)
{
if (od->device)
free(od->device);
if (od->supported[OSS_RATE])
free(od->supported[OSS_RATE]);
if (od->supported[OSS_CHANNELS])
free(od->supported[OSS_CHANNELS]);
if (od->supported[OSS_BITS])
free(od->supported[OSS_BITS]);
if (od->unsupported[OSS_RATE])
free(od->unsupported[OSS_RATE]);
if (od->unsupported[OSS_CHANNELS])
free(od->unsupported[OSS_CHANNELS]);
if (od->unsupported[OSS_BITS])
free(od->unsupported[OSS_BITS]);
free(od);
}
......@@ -273,18 +307,18 @@ static void freeOssData(OssData * od) {
#define OSS_STAT_DOESN_T_EXIST -3
#define OSS_STAT_OTHER -4
static int oss_statDevice(char * device, int * stErrno) {
static int oss_statDevice(char *device, int *stErrno)
{
struct stat st;
if(0 == stat(device, &st)) {
if(!S_ISCHR(st.st_mode)) {
if (0 == stat(device, &st)) {
if (!S_ISCHR(st.st_mode)) {
return OSS_STAT_NOT_CHAR_DEV;
}
}
else {
} else {
*stErrno = errno;
switch(errno) {
switch (errno) {
case ENOENT:
case ENOTDIR:
return OSS_STAT_DOESN_T_EXIST;
......@@ -298,12 +332,13 @@ static int oss_statDevice(char * device, int * stErrno) {
return 0;
}
static int oss_testDefault(void) {
static int oss_testDefault(void)
{
int fd;
fd = open("/dev/sound/dsp", O_WRONLY);
if(fd >= 0) {
if (fd >= 0) {
close(fd);
return 0;
}
......@@ -313,108 +348,106 @@ static int oss_testDefault(void) {
fd = open("/dev/dsp", O_WRONLY);
if(fd >= 0) {
if (fd >= 0) {
close(fd);
return 0;
}
WARNING("Error opening OSS device \"/dev/dsp\": %s\n",
strerror(errno));
WARNING("Error opening OSS device \"/dev/dsp\": %s\n", strerror(errno));
return -1;
}
static int oss_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
BlockParam * bp = NULL;
OssData * od;
static int oss_initDriver(AudioOutput * audioOutput, ConfigParam * param)
{
BlockParam *bp = NULL;
OssData *od;
if(param) bp = getBlockParam(param, "device");
if (param)
bp = getBlockParam(param, "device");
od = newOssData();
audioOutput->data = od;
if(!bp) {
if (!bp) {
int err[2];
int ret[2];
ret[0] = oss_statDevice("/dev/sound/dsp", err);
ret[1] = oss_statDevice("/dev/dsp", err+1);
ret[1] = oss_statDevice("/dev/dsp", err + 1);
if(ret[0] == 0) od->device = strdup("/dev/sound/dsp");
else if(ret[1] == 0) od->device = strdup("/dev/dsp");
if (ret[0] == 0)
od->device = strdup("/dev/sound/dsp");
else if (ret[1] == 0)
od->device = strdup("/dev/dsp");
else {
if(param) {
if (param) {
ERROR("Error trying to open default OSS device "
"specified at line %i\n", param->line);
}
else {
} else {
ERROR("Error trying to open default OSS "
"device\n");
}
if((ret[0] == OSS_STAT_DOESN_T_EXIST) &&
if ((ret[0] == OSS_STAT_DOESN_T_EXIST) &&
(ret[1] == OSS_STAT_DOESN_T_EXIST)) {
ERROR("Neither /dev/dsp nor /dev/sound/dsp "
"were found\n");
}
else if(ret[0] == OSS_STAT_NOT_CHAR_DEV) {
} else if (ret[0] == OSS_STAT_NOT_CHAR_DEV) {
ERROR("/dev/sound/dsp is not a char device");
}
else if(ret[1] == OSS_STAT_NOT_CHAR_DEV) {
} else if (ret[1] == OSS_STAT_NOT_CHAR_DEV) {
ERROR("/dev/dsp is not a char device");
}
else if(ret[0] == OSS_STAT_NO_PERMS) {
} else if (ret[0] == OSS_STAT_NO_PERMS) {
ERROR("no permission to access /dev/sound/dsp");
}
else if(ret[1] == OSS_STAT_NO_PERMS) {
} else if (ret[1] == OSS_STAT_NO_PERMS) {
ERROR("no permission to access /dev/dsp");
}
else if(ret[0] == OSS_STAT_OTHER) {
} else if (ret[0] == OSS_STAT_OTHER) {
ERROR("Error accessing /dev/sound/dsp: %s",
strerror(err[0]));
}
else if(ret[1] == OSS_STAT_OTHER) {
} else if (ret[1] == OSS_STAT_OTHER) {
ERROR("Error accessing /dev/dsp: %s",
strerror(err[1]));
}
exit(EXIT_FAILURE);
}
}
else od->device = strdup(bp->value);
} else
od->device = strdup(bp->value);
return 0;
}
static void oss_finishDriver(AudioOutput * audioOutput) {
OssData * od = audioOutput->data;
static void oss_finishDriver(AudioOutput * audioOutput)
{
OssData *od = audioOutput->data;
freeOssData(od);
}
static int setParam(OssData * od, int param, int * value) {
static int setParam(OssData * od, int param, int *value)
{
int val = *value;
int copy;
int supported = isSupportedParam(od, param, val);
do {
if(supported == OSS_UNSUPPORTED) {
if (supported == OSS_UNSUPPORTED) {
val = getSupportedParam(od, param, val);
if(copy < 0) return -1;
if (copy < 0)
return -1;
}
copy = val;
if(ioctl(od->fd, param, &copy)) {
if (ioctl(od->fd, param, &copy)) {
unsupportParam(od, param, val);
supported = OSS_UNSUPPORTED;
}
else {
if(supported == OSS_UNKNOWN) {
} else {
if (supported == OSS_UNKNOWN) {
supportParam(od, param, val);
supported = OSS_SUPPORTED;
}
val = copy;
}
} while( supported == OSS_UNSUPPORTED );
} while (supported == OSS_UNSUPPORTED);
*value = val;
......@@ -423,37 +456,35 @@ static int setParam(OssData * od, int param, int * value) {
static void oss_close(OssData * od)
{
if(od->fd >= 0) while (close(od->fd) && errno == EINTR);
if (od->fd >= 0)
while (close(od->fd) && errno == EINTR) ;
od->fd = -1;
}
static int oss_open(AudioOutput * audioOutput) {
static int oss_open(AudioOutput * audioOutput)
{
int tmp;
OssData * od = audioOutput->data;
OssData *od = audioOutput->data;
if((od->fd = open(od->device, O_WRONLY)) < 0) {
if ((od->fd = open(od->device, O_WRONLY)) < 0) {
ERROR("Error opening OSS device \"%s\": %s\n", od->device,
strerror(errno));
goto fail;
}
if(setParam(od, SNDCTL_DSP_CHANNELS, &od->channels)) {
if (setParam(od, SNDCTL_DSP_CHANNELS, &od->channels)) {
ERROR("OSS device \"%s\" does not support %i channels: %s\n",
od->device,
od->channels,
strerror(errno));
od->device, od->channels, strerror(errno));
goto fail;
}
if(setParam(od, SNDCTL_DSP_SPEED, &od->sampleRate)) {
if (setParam(od, SNDCTL_DSP_SPEED, &od->sampleRate)) {
ERROR("OSS device \"%s\" does not support %i Hz audio: %s\n",
od->device,
od->sampleRate,
strerror(errno));
od->device, od->sampleRate, strerror(errno));
goto fail;
}
switch(od->bits) {
switch (od->bits) {
case 8:
tmp = AFMT_S8;
break;
......@@ -461,11 +492,9 @@ static int oss_open(AudioOutput * audioOutput) {
tmp = AFMT_S16_MPD;
}
if(setParam(od, SNDCTL_DSP_SAMPLESIZE, &tmp)) {
if (setParam(od, SNDCTL_DSP_SAMPLESIZE, &tmp)) {
ERROR("OSS device \"%s\" does not support %i bit audio: %s\n",
od->device,
tmp,
strerror(errno));
od->device, tmp, strerror(errno));
goto fail;
}
......@@ -473,7 +502,7 @@ static int oss_open(AudioOutput * audioOutput) {
return 0;
fail:
fail:
oss_close(od);
audioOutput->open = 0;
return -1;
......@@ -482,8 +511,8 @@ fail:
static int oss_openDevice(AudioOutput * audioOutput)
{
int ret = -1;
OssData * od = audioOutput->data;
AudioFormat * audioFormat = &audioOutput->outAudioFormat;
OssData *od = audioOutput->data;
AudioFormat *audioFormat = &audioOutput->outAudioFormat;
od->channels = audioFormat->channels;
od->sampleRate = audioFormat->sampleRate;
......@@ -497,43 +526,44 @@ static int oss_openDevice(AudioOutput * audioOutput)
audioFormat->bits = od->bits;
DEBUG("oss device \"%s\" will be playing %i bit %i channel audio at "
"%i Hz\n", od->device, od->bits,
od->channels, od->sampleRate);
"%i Hz\n", od->device, od->bits, od->channels, od->sampleRate);
return ret;
}
static void oss_closeDevice(AudioOutput * audioOutput) {
OssData * od = audioOutput->data;
static void oss_closeDevice(AudioOutput * audioOutput)
{
OssData *od = audioOutput->data;
oss_close(od);
audioOutput->open = 0;
}
static void oss_dropBufferedAudio(AudioOutput * audioOutput) {
OssData * od = audioOutput->data;
static void oss_dropBufferedAudio(AudioOutput * audioOutput)
{
OssData *od = audioOutput->data;
if(od->fd >= 0) {
if (od->fd >= 0) {
ioctl(od->fd, SNDCTL_DSP_RESET, 0);
oss_close(od);
}
}
static int oss_playAudio(AudioOutput * audioOutput, char * playChunk,
int size)
static int oss_playAudio(AudioOutput * audioOutput, char *playChunk, int size)
{
OssData * od = audioOutput->data;
OssData *od = audioOutput->data;
int ret;
/* reopen the device since it was closed by dropBufferedAudio */
if(od->fd < 0 && oss_open(audioOutput) < 0)
if (od->fd < 0 && oss_open(audioOutput) < 0)
return -1;
while (size > 0) {
ret = write(od->fd, playChunk, size);
if(ret<0) {
if(errno == EINTR) continue;
if (ret < 0) {
if (errno == EINTR)
continue;
ERROR("closing oss device \"%s\" due to write error: "
"%s\n", od->device, strerror(errno));
oss_closeDevice(audioOutput);
......@@ -546,8 +576,7 @@ static int oss_playAudio(AudioOutput * audioOutput, char * playChunk,
return 0;
}
AudioOutputPlugin ossPlugin =
{
AudioOutputPlugin ossPlugin = {
"oss",
oss_testDefault,
oss_initDriver,
......@@ -562,5 +591,4 @@ AudioOutputPlugin ossPlugin =
#else /* HAVE OSS */
DISABLED_AUDIO_OUTPUT_PLUGIN(ossPlugin)
#endif /* HAVE_OSS */
......@@ -31,15 +31,16 @@ typedef struct _OsxData {
AudioUnit au;
pthread_mutex_t mutex;
pthread_cond_t condition;
char * buffer;
char *buffer;
int bufferSize;
int pos;
int len;
int started;
} OsxData;
static OsxData * newOsxData() {
OsxData * ret = malloc(sizeof(OsxData));
static OsxData *newOsxData()
{
OsxData *ret = malloc(sizeof(OsxData));
pthread_mutex_init(&ret->mutex, NULL);
pthread_cond_init(&ret->condition, NULL);
......@@ -53,7 +54,8 @@ static OsxData * newOsxData() {
return ret;
}
static int osx_testDefault() {
static int osx_testDefault()
{
/*AudioUnit au;
ComponentDescription desc;
Component comp;
......@@ -75,49 +77,55 @@ static int osx_testDefault() {
return -1;
}
CloseComponent(au);*/
CloseComponent(au); */
return 0;
}
static int osx_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
OsxData * od = newOsxData();
static int osx_initDriver(AudioOutput * audioOutput, ConfigParam * param)
{
OsxData *od = newOsxData();
audioOutput->data = od;
return 0;
}
static void freeOsxData(OsxData * od) {
if(od->buffer) free(od->buffer);
static void freeOsxData(OsxData * od)
{
if (od->buffer)
free(od->buffer);
pthread_mutex_destroy(&od->mutex);
pthread_cond_destroy(&od->condition);
free(od);
}
static void osx_finishDriver(AudioOutput * audioOutput) {
OsxData * od = (OsxData *)audioOutput->data;
static void osx_finishDriver(AudioOutput * audioOutput)
{
OsxData *od = (OsxData *) audioOutput->data;
freeOsxData(od);
}
static void osx_dropBufferedAudio(AudioOutput * audioOutput) {
OsxData * od = (OsxData *)audioOutput->data;
static void osx_dropBufferedAudio(AudioOutput * audioOutput)
{
OsxData *od = (OsxData *) audioOutput->data;
pthread_mutex_lock(&od->mutex);
od->len = 0;
pthread_mutex_unlock(&od->mutex);
}
static void osx_closeDevice(AudioOutput * audioOutput) {
OsxData * od = (OsxData *) audioOutput->data;
static void osx_closeDevice(AudioOutput * audioOutput)
{
OsxData *od = (OsxData *) audioOutput->data;
pthread_mutex_lock(&od->mutex);
while(od->len) {
while (od->len) {
pthread_cond_wait(&od->condition, &od->mutex);
}
pthread_mutex_unlock(&od->mutex);
if(od->started) {
if (od->started) {
AudioOutputUnitStop(od->au);
od->started = 0;
}
......@@ -128,14 +136,14 @@ static void osx_closeDevice(AudioOutput * audioOutput) {
audioOutput->open = 0;
}
static OSStatus osx_render(void * vdata,
AudioUnitRenderActionFlags *ioActionFlags,
static OSStatus osx_render(void *vdata,
AudioUnitRenderActionFlags * ioActionFlags,
const AudioTimeStamp * inTimeStamp,
UInt32 inBusNumber, UInt32 inNumberFrames,
AudioBufferList *bufferList)
AudioBufferList * bufferList)
{
OsxData * od = (OsxData *)vdata;
AudioBuffer * buffer = &bufferList->mBuffers[0];
OsxData *od = (OsxData *) vdata;
AudioBuffer *buffer = &bufferList->mBuffers[0];
int bufferSize = buffer->mDataByteSize;
int bytesToCopy;
int curpos = 0;
......@@ -161,7 +169,7 @@ static OSStatus osx_render(void * vdata,
if(*ioActionFlags & kAudioOfflineUnitRenderAction_Complete) {
DEBUG("complete\n");
}
}*/
} */
/* while(bufferSize) {
DEBUG("osx_render: lock\n"); */
......@@ -180,19 +188,20 @@ static OSStatus osx_render(void * vdata,
bufferSize = bytesToCopy;
od->len -= bytesToCopy;
if(od->pos+bytesToCopy > od->bufferSize) {
int bytes = od->bufferSize-od->pos;
memcpy(buffer->mData+curpos, od->buffer+od->pos, bytes);
if (od->pos + bytesToCopy > od->bufferSize) {
int bytes = od->bufferSize - od->pos;
memcpy(buffer->mData + curpos, od->buffer + od->pos, bytes);
od->pos = 0;
curpos += bytes;
bytesToCopy -= bytes;
}
memcpy(buffer->mData+curpos, od->buffer+od->pos, bytesToCopy);
memcpy(buffer->mData + curpos, od->buffer + od->pos, bytesToCopy);
od->pos += bytesToCopy;
curpos += bytesToCopy;
if(od->pos >= od->bufferSize) od->pos = 0;
if (od->pos >= od->bufferSize)
od->pos = 0;
/* DEBUG("osx_render: unlock\n"); */
pthread_mutex_unlock(&od->mutex);
pthread_cond_signal(&od->condition);
......@@ -200,7 +209,7 @@ static OSStatus osx_render(void * vdata,
buffer->mDataByteSize = bufferSize;
if(!bufferSize) {
if (!bufferSize) {
my_usleep(1000);
}
......@@ -208,12 +217,13 @@ static OSStatus osx_render(void * vdata,
return 0;
}
static int osx_openDevice(AudioOutput * audioOutput) {
OsxData * od = (OsxData *)audioOutput->data;
static int osx_openDevice(AudioOutput * audioOutput)
{
OsxData *od = (OsxData *) audioOutput->data;
ComponentDescription desc;
Component comp;
AURenderCallbackStruct callback;
AudioFormat * audioFormat = &audioOutput->outAudioFormat;
AudioFormat *audioFormat = &audioOutput->outAudioFormat;
AudioStreamBasicDescription streamDesc;
desc.componentType = kAudioUnitType_Output;
......@@ -223,17 +233,17 @@ static int osx_openDevice(AudioOutput * audioOutput) {
desc.componentFlagsMask = 0;
comp = FindNextComponent(NULL, &desc);
if(comp == 0) {
if (comp == 0) {
ERROR("Error finding OS X component\n");
return -1;
}
if(OpenAComponent(comp, &od->au) != noErr) {
if (OpenAComponent(comp, &od->au) != noErr) {
ERROR("Unable to open OS X component\n");
return -1;
}
if(AudioUnitInitialize(od->au) != 0) {
if (AudioUnitInitialize(od->au) != 0) {
CloseComponent(od->au);
ERROR("Unable to initialuze OS X audio unit\n");
return -1;
......@@ -242,10 +252,9 @@ static int osx_openDevice(AudioOutput * audioOutput) {
callback.inputProc = osx_render;
callback.inputProcRefCon = od;
if(AudioUnitSetProperty(od->au, kAudioUnitProperty_SetRenderCallback,
if (AudioUnitSetProperty(od->au, kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Input, 0,
&callback, sizeof(callback)) != 0)
{
&callback, sizeof(callback)) != 0) {
AudioUnitUninitialize(od->au);
CloseComponent(od->au);
ERROR("unable to set callbak for OS X audio unit\n");
......@@ -256,16 +265,16 @@ static int osx_openDevice(AudioOutput * audioOutput) {
streamDesc.mFormatID = kAudioFormatLinearPCM;
streamDesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger |
kLinearPCMFormatFlagIsBigEndian;
streamDesc.mBytesPerPacket = audioFormat->channels*audioFormat->bits/8;
streamDesc.mBytesPerPacket =
audioFormat->channels * audioFormat->bits / 8;
streamDesc.mFramesPerPacket = 1;
streamDesc.mBytesPerFrame = streamDesc.mBytesPerPacket;
streamDesc.mChannelsPerFrame = audioFormat->channels;
streamDesc.mBitsPerChannel = audioFormat->bits;
if(AudioUnitSetProperty(od->au, kAudioUnitProperty_StreamFormat,
if (AudioUnitSetProperty(od->au, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input, 0,
&streamDesc, sizeof(streamDesc)) != 0)
{
&streamDesc, sizeof(streamDesc)) != 0) {
AudioUnitUninitialize(od->au);
CloseComponent(od->au);
ERROR("Unable to set format on OS X device\n");
......@@ -285,18 +294,19 @@ static int osx_openDevice(AudioOutput * audioOutput) {
return 0;
}
static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) {
OsxData * od = (OsxData *)audioOutput->data;
static int osx_play(AudioOutput * audioOutput, char *playChunk, int size)
{
OsxData *od = (OsxData *) audioOutput->data;
int bytesToCopy;
int curpos;
/* DEBUG("osx_play: enter\n"); */
if(!od->started) {
if (!od->started) {
int err;
od->started = 1;
err = AudioOutputUnitStart(od->au);
if(err) {
if (err) {
ERROR("unable to start audio output: %i\n", err);
return -1;
}
......@@ -304,14 +314,15 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) {
pthread_mutex_lock(&od->mutex);
while(size) {
while (size) {
/* DEBUG("osx_play: lock\n"); */
curpos = od->pos+od->len;
if(curpos >= od->bufferSize) curpos -= od->bufferSize;
curpos = od->pos + od->len;
if (curpos >= od->bufferSize)
curpos -= od->bufferSize;
bytesToCopy = od->bufferSize < size ? od->bufferSize : size;
while(od->len > od->bufferSize-bytesToCopy) {
while (od->len > od->bufferSize - bytesToCopy) {
/* DEBUG("osx_play: wait\n"); */
pthread_cond_wait(&od->condition, &od->mutex);
}
......@@ -321,15 +332,15 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) {
size -= bytesToCopy;
od->len += bytesToCopy;
if(curpos+bytesToCopy > od->bufferSize) {
int bytes = od->bufferSize-curpos;
memcpy(od->buffer+curpos, playChunk, bytes);
if (curpos + bytesToCopy > od->bufferSize) {
int bytes = od->bufferSize - curpos;
memcpy(od->buffer + curpos, playChunk, bytes);
curpos = 0;
playChunk += bytes;
bytesToCopy -= bytes;
}
memcpy(od->buffer+curpos, playChunk, bytesToCopy);
memcpy(od->buffer + curpos, playChunk, bytesToCopy);
curpos += bytesToCopy;
playChunk += bytesToCopy;
......@@ -341,8 +352,7 @@ static int osx_play(AudioOutput * audioOutput, char * playChunk, int size) {
return 0;
}
AudioOutputPlugin osxPlugin =
{
AudioOutputPlugin osxPlugin = {
"osx",
osx_testDefault,
osx_initDriver,
......@@ -359,5 +369,4 @@ AudioOutputPlugin osxPlugin =
#include <stdio.h>
DISABLED_AUDIO_OUTPUT_PLUGIN(osxPlugin)
#endif
......@@ -34,16 +34,16 @@
#define CONN_ATTEMPT_INTERVAL 60
typedef struct _PulseData {
pa_simple * s;
char * server;
char * sink;
pa_simple *s;
char *server;
char *sink;
int connAttempts;
time_t lastAttempt;
} PulseData;
static PulseData * newPulseData()
static PulseData *newPulseData()
{
PulseData * ret;
PulseData *ret;
ret = malloc(sizeof(PulseData));
......@@ -58,16 +58,18 @@ static PulseData * newPulseData()
static void freePulseData(PulseData * pd)
{
if (pd->server) free(pd->server);
if (pd->sink) free(pd->sink);
if (pd->server)
free(pd->server);
if (pd->sink)
free(pd->sink);
free(pd);
}
static int pulse_initDriver(AudioOutput * audioOutput, ConfigParam * param)
{
BlockParam * server = NULL;
BlockParam * sink = NULL;
PulseData * pd;
BlockParam *server = NULL;
BlockParam *sink = NULL;
PulseData *pd;
if (param) {
server = getBlockParam(param, "server");
......@@ -89,7 +91,7 @@ static void pulse_finishDriver(AudioOutput * audioOutput)
static int pulse_testDefault()
{
pa_simple * s;
pa_simple *s;
pa_sample_spec ss;
int error;
......@@ -112,8 +114,8 @@ static int pulse_testDefault()
static int pulse_openDevice(AudioOutput * audioOutput)
{
PulseData * pd;
AudioFormat * audioFormat;
PulseData *pd;
AudioFormat *audioFormat;
pa_sample_spec ss;
time_t t;
int error;
......@@ -123,7 +125,8 @@ static int pulse_openDevice(AudioOutput * audioOutput)
audioFormat = &audioOutput->outAudioFormat;
if (pd->connAttempts != 0 &&
(t - pd->lastAttempt) < CONN_ATTEMPT_INTERVAL) return -1;
(t - pd->lastAttempt) < CONN_ATTEMPT_INTERVAL)
return -1;
pd->connAttempts++;
pd->lastAttempt = t;
......@@ -142,7 +145,7 @@ static int pulse_openDevice(AudioOutput * audioOutput)
pd->sink, audioOutput->name, &ss, NULL, NULL,
&error);
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,
pd->connAttempts, pa_strerror(error));
return -1;
......@@ -151,7 +154,7 @@ static int pulse_openDevice(AudioOutput * audioOutput)
pd->connAttempts = 0;
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,
audioFormat->channels, audioFormat->sampleRate);
......@@ -160,7 +163,7 @@ static int pulse_openDevice(AudioOutput * audioOutput)
static void pulse_dropBufferedAudio(AudioOutput * audioOutput)
{
PulseData * pd;
PulseData *pd;
int error;
pd = audioOutput->data;
......@@ -171,7 +174,7 @@ static void pulse_dropBufferedAudio(AudioOutput * audioOutput)
static void pulse_closeDevice(AudioOutput * audioOutput)
{
PulseData * pd;
PulseData *pd;
pd = audioOutput->data;
if (pd->s) {
......@@ -182,16 +185,15 @@ static void pulse_closeDevice(AudioOutput * audioOutput)
audioOutput->open = 0;
}
static int pulse_playAudio(AudioOutput * audioOutput, char * playChunk,
int size)
static int pulse_playAudio(AudioOutput * audioOutput, char *playChunk, int size)
{
PulseData * pd;
PulseData *pd;
int error;
pd = audioOutput->data;
if (pa_simple_write(pd->s, playChunk, size, &error) < 0) {
ERROR("PulseAudio output \"%s\" disconnecting due to write " \
ERROR("PulseAudio output \"%s\" disconnecting due to write "
"error: %s\n", audioOutput->name, pa_strerror(error));
pulse_closeDevice(audioOutput);
return -1;
......@@ -215,5 +217,4 @@ AudioOutputPlugin pulsePlugin = {
#else /* HAVE_PULSE */
DISABLED_AUDIO_OUTPUT_PLUGIN(pulsePlugin)
#endif /* HAVE_PULSE */
......@@ -42,7 +42,7 @@ static int shoutInitCount = 0;
/* lots of this code blatantly stolent from bossogg/bossao2 */
typedef struct _ShoutData {
shout_t * shoutConn;
shout_t *shoutConn;
int shoutError;
ogg_stream_state os;
......@@ -62,18 +62,19 @@ typedef struct _ShoutData {
int opened;
MpdTag * tag;
MpdTag *tag;
int tagToSend;
int connAttempts;
time_t lastAttempt;
/* just a pointer to audioOutput->outAudioFormat */
AudioFormat * audioFormat;
AudioFormat *audioFormat;
} ShoutData;
static ShoutData * newShoutData(void) {
ShoutData * ret = malloc(sizeof(ShoutData));
static ShoutData *newShoutData(void)
{
ShoutData *ret = malloc(sizeof(ShoutData));
ret->shoutConn = shout_new();
ret->opened = 0;
......@@ -88,9 +89,12 @@ static ShoutData * newShoutData(void) {
return ret;
}
static void freeShoutData(ShoutData * sd) {
if(sd->shoutConn) shout_free(sd->shoutConn);
if(sd->tag) freeMpdTag(sd->tag);
static void freeShoutData(ShoutData * sd)
{
if (sd->shoutConn)
shout_free(sd->shoutConn);
if (sd->tag)
freeMpdTag(sd->tag);
free(sd);
}
......@@ -104,21 +108,23 @@ static void freeShoutData(ShoutData * sd) {
} \
}
static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
ShoutData * sd;
char * test;
static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param)
{
ShoutData *sd;
char *test;
int port;
char * host;
char * mount;
char * passwd;
char * user;
char * name;
BlockParam * blockParam;
char *host;
char *mount;
char *passwd;
char *user;
char *name;
BlockParam *blockParam;
unsigned int public;
sd = newShoutData();
if(shoutInitCount == 0) shout_init();
if (shoutInitCount == 0)
shout_init();
shoutInitCount++;
......@@ -132,7 +138,7 @@ static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
port = strtol(blockParam->value, &test, 10);
if(*test != '\0' || port <= 0) {
if (*test != '\0' || port <= 0) {
ERROR("shout port \"%s\" is not a positive integer, line %i\n",
blockParam->value, blockParam->line);
exit(EXIT_FAILURE);
......@@ -145,29 +151,33 @@ static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
name = blockParam->value;
blockParam = getBlockParam(param, "public");
if(blockParam) {
if(0 == strcmp(blockParam->value, "yes")) public = 1;
else if(0 == strcmp(blockParam->value, "no")) public = 0;
if (blockParam) {
if (0 == strcmp(blockParam->value, "yes"))
public = 1;
else if (0 == strcmp(blockParam->value, "no"))
public = 0;
else {
ERROR("public \"%s\" is not \"yes\" or \"no\" at line "
"%i\n", param->value, param->line);
exit(EXIT_FAILURE);
}
}
else public = 0;
} else
public = 0;
blockParam = getBlockParam(param, "user");
if(blockParam) user = blockParam->value;
else user = "source";
if (blockParam)
user = blockParam->value;
else
user = "source";
blockParam = getBlockParam(param, "quality");
if(blockParam) {
if (blockParam) {
int line = blockParam->line;
sd->quality = strtod(blockParam->value, &test);
if(*test != '\0' || sd->quality < 0.0 || sd->quality > 10.0) {
if (*test != '\0' || sd->quality < 0.0 || sd->quality > 10.0) {
ERROR("shout quality \"%s\" is not a number in the "
"range 0-10, line %i\n", blockParam->value,
blockParam->line);
......@@ -176,17 +186,16 @@ static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
blockParam = getBlockParam(param, "bitrate");
if(blockParam) {
if (blockParam) {
ERROR("quality (line %i) and bitrate (line %i) are "
"both defined for shout output\n", line,
blockParam->line);
exit(EXIT_FAILURE);
}
}
else {
} else {
blockParam = getBlockParam(param, "bitrate");
if(!blockParam) {
if (!blockParam) {
ERROR("neither bitrate nor quality defined for shout "
"output at line %i\n", param->line);
exit(EXIT_FAILURE);
......@@ -194,7 +203,7 @@ static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
sd->bitrate = strtol(blockParam->value, &test, 10);
if(*test != '\0' || sd->bitrate <= 0) {
if (*test != '\0' || sd->bitrate <= 0) {
ERROR("bitrate at line %i should be a positive integer "
"\n", blockParam->line);
exit(EXIT_FAILURE);
......@@ -204,7 +213,7 @@ static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
checkBlockParam("format");
sd->audioFormat = &audioOutput->outAudioFormat;
if(shout_set_host(sd->shoutConn, host) != SHOUTERR_SUCCESS ||
if (shout_set_host(sd->shoutConn, host) != SHOUTERR_SUCCESS ||
shout_set_port(sd->shoutConn, port) != SHOUTERR_SUCCESS ||
shout_set_password(sd->shoutConn, passwd) != SHOUTERR_SUCCESS ||
shout_set_mount(sd->shoutConn, mount) != SHOUTERR_SUCCESS ||
......@@ -215,30 +224,25 @@ static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
!= SHOUTERR_SUCCESS ||
shout_set_protocol(sd->shoutConn, SHOUT_PROTOCOL_HTTP)
!= SHOUTERR_SUCCESS ||
shout_set_agent(sd->shoutConn, "MPD") != SHOUTERR_SUCCESS)
{
shout_set_agent(sd->shoutConn, "MPD") != SHOUTERR_SUCCESS) {
ERROR("error configuring shout defined at line %i: %s\n",
param->line,
shout_get_error(sd->shoutConn));
param->line, shout_get_error(sd->shoutConn));
exit(EXIT_FAILURE);
}
/* optional paramters */
blockParam = getBlockParam(param, "genre");
if(blockParam && shout_set_genre(sd->shoutConn, blockParam->value)) {
if (blockParam && shout_set_genre(sd->shoutConn, blockParam->value)) {
ERROR("error configuring shout defined at line %i: %s\n",
param->line,
shout_get_error(sd->shoutConn));
param->line, shout_get_error(sd->shoutConn));
exit(EXIT_FAILURE);
}
blockParam = getBlockParam(param, "description");
if(blockParam && shout_set_description(sd->shoutConn,
blockParam->value))
{
if (blockParam && shout_set_description(sd->shoutConn,
blockParam->value)) {
ERROR("error configuring shout defined at line %i: %s\n",
param->line,
shout_get_error(sd->shoutConn));
param->line, shout_get_error(sd->shoutConn));
exit(EXIT_FAILURE);
}
......@@ -253,12 +257,11 @@ static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
shout_set_audio_info(sd->shoutConn, SHOUT_AI_SAMPLERATE, temp);
if(sd->quality >= 0) {
if (sd->quality >= 0) {
snprintf(temp, sizeof(temp), "%2.2f", sd->quality);
shout_set_audio_info(sd->shoutConn, SHOUT_AI_QUALITY,
temp);
}
else {
} else {
snprintf(temp, sizeof(temp), "%d", sd->bitrate);
shout_set_audio_info(sd->shoutConn, SHOUT_AI_BITRATE,
temp);
......@@ -270,8 +273,9 @@ static int myShout_initDriver(AudioOutput * audioOutput, ConfigParam * param) {
return 0;
}
static int myShout_handleError(ShoutData * sd, int err) {
switch(err) {
static int myShout_handleError(ShoutData * sd, int err)
{
switch (err) {
case SHOUTERR_SUCCESS:
break;
case SHOUTERR_UNCONNECTED:
......@@ -294,39 +298,46 @@ static int myShout_handleError(ShoutData * sd, int err) {
return 0;
}
static int write_page(ShoutData * sd) {
static int write_page(ShoutData * sd)
{
int err = 0;
/*DEBUG("shout_delay: %i\n", shout_delay(sd->shoutConn));*/
/*DEBUG("shout_delay: %i\n", shout_delay(sd->shoutConn)); */
shout_sync(sd->shoutConn);
err = shout_send(sd->shoutConn, sd->og.header, sd->og.header_len);
if(myShout_handleError(sd, err) < 0) return -1;
if (myShout_handleError(sd, err) < 0)
return -1;
err = shout_send(sd->shoutConn, sd->og.body, sd->og.body_len);
if(myShout_handleError(sd, err) < 0) return -1;
if (myShout_handleError(sd, err) < 0)
return -1;
return 0;
}
static void finishEncoder(ShoutData * sd) {
static void finishEncoder(ShoutData * sd)
{
vorbis_analysis_wrote(&sd->vd, 0);
while(vorbis_analysis_blockout(&sd->vd, &sd->vb) == 1) {
while (vorbis_analysis_blockout(&sd->vd, &sd->vb) == 1) {
vorbis_analysis(&sd->vb, NULL);
vorbis_bitrate_addblock(&sd->vb);
while(vorbis_bitrate_flushpacket(&sd->vd, &sd->op)) {
while (vorbis_bitrate_flushpacket(&sd->vd, &sd->op)) {
ogg_stream_packetin(&sd->os, &sd->op);
}
}
}
static int flushEncoder(ShoutData * sd) {
static int flushEncoder(ShoutData * sd)
{
return (ogg_stream_pageout(&sd->os, &sd->og) > 0);
}
static void clearEncoder(ShoutData * sd) {
static void clearEncoder(ShoutData * sd)
{
finishEncoder(sd);
while(1 == flushEncoder(sd)) {
if(!sd->shoutError) write_page(sd);
while (1 == flushEncoder(sd)) {
if (!sd->shoutError)
write_page(sd);
}
vorbis_comment_clear(&sd->vc);
......@@ -336,11 +347,12 @@ static void clearEncoder(ShoutData * sd) {
vorbis_info_clear(&sd->vi);
}
static void myShout_closeShoutConn(ShoutData * sd) {
if(sd->opened) {
static void myShout_closeShoutConn(ShoutData * sd)
{
if (sd->opened) {
clearEncoder(sd);
if(shout_close(sd->shoutConn) != SHOUTERR_SUCCESS) {
if (shout_close(sd->shoutConn) != SHOUTERR_SUCCESS) {
ERROR("problem closing connection to shout server: "
"%s\n", shout_get_error(sd->shoutConn));
}
......@@ -349,8 +361,9 @@ static void myShout_closeShoutConn(ShoutData * sd) {
sd->opened = 0;
}
static void myShout_finishDriver(AudioOutput * audioOutput) {
ShoutData * sd = (ShoutData *)audioOutput->data;
static void myShout_finishDriver(AudioOutput * audioOutput)
{
ShoutData *sd = (ShoutData *) audioOutput->data;
myShout_closeShoutConn(sd);
......@@ -358,15 +371,18 @@ static void myShout_finishDriver(AudioOutput * audioOutput) {
shoutInitCount--;
if(shoutInitCount == 0) shout_shutdown();
if (shoutInitCount == 0)
shout_shutdown();
}
static void myShout_dropBufferedAudio(AudioOutput * audioOutput) {
static void myShout_dropBufferedAudio(AudioOutput * audioOutput)
{
/* needs to be implemented */
}
static void myShout_closeDevice(AudioOutput * audioOutput) {
ShoutData * sd = (ShoutData *)audioOutput->data;
static void myShout_closeDevice(AudioOutput * audioOutput)
{
ShoutData *sd = (ShoutData *) audioOutput->data;
myShout_closeShoutConn(sd);
......@@ -377,12 +393,13 @@ static void myShout_closeDevice(AudioOutput * audioOutput) {
if(value) vorbis_comment_add_tag(&(sd->vc), name, value); \
}
static void copyTagToVorbisComment(ShoutData * sd) {
if(sd->tag) {
static void copyTagToVorbisComment(ShoutData * sd)
{
if (sd->tag) {
int i;
for(i = 0; i < sd->tag->numOfItems; i++) {
switch(sd->tag->items[i].type) {
for (i = 0; i < sd->tag->numOfItems; i++) {
switch (sd->tag->items[i].type) {
case TAG_ITEM_ARTIST:
addTag("ARTIST", sd->tag->items[i].value);
break;
......@@ -397,25 +414,24 @@ static void copyTagToVorbisComment(ShoutData * sd) {
}
}
static int initEncoder(ShoutData * sd) {
static int initEncoder(ShoutData * sd)
{
vorbis_info_init(&(sd->vi));
if(sd->quality >= 0) {
if( 0 != vorbis_encode_init_vbr(&(sd->vi),
if (sd->quality >= 0) {
if (0 != vorbis_encode_init_vbr(&(sd->vi),
sd->audioFormat->channels,
sd->audioFormat->sampleRate, sd->quality*0.1) )
{
sd->audioFormat->sampleRate,
sd->quality * 0.1)) {
ERROR("problem seting up vorbis encoder for shout\n");
vorbis_info_clear(&(sd->vi));
return -1;
}
}
else {
if( 0 != vorbis_encode_init(&(sd->vi),
} else {
if (0 != vorbis_encode_init(&(sd->vi),
sd->audioFormat->channels,
sd->audioFormat->sampleRate, -1.0,
sd->bitrate*1000, -1.0) )
{
sd->bitrate * 1000, -1.0)) {
ERROR("problem seting up vorbis encoder for shout\n");
vorbis_info_clear(&(sd->vi));
return -1;
......@@ -423,7 +439,7 @@ static int initEncoder(ShoutData * sd) {
}
vorbis_analysis_init(&(sd->vd), &(sd->vi));
vorbis_block_init (&(sd->vd), &(sd->vb));
vorbis_block_init(&(sd->vd), &(sd->vb));
ogg_stream_init(&(sd->os), rand());
......@@ -432,13 +448,13 @@ static int initEncoder(ShoutData * sd) {
return 0;
}
static int myShout_openShoutConn(AudioOutput * audioOutput) {
ShoutData * sd = (ShoutData *)audioOutput->data;
static int myShout_openShoutConn(AudioOutput * audioOutput)
{
ShoutData *sd = (ShoutData *) audioOutput->data;
time_t t = time(NULL);
if(sd->connAttempts!= 0 &&
(t - sd->lastAttempt) < CONN_ATTEMPT_INTERVAL)
{
if (sd->connAttempts != 0 &&
(t - sd->lastAttempt) < CONN_ATTEMPT_INTERVAL) {
return -1;
}
......@@ -446,17 +462,16 @@ static int myShout_openShoutConn(AudioOutput * audioOutput) {
sd->lastAttempt = t;
if(shout_open(sd->shoutConn) != SHOUTERR_SUCCESS) {
if (shout_open(sd->shoutConn) != SHOUTERR_SUCCESS) {
ERROR("problem opening connection to shout server %s:%i "
"(attempt %i): %s\n",
shout_get_host(sd->shoutConn),
shout_get_port(sd->shoutConn),
sd->connAttempts,
shout_get_error(sd->shoutConn));
sd->connAttempts, shout_get_error(sd->shoutConn));
return -1;
}
if(initEncoder(sd) < 0) {
if (initEncoder(sd) < 0) {
shout_close(sd->shoutConn);
return -1;
}
......@@ -466,7 +481,8 @@ static int myShout_openShoutConn(AudioOutput * audioOutput) {
copyTagToVorbisComment(sd);
vorbis_analysis_headerout(&(sd->vd), &(sd->vc), &(sd->header_main),
&(sd->header_comments), &(sd->header_codebooks));
&(sd->header_comments),
&(sd->header_codebooks));
ogg_stream_packetin(&(sd->os), &(sd->header_main));
ogg_stream_packetin(&(sd->os), &(sd->header_comments));
......@@ -475,9 +491,8 @@ static int myShout_openShoutConn(AudioOutput * audioOutput) {
sd->opened = 1;
sd->tagToSend = 0;
while(ogg_stream_flush(&(sd->os), &(sd->og)))
{
if(write_page(sd) < 0) {
while (ogg_stream_flush(&(sd->os), &(sd->og))) {
if (write_page(sd) < 0) {
myShout_closeShoutConn(sd);
return -1;
}
......@@ -488,14 +503,16 @@ static int myShout_openShoutConn(AudioOutput * audioOutput) {
return 0;
}
static int myShout_openDevice(AudioOutput * audioOutput) {
ShoutData * sd = (ShoutData *)audioOutput->data;
static int myShout_openDevice(AudioOutput * audioOutput)
{
ShoutData *sd = (ShoutData *) audioOutput->data;
audioOutput->open = 1;
if(sd->opened) return 0;
if (sd->opened)
return 0;
if(myShout_openShoutConn(audioOutput) < 0) {
if (myShout_openShoutConn(audioOutput) < 0) {
audioOutput->open = 0;
return -1;
}
......@@ -503,76 +520,80 @@ static int myShout_openDevice(AudioOutput * audioOutput) {
return 0;
}
static void myShout_sendMetadata(ShoutData * sd) {
if(!sd->opened || !sd->tag) return;
static void myShout_sendMetadata(ShoutData * sd)
{
if (!sd->opened || !sd->tag)
return;
clearEncoder(sd);
if(initEncoder(sd) < 0) return;
if (initEncoder(sd) < 0)
return;
copyTagToVorbisComment(sd);
vorbis_analysis_headerout(&(sd->vd), &(sd->vc), &(sd->header_main),
&(sd->header_comments), &(sd->header_codebooks));
&(sd->header_comments),
&(sd->header_codebooks));
ogg_stream_packetin(&(sd->os), &(sd->header_main));
ogg_stream_packetin(&(sd->os), &(sd->header_comments));
ogg_stream_packetin(&(sd->os), &(sd->header_codebooks));
while(ogg_stream_flush(&(sd->os), &(sd->og)))
{
if(write_page(sd) < 0) {
while (ogg_stream_flush(&(sd->os), &(sd->og))) {
if (write_page(sd) < 0) {
myShout_closeShoutConn(sd);
return;
}
}
/*if(sd->tag) freeMpdTag(sd->tag);
sd->tag = NULL;*/
sd->tag = NULL; */
sd->tagToSend = 0;
}
static int myShout_play(AudioOutput * audioOutput, char * playChunk, int size) {
int i,j;
ShoutData * sd = (ShoutData *)audioOutput->data;
float ** vorbbuf;
static int myShout_play(AudioOutput * audioOutput, char *playChunk, int size)
{
int i, j;
ShoutData *sd = (ShoutData *) audioOutput->data;
float **vorbbuf;
int samples;
int bytes = sd->audioFormat->bits/8;
int bytes = sd->audioFormat->bits / 8;
if(sd->opened && sd->tagToSend) myShout_sendMetadata(sd);
if (sd->opened && sd->tagToSend)
myShout_sendMetadata(sd);
if(!sd->opened) {
if(myShout_openShoutConn(audioOutput) < 0) {
if (!sd->opened) {
if (myShout_openShoutConn(audioOutput) < 0) {
return -1;
}
}
samples = size/(bytes*sd->audioFormat->channels);
samples = size / (bytes * sd->audioFormat->channels);
/* this is for only 16-bit audio */
vorbbuf = vorbis_analysis_buffer(&(sd->vd), samples);
for(i=0; i<samples; i++) {
for(j=0; j<sd->audioFormat->channels; j++) {
vorbbuf[j][i] = (*((mpd_sint16 *)playChunk)) / 32768.0;
for (i = 0; i < samples; i++) {
for (j = 0; j < sd->audioFormat->channels; j++) {
vorbbuf[j][i] = (*((mpd_sint16 *) playChunk)) / 32768.0;
playChunk += bytes;
}
}
vorbis_analysis_wrote(&(sd->vd), samples);
while(1 == vorbis_analysis_blockout(&(sd->vd), &(sd->vb))) {
while (1 == vorbis_analysis_blockout(&(sd->vd), &(sd->vb))) {
vorbis_analysis(&(sd->vb), NULL);
vorbis_bitrate_addblock(&(sd->vb));
while(vorbis_bitrate_flushpacket(&(sd->vd), &(sd->op))) {
while (vorbis_bitrate_flushpacket(&(sd->vd), &(sd->op))) {
ogg_stream_packetin(&(sd->os), &(sd->op));
}
}
while(ogg_stream_pageout(&(sd->os), &(sd->og)) != 0) {
if(write_page(sd) < 0) {
while (ogg_stream_pageout(&(sd->os), &(sd->og)) != 0) {
if (write_page(sd) < 0) {
myShout_closeShoutConn(sd);
return -1;
}
......@@ -581,21 +602,23 @@ static int myShout_play(AudioOutput * audioOutput, char * playChunk, int size) {
return 0;
}
static void myShout_setTag(AudioOutput * audioOutput, MpdTag * tag) {
ShoutData * sd = (ShoutData *)audioOutput->data;
static void myShout_setTag(AudioOutput * audioOutput, MpdTag * tag)
{
ShoutData *sd = (ShoutData *) audioOutput->data;
if(sd->tag) freeMpdTag(sd->tag);
if (sd->tag)
freeMpdTag(sd->tag);
sd->tag = NULL;
sd->tagToSend = 0;
if(!tag) return;
if (!tag)
return;
sd->tag = mpdTagDup(tag);
sd->tagToSend = 1;
}
AudioOutputPlugin shoutPlugin =
{
AudioOutputPlugin shoutPlugin = {
"shout",
NULL,
myShout_initDriver,
......@@ -610,5 +633,4 @@ AudioOutputPlugin shoutPlugin =
#else
DISABLED_AUDIO_OUTPUT_PLUGIN(shoutPlugin)
#endif
......@@ -22,79 +22,74 @@
#include <stdlib.h>
#include <string.h>
int buffer2array(char * origBuffer, char *** array) {
int buffer2array(char *origBuffer, char ***array)
{
int quotes = 0;
int count = 0;
int i;
int curr;
int * beginArray;
char * buffer = strdup(origBuffer);
int *beginArray;
char *buffer = strdup(origBuffer);
int bufferLength = strlen(buffer);
char * markArray = malloc(sizeof(char)*(bufferLength+1));
char *markArray = malloc(sizeof(char) * (bufferLength + 1));
for(curr=0;curr<bufferLength;curr++) {
if(!quotes && (buffer[curr]==' ' || buffer[curr]=='\t') ) {
for (curr = 0; curr < bufferLength; curr++) {
if (!quotes && (buffer[curr] == ' ' || buffer[curr] == '\t')) {
markArray[curr] = '0';
}
else if(buffer[curr] == '\"') {
if(curr>0 && buffer[curr-1]!='\\') {
quotes = quotes?0:1;
} else if (buffer[curr] == '\"') {
if (curr > 0 && buffer[curr - 1] != '\\') {
quotes = quotes ? 0 : 1;
markArray[curr] = '0';
}
else {
} else {
markArray[curr] = '1';
}
}
else {
} else {
markArray[curr] = '1';
}
if(markArray[curr]=='1') {
if(curr>0) {
if(markArray[curr-1]=='0') {
if (markArray[curr] == '1') {
if (curr > 0) {
if (markArray[curr - 1] == '0') {
count++;
}
}
else {
} else {
count++;
}
}
}
markArray[bufferLength] = '\0';
if(!count) {
if (!count) {
free(buffer);
free(markArray);
return count;
}
beginArray = malloc(sizeof(int)*count);
(*array) = malloc(sizeof(char *)*count);
beginArray = malloc(sizeof(int) * count);
(*array) = malloc(sizeof(char *) * count);
count = 0;
for(curr=0;curr<bufferLength;curr++) {
if(markArray[curr]=='1') {
if(curr>0) {
if(markArray[curr-1]=='0') {
for (curr = 0; curr < bufferLength; curr++) {
if (markArray[curr] == '1') {
if (curr > 0) {
if (markArray[curr - 1] == '0') {
beginArray[count++] = curr;
}
}
else {
} else {
beginArray[count++] = curr;
}
}
else {
} else {
buffer[curr] = '\0';
}
}
for(i=0;i<count;i++) {
int len = strlen(buffer+beginArray[i])+1;
for (i = 0; i < count; i++) {
int len = strlen(buffer + beginArray[i]) + 1;
int arrayCurr = 0;
(*array)[i] = malloc(sizeof(char)*len);
for(curr=beginArray[i];buffer[curr]!='\0';curr++) {
if(buffer[curr]=='\\') {
if(buffer[curr+1]!='\0') {
(*array)[i] = malloc(sizeof(char) * len);
for (curr = beginArray[i]; buffer[curr] != '\0'; curr++) {
if (buffer[curr] == '\\') {
if (buffer[curr + 1] != '\0') {
curr++;
}
}
......@@ -110,12 +105,14 @@ int buffer2array(char * origBuffer, char *** array) {
return count;
}
void freeArgArray(char ** array, int argArrayLength) {
void freeArgArray(char **array, int argArrayLength)
{
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);
......
......@@ -21,8 +21,8 @@
#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
......@@ -29,8 +29,8 @@
iconv_t char_conv_iconv;
#endif
char * char_conv_to = NULL;
char * char_conv_from = NULL;
char *char_conv_to = NULL;
char *char_conv_from = NULL;
mpd_sint8 char_conv_same = 0;
mpd_sint8 char_conv_use_iconv = 0;
......@@ -43,37 +43,37 @@ mpd_sint8 char_conv_latin1ToUtf8 = 0;
static void closeCharSetConversion();
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)
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)
{
return 0;
}
closeCharSetConversion();
if(0==strcmp(to,from)) {
if (0 == strcmp(to, from)) {
char_conv_same = 1;
char_conv_to = strdup(to);
char_conv_from = strdup(from);
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;
}
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;
}
if(char_conv_latin1ToUtf8!=0) {
if (char_conv_latin1ToUtf8 != 0) {
char_conv_to = strdup(to);
char_conv_from = strdup(from);
return 0;
}
#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_from = strdup(from);
......@@ -85,37 +85,42 @@ int setCharSetConversion(char * to, char * from) {
return -1;
}
char * convStrDup(char * string) {
if(!char_conv_to) return NULL;
char *convStrDup(char *string)
{
if (!char_conv_to)
return NULL;
if(char_conv_same) return strdup(string);
if (char_conv_same)
return strdup(string);
#ifdef HAVE_ICONV
if(char_conv_use_iconv) {
if (char_conv_use_iconv) {
char buffer[BUFFER_SIZE];
size_t inleft = strlen(string);
char * ret;
char *ret;
size_t outleft;
size_t retlen = 0;
size_t err;
char * bufferPtr;
char *bufferPtr;
ret = malloc(1);
ret[0] = '\0';
while(inleft) {
while (inleft) {
bufferPtr = buffer;
outleft = BUFFER_SIZE;
err = iconv(char_conv_iconv,&string,&inleft,&bufferPtr,
err =
iconv(char_conv_iconv, &string, &inleft, &bufferPtr,
&outleft);
if(outleft==BUFFER_SIZE || (err<0 && errno!=E2BIG)) {
if (outleft == BUFFER_SIZE
|| (err < 0 && errno != E2BIG)) {
free(ret);
return NULL;
}
ret = realloc(ret,retlen+BUFFER_SIZE-outleft+1);
memcpy(ret+retlen,buffer,BUFFER_SIZE-outleft);
retlen+=BUFFER_SIZE-outleft;
ret = realloc(ret, retlen + BUFFER_SIZE - outleft + 1);
memcpy(ret + retlen, buffer, BUFFER_SIZE - outleft);
retlen += BUFFER_SIZE - outleft;
ret[retlen] = '\0';
}
......@@ -123,7 +128,7 @@ char * convStrDup(char * string) {
}
#endif
switch(char_conv_latin1ToUtf8) {
switch (char_conv_latin1ToUtf8) {
case 1:
return latin1StrToUtf8Dup(string);
break;
......@@ -135,10 +140,12 @@ char * convStrDup(char * string) {
return NULL;
}
static void closeCharSetConversion(void) {
if(char_conv_to) {
static void closeCharSetConversion(void)
{
if (char_conv_to) {
#ifdef HAVE_ICONV
if(char_conv_use_iconv) iconv_close(char_conv_iconv);
if (char_conv_use_iconv)
iconv_close(char_conv_iconv);
#endif
free(char_conv_to);
free(char_conv_from);
......
......@@ -21,8 +21,8 @@
#include "../config.h"
int setCharSetConversion(char * to, char * from);
int setCharSetConversion(char *to, char *from);
char * convStrDup(char * string);
char *convStrDup(char *string);
#endif
......@@ -106,15 +106,14 @@
typedef struct _CommandEntry CommandEntry;
typedef int (* CommandHandlerFunction)(FILE *, int *, int, char **);
typedef int (* CommandListHandlerFunction)
(FILE *, int *, int, char **,ListNode *, CommandEntry *);
typedef int (*CommandHandlerFunction) (FILE *, int *, int, char **);
typedef int (*CommandListHandlerFunction)
(FILE *, int *, int, char **, ListNode *, CommandEntry *);
/* if min: -1 don't check args *
* if max: -1 no max args */
struct _CommandEntry {
char * cmd;
char *cmd;
int min;
int max;
int reqPermission;
......@@ -122,15 +121,16 @@ struct _CommandEntry {
CommandListHandlerFunction listHandler;
};
char * current_command = NULL;
char *current_command = NULL;
int command_listNum = 0;
static CommandEntry * getCommandEntryFromString(char * string, int * permission);
static CommandEntry *getCommandEntryFromString(char *string, int *permission);
List * commandList;
List *commandList;
CommandEntry * newCommandEntry(void) {
CommandEntry * cmd = malloc(sizeof(CommandEntry));
CommandEntry *newCommandEntry(void)
{
CommandEntry *cmd = malloc(sizeof(CommandEntry));
cmd->cmd = NULL;
cmd->min = 0;
cmd->max = 0;
......@@ -140,14 +140,14 @@ CommandEntry * newCommandEntry(void) {
return cmd;
}
static void addCommand(char * name,
static void addCommand(char *name,
int reqPermission,
int minargs,
int maxargs,
CommandHandlerFunction handler_func,
CommandListHandlerFunction listHandler_func)
{
CommandEntry * cmd = newCommandEntry();
CommandEntry *cmd = newCommandEntry();
cmd->cmd = name;
cmd->min = minargs;
cmd->max = maxargs;
......@@ -158,38 +158,38 @@ static void addCommand(char * name,
insertInList(commandList, cmd->cmd, cmd);
}
static int handleUrlHandlers(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleUrlHandlers(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return printRemoteUrlHandlers(fp);
}
static int handlePlay(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handlePlay(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int song = -1;
char * test;
char *test;
if(argArrayLength==2) {
song = strtol(argArray[1],&test,10);
if(*test!='\0') {
if (argArrayLength == 2) {
song = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"need a positive integer", NULL);
return -1;
}
}
return playPlaylist(fp,song,0);
return playPlaylist(fp, song, 0);
}
static int handlePlayId(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handlePlayId(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int id = -1;
char * test;
char *test;
if(argArrayLength==2) {
id = strtol(argArray[1],&test,10);
if(*test!='\0') {
if (argArrayLength == 2) {
id = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"need a positive integer", NULL);
return -1;
......@@ -198,48 +198,49 @@ static int handlePlayId(FILE * fp, int * permission, int argArrayLength,
return playPlaylistById(fp, id, 0);
}
static int handleStop(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleStop(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return stopPlaylist(fp);
}
static int handleCurrentSong(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleCurrentSong(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int song = getPlaylistCurrentSong();
if(song >= 0) {
if (song >= 0) {
return playlistInfo(fp, song);
}
else return 0;
} else
return 0;
}
static int handlePause(FILE * fp, int * permission,
int argArrayLength, char ** argArray)
static int handlePause(FILE * fp, int *permission,
int argArrayLength, char **argArray)
{
if(argArrayLength==2) {
char * test;
int pause = strtol(argArray[1],&test,10);
if(*test!='\0' || (pause!=0 && pause!=1)) {
commandError(fp, ACK_ERROR_ARG, "\"%s\" is not 0 or 1", argArray[1]);
if (argArrayLength == 2) {
char *test;
int pause = strtol(argArray[1], &test, 10);
if (*test != '\0' || (pause != 0 && pause != 1)) {
commandError(fp, ACK_ERROR_ARG, "\"%s\" is not 0 or 1",
argArray[1]);
return -1;
}
return playerSetPause(fp,pause);
return playerSetPause(fp, pause);
}
return playerPause(fp);
}
static int commandStatus(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int commandStatus(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
char * state = NULL;
char *state = NULL;
int updateJobId;
int song;
/*syncPlayerAndPlaylist();*/
/*syncPlayerAndPlaylist(); */
playPlaylistIfPlayerStopped();
switch(getPlayerState()) {
switch (getPlayerState()) {
case PLAYER_STATE_STOP:
state = COMMAND_STOP;
break;
......@@ -251,90 +252,101 @@ static int commandStatus(FILE * fp, int * permission, int argArrayLength,
break;
}
myfprintf(fp,"%s: %i\n",COMMAND_STATUS_VOLUME,getVolumeLevel());
myfprintf(fp,"%s: %i\n",COMMAND_STATUS_REPEAT,getPlaylistRepeatStatus());
myfprintf(fp,"%s: %i\n",COMMAND_STATUS_RANDOM,getPlaylistRandomStatus());
myfprintf(fp,"%s: %li\n",COMMAND_STATUS_PLAYLIST,getPlaylistVersion());
myfprintf(fp,"%s: %i\n",COMMAND_STATUS_PLAYLIST_LENGTH,getPlaylistLength());
myfprintf(fp,"%s: %i\n",COMMAND_STATUS_CROSSFADE,
(int)(getPlayerCrossFade()+0.5));
myfprintf(fp, "%s: %i\n", COMMAND_STATUS_VOLUME, getVolumeLevel());
myfprintf(fp, "%s: %i\n", COMMAND_STATUS_REPEAT,
getPlaylistRepeatStatus());
myfprintf(fp, "%s: %i\n", COMMAND_STATUS_RANDOM,
getPlaylistRandomStatus());
myfprintf(fp, "%s: %li\n", COMMAND_STATUS_PLAYLIST,
getPlaylistVersion());
myfprintf(fp, "%s: %i\n", COMMAND_STATUS_PLAYLIST_LENGTH,
getPlaylistLength());
myfprintf(fp, "%s: %i\n", COMMAND_STATUS_CROSSFADE,
(int)(getPlayerCrossFade() + 0.5));
myfprintf(fp,"%s: %s\n",COMMAND_STATUS_STATE,state);
myfprintf(fp, "%s: %s\n", COMMAND_STATUS_STATE, state);
song = getPlaylistCurrentSong();
if(song >= 0) {
myfprintf(fp,"%s: %i\n", COMMAND_STATUS_SONG, song);
myfprintf(fp,"%s: %i\n", COMMAND_STATUS_SONGID,
if (song >= 0) {
myfprintf(fp, "%s: %i\n", COMMAND_STATUS_SONG, song);
myfprintf(fp, "%s: %i\n", COMMAND_STATUS_SONGID,
getPlaylistSongId(song));
}
if(getPlayerState()!=PLAYER_STATE_STOP) {
myfprintf(fp,"%s: %i:%i\n",COMMAND_STATUS_TIME,getPlayerElapsedTime(),getPlayerTotalTime());
myfprintf(fp,"%s: %li\n",COMMAND_STATUS_BITRATE,getPlayerBitRate(),getPlayerTotalTime());
myfprintf(fp,"%s: %u:%i:%i\n",COMMAND_STATUS_AUDIO,getPlayerSampleRate(),getPlayerBits(),getPlayerChannels());
if (getPlayerState() != PLAYER_STATE_STOP) {
myfprintf(fp, "%s: %i:%i\n", COMMAND_STATUS_TIME,
getPlayerElapsedTime(), getPlayerTotalTime());
myfprintf(fp, "%s: %li\n", COMMAND_STATUS_BITRATE,
getPlayerBitRate(), getPlayerTotalTime());
myfprintf(fp, "%s: %u:%i:%i\n", COMMAND_STATUS_AUDIO,
getPlayerSampleRate(), getPlayerBits(),
getPlayerChannels());
}
if((updateJobId = isUpdatingDB())) {
myfprintf(fp,"%s: %i\n",COMMAND_STATUS_UPDATING_DB,updateJobId);
if ((updateJobId = isUpdatingDB())) {
myfprintf(fp, "%s: %i\n", COMMAND_STATUS_UPDATING_DB,
updateJobId);
}
if(getPlayerError()!=PLAYER_ERROR_NOERROR) {
myfprintf(fp,"%s: %s\n",COMMAND_STATUS_ERROR,getPlayerErrorStr());
if (getPlayerError() != PLAYER_ERROR_NOERROR) {
myfprintf(fp, "%s: %s\n", COMMAND_STATUS_ERROR,
getPlayerErrorStr());
}
return 0;
}
static int handleKill(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleKill(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return COMMAND_RETURN_KILL;
}
static int handleClose(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleClose(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return COMMAND_RETURN_CLOSE;
}
static int handleAdd(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleAdd(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
char * path = argArray[1];
char *path = argArray[1];
if(isRemoteUrl(path)) return addToPlaylist(fp, path, 0);
if (isRemoteUrl(path))
return addToPlaylist(fp, path, 0);
return addAllIn(fp,path);
return addAllIn(fp, path);
}
static int handleAddId(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleAddId(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return addToPlaylist(fp, argArray[1], 1);
}
static int handleDelete(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleDelete(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int song;
char * test;
char *test;
song = strtol(argArray[1],&test,10);
if(*test!='\0') {
song = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"need a positive integer", NULL);
return -1;
}
return deleteFromPlaylist(fp,song);
return deleteFromPlaylist(fp, song);
}
static int handleDeleteId(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleDeleteId(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int id;
char * test;
char *test;
id = strtol(argArray[1],&test,10);
if(*test!='\0') {
id = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"need a positive integer", NULL);
return -1;
......@@ -342,75 +354,78 @@ static int handleDeleteId(FILE * fp, int * permission, int argArrayLength,
return deleteFromPlaylistById(fp, id);
}
static int handlePlaylist(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handlePlaylist(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return showPlaylist(fp);
}
static int handleShuffle(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleShuffle(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return shufflePlaylist(fp);
}
static int handleClear(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleClear(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return clearPlaylist(fp);
}
static int handleSave(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleSave(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return savePlaylist(fp,argArray[1]);
return savePlaylist(fp, argArray[1]);
}
static int handleLoad(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleLoad(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return loadPlaylist(fp,argArray[1]);
return loadPlaylist(fp, argArray[1]);
}
static int handleListPlaylist(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleListPlaylist(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return PlaylistInfo(fp,argArray[1],0);
return PlaylistInfo(fp, argArray[1], 0);
}
static int handleListPlaylistInfo(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleListPlaylistInfo(FILE * fp, int *permission,
int argArrayLength, char **argArray)
{
return PlaylistInfo(fp,argArray[1], 1);
return PlaylistInfo(fp, argArray[1], 1);
}
static int handleLsInfo(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleLsInfo(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
if(argArrayLength==1) {
if(printDirectoryInfo(fp,NULL)<0) return -1;
else return lsPlaylists(fp,"");
}
else {
if(printDirectoryInfo(fp,argArray[1])<0) return -1;
else return lsPlaylists(fp,argArray[1]);
if (argArrayLength == 1) {
if (printDirectoryInfo(fp, NULL) < 0)
return -1;
else
return lsPlaylists(fp, "");
} else {
if (printDirectoryInfo(fp, argArray[1]) < 0)
return -1;
else
return lsPlaylists(fp, argArray[1]);
}
}
static int handleRm(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleRm(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return deletePlaylist(fp,argArray[1]);
return deletePlaylist(fp, argArray[1]);
}
static int handlePlaylistChanges(FILE * fp, int * permission,
int argArrayLength, char ** argArray)
static int handlePlaylistChanges(FILE * fp, int *permission,
int argArrayLength, char **argArray)
{
unsigned long version;
char * test;
char *test;
version = strtoul(argArray[1], &test, 10);
if(*test!='\0') {
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG, "need a positive integer",
NULL);
return -1;
......@@ -418,14 +433,14 @@ static int handlePlaylistChanges(FILE * fp, int * permission,
return playlistChanges(fp, version);
}
static int handlePlaylistChangesPosId(FILE * fp, int * permission,
int argArrayLength, char ** argArray)
static int handlePlaylistChangesPosId(FILE * fp, int *permission,
int argArrayLength, char **argArray)
{
unsigned long version;
char * test;
char *test;
version = strtoul(argArray[1], &test, 10);
if(*test!='\0') {
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG, "need a positive integer",
NULL);
return -1;
......@@ -433,32 +448,32 @@ static int handlePlaylistChangesPosId(FILE * fp, int * permission,
return playlistChangesPosId(fp, version);
}
static int handlePlaylistInfo(FILE * fp, int * permission,
int argArrayLength, char ** argArray)
static int handlePlaylistInfo(FILE * fp, int *permission,
int argArrayLength, char **argArray)
{
int song = -1;
char * test;
char *test;
if(argArrayLength == 2) {
song = strtol(argArray[1],&test,10);
if(*test!='\0') {
if (argArrayLength == 2) {
song = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"need a positive integer", NULL);
return -1;
}
}
return playlistInfo(fp,song);
return playlistInfo(fp, song);
}
static int handlePlaylistId(FILE * fp, int * permission,
int argArrayLength, char ** argArray)
static int handlePlaylistId(FILE * fp, int *permission,
int argArrayLength, char **argArray)
{
int id = -1;
char * test;
char *test;
if(argArrayLength == 2) {
id = strtol(argArray[1],&test,10);
if(*test!='\0') {
if (argArrayLength == 2) {
id = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"need a positive integer", NULL);
return -1;
......@@ -467,16 +482,17 @@ static int handlePlaylistId(FILE * fp, int * permission,
return playlistId(fp, id);
}
static int handleFind(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleFind(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int ret;
LocateTagItem * items;
int numItems = newLocateTagItemArrayFromArgArray(argArray+1,
argArrayLength-1, &items);
LocateTagItem *items;
int numItems = newLocateTagItemArrayFromArgArray(argArray + 1,
argArrayLength - 1,
&items);
if(numItems <= 0) {
if (numItems <= 0) {
commandError(fp, ACK_ERROR_ARG, "incorrect arguments", NULL);
return -1;
}
......@@ -488,16 +504,17 @@ static int handleFind(FILE * fp, int * permission, int argArrayLength,
return ret;
}
static int handleSearch(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleSearch(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int ret;
LocateTagItem * items;
int numItems = newLocateTagItemArrayFromArgArray(argArray+1,
argArrayLength-1, &items);
LocateTagItem *items;
int numItems = newLocateTagItemArrayFromArgArray(argArray + 1,
argArrayLength - 1,
&items);
if(numItems <= 0) {
if (numItems <= 0) {
commandError(fp, ACK_ERROR_ARG, "incorrect arguments", NULL);
return -1;
}
......@@ -510,28 +527,30 @@ static int handleSearch(FILE * fp, int * permission, int argArrayLength,
}
static int listHandleUpdate(FILE * fp,
int * permission,
int *permission,
int argArrayLength,
char ** argArray,
ListNode * commandNode,
CommandEntry * cmd)
char **argArray,
ListNode * commandNode, CommandEntry * cmd)
{
static List * pathList = NULL;
CommandEntry * nextCmd = NULL;
ListNode * nextNode = commandNode->nextNode;;
static List *pathList = NULL;
CommandEntry *nextCmd = NULL;
ListNode *nextNode = commandNode->nextNode;;
if(!pathList) pathList = makeList(NULL, 1);
if (!pathList)
pathList = makeList(NULL, 1);
if(argArrayLength==2) insertInList(pathList,argArray[1],NULL);
else insertInList(pathList,"",NULL);
if (argArrayLength == 2)
insertInList(pathList, argArray[1], NULL);
else
insertInList(pathList, "", NULL);
if(nextNode) {
if (nextNode) {
nextCmd = getCommandEntryFromString((void *)nextNode->data,
permission);
}
if(cmd!=nextCmd) {
int ret = updateInit(fp,pathList);
if (cmd != nextCmd) {
int ret = updateInit(fp, pathList);
freeList(pathList);
pathList = NULL;
return ret;
......@@ -540,127 +559,128 @@ static int listHandleUpdate(FILE * fp,
return 0;
}
static int handleUpdate(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleUpdate(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
if(argArrayLength==2) {
if (argArrayLength == 2) {
int ret;
List * pathList = makeList(NULL, 1);
insertInList(pathList,argArray[1],NULL);
ret = updateInit(fp,pathList);
List *pathList = makeList(NULL, 1);
insertInList(pathList, argArray[1], NULL);
ret = updateInit(fp, pathList);
freeList(pathList);
return ret;
}
return updateInit(fp,NULL);
return updateInit(fp, NULL);
}
static int handleNext(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleNext(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return nextSongInPlaylist(fp);
}
static int handlePrevious(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handlePrevious(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return previousSongInPlaylist(fp);
}
static int handleListAll(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleListAll(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
char * directory = NULL;
char *directory = NULL;
if(argArrayLength==2) directory = argArray[1];
return printAllIn(fp,directory);
if (argArrayLength == 2)
directory = argArray[1];
return printAllIn(fp, directory);
}
static int handleVolume(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleVolume(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int change;
char * test;
char *test;
change = strtol(argArray[1],&test,10);
if(*test!='\0') {
change = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG, "need an integer", NULL);
return -1;
}
return changeVolumeLevel(fp,change,1);
return changeVolumeLevel(fp, change, 1);
}
static int handleSetVol(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleSetVol(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int level;
char * test;
char *test;
level = strtol(argArray[1],&test,10);
if(*test!='\0') {
level = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG, "need an integer", NULL);
return -1;
}
return changeVolumeLevel(fp,level,0);
return changeVolumeLevel(fp, level, 0);
}
static int handleRepeat(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleRepeat(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int status;
char * test;
char *test;
status = strtol(argArray[1],&test,10);
if(*test!='\0') {
status = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG, "need an integer", NULL);
return -1;
}
return setPlaylistRepeatStatus(fp,status);
return setPlaylistRepeatStatus(fp, status);
}
static int handleRandom(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleRandom(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int status;
char * test;
char *test;
status = strtol(argArray[1],&test,10);
if(*test!='\0') {
status = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG, "need an integer", NULL);
return -1;
}
return setPlaylistRandomStatus(fp,status);
return setPlaylistRandomStatus(fp, status);
}
static int handleStats(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleStats(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return printStats(fp);
}
static int handleClearError(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleClearError(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
clearPlayerError();
return 0;
}
static int handleList(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleList(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int numConditionals = 0;
LocateTagItem * conditionals = NULL;
LocateTagItem *conditionals = NULL;
int tagType = getLocateTagItemType(argArray[1]);
int ret;
if(tagType < 0) {
if (tagType < 0) {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not known", argArray[1]);
return -1;
}
/* for compatibility with < 0.12.0 */
if(argArrayLength==3) {
if(tagType != TAG_ITEM_ALBUM) {
if (argArrayLength == 3) {
if (tagType != TAG_ITEM_ALBUM) {
commandError(fp, ACK_ERROR_ARG,
"should be \"%s\" for 3 arguments",
mpdTagItemKeys[TAG_ITEM_ALBUM]);
......@@ -669,62 +689,64 @@ static int handleList(FILE * fp, int * permission, int argArrayLength,
conditionals = newLocateTagItem(mpdTagItemKeys[TAG_ITEM_ARTIST],
argArray[2]);
numConditionals = 1;
}
else {
numConditionals = newLocateTagItemArrayFromArgArray(argArray+2,
argArrayLength-2, &conditionals);
} else {
numConditionals =
newLocateTagItemArrayFromArgArray(argArray + 2,
argArrayLength - 2,
&conditionals);
if(numConditionals < 0) {
if (numConditionals < 0) {
commandError(fp, ACK_ERROR_ARG,
"not able to parse args", NULL);
return -1;
}
}
ret = listAllUniqueTags(fp, tagType, numConditionals,conditionals);
ret = listAllUniqueTags(fp, tagType, numConditionals, conditionals);
if(conditionals) freeLocateTagItemArray(numConditionals, conditionals);
if (conditionals)
freeLocateTagItemArray(numConditionals, conditionals);
return ret;
}
static int handleMove(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleMove(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int from;
int to;
char * test;
char *test;
from = strtol(argArray[1],&test,10);
if(*test!='\0') {
from = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[1]);
return -1;
}
to = strtol(argArray[2],&test,10);
if(*test!='\0') {
to = strtol(argArray[2], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[2]);
return -1;
}
return moveSongInPlaylist(fp,from,to);
return moveSongInPlaylist(fp, from, to);
}
static int handleMoveId(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleMoveId(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int id;
int to;
char * test;
char *test;
id = strtol(argArray[1],&test,10);
if(*test!='\0') {
id = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[1]);
return -1;
}
to = strtol(argArray[2],&test,10);
if(*test!='\0') {
to = strtol(argArray[2], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[2]);
return -1;
......@@ -732,43 +754,43 @@ static int handleMoveId(FILE * fp, int * permission, int argArrayLength,
return moveSongInPlaylistById(fp, id, to);
}
static int handleSwap(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleSwap(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int song1;
int song2;
char * test;
char *test;
song1 = strtol(argArray[1],&test,10);
if(*test!='\0') {
song1 = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[1]);
return -1;
}
song2 = strtol(argArray[2],&test,10);
if(*test!='\0') {
song2 = strtol(argArray[2], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG, "\"%s\" is not a integer",
argArray[2]);
return -1;
}
return swapSongsInPlaylist(fp,song1,song2);
return swapSongsInPlaylist(fp, song1, song2);
}
static int handleSwapId(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleSwapId(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int id1;
int id2;
char * test;
char *test;
id1 = strtol(argArray[1],&test,10);
if(*test!='\0') {
id1 = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[1]);
return -1;
}
id2 = strtol(argArray[2],&test,10);
if(*test!='\0') {
id2 = strtol(argArray[2], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG, "\"%s\" is not a integer",
argArray[2]);
return -1;
......@@ -776,43 +798,43 @@ static int handleSwapId(FILE * fp, int * permission, int argArrayLength,
return swapSongsInPlaylistById(fp, id1, id2);
}
static int handleSeek(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleSeek(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int song;
int time;
char * test;
char *test;
song = strtol(argArray[1],&test,10);
if(*test!='\0') {
song = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[1]);
return -1;
}
time = strtol(argArray[2],&test,10);
if(*test!='\0') {
time = strtol(argArray[2], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[2]);
return -1;
}
return seekSongInPlaylist(fp,song,time);
return seekSongInPlaylist(fp, song, time);
}
static int handleSeekId(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleSeekId(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int id;
int time;
char * test;
char *test;
id = strtol(argArray[1],&test,10);
if(*test!='\0') {
id = strtol(argArray[1], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[1]);
return -1;
}
time = strtol(argArray[2],&test,10);
if(*test!='\0') {
time = strtol(argArray[2], &test, 10);
if (*test != '\0') {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer", argArray[2]);
return -1;
......@@ -820,40 +842,42 @@ static int handleSeekId(FILE * fp, int * permission, int argArrayLength,
return seekSongInPlaylistById(fp, id, time);
}
static int handleListAllInfo(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleListAllInfo(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
char * directory = NULL;
char *directory = NULL;
if(argArrayLength==2) directory = argArray[1];
return printInfoForAllIn(fp,directory);
if (argArrayLength == 2)
directory = argArray[1];
return printInfoForAllIn(fp, directory);
}
static int handlePing(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handlePing(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
return 0;
}
static int handlePassword(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handlePassword(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
if(getPermissionFromPassword(argArray[1],permission)<0) {
commandError(fp, ACK_ERROR_PASSWORD, "incorrect password", NULL);
if (getPermissionFromPassword(argArray[1], permission) < 0) {
commandError(fp, ACK_ERROR_PASSWORD, "incorrect password",
NULL);
return -1;
}
return 0;
}
static int handleCrossfade(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleCrossfade(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int time;
char * test;
char *test;
time = strtol(argArray[1],&test,10);
if(*test!='\0' || time<0) {
time = strtol(argArray[1], &test, 10);
if (*test != '\0' || time < 0) {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer >= 0", argArray[1]);
return -1;
......@@ -864,14 +888,14 @@ static int handleCrossfade(FILE * fp, int * permission, int argArrayLength,
return 0;
}
static int handleEnableDevice(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleEnableDevice(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
int device;
char * test;
char *test;
device = strtol(argArray[1],&test,10);
if(*test!='\0' || device<0) {
device = strtol(argArray[1], &test, 10);
if (*test != '\0' || device < 0) {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer >= 0", argArray[1]);
return -1;
......@@ -880,14 +904,14 @@ static int handleEnableDevice(FILE * fp, int * permission, int argArrayLength,
return enableAudioDevice(fp, device);
}
static int handleDisableDevice(FILE * fp, int * permission,
int argArrayLength, char ** argArray)
static int handleDisableDevice(FILE * fp, int *permission,
int argArrayLength, char **argArray)
{
int device;
char * test;
char *test;
device = strtol(argArray[1],&test,10);
if(*test!='\0' || device<0) {
device = strtol(argArray[1], &test, 10);
if (*test != '\0' || device < 0) {
commandError(fp, ACK_ERROR_ARG,
"\"%s\" is not a integer >= 0", argArray[1]);
return -1;
......@@ -896,8 +920,8 @@ static int handleDisableDevice(FILE * fp, int * permission,
return disableAudioDevice(fp, device);
}
static int handleDevices(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleDevices(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
printAudioDevices(fp);
......@@ -905,15 +929,15 @@ static int handleDevices(FILE * fp, int * permission, int argArrayLength,
}
/* don't be fooled, this is the command handler for "commands" command */
static int handleCommands(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleCommands(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
ListNode * node = commandList->firstNode;
CommandEntry * cmd;
ListNode *node = commandList->firstNode;
CommandEntry *cmd;
while(node != NULL) {
while (node != NULL) {
cmd = (CommandEntry *) node->data;
if(cmd->reqPermission == (*permission & cmd->reqPermission)) {
if (cmd->reqPermission == (*permission & cmd->reqPermission)) {
myfprintf(fp, "command: %s\n", cmd->cmd);
}
......@@ -923,16 +947,16 @@ static int handleCommands(FILE * fp, int * permission, int argArrayLength,
return 0;
}
static int handleNotcommands(FILE * fp, int * permission, int argArrayLength,
char ** argArray)
static int handleNotcommands(FILE * fp, int *permission, int argArrayLength,
char **argArray)
{
ListNode * node = commandList->firstNode;
CommandEntry * cmd;
ListNode *node = commandList->firstNode;
CommandEntry *cmd;
while(node != NULL) {
while (node != NULL) {
cmd = (CommandEntry *) node->data;
if(cmd->reqPermission != (*permission & cmd->reqPermission)) {
if (cmd->reqPermission != (*permission & cmd->reqPermission)) {
myfprintf(fp, "command: %s\n", cmd->cmd);
}
......@@ -942,79 +966,108 @@ static int handleNotcommands(FILE * fp, int * permission, int argArrayLength,
return 0;
}
void initCommands(void) {
void initCommands(void)
{
commandList = makeList(free, 1);
addCommand(COMMAND_PLAY ,PERMISSION_CONTROL, 0, 1,handlePlay,NULL);
addCommand(COMMAND_PLAYID ,PERMISSION_CONTROL, 0, 1,handlePlayId,NULL);
addCommand(COMMAND_STOP ,PERMISSION_CONTROL, 0, 0,handleStop,NULL);
addCommand(COMMAND_CURRENTSONG ,PERMISSION_READ , 0, 0,handleCurrentSong,NULL);
addCommand(COMMAND_PAUSE ,PERMISSION_CONTROL, 0, 1,handlePause,NULL);
addCommand(COMMAND_STATUS ,PERMISSION_READ, 0, 0,commandStatus,NULL);
addCommand(COMMAND_KILL ,PERMISSION_ADMIN, -1,-1,handleKill,NULL);
addCommand(COMMAND_CLOSE ,0, -1,-1,handleClose,NULL);
addCommand(COMMAND_ADD ,PERMISSION_ADD, 1, 1,handleAdd,NULL);
addCommand(COMMAND_ADDID ,PERMISSION_ADD, 1, 1,handleAddId,NULL);
addCommand(COMMAND_DELETE ,PERMISSION_CONTROL, 1, 1,handleDelete,NULL);
addCommand(COMMAND_DELETEID ,PERMISSION_CONTROL, 1, 1,handleDeleteId,NULL);
addCommand(COMMAND_PLAYLIST ,PERMISSION_READ, 0, 0,handlePlaylist,NULL);
addCommand(COMMAND_PLAYLISTID ,PERMISSION_READ, 0, 1,handlePlaylistId,NULL);
addCommand(COMMAND_SHUFFLE ,PERMISSION_CONTROL, 0, 0,handleShuffle,NULL);
addCommand(COMMAND_CLEAR ,PERMISSION_CONTROL, 0, 0,handleClear,NULL);
addCommand(COMMAND_SAVE ,PERMISSION_CONTROL, 1, 1,handleSave,NULL);
addCommand(COMMAND_LOAD ,PERMISSION_ADD, 1, 1,handleLoad,NULL);
addCommand(COMMAND_LISTPLAYLIST,PERMISSION_READ, 1, 1,handleListPlaylist,NULL);
addCommand(COMMAND_LISTPLAYLISTINFO,PERMISSION_READ, 1, 1,handleListPlaylistInfo,NULL);
addCommand(COMMAND_LSINFO ,PERMISSION_READ, 0, 1,handleLsInfo,NULL);
addCommand(COMMAND_RM ,PERMISSION_CONTROL, 1, 1,handleRm,NULL);
addCommand(COMMAND_PLAYLISTINFO,PERMISSION_READ, 0, 1,handlePlaylistInfo,NULL);
addCommand(COMMAND_FIND ,PERMISSION_READ, 2,-1,handleFind,NULL);
addCommand(COMMAND_SEARCH ,PERMISSION_READ, 2,-1,handleSearch,NULL);
addCommand(COMMAND_UPDATE ,PERMISSION_ADMIN, 0, 1,handleUpdate,listHandleUpdate);
addCommand(COMMAND_NEXT ,PERMISSION_CONTROL, 0, 0,handleNext,NULL);
addCommand(COMMAND_PREVIOUS ,PERMISSION_CONTROL, 0, 0,handlePrevious,NULL);
addCommand(COMMAND_LISTALL ,PERMISSION_READ, 0, 1,handleListAll,NULL);
addCommand(COMMAND_VOLUME ,PERMISSION_CONTROL, 1, 1,handleVolume,NULL);
addCommand(COMMAND_REPEAT ,PERMISSION_CONTROL, 1, 1,handleRepeat,NULL);
addCommand(COMMAND_RANDOM ,PERMISSION_CONTROL, 1, 1,handleRandom,NULL);
addCommand(COMMAND_STATS ,PERMISSION_READ, 0, 0,handleStats,NULL);
addCommand(COMMAND_CLEAR_ERROR ,PERMISSION_CONTROL, 0, 0,handleClearError,NULL);
addCommand(COMMAND_LIST ,PERMISSION_READ, 1,-1,handleList,NULL);
addCommand(COMMAND_MOVE ,PERMISSION_CONTROL, 2, 2,handleMove,NULL);
addCommand(COMMAND_MOVEID ,PERMISSION_CONTROL, 2, 2,handleMoveId,NULL);
addCommand(COMMAND_SWAP ,PERMISSION_CONTROL, 2, 2,handleSwap,NULL);
addCommand(COMMAND_SWAPID ,PERMISSION_CONTROL, 2, 2,handleSwapId,NULL);
addCommand(COMMAND_SEEK ,PERMISSION_CONTROL, 2, 2,handleSeek,NULL);
addCommand(COMMAND_SEEKID ,PERMISSION_CONTROL, 2, 2,handleSeekId,NULL);
addCommand(COMMAND_LISTALLINFO ,PERMISSION_READ, 0, 1,handleListAllInfo,NULL);
addCommand(COMMAND_PING ,0, 0, 0,handlePing,NULL);
addCommand(COMMAND_SETVOL ,PERMISSION_CONTROL, 1, 1,handleSetVol,NULL);
addCommand(COMMAND_PASSWORD ,0, 1, 1,handlePassword,NULL);
addCommand(COMMAND_CROSSFADE ,PERMISSION_CONTROL, 1, 1,handleCrossfade,NULL);
addCommand(COMMAND_URL_HANDLERS,PERMISSION_READ, 0, 0,handleUrlHandlers,NULL);
addCommand(COMMAND_PLCHANGES ,PERMISSION_READ, 1, 1,handlePlaylistChanges,NULL);
addCommand(COMMAND_PLCHANGESPOSID ,PERMISSION_READ, 1, 1,handlePlaylistChangesPosId,NULL);
addCommand(COMMAND_ENABLE_DEV ,PERMISSION_ADMIN, 1, 1,handleEnableDevice,NULL);
addCommand(COMMAND_DISABLE_DEV ,PERMISSION_ADMIN, 1, 1,handleDisableDevice,NULL);
addCommand(COMMAND_DEVICES ,PERMISSION_READ, 0, 0,handleDevices,NULL);
addCommand(COMMAND_COMMANDS ,0, 0, 0,handleCommands,NULL);
addCommand(COMMAND_NOTCOMMANDS ,0, 0, 0,handleNotcommands,NULL);
addCommand(COMMAND_PLAY, PERMISSION_CONTROL, 0, 1, handlePlay, NULL);
addCommand(COMMAND_PLAYID, PERMISSION_CONTROL, 0, 1, handlePlayId,
NULL);
addCommand(COMMAND_STOP, PERMISSION_CONTROL, 0, 0, handleStop, NULL);
addCommand(COMMAND_CURRENTSONG, PERMISSION_READ, 0, 0,
handleCurrentSong, NULL);
addCommand(COMMAND_PAUSE, PERMISSION_CONTROL, 0, 1, handlePause, NULL);
addCommand(COMMAND_STATUS, PERMISSION_READ, 0, 0, commandStatus, NULL);
addCommand(COMMAND_KILL, PERMISSION_ADMIN, -1, -1, handleKill, NULL);
addCommand(COMMAND_CLOSE, 0, -1, -1, handleClose, NULL);
addCommand(COMMAND_ADD, PERMISSION_ADD, 1, 1, handleAdd, NULL);
addCommand(COMMAND_ADDID, PERMISSION_ADD, 1, 1, handleAddId, NULL);
addCommand(COMMAND_DELETE, PERMISSION_CONTROL, 1, 1, handleDelete,
NULL);
addCommand(COMMAND_DELETEID, PERMISSION_CONTROL, 1, 1, handleDeleteId,
NULL);
addCommand(COMMAND_PLAYLIST, PERMISSION_READ, 0, 0, handlePlaylist,
NULL);
addCommand(COMMAND_PLAYLISTID, PERMISSION_READ, 0, 1, handlePlaylistId,
NULL);
addCommand(COMMAND_SHUFFLE, PERMISSION_CONTROL, 0, 0, handleShuffle,
NULL);
addCommand(COMMAND_CLEAR, PERMISSION_CONTROL, 0, 0, handleClear, NULL);
addCommand(COMMAND_SAVE, PERMISSION_CONTROL, 1, 1, handleSave, NULL);
addCommand(COMMAND_LOAD, PERMISSION_ADD, 1, 1, handleLoad, NULL);
addCommand(COMMAND_LISTPLAYLIST, PERMISSION_READ, 1, 1,
handleListPlaylist, NULL);
addCommand(COMMAND_LISTPLAYLISTINFO, PERMISSION_READ, 1, 1,
handleListPlaylistInfo, NULL);
addCommand(COMMAND_LSINFO, PERMISSION_READ, 0, 1, handleLsInfo, NULL);
addCommand(COMMAND_RM, PERMISSION_CONTROL, 1, 1, handleRm, NULL);
addCommand(COMMAND_PLAYLISTINFO, PERMISSION_READ, 0, 1,
handlePlaylistInfo, NULL);
addCommand(COMMAND_FIND, PERMISSION_READ, 2, -1, handleFind, NULL);
addCommand(COMMAND_SEARCH, PERMISSION_READ, 2, -1, handleSearch, NULL);
addCommand(COMMAND_UPDATE, PERMISSION_ADMIN, 0, 1, handleUpdate,
listHandleUpdate);
addCommand(COMMAND_NEXT, PERMISSION_CONTROL, 0, 0, handleNext, NULL);
addCommand(COMMAND_PREVIOUS, PERMISSION_CONTROL, 0, 0, handlePrevious,
NULL);
addCommand(COMMAND_LISTALL, PERMISSION_READ, 0, 1, handleListAll, NULL);
addCommand(COMMAND_VOLUME, PERMISSION_CONTROL, 1, 1, handleVolume,
NULL);
addCommand(COMMAND_REPEAT, PERMISSION_CONTROL, 1, 1, handleRepeat,
NULL);
addCommand(COMMAND_RANDOM, PERMISSION_CONTROL, 1, 1, handleRandom,
NULL);
addCommand(COMMAND_STATS, PERMISSION_READ, 0, 0, handleStats, NULL);
addCommand(COMMAND_CLEAR_ERROR, PERMISSION_CONTROL, 0, 0,
handleClearError, NULL);
addCommand(COMMAND_LIST, PERMISSION_READ, 1, -1, handleList, NULL);
addCommand(COMMAND_MOVE, PERMISSION_CONTROL, 2, 2, handleMove, NULL);
addCommand(COMMAND_MOVEID, PERMISSION_CONTROL, 2, 2, handleMoveId,
NULL);
addCommand(COMMAND_SWAP, PERMISSION_CONTROL, 2, 2, handleSwap, NULL);
addCommand(COMMAND_SWAPID, PERMISSION_CONTROL, 2, 2, handleSwapId,
NULL);
addCommand(COMMAND_SEEK, PERMISSION_CONTROL, 2, 2, handleSeek, NULL);
addCommand(COMMAND_SEEKID, PERMISSION_CONTROL, 2, 2, handleSeekId,
NULL);
addCommand(COMMAND_LISTALLINFO, PERMISSION_READ, 0, 1,
handleListAllInfo, NULL);
addCommand(COMMAND_PING, 0, 0, 0, handlePing, NULL);
addCommand(COMMAND_SETVOL, PERMISSION_CONTROL, 1, 1, handleSetVol,
NULL);
addCommand(COMMAND_PASSWORD, 0, 1, 1, handlePassword, NULL);
addCommand(COMMAND_CROSSFADE, PERMISSION_CONTROL, 1, 1, handleCrossfade,
NULL);
addCommand(COMMAND_URL_HANDLERS, PERMISSION_READ, 0, 0,
handleUrlHandlers, NULL);
addCommand(COMMAND_PLCHANGES, PERMISSION_READ, 1, 1,
handlePlaylistChanges, NULL);
addCommand(COMMAND_PLCHANGESPOSID, PERMISSION_READ, 1, 1,
handlePlaylistChangesPosId, NULL);
addCommand(COMMAND_ENABLE_DEV, PERMISSION_ADMIN, 1, 1,
handleEnableDevice, NULL);
addCommand(COMMAND_DISABLE_DEV, PERMISSION_ADMIN, 1, 1,
handleDisableDevice, NULL);
addCommand(COMMAND_DEVICES, PERMISSION_READ, 0, 0, handleDevices, NULL);
addCommand(COMMAND_COMMANDS, 0, 0, 0, handleCommands, NULL);
addCommand(COMMAND_NOTCOMMANDS, 0, 0, 0, handleNotcommands, NULL);
sortList(commandList);
}
void finishCommands(void) {
void finishCommands(void)
{
freeList(commandList);
}
static int checkArgcAndPermission(CommandEntry * cmd, FILE *fp,
int permission, int argc, char** argArray)
static int checkArgcAndPermission(CommandEntry * cmd, FILE * fp,
int permission, int argc, char **argArray)
{
int min = cmd->min + 1;
int max = cmd->max + 1;
if (cmd->reqPermission != (permission & cmd->reqPermission)) {
if(fp) {
if (fp) {
commandError(fp, ACK_ERROR_PERMISSION,
"you don't have permission for \"%s\"",
cmd->cmd);
......@@ -1022,47 +1075,50 @@ static int checkArgcAndPermission(CommandEntry * cmd, FILE *fp,
return -1;
}
if (min == 0) return 0;
if (min == 0)
return 0;
if (min == max && max != argc) {
if(fp) {
if (fp) {
commandError(fp, ACK_ERROR_ARG,
"wrong number of arguments for \"%s\"",
argArray[0]);
}
return -1;
}
else if (argc < min) {
if(fp) {
} else if (argc < min) {
if (fp) {
commandError(fp, ACK_ERROR_ARG,
"too few arguments for \"%s\"",
argArray[0]);
}
return -1;
}
else if (argc > max && max /* != 0 */) {
if(fp) {
} else if (argc > max && max /* != 0 */ ) {
if (fp) {
commandError(fp, ACK_ERROR_ARG,
"too many arguments for \"%s\"",
argArray[0]);
}
return -1;
}
else return 0;
} else
return 0;
}
static CommandEntry * getCommandEntryAndCheckArgcAndPermission(FILE * fp,
int * permission, int argArrayLength, char ** argArray)
static CommandEntry *getCommandEntryAndCheckArgcAndPermission(FILE * fp,
int *permission,
int
argArrayLength,
char **argArray)
{
static char unknown[] = "";
CommandEntry * cmd;
CommandEntry *cmd;
current_command = unknown;
if(argArrayLength == 0) return NULL;
if (argArrayLength == 0)
return NULL;
if(!findInList(commandList, argArray[0],(void *)&cmd)) {
if(fp) {
if (!findInList(commandList, argArray[0], (void *)&cmd)) {
if (fp) {
commandError(fp, ACK_ERROR_UNKNOWN,
"unknown command \"%s\"", argArray[0]);
}
......@@ -1071,82 +1127,85 @@ static CommandEntry * getCommandEntryAndCheckArgcAndPermission(FILE * fp,
current_command = cmd->cmd;
if(checkArgcAndPermission(cmd, fp, *permission, argArrayLength,
argArray) < 0)
{
if (checkArgcAndPermission(cmd, fp, *permission, argArrayLength,
argArray) < 0) {
return NULL;
}
return cmd;
}
static CommandEntry * getCommandEntryFromString(char * string, int * permission) {
CommandEntry * cmd = NULL;
char ** argArray;
int argArrayLength = buffer2array(string,&argArray);
static CommandEntry *getCommandEntryFromString(char *string, int *permission)
{
CommandEntry *cmd = NULL;
char **argArray;
int argArrayLength = buffer2array(string, &argArray);
if(0==argArrayLength) return NULL;
if (0 == argArrayLength)
return NULL;
cmd = getCommandEntryAndCheckArgcAndPermission(NULL,permission,
argArrayLength,argArray);
freeArgArray(argArray,argArrayLength);
cmd = getCommandEntryAndCheckArgcAndPermission(NULL, permission,
argArrayLength,
argArray);
freeArgArray(argArray, argArrayLength);
return cmd;
}
static int processCommandInternal(FILE * fp, int * permission,
char * commandString,
ListNode * commandNode)
static int processCommandInternal(FILE * fp, int *permission,
char *commandString, ListNode * commandNode)
{
int argArrayLength;
char ** argArray;
CommandEntry * cmd;
char **argArray;
CommandEntry *cmd;
int ret = -1;
argArrayLength = buffer2array(commandString,&argArray);
argArrayLength = buffer2array(commandString, &argArray);
if(argArrayLength == 0) return 0;
if (argArrayLength == 0)
return 0;
if((cmd = getCommandEntryAndCheckArgcAndPermission(fp,permission,
argArrayLength,argArray)))
{
if(NULL==commandNode || NULL==cmd->listHandler) {
if ((cmd = getCommandEntryAndCheckArgcAndPermission(fp, permission,
argArrayLength,
argArray))) {
if (NULL == commandNode || NULL == cmd->listHandler) {
ret = cmd->handler(fp, permission, argArrayLength,
argArray);
}
else {
} else {
ret = cmd->listHandler(fp, permission, argArrayLength,
argArray, commandNode, cmd);
}
}
freeArgArray(argArray,argArrayLength);
freeArgArray(argArray, argArrayLength);
current_command = NULL;
return ret;
}
int processListOfCommands(FILE * fp, int * permission, int * expired,
int processListOfCommands(FILE * fp, int *permission, int *expired,
int listOK, List * list)
{
ListNode * node = list->firstNode;
ListNode * tempNode;
ListNode *node = list->firstNode;
ListNode *tempNode;
int ret = 0;
command_listNum = 0;
while(node!=NULL) {
while (node != NULL) {
DEBUG("processListOfCommands: process command \"%s\"\n",
node->data);
ret = processCommandInternal(fp,permission,(char *)node->data,
ret = processCommandInternal(fp, permission, (char *)node->data,
node);
DEBUG("processListOfCommands: command returned %i\n",ret);
DEBUG("processListOfCommands: command returned %i\n", ret);
tempNode = node->nextNode;
deleteNodeFromList(list,node);
deleteNodeFromList(list, node);
node = tempNode;
if(ret!=0 || (*expired)!=0) node = NULL;
else if(listOK) myfprintf(fp, "list_OK\n");
if (ret != 0 || (*expired) != 0)
node = NULL;
else if (listOK)
myfprintf(fp, "list_OK\n");
command_listNum++;
}
......@@ -1155,6 +1214,7 @@ int processListOfCommands(FILE * fp, int * permission, int * expired,
return ret;
}
int processCommand(FILE * fp, int * permission, char * commandString) {
return processCommandInternal(fp,permission,commandString,NULL);
int processCommand(FILE * fp, int *permission, char *commandString)
{
return processCommandInternal(fp, permission, commandString, NULL);
}
......@@ -32,13 +32,13 @@
#define COMMAND_RETURN_CLOSE 20
#define COMMAND_MASTER_READY 30
extern char * current_command;
extern char *current_command;
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 processCommand(FILE * fp, int * permission, char * commandString);
int processCommand(FILE * fp, int *permission, char *commandString);
void initCommands();
......
......@@ -44,16 +44,19 @@
typedef struct _configEntry {
unsigned char mask;
List * configParamList;
List *configParamList;
} ConfigEntry;
static List * configEntriesList = NULL;
static List *configEntriesList = NULL;
static ConfigParam * newConfigParam(char * value, int line) {
ConfigParam * ret = malloc(sizeof(ConfigParam));
static ConfigParam *newConfigParam(char *value, int line)
{
ConfigParam *ret = malloc(sizeof(ConfigParam));
if(!value) ret->value = NULL;
else ret->value = strdup(value);
if (!value)
ret->value = NULL;
else
ret->value = strdup(value);
ret->line = line;
......@@ -63,46 +66,55 @@ static ConfigParam * newConfigParam(char * value, int line) {
return ret;
}
static void freeConfigParam(ConfigParam * param) {
static void freeConfigParam(ConfigParam * param)
{
int i;
if(param->value) free(param->value);
if (param->value)
free(param->value);
for(i=0; i<param->numberOfBlockParams; i++) {
if(param->blockParams[i].name) {
for (i = 0; i < param->numberOfBlockParams; i++) {
if (param->blockParams[i].name) {
free(param->blockParams[i].name);
}
if(param->blockParams[i].value) {
if (param->blockParams[i].value) {
free(param->blockParams[i].value);
}
}
if(param->numberOfBlockParams) free(param->blockParams);
if (param->numberOfBlockParams)
free(param->blockParams);
free(param);
}
ConfigEntry * newConfigEntry(int repeatable, int block) {
ConfigEntry * ret = malloc(sizeof(ConfigEntry));
ConfigEntry *newConfigEntry(int repeatable, int block)
{
ConfigEntry *ret = malloc(sizeof(ConfigEntry));
ret->mask = 0;
ret->configParamList = makeList((ListFreeDataFunc *)freeConfigParam, 1);
ret->configParamList =
makeList((ListFreeDataFunc *) freeConfigParam, 1);
if(repeatable) ret->mask |= CONF_REPEATABLE_MASK;
if(block) ret->mask |= CONF_BLOCK_MASK;
if (repeatable)
ret->mask |= CONF_REPEATABLE_MASK;
if (block)
ret->mask |= CONF_BLOCK_MASK;
return ret;
}
void freeConfigEntry(ConfigEntry * entry) {
void freeConfigEntry(ConfigEntry * entry)
{
freeList(entry->configParamList);
free(entry);
}
static void registerConfigParam(char * name, int repeatable, int block) {
ConfigEntry * entry;
static void registerConfigParam(char *name, int repeatable, int block)
{
ConfigEntry *entry;
if(findInList(configEntriesList, name, NULL)) {
if (findInList(configEntriesList, name, NULL)) {
ERROR("config parameter \"%s\" already registered\n", name);
exit(EXIT_FAILURE);
}
......@@ -112,12 +124,14 @@ static void registerConfigParam(char * name, int repeatable, int block) {
insertInList(configEntriesList, name, entry);
}
void finishConf(void) {
void finishConf(void)
{
freeList(configEntriesList);
}
void initConf(void) {
configEntriesList = makeList((ListFreeDataFunc *)freeConfigEntry, 1);
void initConf(void)
{
configEntriesList = makeList((ListFreeDataFunc *) freeConfigEntry, 1);
/* registerConfigParam(name, repeatable, block); */
registerConfigParam(CONF_PORT, 0, 0);
......@@ -159,61 +173,63 @@ void initConf(void) {
registerConfigParam(CONF_ID3V1_ENCODING, 0, 0);
}
static void addBlockParam(ConfigParam * param, char * name, char * value,
static void addBlockParam(ConfigParam * param, char *name, char *value,
int line)
{
param->numberOfBlockParams++;
param->blockParams = realloc(param->blockParams,
param->numberOfBlockParams*sizeof(BlockParam));
param->numberOfBlockParams *
sizeof(BlockParam));
param->blockParams[param->numberOfBlockParams-1].name = strdup(name);
param->blockParams[param->numberOfBlockParams-1].value = strdup(value);
param->blockParams[param->numberOfBlockParams-1].line = line;
param->blockParams[param->numberOfBlockParams - 1].name = strdup(name);
param->blockParams[param->numberOfBlockParams - 1].value =
strdup(value);
param->blockParams[param->numberOfBlockParams - 1].line = line;
}
static ConfigParam * readConfigBlock(FILE * fp, int * count, char * string) {
ConfigParam * ret = newConfigParam(NULL, *count);
static ConfigParam *readConfigBlock(FILE * fp, int *count, char *string)
{
ConfigParam *ret = newConfigParam(NULL, *count);
char ** array;
char **array;
int i;
int numberOfArgs;
int argsMinusComment;
while(myFgets(string, MAX_STRING_SIZE ,fp)) {
while (myFgets(string, MAX_STRING_SIZE, fp)) {
(*count)++;
numberOfArgs = buffer2array(string, &array);
for(i=0; i<numberOfArgs; i++) {
if(array[i][0] == CONF_COMMENT) break;
for (i = 0; i < numberOfArgs; i++) {
if (array[i][0] == CONF_COMMENT)
break;
}
argsMinusComment = i;
if(0 == argsMinusComment) {
if (0 == argsMinusComment) {
freeArgArray(array, numberOfArgs);
continue;
}
if(1 == argsMinusComment &&
0 == strcmp(array[0], CONF_BLOCK_END))
{
if (1 == argsMinusComment &&
0 == strcmp(array[0], CONF_BLOCK_END)) {
freeArgArray(array, numberOfArgs);
break;
}
if(2 != argsMinusComment) {
if (2 != argsMinusComment) {
ERROR("improperly formatted config file at line %i:"
" %s\n", *count, string);
exit(EXIT_FAILURE);
}
if(0 == strcmp(array[0], CONF_BLOCK_BEGIN) ||
if (0 == strcmp(array[0], CONF_BLOCK_BEGIN) ||
0 == strcmp(array[1], CONF_BLOCK_BEGIN) ||
0 == strcmp(array[0], CONF_BLOCK_END) ||
0 == strcmp(array[1], CONF_BLOCK_END))
{
0 == strcmp(array[1], CONF_BLOCK_END)) {
ERROR("improperly formatted config file at line %i:"
" %s\n", count, string);
ERROR("in block begining at line %i\n", ret->line);
......@@ -228,47 +244,49 @@ static ConfigParam * readConfigBlock(FILE * fp, int * count, char * string) {
return ret;
}
void readConf(char * file) {
FILE * fp;
char string[MAX_STRING_SIZE+1];
char ** array;
void readConf(char *file)
{
FILE *fp;
char string[MAX_STRING_SIZE + 1];
char **array;
int i;
int numberOfArgs;
int argsMinusComment;
int count = 0;
ConfigEntry * entry;
void * voidPtr;
ConfigParam * param;
ConfigEntry *entry;
void *voidPtr;
ConfigParam *param;
if(!(fp=fopen(file,"r"))) {
if (!(fp = fopen(file, "r"))) {
ERROR("problems opening file %s for reading: %s\n", file,
strerror(errno));
exit(EXIT_FAILURE);
}
while(myFgets(string, MAX_STRING_SIZE, fp)) {
while (myFgets(string, MAX_STRING_SIZE, fp)) {
count++;
numberOfArgs = buffer2array(string, &array);
for(i=0; i<numberOfArgs; i++) {
if(array[i][0] == CONF_COMMENT) break;
for (i = 0; i < numberOfArgs; i++) {
if (array[i][0] == CONF_COMMENT)
break;
}
argsMinusComment = i;
if(0 == argsMinusComment) {
if (0 == argsMinusComment) {
freeArgArray(array, numberOfArgs);
continue;
}
if(2 != argsMinusComment) {
if (2 != argsMinusComment) {
ERROR("improperly formatted config file at line %i:"
" %s\n", count, string);
exit(EXIT_FAILURE);
}
if(!findInList(configEntriesList, array[0], &voidPtr)) {
if (!findInList(configEntriesList, array[0], &voidPtr)) {
ERROR("unrecognized parameter in config file at line "
"%i: %s\n", count, string);
exit(EXIT_FAILURE);
......@@ -276,25 +294,25 @@ void readConf(char * file) {
entry = (ConfigEntry *) voidPtr;
if( !(entry->mask & CONF_REPEATABLE_MASK) &&
entry->configParamList->numberOfNodes)
{
if (!(entry->mask & CONF_REPEATABLE_MASK) &&
entry->configParamList->numberOfNodes) {
param = entry->configParamList->firstNode->data;
ERROR("config parameter \"%s\" is first defined on line "
"%i and redefined on line %i\n",
array[0], param->line, count);
ERROR
("config parameter \"%s\" is first defined on line "
"%i and redefined on line %i\n", array[0],
param->line, count);
exit(EXIT_FAILURE);
}
if(entry->mask & CONF_BLOCK_MASK) {
if(0 != strcmp(array[1], CONF_BLOCK_BEGIN)) {
if (entry->mask & CONF_BLOCK_MASK) {
if (0 != strcmp(array[1], CONF_BLOCK_BEGIN)) {
ERROR("improperly formatted config file at "
"line %i: %s\n", count, string);
exit(EXIT_FAILURE);
}
param = readConfigBlock(fp, &count, string);
}
else param = newConfigParam(array[1], count);
} else
param = newConfigParam(array[1], count);
insertInListWithoutKey(entry->configParamList, param);
......@@ -303,120 +321,129 @@ void readConf(char * file) {
fclose(fp);
}
ConfigParam * getNextConfigParam(char * name, ConfigParam * last) {
void * voidPtr;
ConfigEntry * entry;
ListNode * node;
ConfigParam * param;
ConfigParam *getNextConfigParam(char *name, ConfigParam * last)
{
void *voidPtr;
ConfigEntry *entry;
ListNode *node;
ConfigParam *param;
if(!findInList(configEntriesList, name, &voidPtr)) return NULL;
if (!findInList(configEntriesList, name, &voidPtr))
return NULL;
entry = voidPtr;
node = entry->configParamList->firstNode;
if(last) {
while(node!=NULL) {
if (last) {
while (node != NULL) {
param = node->data;
node = node->nextNode;
if(param == last) break;
if (param == last)
break;
}
}
if(node == NULL) return NULL;
if (node == NULL)
return NULL;
param = node->data;
return param;
}
char * getConfigParamValue(char * name) {
ConfigParam * param = getConfigParam(name);
char *getConfigParamValue(char *name)
{
ConfigParam *param = getConfigParam(name);
if(!param) return NULL;
if (!param)
return NULL;
return param->value;
}
BlockParam * getBlockParam(ConfigParam * param, char * name) {
BlockParam * ret = NULL;
BlockParam *getBlockParam(ConfigParam * param, char *name)
{
BlockParam *ret = NULL;
int i;
for(i = 0; i < param->numberOfBlockParams; i++) {
if(0 == strcmp(name, param->blockParams[i].name)) {
if(ret) {
for (i = 0; i < param->numberOfBlockParams; i++) {
if (0 == strcmp(name, param->blockParams[i].name)) {
if (ret) {
ERROR("\"%s\" first defined on line %i, and "
"redefined on line %i\n", name,
ret->line, param->blockParams[i].line);
}
ret = param->blockParams+i;
ret = param->blockParams + i;
}
}
return ret;
}
ConfigParam * parseConfigFilePath(char * name, int force) {
ConfigParam * param = getConfigParam(name);
char * path;
ConfigParam *parseConfigFilePath(char *name, int force)
{
ConfigParam *param = getConfigParam(name);
char *path;
if(!param && force) {
if (!param && force) {
ERROR("config parameter \"%s\" not found\n", name);
exit(EXIT_FAILURE);
}
if(!param) return NULL;
if (!param)
return NULL;
path = param->value;
if(path[0] != '/' && path[0] != '~') {
if (path[0] != '/' && path[0] != '~') {
ERROR("\"%s\" is not an absolute path at line %i\n",
param->value, param->line);
exit(EXIT_FAILURE);
}
/* Parse ~ in path */
else if(path[0] == '~') {
struct passwd * pwd = NULL;
char * newPath;
else if (path[0] == '~') {
struct passwd *pwd = NULL;
char *newPath;
int pos = 1;
if(path[1]=='/' || path[1] == '\0') {
ConfigParam * userParam = getConfigParam(CONF_USER);
if (path[1] == '/' || path[1] == '\0') {
ConfigParam *userParam = getConfigParam(CONF_USER);
if(userParam) {
if (userParam) {
pwd = getpwnam(userParam->value);
if(!pwd) {
if (!pwd) {
ERROR("no such user %s at line %i\n",
userParam->value,
userParam->line);
exit(EXIT_FAILURE);
}
}
else {
} else {
uid_t uid = geteuid();
if((pwd = getpwuid(uid)) == NULL) {
if ((pwd = getpwuid(uid)) == NULL) {
ERROR("problems getting passwd entry "
"for current user\n");
exit(EXIT_FAILURE);
}
}
}
else {
} else {
int foundSlash = 0;
char * ch = path+1;
for(;*ch!='\0' && *ch!='/';ch++);
if(*ch=='/') foundSlash = 1;
* ch = '\0';
pos+= ch-path-1;
if((pwd = getpwnam(path+1)) == NULL) {
char *ch = path + 1;
for (; *ch != '\0' && *ch != '/'; ch++) ;
if (*ch == '/')
foundSlash = 1;
*ch = '\0';
pos += ch - path - 1;
if ((pwd = getpwnam(path + 1)) == NULL) {
ERROR("user \"%s\" not found at line %i\n",
path+1, param->line);
path + 1, param->line);
exit(EXIT_FAILURE);
}
if(foundSlash) *ch = '/';
if (foundSlash)
*ch = '/';
}
newPath = malloc(strlen(pwd->pw_dir)+strlen(path+pos)+1);
newPath = malloc(strlen(pwd->pw_dir) + strlen(path + pos) + 1);
strcpy(newPath, pwd->pw_dir);
strcat(newPath, path+pos);
strcat(newPath, path + pos);
free(param->value);
param->value = newPath;
}
......
......@@ -60,33 +60,33 @@
#define CONF_ID3V1_ENCODING "id3v1_encoding"
typedef struct _BlockParam {
char * name;
char * value;
char *name;
char *value;
int line;
} BlockParam;
typedef struct _ConfigParam {
char * value;
char *value;
unsigned int line;
BlockParam * blockParams;
BlockParam *blockParams;
int numberOfBlockParams;
} ConfigParam;
void initConf();
void finishConf();
void readConf(char * file);
void readConf(char *file);
/* don't free the returned value
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)
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
......@@ -31,52 +31,54 @@
#define LOCATE_TAG_ANY_TYPE TAG_NUM_OF_ITEM_TYPES+20
#define LOCATE_TAG_ANY_KEY "any"
typedef struct _ListCommandItem {
mpd_sint8 tagType;
int numConditionals;
LocateTagItem * conditionals;
LocateTagItem *conditionals;
} ListCommandItem;
typedef struct _LocateTagItemArray {
int numItems;
LocateTagItem * items;
LocateTagItem *items;
} LocateTagItemArray;
int getLocateTagItemType(char * str) {
int getLocateTagItemType(char *str)
{
int i;
if(0 == strcasecmp(str, LOCATE_TAG_FILE_KEY)) {
if (0 == strcasecmp(str, LOCATE_TAG_FILE_KEY)) {
return LOCATE_TAG_FILE_TYPE;
}
if(0 == strcasecmp(str, LOCATE_TAG_ANY_KEY)) {
if (0 == strcasecmp(str, LOCATE_TAG_ANY_KEY)) {
return LOCATE_TAG_ANY_TYPE;
}
for(i = 0; i < TAG_NUM_OF_ITEM_TYPES; i++) {
if(0 == strcasecmp(str, mpdTagItemKeys[i])) return i;
for (i = 0; i < TAG_NUM_OF_ITEM_TYPES; i++) {
if (0 == strcasecmp(str, mpdTagItemKeys[i]))
return i;
}
return -1;
}
static int initLocateTagItem(LocateTagItem * item, char * typeStr,
char * needle)
static int initLocateTagItem(LocateTagItem * item, char *typeStr, char *needle)
{
item->tagType = getLocateTagItemType(typeStr);
if(item->tagType < 0) return -1;
if (item->tagType < 0)
return -1;
item->needle = strdup(needle);
return 0;
}
LocateTagItem * newLocateTagItem(char * typeStr, char * needle) {
LocateTagItem * ret = malloc(sizeof(LocateTagItem));
LocateTagItem *newLocateTagItem(char *typeStr, char *needle)
{
LocateTagItem *ret = malloc(sizeof(LocateTagItem));
if(initLocateTagItem(ret, typeStr, needle) < 0) {
if (initLocateTagItem(ret, typeStr, needle) < 0) {
free(ret);
ret = NULL;
}
......@@ -84,36 +86,40 @@ LocateTagItem * newLocateTagItem(char * typeStr, char * needle) {
return ret;
}
void freeLocateTagItemArray(int count, LocateTagItem * array) {
void freeLocateTagItemArray(int count, LocateTagItem * array)
{
int i;
for(i = 0; i < count; i++) free(array[i].needle);
for (i = 0; i < count; i++)
free(array[i].needle);
free(array);
}
int newLocateTagItemArrayFromArgArray(char * argArray[],
int numArgs,
LocateTagItem ** arrayRet)
int newLocateTagItemArrayFromArgArray(char *argArray[],
int numArgs, LocateTagItem ** arrayRet)
{
int i,j;
LocateTagItem * item;
int i, j;
LocateTagItem *item;
if(numArgs == 0) return 0;
if (numArgs == 0)
return 0;
if(numArgs%2 != 0) return -1;
if (numArgs % 2 != 0)
return -1;
*arrayRet = malloc(sizeof(LocateTagItem)*numArgs/2);
*arrayRet = malloc(sizeof(LocateTagItem) * numArgs / 2);
for(i = 0, item = *arrayRet; i < numArgs/2; i++, item++) {
if(initLocateTagItem(item, argArray[i*2], argArray[i*2+1]) < 0)
for (i = 0, item = *arrayRet; i < numArgs / 2; i++, item++) {
if (initLocateTagItem
(item, argArray[i * 2], argArray[i * 2 + 1]) < 0)
goto fail;
}
return numArgs/2;
return numArgs / 2;
fail:
for(j = 0; j < i; j++) {
fail:
for (j = 0; j < i; j++) {
free((*arrayRet)[j].needle);
}
......@@ -122,70 +128,78 @@ fail:
return -1;
}
void freeLocateTagItem(LocateTagItem * item) {
void freeLocateTagItem(LocateTagItem * item)
{
free(item->needle);
free(item);
}
static int countSongsInDirectory(FILE * fp, Directory * directory, void * data) {
int * count = (int *)data;
static int countSongsInDirectory(FILE * fp, Directory * directory, void *data)
{
int *count = (int *)data;
*count+=directory->songs->numberOfNodes;
*count += directory->songs->numberOfNodes;
return 0;
}
static int printDirectoryInDirectory(FILE * fp, Directory * directory, void * data) {
if(directory->path) {
myfprintf(fp,"directory: %s\n", getDirectoryPath(directory));
static int printDirectoryInDirectory(FILE * fp, Directory * directory,
void *data)
{
if (directory->path) {
myfprintf(fp, "directory: %s\n", getDirectoryPath(directory));
}
return 0;
}
static int printSongInDirectory(FILE * fp, Song * song, void * data) {
static int printSongInDirectory(FILE * fp, Song * song, void *data)
{
printSongUrl(fp, song);
return 0;
}
static int strstrSearchTag(Song * song, int type, char * str) {
static int strstrSearchTag(Song * song, int type, char *str)
{
int i;
char * dup;
char *dup;
int ret = 0;
if(type == LOCATE_TAG_FILE_TYPE || type == LOCATE_TAG_ANY_TYPE) {
if (type == LOCATE_TAG_FILE_TYPE || type == LOCATE_TAG_ANY_TYPE) {
dup = strDupToUpper(getSongUrl(song));
if(strstr(dup, str)) ret = 1;
if (strstr(dup, str))
ret = 1;
free(dup);
if (ret == 1 || type == LOCATE_TAG_FILE_TYPE) {
return ret;
}
}
if(!song->tag) return 0;
if (!song->tag)
return 0;
for(i = 0; i < song->tag->numOfItems && !ret; i++) {
if(type != LOCATE_TAG_ANY_TYPE &&
song->tag->items[i].type != type)
{
for (i = 0; i < song->tag->numOfItems && !ret; i++) {
if (type != LOCATE_TAG_ANY_TYPE &&
song->tag->items[i].type != type) {
continue;
}
dup = strDupToUpper(song->tag->items[i].value);
if(strstr(dup, str)) ret = 1;
if (strstr(dup, str))
ret = 1;
free(dup);
}
return ret;
}
static int searchInDirectory(FILE * fp, Song * song, void * data) {
LocateTagItemArray * array = data;
static int searchInDirectory(FILE * fp, Song * song, void *data)
{
LocateTagItemArray *array = data;
int i;
for(i = 0; i < array->numItems; i++) {
if(!strstrSearchTag(song, array->items[i].tagType,
array->items[i].needle))
{
for (i = 0; i < array->numItems; i++) {
if (!strstrSearchTag(song, array->items[i].tagType,
array->items[i].needle)) {
return 0;
}
}
......@@ -195,16 +209,15 @@ static int searchInDirectory(FILE * fp, Song * song, void * data) {
return 0;
}
int searchForSongsIn(FILE * fp, char * name, int numItems,
LocateTagItem * items)
int searchForSongsIn(FILE * fp, char *name, int numItems, LocateTagItem * items)
{
int ret = -1;
int i;
char ** originalNeedles = malloc(numItems*sizeof(char *));
char **originalNeedles = malloc(numItems * sizeof(char *));
LocateTagItemArray array;
for(i = 0; i < numItems; i++) {
for (i = 0; i < numItems; i++) {
originalNeedles[i] = items[i].needle;
items[i].needle = strDupToUpper(originalNeedles[i]);
}
......@@ -212,9 +225,9 @@ int searchForSongsIn(FILE * fp, char * name, int numItems,
array.numItems = numItems;
array.items = items;
ret = traverseAllIn(fp,name,searchInDirectory, NULL, &array);
ret = traverseAllIn(fp, name, searchInDirectory, NULL, &array);
for(i = 0; i < numItems; i++) {
for (i = 0; i < numItems; i++) {
free(items[i].needle);
items[i].needle = originalNeedles[i];
}
......@@ -224,32 +237,37 @@ int searchForSongsIn(FILE * fp, char * name, int numItems,
return ret;
}
static int tagItemFoundAndMatches(Song * song, int type, char * str) {
static int tagItemFoundAndMatches(Song * song, int type, char *str)
{
int i;
if(type == LOCATE_TAG_FILE_TYPE) {
if(0 == strcmp(str, getSongUrl(song))) return 1;
if (type == LOCATE_TAG_FILE_TYPE) {
if (0 == strcmp(str, getSongUrl(song)))
return 1;
}
if(!song->tag) return 0;
if (!song->tag)
return 0;
for(i = 0; i < song->tag->numOfItems; i++) {
if(song->tag->items[i].type != type) continue;
for (i = 0; i < song->tag->numOfItems; i++) {
if (song->tag->items[i].type != type)
continue;
if(0 == strcmp(str, song->tag->items[i].value)) return 1;
if (0 == strcmp(str, song->tag->items[i].value))
return 1;
}
return 0;
}
static int findInDirectory(FILE * fp, Song * song, void * data) {
LocateTagItemArray * array = data;
static int findInDirectory(FILE * fp, Song * song, void *data)
{
LocateTagItemArray *array = data;
int i;
for(i = 0; i < array->numItems; i++) {
if(!tagItemFoundAndMatches(song, array->items[i].tagType,
array->items[i].needle))
{
for (i = 0; i < array->numItems; i++) {
if (!tagItemFoundAndMatches(song, array->items[i].tagType,
array->items[i].needle)) {
return 0;
}
}
......@@ -259,67 +277,77 @@ static int findInDirectory(FILE * fp, Song * song, void * data) {
return 0;
}
int findSongsIn(FILE * fp, char * name, int numItems, LocateTagItem * items) {
int findSongsIn(FILE * fp, char *name, int numItems, LocateTagItem * items)
{
LocateTagItemArray array;
array.numItems = numItems;
array.items = items;
return traverseAllIn(fp, name, findInDirectory, NULL,
(void *)&array);
return traverseAllIn(fp, name, findInDirectory, NULL, (void *)&array);
}
int printAllIn(FILE * fp, char * name) {
return traverseAllIn(fp,name,printSongInDirectory,
printDirectoryInDirectory,NULL);
int printAllIn(FILE * fp, char *name)
{
return traverseAllIn(fp, name, printSongInDirectory,
printDirectoryInDirectory, NULL);
}
static int directoryAddSongToPlaylist(FILE * fp, Song * song, void * data) {
static int directoryAddSongToPlaylist(FILE * fp, Song * song, void *data)
{
return addSongToPlaylist(fp, song, 0);
}
int addAllIn(FILE * fp, char * name) {
return traverseAllIn(fp,name,directoryAddSongToPlaylist,NULL,NULL);
int addAllIn(FILE * fp, char *name)
{
return traverseAllIn(fp, name, directoryAddSongToPlaylist, NULL, NULL);
}
static int directoryPrintSongInfo(FILE * fp, Song * song, void * data) {
return printSongInfo(fp,song);
static int directoryPrintSongInfo(FILE * fp, Song * song, void *data)
{
return printSongInfo(fp, song);
}
static int sumSongTime(FILE * fp, Song * song, void * data) {
unsigned long * time = (unsigned long *)data;
static int sumSongTime(FILE * fp, Song * song, void *data)
{
unsigned long *time = (unsigned long *)data;
if(song->tag && song->tag->time>=0) *time+=song->tag->time;
if (song->tag && song->tag->time >= 0)
*time += song->tag->time;
return 0;
}
int printInfoForAllIn(FILE * fp, char * name) {
return traverseAllIn(fp,name,directoryPrintSongInfo,printDirectoryInDirectory,NULL);
int printInfoForAllIn(FILE * fp, char *name)
{
return traverseAllIn(fp, name, directoryPrintSongInfo,
printDirectoryInDirectory, NULL);
}
int countSongsIn(FILE * fp, char * name) {
int countSongsIn(FILE * fp, char *name)
{
int count = 0;
void * ptr = (void *)&count;
void *ptr = (void *)&count;
traverseAllIn(fp,name,NULL,countSongsInDirectory,ptr);
traverseAllIn(fp, name, NULL, countSongsInDirectory, ptr);
return count;
}
unsigned long sumSongTimesIn(FILE * fp, char * name) {
unsigned long sumSongTimesIn(FILE * fp, char *name)
{
unsigned long dbPlayTime = 0;
void * ptr = (void *)&dbPlayTime;
void *ptr = (void *)&dbPlayTime;
traverseAllIn(fp,name,sumSongTime,NULL,ptr);
traverseAllIn(fp, name, sumSongTime, NULL, ptr);
return dbPlayTime;
}
static ListCommandItem * newListCommandItem(int tagType, int numConditionals,
static ListCommandItem *newListCommandItem(int tagType, int numConditionals,
LocateTagItem * conditionals)
{
ListCommandItem * item = malloc(sizeof(ListCommandItem));
ListCommandItem *item = malloc(sizeof(ListCommandItem));
item->tagType = tagType;
item->numConditionals = numConditionals;
......@@ -328,36 +356,39 @@ static ListCommandItem * newListCommandItem(int tagType, int numConditionals,
return item;
}
static void freeListCommandItem(ListCommandItem * item) {
static void freeListCommandItem(ListCommandItem * item)
{
free(item);
}
static void visitTag(FILE * fp, Song * song, int tagType) {
static void visitTag(FILE * fp, Song * song, int tagType)
{
int i;
MpdTag * tag = song->tag;
MpdTag *tag = song->tag;
if(tagType == LOCATE_TAG_FILE_TYPE) {
if (tagType == LOCATE_TAG_FILE_TYPE) {
printSongUrl(fp, song);
return;
}
if(!tag) return;
if (!tag)
return;
for(i = 0; i < tag->numOfItems; i++) {
if(tag->items[i].type == tagType) {
for (i = 0; i < tag->numOfItems; i++) {
if (tag->items[i].type == tagType) {
visitInTagTracker(tagType, tag->items[i].value);
}
}
}
static int listUniqueTagsInDirectory(FILE * fp, Song * song, void * data) {
ListCommandItem * item = data;
static int listUniqueTagsInDirectory(FILE * fp, Song * song, void *data)
{
ListCommandItem *item = data;
int i;
for(i = 0; i < item->numConditionals; i++) {
if(!tagItemFoundAndMatches(song, item->conditionals[i].tagType,
item->conditionals[i].needle))
{
for (i = 0; i < item->numConditionals; i++) {
if (!tagItemFoundAndMatches(song, item->conditionals[i].tagType,
item->conditionals[i].needle)) {
return 0;
}
}
......@@ -371,17 +402,17 @@ int listAllUniqueTags(FILE * fp, int type, int numConditionals,
LocateTagItem * conditionals)
{
int ret;
ListCommandItem * item = newListCommandItem(type, numConditionals,
ListCommandItem *item = newListCommandItem(type, numConditionals,
conditionals);
if(type >= 0 && type <= TAG_NUM_OF_ITEM_TYPES) {
if (type >= 0 && type <= TAG_NUM_OF_ITEM_TYPES) {
resetVisitedFlagsInTagTracker(type);
}
ret = traverseAllIn(fp, NULL, listUniqueTagsInDirectory, NULL,
(void *)item);
if(type >= 0 && type <= TAG_NUM_OF_ITEM_TYPES) {
if (type >= 0 && type <= TAG_NUM_OF_ITEM_TYPES) {
printVisitedInTagTracker(fp, type);
}
......@@ -390,26 +421,31 @@ int listAllUniqueTags(FILE * fp, int type, int numConditionals,
return ret;
}
static int sumSavedFilenameMemoryInDirectory(FILE * fp, Directory * dir, void * data) {
int * sum = data;
static int sumSavedFilenameMemoryInDirectory(FILE * fp, Directory * dir,
void *data)
{
int *sum = data;
if(!dir->path) return 0;
if (!dir->path)
return 0;
*sum += (strlen(getDirectoryPath(dir))+1-sizeof(Directory *))*
*sum += (strlen(getDirectoryPath(dir)) + 1 - sizeof(Directory *)) *
dir->songs->numberOfNodes;
return 0;
}
static int sumSavedFilenameMemoryInSong(FILE * fp, Song * song, void * data) {
int * sum = data;
static int sumSavedFilenameMemoryInSong(FILE * fp, Song * song, void *data)
{
int *sum = data;
*sum += strlen(song->url)+1;
*sum += strlen(song->url) + 1;
return 0;
}
void printSavedMemoryFromFilenames(void) {
void printSavedMemoryFromFilenames(void)
{
int sum = 0;
traverseAllIn(stderr, NULL, sumSavedFilenameMemoryInSong,
......
......@@ -27,38 +27,36 @@
typedef struct _LocateTagItem {
mpd_sint8 tagType;
/* what we are looking for */
char * needle;
char *needle;
} LocateTagItem;
int getLocateTagItemType(char * str);
int getLocateTagItemType(char *str);
/* 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 */
int newLocateTagItemArrayFromArgArray(char * argArray[], int numArgs,
int newLocateTagItemArrayFromArgArray(char *argArray[], int numArgs,
LocateTagItem ** arrayRet);
void freeLocateTagItemArray(int count, LocateTagItem * array);
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);
int findSongsIn(FILE * fp, char * name, int numItems,
LocateTagItem * items);
int findSongsIn(FILE * fp, char *name, int numItems, 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,
LocateTagItem * conditionals);
......
......@@ -39,40 +39,42 @@
static int decode_pid = 0;
void decodeSigHandler(int sig, siginfo_t * si, void * v) {
if(sig==SIGCHLD) {
void decodeSigHandler(int sig, siginfo_t * si, void *v)
{
if (sig == SIGCHLD) {
int status;
if(decode_pid==wait3(&status,WNOHANG,NULL)) {
if(WIFSIGNALED(status)) {
if(WTERMSIG(status)!=SIGTERM) {
if (decode_pid == wait3(&status, WNOHANG, NULL)) {
if (WIFSIGNALED(status)) {
if (WTERMSIG(status) != SIGTERM) {
ERROR("decode process died from "
"signal: %i\n",
WTERMSIG(status));
"signal: %i\n", WTERMSIG(status));
}
}
decode_pid = 0;
getPlayerData()->playerControl.decode_pid = 0;
}
}
else if(sig==SIGTERM) {
} else if (sig == SIGTERM) {
int pid = decode_pid;
if(pid > 0) {
if (pid > 0) {
DEBUG("player (or child) got SIGTERM\n");
kill(pid,SIGTERM);
}
else DEBUG("decoder (or child) got SIGTERM\n");
kill(pid, SIGTERM);
} else
DEBUG("decoder (or child) got SIGTERM\n");
exit(EXIT_SUCCESS);
}
}
static void stopDecode(DecoderControl * dc) {
if(decode_pid>0 && (dc->start || dc->state!=DECODE_STATE_STOP)) {
static void stopDecode(DecoderControl * dc)
{
if (decode_pid > 0 && (dc->start || dc->state != DECODE_STATE_STOP)) {
dc->stop = 1;
while(decode_pid>0 && dc->stop) my_usleep(10000);
while (decode_pid > 0 && dc->stop)
my_usleep(10000);
}
}
static void quitDecode(PlayerControl * pc, DecoderControl * dc) {
static void quitDecode(PlayerControl * pc, DecoderControl * dc)
{
stopDecode(dc);
pc->metadataState = PLAYER_METADATA_STATE_READ;
pc->state = PLAYER_STATE_STOP;
......@@ -80,22 +82,25 @@ static void quitDecode(PlayerControl * pc, DecoderControl * dc) {
pc->play = 0;
pc->stop = 0;
pc->pause = 0;
kill(getppid(),SIGUSR1);
kill(getppid(), SIGUSR1);
}
static int calculateCrossFadeChunks(PlayerControl * pc, AudioFormat * af) {
static int calculateCrossFadeChunks(PlayerControl * pc, AudioFormat * af)
{
long chunks;
if(pc->crossFade<=0) return 0;
if (pc->crossFade <= 0)
return 0;
chunks = (af->sampleRate*af->bits*af->channels/8.0/CHUNK_SIZE);
chunks = (chunks*pc->crossFade+0.5);
chunks = (af->sampleRate * af->bits * af->channels / 8.0 / CHUNK_SIZE);
chunks = (chunks * pc->crossFade + 0.5);
if(chunks>(buffered_chunks-buffered_before_play)) {
chunks = buffered_chunks-buffered_before_play;
if (chunks > (buffered_chunks - buffered_before_play)) {
chunks = buffered_chunks - buffered_before_play;
}
if(chunks<0) chunks = 0;
if (chunks < 0)
chunks = 0;
return (int)chunks;
}
......@@ -136,24 +141,25 @@ static int calculateCrossFadeChunks(PlayerControl * pc, AudioFormat * af) {
} \
}
static int waitOnDecode(PlayerControl * pc, DecoderControl * dc, OutputBuffer * cb,
int * decodeWaitedOn)
static int waitOnDecode(PlayerControl * pc, DecoderControl * dc,
OutputBuffer * cb, int *decodeWaitedOn)
{
MpdTag * tag = NULL;
MpdTag *tag = NULL;
strncpy(pc->currentUrl, pc->utf8url, MAXPATHLEN);
pc->currentUrl[MAXPATHLEN] = '\0';
while(decode_pid>0 && dc->start) my_usleep(10000);
while (decode_pid > 0 && dc->start)
my_usleep(10000);
if(dc->start || dc->error!=DECODE_ERROR_NOERROR) {
if (dc->start || dc->error != DECODE_ERROR_NOERROR) {
strncpy(pc->erroredUrl, pc->utf8url, MAXPATHLEN);
pc->erroredUrl[MAXPATHLEN] = '\0';
pc->error = PLAYER_ERROR_FILE;
quitDecode(pc,dc);
quitDecode(pc, dc);
return -1;
}
if((tag = metadataChunkToMpdTagDup(&(pc->fileMetadataChunk)))) {
if ((tag = metadataChunkToMpdTagDup(&(pc->fileMetadataChunk)))) {
sendMetadataToAudioDevice(tag);
freeMpdTag(tag);
}
......@@ -168,35 +174,33 @@ static int waitOnDecode(PlayerControl * pc, DecoderControl * dc, OutputBuffer *
return 0;
}
static int decodeSeek(PlayerControl * pc, DecoderControl * dc, OutputBuffer * cb,
int * decodeWaitedOn, int * next)
static int decodeSeek(PlayerControl * pc, DecoderControl * dc,
OutputBuffer * cb, int *decodeWaitedOn, int *next)
{
int ret = -1;
if(decode_pid>0) {
if(dc->state==DECODE_STATE_STOP || dc->error ||
strcmp(dc->utf8url, pc->utf8url)!=0)
{
if (decode_pid > 0) {
if (dc->state == DECODE_STATE_STOP || dc->error ||
strcmp(dc->utf8url, pc->utf8url) != 0) {
stopDecode(dc);
*next = -1;
cb->begin = 0;
cb->end = 0;
dc->error = 0;
dc->start = 1;
waitOnDecode(pc,dc,cb,decodeWaitedOn);
waitOnDecode(pc, dc, cb, decodeWaitedOn);
}
if(decode_pid>0 && dc->state!=DECODE_STATE_STOP &&
dc->seekable)
{
if (decode_pid > 0 && dc->state != DECODE_STATE_STOP &&
dc->seekable) {
*next = -1;
dc->seekWhere = pc->seekWhere > pc->totalTime-0.1 ?
pc->totalTime-0.1 :
pc->seekWhere;
dc->seekWhere = pc->seekWhere > pc->totalTime - 0.1 ?
pc->totalTime - 0.1 : pc->seekWhere;
dc->seekWhere = 0 > dc->seekWhere ? 0 : dc->seekWhere;
dc->seekError = 0;
dc->seek = 1;
while(decode_pid>0 && dc->seek) my_usleep(10000);
if(!dc->seekError) {
while (decode_pid > 0 && dc->seek)
my_usleep(10000);
if (!dc->seekError) {
pc->elapsedTime = dc->seekWhere;
ret = 0;
}
......@@ -256,23 +260,24 @@ static int decodeSeek(PlayerControl * pc, DecoderControl * dc, OutputBuffer * cb
return; \
}
static void decodeStart(PlayerControl * pc, OutputBuffer * cb, DecoderControl * dc) {
static void decodeStart(PlayerControl * pc, OutputBuffer * cb,
DecoderControl * dc)
{
int ret;
InputStream inStream;
InputPlugin * plugin = NULL;
char * path;
char * relativePath;
InputPlugin *plugin = NULL;
char *path;
char *relativePath;
if(isRemoteUrl(pc->utf8url)) {
if (isRemoteUrl(pc->utf8url)) {
path = utf8StrToLatin1Dup(pc->utf8url);
}
else {
} else {
relativePath = utf8ToFsCharset(pc->utf8url);
path = strdup(rmp2amp(relativePath));
free(relativePath);
}
if(!path) {
if (!path) {
dc->error = DECODE_ERROR_FILE;
dc->state = DECODE_STATE_STOP;
dc->start = 0;
......@@ -284,7 +289,7 @@ static void decodeStart(PlayerControl * pc, OutputBuffer * cb, DecoderControl *
strncpy(dc->utf8url, pc->utf8url, MAXPATHLEN);
dc->utf8url[MAXPATHLEN] = '\0';
if(openInputStream(&inStream, path) < 0) {
if (openInputStream(&inStream, path) < 0) {
dc->error = DECODE_ERROR_FILE;
dc->state = DECODE_STATE_STOP;
dc->start = 0;
......@@ -296,14 +301,13 @@ static void decodeStart(PlayerControl * pc, OutputBuffer * cb, DecoderControl *
dc->state = DECODE_STATE_START;
dc->start = 0;
while(!inputStreamAtEOF(&inStream) && bufferInputStream(&inStream) < 0
&& !dc->stop)
{
while (!inputStreamAtEOF(&inStream) && bufferInputStream(&inStream) < 0
&& !dc->stop) {
/* sleep so we don't consume 100% of the cpu */
my_usleep(1000);
}
if(dc->stop) {
if (dc->stop) {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
free(path);
......@@ -315,88 +319,87 @@ static void decodeStart(PlayerControl * pc, OutputBuffer * cb, DecoderControl *
tag->name = strdup(inStream.metaName);
copyMpdTagToOutputBuffer(cb, tag);
freeMpdTag(tag);
}*/
} */
/* reset Metadata in OutputBuffer */
ret = DECODE_ERROR_UNKTYPE;
if(isRemoteUrl(dc->utf8url)) {
if (isRemoteUrl(dc->utf8url)) {
unsigned int next = 0;
cb->acceptMetadata = 1;
/* first we try mime types: */
while(ret && (plugin = getInputPluginFromMimeType(
inStream.mime, next++))) {
while (ret
&& (plugin =
getInputPluginFromMimeType(inStream.mime, next++))) {
if (!plugin->streamDecodeFunc)
continue;
if (!(plugin->streamTypes & INPUT_PLUGIN_STREAM_URL))
continue;
if(plugin->tryDecodeFunc && !plugin->tryDecodeFunc(
&inStream))
if (plugin->tryDecodeFunc
&& !plugin->tryDecodeFunc(&inStream))
continue;
ret = plugin->streamDecodeFunc(cb, dc, &inStream);
break;
}
/* if that fails, try suffix matching the URL: */
if(plugin == NULL) {
char * s = getSuffix(dc->utf8url);
if (plugin == NULL) {
char *s = getSuffix(dc->utf8url);
next = 0;
while(ret && (plugin = getInputPluginFromSuffix(
s, next++))) {
while (ret
&& (plugin =
getInputPluginFromSuffix(s, next++))) {
if (!plugin->streamDecodeFunc)
continue;
if(!(plugin->streamTypes &
if (!(plugin->streamTypes &
INPUT_PLUGIN_STREAM_URL))
continue;
if(plugin->tryDecodeFunc &&
!plugin->tryDecodeFunc(
&inStream))
if (plugin->tryDecodeFunc &&
!plugin->tryDecodeFunc(&inStream))
continue;
ret = plugin->streamDecodeFunc(
cb, dc, &inStream);
ret =
plugin->streamDecodeFunc(cb, dc, &inStream);
break;
}
}
/* fallback to mp3: */
/* this is needed for bastard streams that don't have a suffix
or set the mimeType */
if(plugin == NULL) {
if (plugin == NULL) {
/* we already know our mp3Plugin supports streams, no
* need to check for stream{Types,DecodeFunc} */
if ((plugin = getInputPluginFromName("mp3")))
ret = plugin->streamDecodeFunc(cb, dc,
&inStream);
}
}
else {
} else {
unsigned int next = 0;
char * s = getSuffix(dc->utf8url);
char *s = getSuffix(dc->utf8url);
cb->acceptMetadata = 0;
while (ret && (plugin = getInputPluginFromSuffix(s, next++))) {
if(!plugin->streamTypes & INPUT_PLUGIN_STREAM_FILE)
if (!plugin->streamTypes & INPUT_PLUGIN_STREAM_FILE)
continue;
if(plugin->tryDecodeFunc && !plugin->tryDecodeFunc(
&inStream))
if (plugin->tryDecodeFunc
&& !plugin->tryDecodeFunc(&inStream))
continue;
if(plugin->streamDecodeFunc) {
ret = plugin->streamDecodeFunc(
cb, dc, &inStream);
if (plugin->streamDecodeFunc) {
ret =
plugin->streamDecodeFunc(cb, dc, &inStream);
break;
}
else if(plugin->fileDecodeFunc) {
} else if (plugin->fileDecodeFunc) {
closeInputStream(&inStream);
ret = plugin->fileDecodeFunc(
cb, dc, path);
ret = plugin->fileDecodeFunc(cb, dc, path);
}
}
}
if(ret<0 || ret == DECODE_ERROR_UNKTYPE) {
if (ret < 0 || ret == DECODE_ERROR_UNKTYPE) {
strncpy(pc->erroredUrl, dc->utf8url, MAXPATHLEN);
pc->erroredUrl[MAXPATHLEN] = '\0';
if(ret != DECODE_ERROR_UNKTYPE) dc->error = DECODE_ERROR_FILE;
if (ret != DECODE_ERROR_UNKTYPE)
dc->error = DECODE_ERROR_FILE;
else {
dc->error = DECODE_ERROR_UNKTYPE;
closeInputStream(&inStream);
......@@ -408,32 +411,33 @@ static void decodeStart(PlayerControl * pc, OutputBuffer * cb, DecoderControl *
free(path);
}
static int decoderInit(PlayerControl * pc, OutputBuffer * cb, DecoderControl * dc) {
static int decoderInit(PlayerControl * pc, OutputBuffer * cb,
DecoderControl * dc)
{
blockSignals();
getPlayerData()->playerControl.decode_pid = 0;
decode_pid = fork();
if(decode_pid==0) {
if (decode_pid == 0) {
/* CHILD */
unblockSignals();
while(1) {
if(dc->cycleLogFiles) {
while (1) {
if (dc->cycleLogFiles) {
myfprintfCloseAndOpenLogFile();
dc->cycleLogFiles = 0;
}
else if(dc->start || dc->seek) decodeStart(pc, cb, dc);
else if(dc->stop) {
} else if (dc->start || dc->seek)
decodeStart(pc, cb, dc);
else if (dc->stop) {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
else my_usleep(10000);
} else
my_usleep(10000);
}
exit(EXIT_SUCCESS);
/* END OF CHILD */
}
else if(decode_pid<0) {
} else if (decode_pid < 0) {
unblockSignals();
strncpy(pc->erroredUrl, pc->utf8url, MAXPATHLEN);
pc->erroredUrl[MAXPATHLEN] = '\0';
......@@ -447,17 +451,17 @@ static int decoderInit(PlayerControl * pc, OutputBuffer * cb, DecoderControl * d
return 0;
}
static void handleMetadata(OutputBuffer * cb, PlayerControl * pc, int * previous,
int * currentChunkSent, MetadataChunk * currentChunk)
static void handleMetadata(OutputBuffer * cb, PlayerControl * pc, int *previous,
int *currentChunkSent, MetadataChunk * currentChunk)
{
if(cb->begin!=cb->end) {
if (cb->begin != cb->end) {
int meta = cb->metaChunk[cb->begin];
if( meta != *previous ) {
if (meta != *previous) {
DEBUG("player: metadata change\n");
if( meta >= 0 && cb->metaChunkSet[meta]) {
if (meta >= 0 && cb->metaChunkSet[meta]) {
DEBUG("player: new metadata from decoder!\n");
memcpy(currentChunk,
cb->metadataChunks+meta,
cb->metadataChunks + meta,
sizeof(MetadataChunk));
*currentChunkSent = 0;
cb->metaChunkSet[meta] = 0;
......@@ -465,14 +469,13 @@ static void handleMetadata(OutputBuffer * cb, PlayerControl * pc, int * previous
}
*previous = meta;
}
if(!(*currentChunkSent) && pc->metadataState ==
PLAYER_METADATA_STATE_WRITE)
{
MpdTag * tag = NULL;
if (!(*currentChunkSent) && pc->metadataState ==
PLAYER_METADATA_STATE_WRITE) {
MpdTag *tag = NULL;
*currentChunkSent = 1;
if((tag = metadataChunkToMpdTagDup(currentChunk))) {
if ((tag = metadataChunkToMpdTagDup(currentChunk))) {
sendMetadataToAudioDevice(tag);
freeMpdTag(tag);
}
......@@ -485,20 +488,21 @@ static void handleMetadata(OutputBuffer * cb, PlayerControl * pc, int * previous
}
static void advanceOutputBufferTo(OutputBuffer * cb, PlayerControl * pc,
int * previous, int * currentChunkSent, MetadataChunk * currentChunk,
int to)
int *previous, int *currentChunkSent,
MetadataChunk * currentChunk, int to)
{
while(cb->begin!=to) {
while (cb->begin != to) {
handleMetadata(cb, pc, previous, currentChunkSent,
currentChunk);
cb->begin++;
if(cb->begin>=buffered_chunks) {
if (cb->begin >= buffered_chunks) {
cb->begin = 0;
}
}
}
void decodeParent(PlayerControl * pc, DecoderControl * dc, OutputBuffer * cb) {
void decodeParent(PlayerControl * pc, DecoderControl * dc, OutputBuffer * cb)
{
int pause = 0;
int quit = 0;
int bbp = buffered_before_play;
......@@ -516,133 +520,125 @@ void decodeParent(PlayerControl * pc, DecoderControl * dc, OutputBuffer * cb) {
int end;
int next = -1;
memset(silence,0,CHUNK_SIZE);
memset(silence, 0, CHUNK_SIZE);
if(waitOnDecode(pc,dc,cb,&decodeWaitedOn)<0) return;
if (waitOnDecode(pc, dc, cb, &decodeWaitedOn) < 0)
return;
pc->elapsedTime = 0;
pc->state = PLAYER_STATE_PLAY;
pc->play = 0;
kill(getppid(),SIGUSR1);
kill(getppid(), SIGUSR1);
while(decode_pid>0 && cb->end-cb->begin<bbp &&
cb->end!=buffered_chunks-1 &&
dc->state!=DECODE_STATE_STOP)
{
while (decode_pid > 0 && cb->end - cb->begin < bbp &&
cb->end != buffered_chunks - 1 &&
dc->state != DECODE_STATE_STOP) {
processDecodeInput();
my_usleep(1000);
}
while(!quit) {
while (!quit) {
processDecodeInput();
handleDecodeStart();
handleMetadata(cb, pc, &previousMetadataChunk,
&currentChunkSent, &currentMetadataChunk);
if(dc->state==DECODE_STATE_STOP &&
pc->queueState==PLAYER_QUEUE_FULL &&
pc->queueLockState==PLAYER_QUEUE_UNLOCKED)
{
if (dc->state == DECODE_STATE_STOP &&
pc->queueState == PLAYER_QUEUE_FULL &&
pc->queueLockState == PLAYER_QUEUE_UNLOCKED) {
next = cb->end;
dc->start = 1;
pc->queueState = PLAYER_QUEUE_DECODE;
kill(getppid(),SIGUSR1);
kill(getppid(), SIGUSR1);
}
if(next>=0 && doCrossFade==0 && !dc->start &&
dc->state!=DECODE_STATE_START)
{
if (next >= 0 && doCrossFade == 0 && !dc->start &&
dc->state != DECODE_STATE_START) {
nextChunk = -1;
if(isCurrentAudioFormat(&(cb->audioFormat))) {
if (isCurrentAudioFormat(&(cb->audioFormat))) {
doCrossFade = 1;
crossFadeChunks =
calculateCrossFadeChunks(pc,
&(cb->audioFormat));
if(!crossFadeChunks ||
pc->crossFade>=dc->totalTime)
{
&(cb->
audioFormat));
if (!crossFadeChunks
|| pc->crossFade >= dc->totalTime) {
doCrossFade = -1;
}
}
else doCrossFade = -1;
} else
doCrossFade = -1;
}
/* copy these to local variables to prevent any potential
race conditions and weirdness */
end = cb->end;
if(pause) my_usleep(10000);
else if(cb->begin!=end && cb->begin!=next) {
if(doCrossFade==1 && next>=0 &&
((next>cb->begin &&
(fadePosition=next-cb->begin)
<=crossFadeChunks) ||
(cb->begin>next &&
(fadePosition=next-cb->begin+
buffered_chunks)<=crossFadeChunks)))
{
if(nextChunk<0) {
if (pause)
my_usleep(10000);
else if (cb->begin != end && cb->begin != next) {
if (doCrossFade == 1 && next >= 0 &&
((next > cb->begin &&
(fadePosition = next - cb->begin)
<= crossFadeChunks) ||
(cb->begin > next &&
(fadePosition = next - cb->begin +
buffered_chunks) <= crossFadeChunks))) {
if (nextChunk < 0) {
crossFadeChunks = fadePosition;
}
test = end;
if(end < cb->begin) test+=buffered_chunks;
nextChunk = cb->begin+crossFadeChunks;
if(nextChunk<test) {
if(nextChunk>=buffered_chunks)
{
if (end < cb->begin)
test += buffered_chunks;
nextChunk = cb->begin + crossFadeChunks;
if (nextChunk < test) {
if (nextChunk >= buffered_chunks) {
nextChunk -= buffered_chunks;
}
pcm_mix(cb->chunks+cb->begin*CHUNK_SIZE,
cb->chunks+nextChunk*
CHUNK_SIZE,
cb->chunkSize[
cb->begin],
cb->chunkSize[
nextChunk],
pcm_mix(cb->chunks +
cb->begin * CHUNK_SIZE,
cb->chunks +
nextChunk * CHUNK_SIZE,
cb->chunkSize[cb->begin],
cb->chunkSize[nextChunk],
&(cb->audioFormat),
((float)fadePosition)/
((float)fadePosition) /
crossFadeChunks);
if(cb->chunkSize[nextChunk]>
if (cb->chunkSize[nextChunk] >
cb->chunkSize[cb->begin]
)
{
) {
cb->chunkSize[cb->begin]
= cb->chunkSize
[nextChunk];
}
= cb->chunkSize[nextChunk];
}
else {
if(dc->state==DECODE_STATE_STOP)
{
} else {
if (dc->state == DECODE_STATE_STOP) {
doCrossFade = -1;
}
else continue;
} else
continue;
}
}
pc->elapsedTime = cb->times[cb->begin];
pc->bitRate = cb->bitRate[cb->begin];
pcm_volumeChange(cb->chunks+cb->begin*
pcm_volumeChange(cb->chunks + cb->begin *
CHUNK_SIZE,
cb->chunkSize[cb->begin],
&(cb->audioFormat),
pc->softwareVolume);
if(playAudio(cb->chunks+cb->begin*CHUNK_SIZE,
cb->chunkSize[cb->begin])<0)
{
if (playAudio(cb->chunks + cb->begin * CHUNK_SIZE,
cb->chunkSize[cb->begin]) < 0) {
quit = 1;
}
pc->totalPlayTime+= sizeToTime*cb->chunkSize[cb->begin];
if( cb->begin+1 >= buffered_chunks ) {
pc->totalPlayTime +=
sizeToTime * cb->chunkSize[cb->begin];
if (cb->begin + 1 >= buffered_chunks) {
cb->begin = 0;
}
else cb->begin++;
}
else if(next==cb->begin) {
if(doCrossFade==1 && nextChunk>=0) {
nextChunk = cb->begin+crossFadeChunks;
} else
cb->begin++;
} else if (next == cb->begin) {
if (doCrossFade == 1 && nextChunk >= 0) {
nextChunk = cb->begin + crossFadeChunks;
test = cb->end;
if(end < cb->begin) test+=buffered_chunks;
if(nextChunk<test) {
if(nextChunk>=buffered_chunks)
{
if (end < cb->begin)
test += buffered_chunks;
if (nextChunk < test) {
if (nextChunk >= buffered_chunks) {
nextChunk -= buffered_chunks;
}
advanceOutputBufferTo(cb, pc,
......@@ -652,44 +648,41 @@ void decodeParent(PlayerControl * pc, DecoderControl * dc, OutputBuffer * cb) {
nextChunk);
}
}
while(pc->queueState==PLAYER_QUEUE_DECODE ||
pc->queueLockState==PLAYER_QUEUE_LOCKED)
{
while (pc->queueState == PLAYER_QUEUE_DECODE ||
pc->queueLockState == PLAYER_QUEUE_LOCKED) {
processDecodeInput();
if(quit) {
quitDecode(pc,dc);
if (quit) {
quitDecode(pc, dc);
return;
}
my_usleep(10000);
}
if(pc->queueState!=PLAYER_QUEUE_PLAY) {
if (pc->queueState != PLAYER_QUEUE_PLAY) {
quit = 1;
break;
}
else {
} else {
next = -1;
if(waitOnDecode(pc,dc,cb,&decodeWaitedOn)<0) {
if (waitOnDecode(pc, dc, cb, &decodeWaitedOn) <
0) {
return;
}
nextChunk = -1;
doCrossFade = 0;
crossFadeChunks = 0;
pc->queueState = PLAYER_QUEUE_EMPTY;
kill(getppid(),SIGUSR1);
}
kill(getppid(), SIGUSR1);
}
else if(decode_pid<=0 ||
(dc->state==DECODE_STATE_STOP && !dc->start))
{
} else if (decode_pid <= 0 ||
(dc->state == DECODE_STATE_STOP && !dc->start)) {
quit = 1;
break;
}
else {
if(playAudio(silence, CHUNK_SIZE) < 0) quit = 1;
} else {
if (playAudio(silence, CHUNK_SIZE) < 0)
quit = 1;
}
}
quitDecode(pc,dc);
quitDecode(pc, dc);
}
/* decode w/ buffering
......@@ -697,10 +690,11 @@ void decodeParent(PlayerControl * pc, DecoderControl * dc, OutputBuffer * cb) {
* child process does decoding
* parent process does playing audio
*/
void decode() {
OutputBuffer * cb;
PlayerControl * pc;
DecoderControl * dc;
void decode()
{
OutputBuffer *cb;
PlayerControl *pc;
DecoderControl *dc;
cb = &(getPlayerData()->buffer);
......@@ -714,8 +708,9 @@ void decode() {
dc->stop = 0;
dc->start = 1;
if(decode_pid<=0) {
if(decoderInit(pc,cb,dc)<0) return;
if (decode_pid <= 0) {
if (decoderInit(pc, cb, dc) < 0)
return;
}
decodeParent(pc, dc, cb);
......
......@@ -58,11 +58,11 @@ typedef struct _DecoderControl {
volatile mpd_sint8 cycleLogFiles;
volatile double seekWhere;
AudioFormat audioFormat;
char utf8url[MAXPATHLEN+1];
char utf8url[MAXPATHLEN + 1];
volatile float totalTime;
} DecoderControl;
void decodeSigHandler(int sig, siginfo_t * siginfo, void * v);
void decodeSigHandler(int sig, siginfo_t * siginfo, void *v);
void decode();
......
......@@ -58,7 +58,7 @@
#define DIRECTORY_RETURN_UPDATE 1
#define DIRECTORY_RETURN_ERROR -1
Directory * mp3rootDirectory = NULL;
Directory *mp3rootDirectory = NULL;
time_t directory_dbModTime = 0;
......@@ -68,9 +68,9 @@ volatile int directory_reReadDB = 0;
volatile mpd_uint16 directory_updateJobId = 0;
static DirectoryList * newDirectoryList();
static DirectoryList *newDirectoryList();
static int addToDirectory(Directory * directory, char * shortname, char * name);
static int addToDirectory(Directory * directory, char *shortname, char *name);
static void freeDirectoryList(DirectoryList * list);
......@@ -82,19 +82,19 @@ static int updateDirectory(Directory * directory);
static void deleteEmptyDirectoriesInDirectory(Directory * directory);
static void removeSongFromDirectory(Directory * directory, char * shortname);
static void removeSongFromDirectory(Directory * directory, char *shortname);
static int addSubDirectoryToDirectory(Directory * directory, char * shortname,
char * name, struct stat * st);
static int addSubDirectoryToDirectory(Directory * directory, char *shortname,
char *name, struct stat *st);
static Directory * getDirectoryDetails(char * name, char ** shortname);
static Directory *getDirectoryDetails(char *name, char **shortname);
static Directory * getDirectory(char * name);
static Directory *getDirectory(char *name);
static Song * getSongDetails(char * file, char ** shortnameRet,
static Song *getSongDetails(char *file, char **shortnameRet,
Directory ** directoryRet);
static int updatePath(char * utf8path);
static int updatePath(char *utf8path);
static void sortDirectory(Directory * directory);
......@@ -102,8 +102,9 @@ static int inodeFoundInParent(Directory * parent, ino_t inode, dev_t device);
static int statDirectory(Directory * dir);
static char * getDbFile() {
ConfigParam * param = parseConfigFilePath(CONF_DB_FILE, 1);
static char *getDbFile()
{
ConfigParam *param = parseConfigFilePath(CONF_DB_FILE, 1);
assert(param);
assert(param->value);
......@@ -111,27 +112,27 @@ static char * getDbFile() {
return param->value;
}
static void clearUpdatePid() {
static void clearUpdatePid()
{
directory_updatePid = 0;
}
int isUpdatingDB() {
if(directory_updatePid>0 || directory_reReadDB) {
int isUpdatingDB()
{
if (directory_updatePid > 0 || directory_reReadDB) {
return directory_updateJobId;
}
return 0;
}
void directory_sigChldHandler(int pid, int status) {
if(directory_updatePid==pid) {
if(WIFSIGNALED(status) && WTERMSIG(status)!=SIGTERM) {
void directory_sigChldHandler(int pid, int status)
{
if (directory_updatePid == pid) {
if (WIFSIGNALED(status) && WTERMSIG(status) != SIGTERM) {
ERROR("update process died from a "
"non-TERM signal: %i\n",
WTERMSIG(status));
}
else if(!WIFSIGNALED(status)) {
switch(WEXITSTATUS(status))
{
"non-TERM signal: %i\n", WTERMSIG(status));
} else if (!WIFSIGNALED(status)) {
switch (WEXITSTATUS(status)) {
case DIRECTORY_UPDATE_EXIT_UPDATE:
directory_reReadDB = 1;
DEBUG("directory_sigChldHandler: "
......@@ -148,8 +149,9 @@ void directory_sigChldHandler(int pid, int status) {
}
}
void readDirectoryDBIfUpdateIsFinished() {
if(directory_reReadDB && 0==directory_updatePid) {
void readDirectoryDBIfUpdateIsFinished()
{
if (directory_reReadDB && 0 == directory_updatePid) {
DEBUG("readDirectoryDB since update finished successfully\n");
readDirectoryDB();
playlistVersionChange();
......@@ -157,8 +159,9 @@ void readDirectoryDBIfUpdateIsFinished() {
}
}
int updateInit(FILE * fp, List * pathList) {
if(directory_updatePid > 0) {
int updateInit(FILE * fp, List * pathList)
{
if (directory_updatePid > 0) {
commandError(fp, ACK_ERROR_UPDATE_ALREADY, "already updating",
NULL);
return -1;
......@@ -168,7 +171,7 @@ int updateInit(FILE * fp, List * pathList) {
even get a chance to assign directory_updatePID */
blockSignals();
directory_updatePid = fork();
if(directory_updatePid==0) {
if (directory_updatePid == 0) {
/* child */
int dbUpdated = 0;
......@@ -180,11 +183,11 @@ int updateInit(FILE * fp, List * pathList) {
finishPlaylist();
finishVolume();
if(pathList) {
ListNode * node = pathList->firstNode;
if (pathList) {
ListNode *node = pathList->firstNode;
while(node) {
switch(updatePath(node->key)) {
while (node) {
switch (updatePath(node->key)) {
case 1:
dbUpdated = 1;
break;
......@@ -195,23 +198,22 @@ int updateInit(FILE * fp, List * pathList) {
}
node = node->nextNode;
}
}
else {
if((dbUpdated = updateDirectory(mp3rootDirectory))<0) {
} else {
if ((dbUpdated = updateDirectory(mp3rootDirectory)) < 0) {
exit(DIRECTORY_UPDATE_EXIT_ERROR);
}
}
if(!dbUpdated) exit(DIRECTORY_UPDATE_EXIT_NOUPDATE);
if (!dbUpdated)
exit(DIRECTORY_UPDATE_EXIT_NOUPDATE);
/* ignore signals since we don't want them to corrupt the db*/
/* ignore signals since we don't want them to corrupt the db */
ignoreSignals();
if(writeDirectoryDB()<0) {
if (writeDirectoryDB() < 0) {
exit(DIRECTORY_UPDATE_EXIT_ERROR);
}
exit(DIRECTORY_UPDATE_EXIT_UPDATE);
}
else if(directory_updatePid < 0) {
} else if (directory_updatePid < 0) {
unblockSignals();
ERROR("updateInit: Problems forking()'ing\n");
commandError(fp, ACK_ERROR_SYSTEM,
......@@ -222,33 +224,40 @@ int updateInit(FILE * fp, List * pathList) {
unblockSignals();
directory_updateJobId++;
if(directory_updateJobId > 1<<15) directory_updateJobId = 1;
if (directory_updateJobId > 1 << 15)
directory_updateJobId = 1;
DEBUG("updateInit: fork()'d update child for update job id %i\n",
(int)directory_updateJobId);
myfprintf(fp,"updating_db: %i\n",(int)directory_updateJobId);
myfprintf(fp, "updating_db: %i\n", (int)directory_updateJobId);
return 0;
}
static DirectoryStat * newDirectoryStat(struct stat * st) {
DirectoryStat * ret = malloc(sizeof(DirectoryStat));
static DirectoryStat *newDirectoryStat(struct stat *st)
{
DirectoryStat *ret = malloc(sizeof(DirectoryStat));
ret->inode = st->st_ino;
ret->device = st->st_dev;
return ret;
}
static void freeDirectoryStatFromDirectory(Directory * dir) {
if(dir->stat) free(dir->stat);
static void freeDirectoryStatFromDirectory(Directory * dir)
{
if (dir->stat)
free(dir->stat);
dir->stat = NULL;
}
static Directory * newDirectory(char * dirname, Directory * parent) {
Directory * directory;
static Directory *newDirectory(char *dirname, Directory * parent)
{
Directory *directory;
directory = malloc(sizeof(Directory));
if(dirname && strlen(dirname)) directory->path = strdup(dirname);
else directory->path = NULL;
if (dirname && strlen(dirname))
directory->path = strdup(dirname);
else
directory->path = NULL;
directory->subDirectories = newDirectoryList();
directory->songs = newSongList();
directory->stat = NULL;
......@@ -257,46 +266,51 @@ static Directory * newDirectory(char * dirname, Directory * parent) {
return directory;
}
static void freeDirectory(Directory * directory) {
static void freeDirectory(Directory * directory)
{
freeDirectoryList(directory->subDirectories);
freeSongList(directory->songs);
if(directory->path) free(directory->path);
if (directory->path)
free(directory->path);
freeDirectoryStatFromDirectory(directory);
free(directory);
/* this resets last dir returned */
/*getDirectoryPath(NULL);*/
/*getDirectoryPath(NULL); */
}
static DirectoryList * newDirectoryList() {
return makeList((ListFreeDataFunc *)freeDirectory, 1);
static DirectoryList *newDirectoryList()
{
return makeList((ListFreeDataFunc *) freeDirectory, 1);
}
static void freeDirectoryList(DirectoryList * directoryList) {
static void freeDirectoryList(DirectoryList * directoryList)
{
freeList(directoryList);
}
static void removeSongFromDirectory(Directory * directory, char * shortname) {
void * song;
static void removeSongFromDirectory(Directory * directory, char *shortname)
{
void *song;
if(findInList(directory->songs,shortname,&song)) {
LOG("removing: %s\n", getSongUrl((Song *)song));
if (findInList(directory->songs, shortname, &song)) {
LOG("removing: %s\n", getSongUrl((Song *) song));
deleteFromList(directory->songs, shortname);
}
}
static void deleteEmptyDirectoriesInDirectory(Directory * directory) {
ListNode * node = directory->subDirectories->firstNode;
ListNode * nextNode;
Directory * subDir;
static void deleteEmptyDirectoriesInDirectory(Directory * directory)
{
ListNode *node = directory->subDirectories->firstNode;
ListNode *nextNode;
Directory *subDir;
while(node) {
subDir = (Directory *)node->data;
while (node) {
subDir = (Directory *) node->data;
deleteEmptyDirectoriesInDirectory(subDir);
nextNode = node->nextNode;
if(subDir->subDirectories->numberOfNodes==0 &&
subDir->songs->numberOfNodes==0)
{
deleteNodeFromList(directory->subDirectories,node);
if (subDir->subDirectories->numberOfNodes == 0 &&
subDir->songs->numberOfNodes == 0) {
deleteNodeFromList(directory->subDirectories, node);
}
node = nextNode;
}
......@@ -307,34 +321,34 @@ static void deleteEmptyDirectoriesInDirectory(Directory * directory) {
0 -> no error, but nothing updated
1 -> no error, and stuff updated
*/
static int updateInDirectory(Directory * directory, char * shortname, char * name) {
void * song;
void * subDir;
static int updateInDirectory(Directory * directory, char *shortname, char *name)
{
void *song;
void *subDir;
struct stat st;
if(myStat(name, &st)) return -1;
if (myStat(name, &st))
return -1;
if(S_ISREG(st.st_mode) && hasMusicSuffix(name, 0)) {
if(0==findInList(directory->songs,shortname,&song)) {
if (S_ISREG(st.st_mode) && hasMusicSuffix(name, 0)) {
if (0 == findInList(directory->songs, shortname, &song)) {
addToDirectory(directory, shortname, name);
return DIRECTORY_RETURN_UPDATE;
}
else if(st.st_mtime!=((Song *)song)->mtime) {
LOG("updating %s\n",name);
if(updateSongInfo((Song *)song)<0) {
removeSongFromDirectory(directory,shortname);
} else if (st.st_mtime != ((Song *) song)->mtime) {
LOG("updating %s\n", name);
if (updateSongInfo((Song *) song) < 0) {
removeSongFromDirectory(directory, shortname);
}
return 1;
}
}
else if(S_ISDIR(st.st_mode)) {
if(findInList(directory->subDirectories,shortname,(void **)&subDir)) {
} else if (S_ISDIR(st.st_mode)) {
if (findInList
(directory->subDirectories, shortname, (void **)&subDir)) {
freeDirectoryStatFromDirectory(subDir);
((Directory *)subDir)->stat = newDirectoryStat(&st);
return updateDirectory((Directory *)subDir);
}
else {
return addSubDirectoryToDirectory(directory,shortname,
((Directory *) subDir)->stat = newDirectoryStat(&st);
return updateDirectory((Directory *) subDir);
} else {
return addSubDirectoryToDirectory(directory, shortname,
name, &st);
}
}
......@@ -347,51 +361,55 @@ static int updateInDirectory(Directory * directory, char * shortname, char * nam
0 -> no error, but nothing removed
1 -> no error, and stuff removed
*/
static int removeDeletedFromDirectory(Directory * directory, DIR * dir) {
static int removeDeletedFromDirectory(Directory * directory, DIR * dir)
{
char cwd[2];
struct dirent * ent;
char * dirname = getDirectoryPath(directory);
List * entList = makeList(free, 1);
void * name;
char * s;
char * utf8;
ListNode * node;
ListNode * tmpNode;
struct dirent *ent;
char *dirname = getDirectoryPath(directory);
List *entList = makeList(free, 1);
void *name;
char *s;
char *utf8;
ListNode *node;
ListNode *tmpNode;
int ret = 0;
cwd[0] = '.';
cwd[1] = '\0';
if(dirname==NULL) dirname=cwd;
if (dirname == NULL)
dirname = cwd;
while((ent = readdir(dir))) {
if(ent->d_name[0]=='.') continue; /* hide hidden stuff */
if(strchr(ent->d_name, '\n')) continue;
while ((ent = readdir(dir))) {
if (ent->d_name[0] == '.')
continue; /* hide hidden stuff */
if (strchr(ent->d_name, '\n'))
continue;
utf8 = fsCharsetToUtf8(ent->d_name);
if(!utf8) continue;
if (!utf8)
continue;
if(directory->path) {
if (directory->path) {
s = malloc(strlen(getDirectoryPath(directory))
+strlen(utf8)+2);
sprintf(s,"%s/%s", getDirectoryPath(directory), utf8);
}
else s= strdup(utf8);
+ strlen(utf8) + 2);
sprintf(s, "%s/%s", getDirectoryPath(directory), utf8);
} else
s = strdup(utf8);
insertInList(entList, utf8, s);
}
node = directory->subDirectories->firstNode;
while(node) {
while (node) {
tmpNode = node->nextNode;
if(findInList(entList,node->key,&name)) {
if(!isDir((char *)name)) {
LOG("removing directory: %s\n",(char*)name);
if (findInList(entList, node->key, &name)) {
if (!isDir((char *)name)) {
LOG("removing directory: %s\n", (char *)name);
deleteFromList(directory->subDirectories,
node->key);
ret = 1;
}
}
else {
} else {
LOG("removing directory: %s/%s\n",
getDirectoryPath(directory), node->key);
deleteFromList(directory->subDirectories, node->key);
......@@ -401,16 +419,15 @@ static int removeDeletedFromDirectory(Directory * directory, DIR * dir) {
}
node = directory->songs->firstNode;
while(node) {
while (node) {
tmpNode = node->nextNode;
if(findInList(entList,node->key,(void **)&name)) {
if(!isMusic(name,NULL,0)) {
removeSongFromDirectory(directory,node->key);
if (findInList(entList, node->key, (void **)&name)) {
if (!isMusic(name, NULL, 0)) {
removeSongFromDirectory(directory, node->key);
ret = 1;
}
}
else {
removeSongFromDirectory(directory,node->key);
} else {
removeSongFromDirectory(directory, node->key);
ret = 1;
}
node = tmpNode;
......@@ -421,71 +438,75 @@ static int removeDeletedFromDirectory(Directory * directory, DIR * dir) {
return ret;
}
static Directory * addDirectoryPathToDB(char * utf8path, char ** shortname) {
char * parent;
Directory * parentDirectory;
void * directory;
static Directory *addDirectoryPathToDB(char *utf8path, char **shortname)
{
char *parent;
Directory *parentDirectory;
void *directory;
parent = strdup(parentPath(utf8path));
if(strlen(parent)==0) parentDirectory = (void *)mp3rootDirectory;
else parentDirectory = addDirectoryPathToDB(parent,shortname);
if (strlen(parent) == 0)
parentDirectory = (void *)mp3rootDirectory;
else
parentDirectory = addDirectoryPathToDB(parent, shortname);
if(!parentDirectory) {
if (!parentDirectory) {
free(parent);
return NULL;
}
*shortname = utf8path+strlen(parent);
while(*(*shortname) && *(*shortname)=='/') (*shortname)++;
*shortname = utf8path + strlen(parent);
while (*(*shortname) && *(*shortname) == '/')
(*shortname)++;
if(!findInList(parentDirectory->subDirectories,*shortname, &directory))
{
if (!findInList
(parentDirectory->subDirectories, *shortname, &directory)) {
struct stat st;
if(myStat(utf8path, &st) < 0 ||
inodeFoundInParent(parentDirectory,
st.st_ino, st.st_dev))
{
if (myStat(utf8path, &st) < 0 ||
inodeFoundInParent(parentDirectory, st.st_ino, st.st_dev)) {
free(parent);
return NULL;
}
else {
} else {
directory = newDirectory(utf8path, parentDirectory);
insertInList(parentDirectory->subDirectories,
*shortname,
directory);
*shortname, directory);
}
}
/* if we're adding directory paths, make sure to delete filenames
with potentially the same name*/
removeSongFromDirectory(parentDirectory,*shortname);
with potentially the same name */
removeSongFromDirectory(parentDirectory, *shortname);
free(parent);
return (Directory *)directory;
return (Directory *) directory;
}
static Directory * addParentPathToDB(char * utf8path, char ** shortname) {
char * parent;
Directory * parentDirectory;
static Directory *addParentPathToDB(char *utf8path, char **shortname)
{
char *parent;
Directory *parentDirectory;
parent = strdup(parentPath(utf8path));
if(strlen(parent)==0) parentDirectory = (void *)mp3rootDirectory;
else parentDirectory = addDirectoryPathToDB(parent,shortname);
if (strlen(parent) == 0)
parentDirectory = (void *)mp3rootDirectory;
else
parentDirectory = addDirectoryPathToDB(parent, shortname);
if(!parentDirectory) {
if (!parentDirectory) {
free(parent);
return NULL;
}
*shortname = utf8path+strlen(parent);
while(*(*shortname) && *(*shortname)=='/') (*shortname)++;
*shortname = utf8path + strlen(parent);
while (*(*shortname) && *(*shortname) == '/')
(*shortname)++;
free(parent);
return (Directory *)parentDirectory;
return (Directory *) parentDirectory;
}
/* return values:
......@@ -493,58 +514,58 @@ static Directory * addParentPathToDB(char * utf8path, char ** shortname) {
0 -> no error, but nothing updated
1 -> no error, and stuff updated
*/
static int updatePath(char * utf8path) {
Directory * directory;
Directory * parentDirectory;
Song * song;
char * shortname;
char * path = sanitizePathDup(utf8path);
static int updatePath(char *utf8path)
{
Directory *directory;
Directory *parentDirectory;
Song *song;
char *shortname;
char *path = sanitizePathDup(utf8path);
time_t mtime;
int ret = 0;
if(NULL==path) return -1;
if (NULL == path)
return -1;
/* if path is in the DB try to update it, or else delete it */
if((directory = getDirectoryDetails(path,&shortname))) {
if ((directory = getDirectoryDetails(path, &shortname))) {
parentDirectory = directory->parent;
/* if this update directory is successfull, we are done */
if((ret = updateDirectory(directory))>=0)
{
if ((ret = updateDirectory(directory)) >= 0) {
free(path);
sortDirectory(directory);
return ret;
}
/* we don't want to delete the root directory */
else if(directory == mp3rootDirectory) {
else if (directory == mp3rootDirectory) {
free(path);
return 0;
}
/* if updateDirectory fials, means we should delete it */
else {
LOG("removing directory: %s\n",path);
LOG("removing directory: %s\n", path);
deleteFromList(parentDirectory->subDirectories,
shortname);
ret = 1;
/* don't return, path maybe a song now*/
/* don't return, path maybe a song now */
}
}
else if((song = getSongDetails(path,&shortname,&parentDirectory))) {
if(!parentDirectory->stat && statDirectory(parentDirectory) < 0)
{
} else if ((song = getSongDetails(path, &shortname, &parentDirectory))) {
if (!parentDirectory->stat
&& statDirectory(parentDirectory) < 0) {
free(path);
return 0;
}
/* if this song update is successfull, we are done */
else if(0 == inodeFoundInParent(
parentDirectory->parent,
else if (0 == inodeFoundInParent(parentDirectory->parent,
parentDirectory->stat->inode,
parentDirectory->stat->device) &&
song && isMusic(getSongUrl(song), &mtime, 0))
{
parentDirectory->stat->device)
&& song && isMusic(getSongUrl(song), &mtime, 0)) {
free(path);
if(song->mtime==mtime) return 0;
else if(updateSongInfo(song)==0) return 1;
if (song->mtime == mtime)
return 0;
else if (updateSongInfo(song) == 0)
return 1;
else {
removeSongFromDirectory(parentDirectory,
shortname);
......@@ -555,7 +576,7 @@ static int updatePath(char * utf8path) {
else {
removeSongFromDirectory(parentDirectory, shortname);
ret = 1;
/* don't return, path maybe a directory now*/
/* don't return, path maybe a directory now */
}
}
......@@ -563,19 +584,16 @@ static int updatePath(char * utf8path) {
* Also, if by chance a directory was replaced by a file of the same
* name or vice versa, we need to add it to the db
*/
if(isDir(path) || isMusic(path,NULL,0)) {
parentDirectory = addParentPathToDB(path,&shortname);
if(!parentDirectory || (
!parentDirectory->stat &&
statDirectory(parentDirectory) < 0))
{
}
else if(0 == inodeFoundInParent(parentDirectory->parent,
if (isDir(path) || isMusic(path, NULL, 0)) {
parentDirectory = addParentPathToDB(path, &shortname);
if (!parentDirectory || (!parentDirectory->stat &&
statDirectory(parentDirectory) < 0)) {
} else if (0 == inodeFoundInParent(parentDirectory->parent,
parentDirectory->stat->inode,
parentDirectory->stat->device) &&
addToDirectory(parentDirectory, shortname, path)
>0)
{
parentDirectory->stat->
device)
&& addToDirectory(parentDirectory, shortname, path)
> 0) {
ret = 1;
}
}
......@@ -590,54 +608,60 @@ static int updatePath(char * utf8path) {
0 -> no error, but nothing updated
1 -> no error, and stuff updated
*/
static int updateDirectory(Directory * directory) {
DIR * dir;
static int updateDirectory(Directory * directory)
{
DIR *dir;
char cwd[2];
struct dirent * ent;
char * s;
char * utf8;
char * dirname = getDirectoryPath(directory);
struct dirent *ent;
char *s;
char *utf8;
char *dirname = getDirectoryPath(directory);
int ret = 0;
{
if(!directory->stat && statDirectory(directory) < 0) {
if (!directory->stat && statDirectory(directory) < 0) {
return -1;
}
else if(inodeFoundInParent(directory->parent,
} else if (inodeFoundInParent(directory->parent,
directory->stat->inode,
directory->stat->device))
{
directory->stat->device)) {
return -1;
}
}
cwd[0] = '.';
cwd[1] = '\0';
if(dirname==NULL) dirname=cwd;
if (dirname == NULL)
dirname = cwd;
if((dir = opendir(rmp2amp(utf8ToFsCharset(dirname))))==NULL) return -1;
if ((dir = opendir(rmp2amp(utf8ToFsCharset(dirname)))) == NULL)
return -1;
if(removeDeletedFromDirectory(directory, dir)>0) ret = 1;
if (removeDeletedFromDirectory(directory, dir) > 0)
ret = 1;
rewinddir(dir);
while((ent = readdir(dir))) {
if(ent->d_name[0]=='.') continue; /* hide hidden stuff */
if(strchr(ent->d_name, '\n')) continue;
while ((ent = readdir(dir))) {
if (ent->d_name[0] == '.')
continue; /* hide hidden stuff */
if (strchr(ent->d_name, '\n'))
continue;
utf8 = fsCharsetToUtf8(ent->d_name);
if(!utf8) continue;
if (!utf8)
continue;
utf8 = strdup(utf8);
if(directory->path) {
s = malloc(strlen(getDirectoryPath(directory))+
strlen(utf8)+2);
sprintf(s,"%s/%s", getDirectoryPath(directory), utf8);
}
else s = strdup(utf8);
if(updateInDirectory(directory,utf8,s)>0) ret = 1;
if (directory->path) {
s = malloc(strlen(getDirectoryPath(directory)) +
strlen(utf8) + 2);
sprintf(s, "%s/%s", getDirectoryPath(directory), utf8);
} else
s = strdup(utf8);
if (updateInDirectory(directory, utf8, s) > 0)
ret = 1;
free(utf8);
free(s);
}
......@@ -652,42 +676,49 @@ static int updateDirectory(Directory * directory) {
0 -> no error, but nothing found
1 -> no error, and stuff found
*/
static int exploreDirectory(Directory * directory) {
DIR * dir;
static int exploreDirectory(Directory * directory)
{
DIR *dir;
char cwd[2];
struct dirent * ent;
char * s;
char * utf8;
char * dirname = getDirectoryPath(directory);
struct dirent *ent;
char *s;
char *utf8;
char *dirname = getDirectoryPath(directory);
int ret = 0;
cwd[0] = '.';
cwd[1] = '\0';
if(dirname==NULL) dirname=cwd;
if (dirname == NULL)
dirname = cwd;
DEBUG("explore: attempting to opendir: %s\n",dirname);
if((dir = opendir(rmp2amp(utf8ToFsCharset(dirname))))==NULL) return -1;
DEBUG("explore: attempting to opendir: %s\n", dirname);
if ((dir = opendir(rmp2amp(utf8ToFsCharset(dirname)))) == NULL)
return -1;
DEBUG("explore: %s\n",dirname);
while((ent = readdir(dir))) {
if(ent->d_name[0]=='.') continue; /* hide hidden stuff */
if(strchr(ent->d_name, '\n')) continue;
DEBUG("explore: %s\n", dirname);
while ((ent = readdir(dir))) {
if (ent->d_name[0] == '.')
continue; /* hide hidden stuff */
if (strchr(ent->d_name, '\n'))
continue;
utf8 = fsCharsetToUtf8(ent->d_name);
if(!utf8) continue;
if (!utf8)
continue;
utf8 = strdup(utf8);
DEBUG("explore: found: %s (%s)\n",ent->d_name,utf8);
DEBUG("explore: found: %s (%s)\n", ent->d_name, utf8);
if(directory->path) {
s = malloc(strlen(getDirectoryPath(directory))+
strlen(utf8)+2);
sprintf(s,"%s/%s", getDirectoryPath(directory) ,utf8);
}
else s = strdup(utf8);
if(addToDirectory(directory,utf8,s)>0) ret = 1;
if (directory->path) {
s = malloc(strlen(getDirectoryPath(directory)) +
strlen(utf8) + 2);
sprintf(s, "%s/%s", getDirectoryPath(directory), utf8);
} else
s = strdup(utf8);
if (addToDirectory(directory, utf8, s) > 0)
ret = 1;
free(utf8);
free(s);
}
......@@ -697,10 +728,11 @@ static int exploreDirectory(Directory * directory) {
return ret;
}
static int statDirectory(Directory * dir) {
static int statDirectory(Directory * dir)
{
struct stat st;
if(myStat(getDirectoryPath(dir) ? getDirectoryPath(dir) : "", &st) < 0) {
if (myStat(getDirectoryPath(dir) ? getDirectoryPath(dir) : "", &st) < 0) {
return -1;
}
......@@ -709,14 +741,15 @@ static int statDirectory(Directory * dir) {
return 0;
}
static int inodeFoundInParent(Directory * parent, ino_t inode, dev_t device) {
while(parent) {
if(!parent->stat) {
if(statDirectory(parent) < 0) return -1;
static int inodeFoundInParent(Directory * parent, ino_t inode, dev_t device)
{
while (parent) {
if (!parent->stat) {
if (statDirectory(parent) < 0)
return -1;
}
if(parent->stat->inode == inode &&
parent->stat->device == device)
{
if (parent->stat->inode == inode &&
parent->stat->device == device) {
DEBUG("recursive directory found\n");
return 1;
}
......@@ -726,117 +759,126 @@ static int inodeFoundInParent(Directory * parent, ino_t inode, dev_t device) {
return 0;
}
static int addSubDirectoryToDirectory(Directory * directory, char * shortname,
char * name, struct stat * st)
static int addSubDirectoryToDirectory(Directory * directory, char *shortname,
char *name, struct stat *st)
{
Directory * subDirectory;
Directory *subDirectory;
if(inodeFoundInParent(directory, st->st_ino, st->st_dev)) return 0;
if (inodeFoundInParent(directory, st->st_ino, st->st_dev))
return 0;
subDirectory = newDirectory(name, directory);
subDirectory->stat = newDirectoryStat(st);
if(exploreDirectory(subDirectory)<1) {
if (exploreDirectory(subDirectory) < 1) {
freeDirectory(subDirectory);
return 0;
}
insertInList(directory->subDirectories, shortname,
subDirectory);
insertInList(directory->subDirectories, shortname, subDirectory);
return 1;
}
static int addToDirectory(Directory * directory, char * shortname, char * name) {
static int addToDirectory(Directory * directory, char *shortname, char *name)
{
struct stat st;
if(myStat(name, &st)) {
if (myStat(name, &st)) {
DEBUG("failed to stat %s: %s\n", name, strerror(errno));
return -1;
}
if(S_ISREG(st.st_mode) && hasMusicSuffix(name, 0)) {
Song * song;
if (S_ISREG(st.st_mode) && hasMusicSuffix(name, 0)) {
Song *song;
song = addSongToList(directory->songs, shortname, name,
SONG_TYPE_FILE, directory);
if(!song) return -1;
if (!song)
return -1;
LOG("added %s\n", name);
return 1;
}
else if(S_ISDIR(st.st_mode)) {
} else if (S_ISDIR(st.st_mode)) {
return addSubDirectoryToDirectory(directory, shortname, name,
&st);
}
DEBUG("addToDirectory: %s is not a directory or music\n",name);
DEBUG("addToDirectory: %s is not a directory or music\n", name);
return -1;
}
void closeMp3Directory() {
void closeMp3Directory()
{
freeDirectory(mp3rootDirectory);
}
static Directory * findSubDirectory(Directory * directory,char * name) {
void * subDirectory;
char * dup = strdup(name);
char * key;
static Directory *findSubDirectory(Directory * directory, char *name)
{
void *subDirectory;
char *dup = strdup(name);
char *key;
key = strtok(dup,"/");
if(!key) {
key = strtok(dup, "/");
if (!key) {
free(dup);
return NULL;
}
if(findInList(directory->subDirectories,key,&subDirectory)) {
if (findInList(directory->subDirectories, key, &subDirectory)) {
free(dup);
return (Directory *)subDirectory;
return (Directory *) subDirectory;
}
free(dup);
return NULL;
}
static Directory * getSubDirectory(Directory * directory, char * name,
char ** shortname)
static Directory *getSubDirectory(Directory * directory, char *name,
char **shortname)
{
Directory * subDirectory;
Directory *subDirectory;
int len;
if(name==NULL || name[0]=='\0' || strcmp(name,"/")==0) {
if (name == NULL || name[0] == '\0' || strcmp(name, "/") == 0) {
return directory;
}
if((subDirectory = findSubDirectory(directory,name))==NULL) return NULL;
if ((subDirectory = findSubDirectory(directory, name)) == NULL)
return NULL;
*shortname = name;
len = 0;
while(name[len]!='/' && name[len]!='\0') len++;
while(name[len]=='/') len++;
while (name[len] != '/' && name[len] != '\0')
len++;
while (name[len] == '/')
len++;
return getSubDirectory(subDirectory,&(name[len]),shortname);
return getSubDirectory(subDirectory, &(name[len]), shortname);
}
static Directory * getDirectoryDetails(char * name, char ** shortname) {
static Directory *getDirectoryDetails(char *name, char **shortname)
{
*shortname = NULL;
return getSubDirectory(mp3rootDirectory,name,shortname);
return getSubDirectory(mp3rootDirectory, name, shortname);
}
static Directory * getDirectory(char * name) {
char * shortname;
static Directory *getDirectory(char *name)
{
char *shortname;
return getSubDirectory(mp3rootDirectory,name,&shortname);
return getSubDirectory(mp3rootDirectory, name, &shortname);
}
static int printDirectoryList(FILE * fp, DirectoryList * directoryList) {
ListNode * node = directoryList->firstNode;
Directory * directory;
static int printDirectoryList(FILE * fp, DirectoryList * directoryList)
{
ListNode *node = directoryList->firstNode;
Directory *directory;
while(node!=NULL) {
directory = (Directory *)node->data;
myfprintf(fp,"%s%s\n", DIRECTORY_DIR,
while (node != NULL) {
directory = (Directory *) node->data;
myfprintf(fp, "%s%s\n", DIRECTORY_DIR,
getDirectoryPath(directory));
node = node->nextNode;
}
......@@ -844,145 +886,146 @@ static int printDirectoryList(FILE * fp, DirectoryList * directoryList) {
return 0;
}
int printDirectoryInfo(FILE * fp, char * name) {
Directory * directory;
int printDirectoryInfo(FILE * fp, char *name)
{
Directory *directory;
if((directory = getDirectory(name))==NULL) {
if ((directory = getDirectory(name)) == NULL) {
commandError(fp, ACK_ERROR_NO_EXIST, "directory not found",
NULL);
return -1;
}
printDirectoryList(fp,directory->subDirectories);
printSongInfoFromList(fp,directory->songs);
printDirectoryList(fp, directory->subDirectories);
printSongInfoFromList(fp, directory->songs);
return 0;
}
static void writeDirectoryInfo(FILE * fp, Directory * directory) {
ListNode * node = (directory->subDirectories)->firstNode;
Directory * subDirectory;
static void writeDirectoryInfo(FILE * fp, Directory * directory)
{
ListNode *node = (directory->subDirectories)->firstNode;
Directory *subDirectory;
if(directory->path) {
myfprintf(fp,"%s%s\n", DIRECTORY_BEGIN,
if (directory->path) {
myfprintf(fp, "%s%s\n", DIRECTORY_BEGIN,
getDirectoryPath(directory));
}
while(node!=NULL) {
subDirectory = (Directory *)node->data;
myfprintf(fp,"%s%s\n",DIRECTORY_DIR,node->key);
writeDirectoryInfo(fp,subDirectory);
while (node != NULL) {
subDirectory = (Directory *) node->data;
myfprintf(fp, "%s%s\n", DIRECTORY_DIR, node->key);
writeDirectoryInfo(fp, subDirectory);
node = node->nextNode;
}
writeSongInfoFromList(fp,directory->songs);
writeSongInfoFromList(fp, directory->songs);
if(directory->path) {
myfprintf(fp,"%s%s\n", DIRECTORY_END,
if (directory->path) {
myfprintf(fp, "%s%s\n", DIRECTORY_END,
getDirectoryPath(directory));
}
}
static void readDirectoryInfo(FILE * fp,Directory * directory) {
char buffer[MAXPATHLEN*2];
int bufferSize = MAXPATHLEN*2;
char * key;
Directory * subDirectory;
static void readDirectoryInfo(FILE * fp, Directory * directory)
{
char buffer[MAXPATHLEN * 2];
int bufferSize = MAXPATHLEN * 2;
char *key;
Directory *subDirectory;
int strcmpRet;
char * name;
ListNode * nextDirNode = directory->subDirectories->firstNode;
ListNode * nodeTemp;
char *name;
ListNode *nextDirNode = directory->subDirectories->firstNode;
ListNode *nodeTemp;
while(myFgets(buffer,bufferSize,fp) && 0!=strncmp(DIRECTORY_END,buffer,strlen(DIRECTORY_END))) {
if(0==strncmp(DIRECTORY_DIR,buffer,strlen(DIRECTORY_DIR))) {
while (myFgets(buffer, bufferSize, fp)
&& 0 != strncmp(DIRECTORY_END, buffer, strlen(DIRECTORY_END))) {
if (0 == strncmp(DIRECTORY_DIR, buffer, strlen(DIRECTORY_DIR))) {
key = strdup(&(buffer[strlen(DIRECTORY_DIR)]));
if(myFgets(buffer,bufferSize,fp)<0) {
if (myFgets(buffer, bufferSize, fp) < 0) {
ERROR("Error reading db, fgets\n");
exit(EXIT_FAILURE);
}
/* for compatibility with db's prior to 0.11 */
if(0==strncmp(DIRECTORY_MTIME,buffer,
strlen(DIRECTORY_MTIME)))
{
if(myFgets(buffer,bufferSize,fp)<0) {
if (0 == strncmp(DIRECTORY_MTIME, buffer,
strlen(DIRECTORY_MTIME))) {
if (myFgets(buffer, bufferSize, fp) < 0) {
ERROR("Error reading db, fgets\n");
exit(EXIT_FAILURE);
}
}
if(strncmp(DIRECTORY_BEGIN,buffer,strlen(DIRECTORY_BEGIN))) {
ERROR("Error reading db at line: %s\n",buffer);
if (strncmp
(DIRECTORY_BEGIN, buffer,
strlen(DIRECTORY_BEGIN))) {
ERROR("Error reading db at line: %s\n", buffer);
exit(EXIT_FAILURE);
}
name = strdup(&(buffer[strlen(DIRECTORY_BEGIN)]));
while(nextDirNode && (strcmpRet =
strcmp(key,nextDirNode->key)) > 0) {
while (nextDirNode && (strcmpRet =
strcmp(key,
nextDirNode->key)) > 0) {
nodeTemp = nextDirNode->nextNode;
deleteNodeFromList(directory->subDirectories,
nextDirNode);
nextDirNode = nodeTemp;
}
if(NULL==nextDirNode) {
if (NULL == nextDirNode) {
subDirectory = newDirectory(name, directory);
insertInList(directory->subDirectories,
key,
(void *)subDirectory);
}
else if(strcmpRet == 0) {
subDirectory = (Directory *)nextDirNode->data;
key, (void *)subDirectory);
} else if (strcmpRet == 0) {
subDirectory = (Directory *) nextDirNode->data;
nextDirNode = nextDirNode->nextNode;
}
else {
} else {
subDirectory = newDirectory(name, directory);
insertInListBeforeNode(
directory->subDirectories,
nextDirNode,
-1,
key,
insertInListBeforeNode(directory->
subDirectories,
nextDirNode, -1, key,
(void *)subDirectory);
}
free(name);
free(key);
readDirectoryInfo(fp,subDirectory);
}
else if(0==strncmp(SONG_BEGIN,buffer,strlen(SONG_BEGIN))) {
readDirectoryInfo(fp, subDirectory);
} else if (0 == strncmp(SONG_BEGIN, buffer, strlen(SONG_BEGIN))) {
readSongInfoIntoList(fp, directory->songs, directory);
}
else {
ERROR("Unknown line in db: %s\n",buffer);
} else {
ERROR("Unknown line in db: %s\n", buffer);
exit(EXIT_FAILURE);
}
}
while(nextDirNode) {
while (nextDirNode) {
nodeTemp = nextDirNode->nextNode;
deleteNodeFromList(directory->subDirectories,nextDirNode);
deleteNodeFromList(directory->subDirectories, nextDirNode);
nextDirNode = nodeTemp;
}
}
static void sortDirectory(Directory * directory) {
ListNode * node = directory->subDirectories->firstNode;
Directory * subDir;
static void sortDirectory(Directory * directory)
{
ListNode *node = directory->subDirectories->firstNode;
Directory *subDir;
sortList(directory->subDirectories);
sortList(directory->songs);
while(node!=NULL) {
subDir = (Directory *)node->data;
while (node != NULL) {
subDir = (Directory *) node->data;
sortDirectory(subDir);
node = node->nextNode;
}
}
int checkDirectoryDB() {
char * dbFile = getDbFile();
int checkDirectoryDB()
{
char *dbFile = getDbFile();
/**
* Check if the file exists
*/
if(access(dbFile, F_OK)) {
if (access(dbFile, F_OK)) {
char *dirPath = NULL;
char *dbPath = strdup(dbFile);
......@@ -995,9 +1038,9 @@ int checkDirectoryDB() {
/**
* Check if we can write to the directory
*/
if(access(dirPath, R_OK|W_OK))
{
ERROR("Can't create db file in \"%s\": %s", dirPath, strerror(errno));
if (access(dirPath, R_OK | W_OK)) {
ERROR("Can't create db file in \"%s\": %s", dirPath,
strerror(errno));
free(dbPath);
return -1;
......@@ -1009,7 +1052,7 @@ int checkDirectoryDB() {
/**
* File exists, now check if we can write it
*/
if(access(dbFile, R_OK|W_OK)) {
if (access(dbFile, R_OK | W_OK)) {
ERROR("db file \"%s\" cannot be opened for reading/writing: %s",
dbFile, strerror(errno));
return -1;
......@@ -1018,9 +1061,10 @@ int checkDirectoryDB() {
return 0;
}
int writeDirectoryDB() {
FILE * fp;
char * dbFile = getDbFile();
int writeDirectoryDB()
{
FILE *fp;
char *dbFile = getDbFile();
DEBUG("removing empty directories from DB\n");
deleteEmptyDirectoriesInDirectory(mp3rootDirectory);
......@@ -1031,34 +1075,36 @@ int writeDirectoryDB() {
DEBUG("writing DB\n");
while(!(fp=fopen(dbFile,"w")) && errno==EINTR);
if(!fp) {
while (!(fp = fopen(dbFile, "w")) && errno == EINTR) ;
if (!fp) {
ERROR("unable to write to db file \"%s\": %s\n",
dbFile, strerror(errno));
return -1;
}
/* block signals when writing the db so we don't get a corrupted db*/
myfprintf(fp,"%s\n",DIRECTORY_INFO_BEGIN);
myfprintf(fp,"%s%s\n",DIRECTORY_MPD_VERSION,VERSION);
myfprintf(fp,"%s%s\n",DIRECTORY_FS_CHARSET,getFsCharset());
myfprintf(fp,"%s\n",DIRECTORY_INFO_END);
/* block signals when writing the db so we don't get a corrupted db */
myfprintf(fp, "%s\n", DIRECTORY_INFO_BEGIN);
myfprintf(fp, "%s%s\n", DIRECTORY_MPD_VERSION, VERSION);
myfprintf(fp, "%s%s\n", DIRECTORY_FS_CHARSET, getFsCharset());
myfprintf(fp, "%s\n", DIRECTORY_INFO_END);
writeDirectoryInfo(fp,mp3rootDirectory);
writeDirectoryInfo(fp, mp3rootDirectory);
while(fclose(fp) && errno==EINTR);
while (fclose(fp) && errno == EINTR) ;
return 0;
}
int readDirectoryDB() {
FILE * fp = NULL;
char * dbFile = getDbFile();
int readDirectoryDB()
{
FILE *fp = NULL;
char *dbFile = getDbFile();
struct stat st;
if(!mp3rootDirectory) mp3rootDirectory = newDirectory(NULL, NULL);
while(!(fp=fopen(dbFile,"r")) && errno==EINTR);
if(fp == NULL) {
if (!mp3rootDirectory)
mp3rootDirectory = newDirectory(NULL, NULL);
while (!(fp = fopen(dbFile, "r")) && errno == EINTR) ;
if (fp == NULL) {
ERROR("unable open db file \"%s\": %s\n",
dbFile, strerror(errno));
return -1;
......@@ -1071,31 +1117,30 @@ int readDirectoryDB() {
int foundFsCharset = 0;
int foundVersion = 0;
if(myFgets(buffer,bufferSize,fp)<0) {
if (myFgets(buffer, bufferSize, fp) < 0) {
ERROR("Error reading db, fgets\n");
exit(EXIT_FAILURE);
}
if(0==strcmp(DIRECTORY_INFO_BEGIN,buffer)) {
while(myFgets(buffer,bufferSize,fp) &&
0!=strcmp(DIRECTORY_INFO_END,buffer))
{
if(0==strncmp(DIRECTORY_MPD_VERSION,buffer,
if (0 == strcmp(DIRECTORY_INFO_BEGIN, buffer)) {
while (myFgets(buffer, bufferSize, fp) &&
0 != strcmp(DIRECTORY_INFO_END, buffer)) {
if (0 == strncmp(DIRECTORY_MPD_VERSION, buffer,
strlen(DIRECTORY_MPD_VERSION)))
{
if(foundVersion) {
if (foundVersion) {
ERROR("already found "
"version in db\n");
exit(EXIT_FAILURE);
}
foundVersion = 1;
}
else if(0==strncmp(DIRECTORY_FS_CHARSET,buffer,
strlen(DIRECTORY_FS_CHARSET)))
{
char * fsCharset;
char * tempCharset;
if(foundFsCharset) {
} else if (0 ==
strncmp(DIRECTORY_FS_CHARSET, buffer,
strlen
(DIRECTORY_FS_CHARSET))) {
char *fsCharset;
char *tempCharset;
if (foundFsCharset) {
WARNING("already found "
"fs charset in db\n");
exit(EXIT_FAILURE);
......@@ -1103,56 +1148,57 @@ int readDirectoryDB() {
foundFsCharset = 1;
fsCharset = &(buffer[strlen(
DIRECTORY_FS_CHARSET)]);
if((tempCharset =
getConfigParamValue(
CONF_FS_CHARSET)) &&
strcmp(fsCharset,tempCharset))
{
fsCharset =
&(buffer
[strlen(DIRECTORY_FS_CHARSET)]);
if ((tempCharset =
getConfigParamValue
(CONF_FS_CHARSET))
&& strcmp(fsCharset, tempCharset)) {
WARNING("Using \"%s\" for the "
"filesystem charset "
"instead of \"%s\"\n",
fsCharset,tempCharset);
fsCharset, tempCharset);
WARNING("maybe you need to "
"recreate the db?\n");
setFsCharset(fsCharset);
}
}
else {
ERROR("directory: unknown line in db info: %s\n",
} else {
ERROR
("directory: unknown line in db info: %s\n",
buffer);
exit(EXIT_FAILURE);
}
}
}
else {
} else {
ERROR("db info not found in db file\n");
ERROR("you should recreate the db using --create-db\n");
fseek(fp,0,SEEK_SET);
fseek(fp, 0, SEEK_SET);
}
}
DEBUG("reading DB\n");
readDirectoryInfo(fp,mp3rootDirectory);
while(fclose(fp) && errno==EINTR);
readDirectoryInfo(fp, mp3rootDirectory);
while (fclose(fp) && errno == EINTR) ;
stats.numberOfSongs = countSongsIn(stderr,NULL);
stats.dbPlayTime = sumSongTimesIn(stderr,NULL);
stats.numberOfSongs = countSongsIn(stderr, NULL);
stats.dbPlayTime = sumSongTimesIn(stderr, NULL);
if(stat(dbFile,&st)==0) directory_dbModTime = st.st_mtime;
if (stat(dbFile, &st) == 0)
directory_dbModTime = st.st_mtime;
return 0;
}
void updateMp3Directory() {
switch(updateDirectory(mp3rootDirectory)) {
void updateMp3Directory()
{
switch (updateDirectory(mp3rootDirectory)) {
case 0:
/* nothing updated */
return;
case 1:
if(writeDirectoryDB()<0) {
if (writeDirectoryDB() < 0) {
exit(EXIT_FAILURE);
}
break;
......@@ -1166,50 +1212,53 @@ void updateMp3Directory() {
}
static int traverseAllInSubDirectory(FILE * fp, Directory * directory,
int (*forEachSong)(FILE *, Song *, void *),
int (*forEachDir)(FILE *, Directory *, void *),
void * data)
int (*forEachSong) (FILE *, Song *,
void *),
int (*forEachDir) (FILE *, Directory *,
void *), void *data)
{
ListNode * node = directory->songs->firstNode;
Song * song;
Directory * dir;
ListNode *node = directory->songs->firstNode;
Song *song;
Directory *dir;
int errFlag = 0;
if(forEachDir) {
errFlag = forEachDir(fp,directory,data);
if(errFlag) return errFlag;
if (forEachDir) {
errFlag = forEachDir(fp, directory, data);
if (errFlag)
return errFlag;
}
if(forEachSong) {
while(node!=NULL && !errFlag) {
song = (Song *)node->data;
errFlag = forEachSong(fp,song,data);
if (forEachSong) {
while (node != NULL && !errFlag) {
song = (Song *) node->data;
errFlag = forEachSong(fp, song, data);
node = node->nextNode;
}
if(errFlag) return errFlag;
if (errFlag)
return errFlag;
}
node = directory->subDirectories->firstNode;
while(node!=NULL && !errFlag) {
dir = (Directory *)node->data;
errFlag = traverseAllInSubDirectory(fp,dir,forEachSong,
forEachDir,data);
while (node != NULL && !errFlag) {
dir = (Directory *) node->data;
errFlag = traverseAllInSubDirectory(fp, dir, forEachSong,
forEachDir, data);
node = node->nextNode;
}
return errFlag;
}
int traverseAllIn(FILE * fp, char * name,
int (*forEachSong)(FILE *, Song *, void *),
int (*forEachDir)(FILE *, Directory *, void *),
void * data) {
Directory * directory;
int traverseAllIn(FILE * fp, char *name,
int (*forEachSong) (FILE *, Song *, void *),
int (*forEachDir) (FILE *, Directory *, void *), void *data)
{
Directory *directory;
if((directory = getDirectory(name))==NULL) {
Song * song;
if((song = getSongFromDB(name)) && forEachSong) {
if ((directory = getDirectory(name)) == NULL) {
Song *song;
if ((song = getSongFromDB(name)) && forEachSong) {
return forEachSong(fp, song, data);
}
commandError(fp, ACK_ERROR_NO_EXIST,
......@@ -1217,77 +1266,85 @@ int traverseAllIn(FILE * fp, char * name,
return -1;
}
return traverseAllInSubDirectory(fp,directory,forEachSong,forEachDir,
return traverseAllInSubDirectory(fp, directory, forEachSong, forEachDir,
data);
}
static void freeAllDirectoryStats(Directory * directory) {
ListNode * node = directory->subDirectories->firstNode;
static void freeAllDirectoryStats(Directory * directory)
{
ListNode *node = directory->subDirectories->firstNode;
while(node != NULL) {
freeAllDirectoryStats((Directory *)node->data);
while (node != NULL) {
freeAllDirectoryStats((Directory *) node->data);
node = node->nextNode;
}
freeDirectoryStatFromDirectory(directory);
}
void initMp3Directory() {
void initMp3Directory()
{
struct stat st;
mp3rootDirectory = newDirectory(NULL, NULL);
exploreDirectory(mp3rootDirectory);
freeAllDirectoryStats(mp3rootDirectory);
stats.numberOfSongs = countSongsIn(stderr,NULL);
stats.dbPlayTime = sumSongTimesIn(stderr,NULL);
stats.numberOfSongs = countSongsIn(stderr, NULL);
stats.dbPlayTime = sumSongTimesIn(stderr, NULL);
if(stat(getDbFile(),&st)==0) directory_dbModTime = st.st_mtime;
if (stat(getDbFile(), &st) == 0)
directory_dbModTime = st.st_mtime;
}
static Song * getSongDetails(char * file, char ** shortnameRet,
static Song *getSongDetails(char *file, char **shortnameRet,
Directory ** directoryRet)
{
void * song = NULL;
Directory * directory;
char * dir = NULL;
char * dup = strdup(file);
char * shortname = dup;
char * c = strtok(dup,"/");
void *song = NULL;
Directory *directory;
char *dir = NULL;
char *dup = strdup(file);
char *shortname = dup;
char *c = strtok(dup, "/");
DEBUG("get song: %s\n",file);
DEBUG("get song: %s\n", file);
while(c) {
while (c) {
shortname = c;
c = strtok(NULL,"/");
c = strtok(NULL, "/");
}
if(shortname!=dup) {
for(c = dup; c < shortname-1; c++) {
if(*c=='\0') *c = '/';
if (shortname != dup) {
for (c = dup; c < shortname - 1; c++) {
if (*c == '\0')
*c = '/';
}
dir = dup;
}
if(!(directory = getDirectory(dir))) {
if (!(directory = getDirectory(dir))) {
free(dup);
return NULL;
}
if(!findInList(directory->songs,shortname,&song)) {
if (!findInList(directory->songs, shortname, &song)) {
free(dup);
return NULL;
}
free(dup);
if(shortnameRet) *shortnameRet = shortname;
if(directoryRet) *directoryRet = directory;
return (Song *)song;
if (shortnameRet)
*shortnameRet = shortname;
if (directoryRet)
*directoryRet = directory;
return (Song *) song;
}
Song * getSongFromDB(char * file) {
return getSongDetails(file,NULL,NULL);
Song *getSongFromDB(char *file)
{
return getSongDetails(file, NULL, NULL);
}
time_t getDbModTime() {
time_t getDbModTime()
{
return directory_dbModTime;
}
......@@ -32,11 +32,11 @@ typedef struct _DirectoryStat {
} DirectoryStat;
typedef struct _Directory {
char * path;
DirectoryList * subDirectories;
SongList * songs;
struct _Directory * parent;
DirectoryStat * stat;
char *path;
DirectoryList *subDirectories;
SongList *songs;
struct _Directory *parent;
DirectoryStat *stat;
} Directory;
void readDirectoryDBIfUpdateIsFinished();
......@@ -51,7 +51,7 @@ void initMp3Directory();
void closeMp3Directory();
int printDirectoryInfo(FILE * fp, char * dirname);
int printDirectoryInfo(FILE * fp, char *dirname);
int checkDirectoryDB();
......@@ -61,14 +61,13 @@ int readDirectoryDB();
void updateMp3Directory();
Song * getSongFromDB(char * file);
Song *getSongFromDB(char *file);
time_t getDbModTime();
int traverseAllIn(FILE * fp, char * name,
int (*forEachSong)(FILE *, Song *, void *),
int (*forEachDir)(FILE *, Directory *, void *),
void * data);
int traverseAllIn(FILE * fp, char *name,
int (*forEachSong) (FILE *, Song *, void *),
int (*forEachDir) (FILE *, Directory *, void *), void *data);
#define getDirectoryPath(dir) ((dir && dir->path) ? dir->path : "")
......
......@@ -24,47 +24,59 @@
#include <stdlib.h>
#include <string.h>
static List * inputPlugin_list = NULL;
static List *inputPlugin_list = NULL;
void loadInputPlugin(InputPlugin * inputPlugin) {
if(!inputPlugin) return;
if(!inputPlugin->name) return;
void loadInputPlugin(InputPlugin * inputPlugin)
{
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);
}
void unloadInputPlugin(InputPlugin * inputPlugin) {
if(inputPlugin->finishFunc) inputPlugin->finishFunc();
void unloadInputPlugin(InputPlugin * inputPlugin)
{
if (inputPlugin->finishFunc)
inputPlugin->finishFunc();
deleteFromList(inputPlugin_list, inputPlugin->name);
}
static int stringFoundInStringArray(char ** array, char * suffix) {
while(array && *array) {
if(strcasecmp(*array, suffix) == 0) return 1;
static int stringFoundInStringArray(char **array, char *suffix)
{
while (array && *array) {
if (strcasecmp(*array, suffix) == 0)
return 1;
array++;
}
return 0;
}
InputPlugin * getInputPluginFromSuffix(char * suffix, unsigned int next) {
static ListNode * pos = NULL;
ListNode * node;
InputPlugin * plugin;
InputPlugin *getInputPluginFromSuffix(char *suffix, unsigned int next)
{
static ListNode *pos = NULL;
ListNode *node;
InputPlugin *plugin;
if(suffix == NULL) return NULL;
if (suffix == NULL)
return NULL;
if (next) {
if (pos) node = pos;
else return NULL;
if (pos)
node = pos;
else
return NULL;
} else
node = inputPlugin_list->firstNode;
while(node != NULL) {
while (node != NULL) {
plugin = node->data;
if(stringFoundInStringArray(plugin->suffixes, suffix)) {
if (stringFoundInStringArray(plugin->suffixes, suffix)) {
pos = node->nextNode;
return plugin;
}
......@@ -74,18 +86,20 @@ InputPlugin * getInputPluginFromSuffix(char * suffix, unsigned int next) {
return NULL;
}
InputPlugin * getInputPluginFromMimeType(char * mimeType, unsigned int next) {
static ListNode * pos = NULL;
ListNode * node;
InputPlugin * plugin;
InputPlugin *getInputPluginFromMimeType(char *mimeType, unsigned int next)
{
static ListNode *pos = NULL;
ListNode *node;
InputPlugin *plugin;
if(mimeType == NULL) return NULL;
if (mimeType == NULL)
return NULL;
node = (next && pos) ? pos : inputPlugin_list->firstNode;
while(node != NULL) {
while (node != NULL) {
plugin = node->data;
if(stringFoundInStringArray(plugin->mimeTypes, mimeType)) {
if (stringFoundInStringArray(plugin->mimeTypes, mimeType)) {
pos = node->nextNode;
return plugin;
}
......@@ -95,23 +109,25 @@ InputPlugin * getInputPluginFromMimeType(char * mimeType, unsigned int next) {
return NULL;
}
InputPlugin * getInputPluginFromName(char * name) {
void * plugin = NULL;
InputPlugin *getInputPluginFromName(char *name)
{
void *plugin = NULL;
findInList(inputPlugin_list, name, &plugin);
return (InputPlugin *)plugin;
return (InputPlugin *) plugin;
}
void printAllInputPluginSuffixes(FILE * fp) {
ListNode * node = inputPlugin_list->firstNode;
InputPlugin * plugin;
char ** suffixes;
void printAllInputPluginSuffixes(FILE * fp)
{
ListNode *node = inputPlugin_list->firstNode;
InputPlugin *plugin;
char **suffixes;
while(node) {
plugin = (InputPlugin *)node->data;
while (node) {
plugin = (InputPlugin *) node->data;
suffixes = plugin->suffixes;
while(suffixes && *suffixes) {
while (suffixes && *suffixes) {
myfprintf(fp, "%s ", *suffixes);
suffixes++;
}
......@@ -130,7 +146,8 @@ extern InputPlugin mpcPlugin;
extern InputPlugin aacPlugin;
extern InputPlugin modPlugin;
void initInputPlugins(void) {
void initInputPlugins(void)
{
inputPlugin_list = makeList(NULL, 1);
/* load plugins here */
......@@ -144,6 +161,7 @@ void initInputPlugins(void) {
loadInputPlugin(&modPlugin);
}
void finishInputPlugins(void) {
void finishInputPlugins(void)
{
freeList(inputPlugin_list);
}
......@@ -31,20 +31,20 @@
/* 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 */
typedef int (* InputPlugin_initFunc) ();
typedef int (*InputPlugin_initFunc) ();
/* 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
* 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
* and networked (HTTP) connections.
*
* returns -1 on error, 0 on success */
typedef int (* InputPlugin_streamDecodeFunc) (OutputBuffer *, DecoderControl *,
typedef int (*InputPlugin_streamDecodeFunc) (OutputBuffer *, DecoderControl *,
InputStream *);
/* 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 *,
* and FLAC libraries allow)
*
* returns -1 on error, 0 on success */
typedef int (* InputPlugin_fileDecodeFunc) (OutputBuffer *, DecoderControl *,
char * path);
typedef int (*InputPlugin_fileDecodeFunc) (OutputBuffer *, DecoderControl *,
char *path);
/* file should be the full path! Returns NULL if a tag cannot be found
* or read */
typedef MpdTag * (* InputPlugin_tagDupFunc) (char * file);
typedef MpdTag *(*InputPlugin_tagDupFunc) (char *file);
typedef struct _InputPlugin {
char * name;
char *name;
InputPlugin_initFunc initFunc;
InputPlugin_finishFunc finishFunc;
InputPlugin_tryDecodeFunc tryDecodeFunc;
......@@ -72,8 +72,8 @@ typedef struct _InputPlugin {
unsigned char streamTypes;
/* last element in these arrays must always be a NULL: */
char ** suffixes;
char ** mimeTypes;
char **suffixes;
char **mimeTypes;
} InputPlugin;
/* individual functions to load/unload plugins */
......@@ -82,11 +82,11 @@ void unloadInputPlugin(InputPlugin * inputPlugin);
/* 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);
......
......@@ -38,7 +38,7 @@
#include <FLAC/format.h>
#include <FLAC/metadata.h>
void init_FlacData (FlacData * data, OutputBuffer * cb,
void init_FlacData(FlacData * data, OutputBuffer * cb,
DecoderControl * dc, InputStream * inStream)
{
data->chunk_length = 0;
......@@ -53,18 +53,18 @@ void init_FlacData (FlacData * data, OutputBuffer * cb,
}
static int flacFindVorbisCommentFloat(const FLAC__StreamMetadata * block,
char * cmnt, float * fl)
char *cmnt, float *fl)
{
int offset = FLAC__metadata_object_vorbiscomment_find_entry_from(
block,0,cmnt);
int offset =
FLAC__metadata_object_vorbiscomment_find_entry_from(block, 0, cmnt);
if(offset >= 0) {
size_t pos = strlen(cmnt)+1; /* 1 is for '=' */
if (offset >= 0) {
size_t pos = strlen(cmnt) + 1; /* 1 is for '=' */
int len = block->data.vorbis_comment.comments[offset].length
-pos;
if(len > 0) {
- pos;
if (len > 0) {
unsigned char tmp;
unsigned char * dup = &(block->data.vorbis_comment.
unsigned char *dup = &(block->data.vorbis_comment.
comments[offset].entry[pos]);
tmp = dup[len];
dup[len] = '\0';
......@@ -79,8 +79,9 @@ static int flacFindVorbisCommentFloat(const FLAC__StreamMetadata * block,
}
/* replaygain stuff by AliasMrJones */
static void flacParseReplayGain(const FLAC__StreamMetadata *block,
FlacData * data) {
static void flacParseReplayGain(const FLAC__StreamMetadata * block,
FlacData * data)
{
unsigned int found = 0;
if (data->replayGainInfo)
......@@ -88,13 +89,13 @@ static void flacParseReplayGain(const FLAC__StreamMetadata *block,
data->replayGainInfo = newReplayGainInfo();
found &= flacFindVorbisCommentFloat(block,"replaygain_album_gain",
found &= flacFindVorbisCommentFloat(block, "replaygain_album_gain",
&data->replayGainInfo->albumGain);
found &= flacFindVorbisCommentFloat(block,"replaygain_album_peak",
found &= flacFindVorbisCommentFloat(block, "replaygain_album_peak",
&data->replayGainInfo->albumPeak);
found &= flacFindVorbisCommentFloat(block,"replaygain_track_gain",
found &= flacFindVorbisCommentFloat(block, "replaygain_track_gain",
&data->replayGainInfo->trackGain);
found &= flacFindVorbisCommentFloat(block,"replaygain_track_peak",
found &= flacFindVorbisCommentFloat(block, "replaygain_track_peak",
&data->replayGainInfo->trackPeak);
if (!found) {
......@@ -105,33 +106,38 @@ static void flacParseReplayGain(const FLAC__StreamMetadata *block,
/* tracknumber is used in VCs, MPD uses "track" ..., all the other
* tag names match */
static const char * VORBIS_COMMENT_TRACK_KEY = "tracknumber";
static const char * VORBIS_COMMENT_DISC_KEY = "discnumber";
static const char *VORBIS_COMMENT_TRACK_KEY = "tracknumber";
static const char *VORBIS_COMMENT_DISC_KEY = "discnumber";
static unsigned int commentMatchesAddToTag(
const FLAC__StreamMetadata_VorbisComment_Entry * entry,
unsigned int itemType,
static unsigned int commentMatchesAddToTag(const
FLAC__StreamMetadata_VorbisComment_Entry
* entry, unsigned int itemType,
MpdTag ** tag)
{
const char * str;
const char *str;
size_t slen;
int vlen;
switch (itemType) {
case TAG_ITEM_TRACK: str = VORBIS_COMMENT_TRACK_KEY; break;
case TAG_ITEM_DISC: str = VORBIS_COMMENT_DISC_KEY; break;
default: str = mpdTagItemKeys[itemType];
case TAG_ITEM_TRACK:
str = VORBIS_COMMENT_TRACK_KEY;
break;
case TAG_ITEM_DISC:
str = VORBIS_COMMENT_DISC_KEY;
break;
default:
str = mpdTagItemKeys[itemType];
}
slen = strlen(str);
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) == '=')) {
if (!*tag)
*tag = newMpdTag();
addItemToMpdTagWithLen(*tag, itemType,
(char *)(entry->entry+slen + 1), vlen);
(char *)(entry->entry + slen + 1), vlen);
return 1;
}
......@@ -139,7 +145,7 @@ static unsigned int commentMatchesAddToTag(
return 0;
}
MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
MpdTag *copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
MpdTag * tag)
{
unsigned int i, j;
......@@ -148,7 +154,7 @@ MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
comments = block->data.vorbis_comment.comments;
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))
break;
}
......@@ -158,12 +164,13 @@ MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
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;
const FLAC__StreamMetadata_StreamInfo *si = &(block->data.stream_info);
switch(block->type) {
switch (block->type) {
case FLAC__METADATA_TYPE_STREAMINFO:
dc->audioFormat.bits = si->bits_per_sample;
dc->audioFormat.sampleRate = si->sample_rate;
......@@ -173,19 +180,20 @@ void flac_metadata_common_cb(const FLAC__StreamMetadata *block, FlacData *data)
&(data->cb->audioFormat));
break;
case FLAC__METADATA_TYPE_VORBIS_COMMENT:
flacParseReplayGain(block,data);
flacParseReplayGain(block, data);
default:
break;
}
}
void flac_error_common_cb( const char * plugin,
void flac_error_common_cb(const char *plugin,
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:
ERROR("%s lost sync\n", plugin);
break;
......@@ -196,7 +204,7 @@ void flac_error_common_cb( const char * plugin,
ERROR("%s crc mismatch\n", plugin);
break;
default:
ERROR("unknown %s error\n",plugin);
ERROR("unknown %s error\n", plugin);
}
}
......
......@@ -41,38 +41,38 @@ typedef struct {
float time;
int bitRate;
FLAC__uint64 position;
OutputBuffer * cb;
DecoderControl * dc;
InputStream * inStream;
ReplayGainInfo * replayGainInfo;
MpdTag * tag;
OutputBuffer *cb;
DecoderControl *dc;
InputStream *inStream;
ReplayGainInfo *replayGainInfo;
MpdTag *tag;
} FlacData;
/* initializes a given FlacData struct */
void init_FlacData (FlacData * data, OutputBuffer * cb,
void init_FlacData(FlacData * data, OutputBuffer * cb,
DecoderControl * dc, InputStream * inStream);
void flac_metadata_common_cb( const FLAC__StreamMetadata *block,
FlacData *data);
void flac_error_common_cb( const char * plugin,
void flac_metadata_common_cb(const FLAC__StreamMetadata * block,
FlacData * data);
void flac_error_common_cb(const char *plugin,
FLAC__StreamDecoderErrorStatus status,
FlacData *data);
FlacData * data);
MpdTag * copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
MpdTag *copyVorbisCommentBlockToMpdTag(const FLAC__StreamMetadata * block,
MpdTag * tag);
/* keep this inlined, this is just macro but prettier :) */
static inline int flacSendChunk(FlacData * data)
{
if (sendDataToOutputBuffer(data->cb, NULL, data->dc, 1, data->chunk,
data->chunk_length, data->time, data->bitRate,
data->replayGainInfo) == OUTPUT_BUFFER_DC_STOP)
data->chunk_length, data->time,
data->bitRate,
data->replayGainInfo) ==
OUTPUT_BUFFER_DC_STOP)
return -1;
return 0;
}
#endif /* HAVE_FLAC || HAVE_OGGFLAC */
#endif /* _FLAC_COMMON_H */
......@@ -51,15 +51,23 @@ ogg_stream_type ogg_stream_type_detect(InputStream * inStream)
seekInputStream(inStream, 0, SEEK_SET);
if (r >= 32 && memcmp(buf, "OggS", 4) == 0 && (
(memcmp(buf+29, "FLAC", 4) == 0
&& memcmp(buf+37, "fLaC", 4) == 0)
|| (memcmp(buf+28, "FLAC", 4) == 0)
|| (memcmp(buf+28, "fLaC", 4) == 0))) {
if (r >= 32 && memcmp(buf, "OggS", 4) == 0 && ((memcmp
(buf + 29, "FLAC",
4) == 0
&& memcmp(buf + 37,
"fLaC",
4) == 0)
||
(memcmp
(buf + 28, "FLAC",
4) == 0)
||
(memcmp
(buf + 28, "fLaC",
4) == 0))) {
return FLAC;
}
return VORBIS;
}
#endif /* defined(HAVE_OGGFLAC || defined(HAVE_OGGVORBIS) */
......@@ -36,7 +36,7 @@
/* all code here is either based on or copied from FAAD2's frontend code */
typedef struct {
InputStream * inStream;
InputStream *inStream;
long bytesIntoBuffer;
long bytesConsumed;
long fileOffset;
......@@ -44,163 +44,193 @@ typedef struct {
int atEof;
} AacBuffer;
static void fillAacBuffer(AacBuffer *b) {
if(b->bytesConsumed > 0) {
static void fillAacBuffer(AacBuffer * b)
{
if (b->bytesConsumed > 0) {
int bread;
if(b->bytesIntoBuffer) {
memmove((void *)b->buffer,(void*)(b->buffer+
b->bytesConsumed),b->bytesIntoBuffer);
if (b->bytesIntoBuffer) {
memmove((void *)b->buffer, (void *)(b->buffer +
b->bytesConsumed),
b->bytesIntoBuffer);
}
if(!b->atEof) {
if (!b->atEof) {
bread = readFromInputStream(b->inStream,
(void *)(b->buffer+b->bytesIntoBuffer),
1,b->bytesConsumed);
if(bread!=b->bytesConsumed) b->atEof = 1;
b->bytesIntoBuffer+=bread;
(void *)(b->buffer +
b->
bytesIntoBuffer),
1, b->bytesConsumed);
if (bread != b->bytesConsumed)
b->atEof = 1;
b->bytesIntoBuffer += bread;
}
b->bytesConsumed = 0;
if(b->bytesIntoBuffer > 3) {
if(memcmp(b->buffer,"TAG",3)==0) b->bytesIntoBuffer = 0;
if (b->bytesIntoBuffer > 3) {
if (memcmp(b->buffer, "TAG", 3) == 0)
b->bytesIntoBuffer = 0;
}
if(b->bytesIntoBuffer > 11) {
if(memcmp(b->buffer,"LYRICSBEGIN",11)==0) {
if (b->bytesIntoBuffer > 11) {
if (memcmp(b->buffer, "LYRICSBEGIN", 11) == 0) {
b->bytesIntoBuffer = 0;
}
}
if(b->bytesIntoBuffer > 8) {
if(memcmp(b->buffer,"APETAGEX",8)==0) {
if (b->bytesIntoBuffer > 8) {
if (memcmp(b->buffer, "APETAGEX", 8) == 0) {
b->bytesIntoBuffer = 0;
}
}
}
}
static void advanceAacBuffer(AacBuffer * b, int bytes) {
b->fileOffset+=bytes;
static void advanceAacBuffer(AacBuffer * b, int bytes)
{
b->fileOffset += bytes;
b->bytesConsumed = bytes;
b->bytesIntoBuffer-=bytes;
b->bytesIntoBuffer -= bytes;
}
static int adtsSampleRates[] = {96000,88200,64000,48000,44100,32000,24000,22050,
16000,12000,11025,8000,7350,0,0,0};
static int adtsSampleRates[] =
{ 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
16000, 12000, 11025, 8000, 7350, 0, 0, 0
};
static int adtsParse(AacBuffer * b, float * length) {
static int adtsParse(AacBuffer * b, float *length)
{
int frames, frameLength;
int tFrameLength = 0;
int sampleRate = 0;
float framesPerSec, bytesPerFrame;
/* Read all frames to ensure correct time and bitrate */
for(frames = 0; ;frames++) {
for (frames = 0;; frames++) {
fillAacBuffer(b);
if(b->bytesIntoBuffer > 7) {
if (b->bytesIntoBuffer > 7) {
/* check syncword */
if (!((b->buffer[0] == 0xFF) &&
((b->buffer[1] & 0xF6) == 0xF0)))
{
((b->buffer[1] & 0xF6) == 0xF0))) {
break;
}
if(frames==0) {
sampleRate = adtsSampleRates[
(b->buffer[2]&0x3c)>>2];
if (frames == 0) {
sampleRate = adtsSampleRates[(b->
buffer[2] & 0x3c)
>> 2];
}
frameLength = ((((unsigned int)b->buffer[3] & 0x3))
<< 11) | (((unsigned int)b->buffer[4])
<< 3) | (b->buffer[5] >> 5);
tFrameLength+=frameLength;
tFrameLength += frameLength;
if(frameLength > b->bytesIntoBuffer) break;
if (frameLength > b->bytesIntoBuffer)
break;
advanceAacBuffer(b,frameLength);
}
else break;
advanceAacBuffer(b, frameLength);
} else
break;
}
framesPerSec = (float)sampleRate/1024.0;
if(frames!=0) {
bytesPerFrame = (float)tFrameLength/(float)(frames*1000);
}
else bytesPerFrame = 0;
if(framesPerSec!=0) *length = (float)frames/framesPerSec;
framesPerSec = (float)sampleRate / 1024.0;
if (frames != 0) {
bytesPerFrame = (float)tFrameLength / (float)(frames * 1000);
} else
bytesPerFrame = 0;
if (framesPerSec != 0)
*length = (float)frames / framesPerSec;
return 1;
}
static void initAacBuffer(InputStream * inStream, AacBuffer * b, float * length,
static void initAacBuffer(InputStream * inStream, AacBuffer * b, float *length,
size_t * retFileread, size_t * retTagsize)
{
size_t fileread;
size_t bread;
size_t tagsize;
if(length) *length = -1;
if (length)
*length = -1;
memset(b,0,sizeof(AacBuffer));
memset(b, 0, sizeof(AacBuffer));
b->inStream = inStream;
fileread = inStream->size;
b->buffer = malloc(FAAD_MIN_STREAMSIZE*AAC_MAX_CHANNELS);
memset(b->buffer,0,FAAD_MIN_STREAMSIZE*AAC_MAX_CHANNELS);
b->buffer = malloc(FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS);
memset(b->buffer, 0, FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS);
bread = readFromInputStream(inStream,b->buffer,1,
FAAD_MIN_STREAMSIZE*AAC_MAX_CHANNELS);
bread = readFromInputStream(inStream, b->buffer, 1,
FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS);
b->bytesIntoBuffer = bread;
b->bytesConsumed = 0;
b->fileOffset = 0;
if(bread!=FAAD_MIN_STREAMSIZE*AAC_MAX_CHANNELS) b->atEof = 1;
if (bread != FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS)
b->atEof = 1;
tagsize = 0;
if(!memcmp(b->buffer,"ID3",3)) {
if (!memcmp(b->buffer, "ID3", 3)) {
tagsize = (b->buffer[6] << 21) | (b->buffer[7] << 14) |
(b->buffer[8] << 7) | (b->buffer[9] << 0);
tagsize+=10;
advanceAacBuffer(b,tagsize);
tagsize += 10;
advanceAacBuffer(b, tagsize);
fillAacBuffer(b);
}
if(retFileread) *retFileread = fileread;
if(retTagsize) *retTagsize = tagsize;
if (retFileread)
*retFileread = fileread;
if (retTagsize)
*retTagsize = tagsize;
if(length==NULL) return;
if (length == NULL)
return;
if((b->buffer[0] == 0xFF) && ((b->buffer[1] & 0xF6) == 0xF0)) {
if ((b->buffer[0] == 0xFF) && ((b->buffer[1] & 0xF6) == 0xF0)) {
adtsParse(b, length);
seekInputStream(b->inStream, tagsize, SEEK_SET);
bread = readFromInputStream(b->inStream, b->buffer, 1,
FAAD_MIN_STREAMSIZE*AAC_MAX_CHANNELS);
if(bread != FAAD_MIN_STREAMSIZE*AAC_MAX_CHANNELS) b->atEof = 1;
else b->atEof = 0;
FAAD_MIN_STREAMSIZE *
AAC_MAX_CHANNELS);
if (bread != FAAD_MIN_STREAMSIZE * AAC_MAX_CHANNELS)
b->atEof = 1;
else
b->atEof = 0;
b->bytesIntoBuffer = bread;
b->bytesConsumed = 0;
b->fileOffset = tagsize;
}
else if(memcmp(b->buffer,"ADIF",4) == 0) {
} else if (memcmp(b->buffer, "ADIF", 4) == 0) {
int bitRate;
int skipSize = (b->buffer[4] & 0x80) ? 9 : 0;
bitRate = ((unsigned int)(b->buffer[4 + skipSize] & 0x0F)<<19) |
((unsigned int)b->buffer[5 + skipSize]<<11) |
((unsigned int)b->buffer[6 + skipSize]<<3) |
((unsigned int)b->buffer[7 + skipSize] & 0xE0);
bitRate =
((unsigned int)(b->
buffer[4 +
skipSize] & 0x0F) << 19) | ((unsigned
int)b->
buffer[5
+
skipSize]
<< 11) |
((unsigned int)b->
buffer[6 + skipSize] << 3) | ((unsigned int)b->buffer[7 +
skipSize]
& 0xE0);
*length = fileread;
if(*length!=0 && bitRate!=0) *length = *length*8.0/bitRate;
if (*length != 0 && bitRate != 0)
*length = *length * 8.0 / bitRate;
}
}
static float getAacFloatTotalTime(char * file) {
static float getAacFloatTotalTime(char *file)
{
AacBuffer b;
float length;
size_t fileread, tagsize;
......@@ -211,46 +241,51 @@ static float getAacFloatTotalTime(char * file) {
InputStream inStream;
size_t bread;
if(openInputStream(&inStream,file) < 0) return -1;
if (openInputStream(&inStream, file) < 0)
return -1;
initAacBuffer(&inStream,&b,&length,&fileread,&tagsize);
initAacBuffer(&inStream, &b, &length, &fileread, &tagsize);
if(length < 0) {
if (length < 0) {
decoder = faacDecOpen();
config = faacDecGetCurrentConfiguration(decoder);
config->outputFormat = FAAD_FMT_16BIT;
faacDecSetConfiguration(decoder,config);
faacDecSetConfiguration(decoder, config);
fillAacBuffer(&b);
#ifdef HAVE_FAAD_BUFLEN_FUNCS
bread = faacDecInit(decoder,b.buffer,b.bytesIntoBuffer,
&sampleRate,&channels);
bread = faacDecInit(decoder, b.buffer, b.bytesIntoBuffer,
&sampleRate, &channels);
#else
bread = faacDecInit(decoder,b.buffer,&sampleRate,&channels);
bread = faacDecInit(decoder, b.buffer, &sampleRate, &channels);
#endif
if(bread >= 0 && sampleRate > 0 && channels > 0) length = 0;
if (bread >= 0 && sampleRate > 0 && channels > 0)
length = 0;
faacDecClose(decoder);
}
if(b.buffer) free(b.buffer);
if (b.buffer)
free(b.buffer);
closeInputStream(&inStream);
return length;
}
static int getAacTotalTime(char * file) {
static int getAacTotalTime(char *file)
{
int time = -1;
float length;
if((length = getAacFloatTotalTime(file))>=0) time = length+0.5;
if ((length = getAacFloatTotalTime(file)) >= 0)
time = length + 0.5;
return time;
}
static int aac_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
static int aac_decode(OutputBuffer * cb, DecoderControl * dc, char *path)
{
float time;
float totalTime;
faacDecHandle decoder;
......@@ -261,20 +296,22 @@ static int aac_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
unsigned char channels;
int eof = 0;
unsigned int sampleCount;
char * sampleBuffer;
char *sampleBuffer;
size_t sampleBufferLen;
/*float * seekTable;
long seekTableEnd = -1;
int seekPositionFound = 0;*/
int seekPositionFound = 0; */
mpd_uint16 bitRate = 0;
AacBuffer b;
InputStream inStream;
if((totalTime = getAacFloatTotalTime(path)) < 0) return -1;
if ((totalTime = getAacFloatTotalTime(path)) < 0)
return -1;
if(openInputStream(&inStream, path) < 0) return -1;
if (openInputStream(&inStream, path) < 0)
return -1;
initAacBuffer(&inStream,&b,NULL,NULL,NULL);
initAacBuffer(&inStream, &b, NULL, NULL, NULL);
decoder = faacDecOpen();
......@@ -286,21 +323,22 @@ static int aac_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
#ifdef HAVE_FAACDECCONFIGURATION_DONTUPSAMPLEIMPLICITSBR
config->dontUpSampleImplicitSBR = 0;
#endif
faacDecSetConfiguration(decoder,config);
faacDecSetConfiguration(decoder, config);
fillAacBuffer(&b);
#ifdef HAVE_FAAD_BUFLEN_FUNCS
bread = faacDecInit(decoder,b.buffer,b.bytesIntoBuffer,
&sampleRate,&channels);
bread = faacDecInit(decoder, b.buffer, b.bytesIntoBuffer,
&sampleRate, &channels);
#else
bread = faacDecInit(decoder,b.buffer,&sampleRate,&channels);
bread = faacDecInit(decoder, b.buffer, &sampleRate, &channels);
#endif
if(bread < 0) {
if (bread < 0) {
ERROR("Error not a AAC stream.\n");
faacDecClose(decoder);
closeInputStream(b.inStream);
if(b.buffer) free(b.buffer);
if (b.buffer)
free(b.buffer);
return -1;
}
......@@ -310,36 +348,34 @@ static int aac_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
time = 0.0;
advanceAacBuffer(&b,bread);
advanceAacBuffer(&b, bread);
while(!eof) {
while (!eof) {
fillAacBuffer(&b);
if(b.bytesIntoBuffer==0) {
if (b.bytesIntoBuffer == 0) {
eof = 1;
break;
}
#ifdef HAVE_FAAD_BUFLEN_FUNCS
sampleBuffer = faacDecDecode(decoder,&frameInfo,b.buffer,
sampleBuffer = faacDecDecode(decoder, &frameInfo, b.buffer,
b.bytesIntoBuffer);
#else
sampleBuffer = faacDecDecode(decoder,&frameInfo,b.buffer);
sampleBuffer = faacDecDecode(decoder, &frameInfo, b.buffer);
#endif
if(frameInfo.error > 0) {
if (frameInfo.error > 0) {
ERROR("error decoding AAC file: %s\n", path);
ERROR("faad2 error: %s\n",
faacDecGetErrorMessage(frameInfo.error));
eof = 1;
break;
}
#ifdef HAVE_FAACDECFRAMEINFO_SAMPLERATE
sampleRate = frameInfo.samplerate;
#endif
if(dc->state != DECODE_STATE_DECODE) {
if (dc->state != DECODE_STATE_DECODE) {
dc->audioFormat.channels = frameInfo.channels;
dc->audioFormat.sampleRate = sampleRate;
getOutputAudioFormat(&(dc->audioFormat),
......@@ -347,27 +383,27 @@ static int aac_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
dc->state = DECODE_STATE_DECODE;
}
advanceAacBuffer(&b,frameInfo.bytesconsumed);
advanceAacBuffer(&b, frameInfo.bytesconsumed);
sampleCount = (unsigned long)(frameInfo.samples);
if(sampleCount>0) {
bitRate = frameInfo.bytesconsumed*8.0*
frameInfo.channels*sampleRate/
frameInfo.samples/1000+0.5;
time+= (float)(frameInfo.samples)/frameInfo.channels/
if (sampleCount > 0) {
bitRate = frameInfo.bytesconsumed * 8.0 *
frameInfo.channels * sampleRate /
frameInfo.samples / 1000 + 0.5;
time +=
(float)(frameInfo.samples) / frameInfo.channels /
sampleRate;
}
sampleBufferLen = sampleCount*2;
sampleBufferLen = sampleCount * 2;
sendDataToOutputBuffer(cb, NULL, dc, 0, sampleBuffer,
sampleBufferLen, time, bitRate, NULL);
if(dc->seek) {
if (dc->seek) {
dc->seekError = 1;
dc->seek = 0;
}
else if(dc->stop) {
} else if (dc->stop) {
eof = 1;
break;
}
......@@ -377,45 +413,48 @@ static int aac_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
faacDecClose(decoder);
closeInputStream(b.inStream);
if(b.buffer) free(b.buffer);
if (b.buffer)
free(b.buffer);
if(dc->state != DECODE_STATE_DECODE) return -1;
if (dc->state != DECODE_STATE_DECODE)
return -1;
if(dc->seek) {
if (dc->seek) {
dc->seekError = 1;
dc->seek = 0;
}
if(dc->stop) {
if (dc->stop) {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
else dc->state = DECODE_STATE_STOP;
} else
dc->state = DECODE_STATE_STOP;
return 0;
}
static MpdTag * aacTagDup(char * file) {
MpdTag * ret = NULL;
static MpdTag *aacTagDup(char *file)
{
MpdTag *ret = NULL;
int time;
time = getAacTotalTime(file);
if(time>=0) {
if((ret = id3Dup(file))==NULL) ret = newMpdTag();
if (time >= 0) {
if ((ret = id3Dup(file)) == NULL)
ret = newMpdTag();
ret->time = time;
}
else {
DEBUG("aacTagDup: Failed to get total song time from: %s\n", file);
} else {
DEBUG("aacTagDup: Failed to get total song time from: %s\n",
file);
}
return ret;
}
static char * aacSuffixes[] = {"aac", NULL};
static char *aacSuffixes[] = { "aac", NULL };
InputPlugin aacPlugin =
{
InputPlugin aacPlugin = {
"aac",
NULL,
NULL,
......@@ -430,8 +469,7 @@ InputPlugin aacPlugin =
#else
InputPlugin aacPlugin =
{
InputPlugin aacPlugin = {
NULL,
NULL,
NULL,
......
......@@ -37,34 +37,35 @@
#include <unistd.h>
#include <audiofile.h>
static int getAudiofileTotalTime(char * file)
static int getAudiofileTotalTime(char *file)
{
int time;
AFfilehandle af_fp = afOpenFile(file, "r", NULL);
if(af_fp == AF_NULL_FILEHANDLE) {
if (af_fp == AF_NULL_FILEHANDLE) {
return -1;
}
time = (int)
((double)afGetFrameCount(af_fp,AF_DEFAULT_TRACK)
/afGetRate(af_fp,AF_DEFAULT_TRACK));
((double)afGetFrameCount(af_fp, AF_DEFAULT_TRACK)
/ afGetRate(af_fp, AF_DEFAULT_TRACK));
afCloseFile(af_fp);
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;
AFfilehandle af_fp;
int bits;
mpd_uint16 bitRate;
struct stat st;
if(stat(path, &st) < 0) {
if (stat(path, &st) < 0) {
ERROR("failed to stat: %s\n", path);
return -1;
}
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);
return -1;
}
......@@ -72,14 +73,15 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path)
afGetSampleFormat(af_fp, AF_DEFAULT_TRACK, &fs, &bits);
dc->audioFormat.bits = bits;
dc->audioFormat.sampleRate = afGetRate(af_fp, AF_DEFAULT_TRACK);
dc->audioFormat.channels = afGetChannels(af_fp,AF_DEFAULT_TRACK);
getOutputAudioFormat(&(dc->audioFormat),&(cb->audioFormat));
dc->audioFormat.channels = afGetChannels(af_fp, AF_DEFAULT_TRACK);
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) {
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)
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;
{
int ret, eof = 0, current = 0;
char chunk[CHUNK_SIZE];
while(!eof) {
if(dc->seek) {
while (!eof) {
if (dc->seek) {
clearOutputBuffer(cb);
current = dc->seekWhere *
dc->audioFormat.sampleRate;
afSeekFrame(af_fp, AF_DEFAULT_TRACK,current);
afSeekFrame(af_fp, AF_DEFAULT_TRACK, current);
dc->seek = 0;
}
ret = afReadFrames(af_fp, AF_DEFAULT_TRACK, chunk, CHUNK_SIZE/fs);
if(ret<=0) eof = 1;
ret =
afReadFrames(af_fp, AF_DEFAULT_TRACK, chunk,
CHUNK_SIZE / fs);
if (ret <= 0)
eof = 1;
else {
current += ret;
sendDataToOutputBuffer(cb,
......@@ -113,12 +118,13 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path)
dc,
1,
chunk,
ret*fs,
ret * fs,
(float)current /
(float)dc->audioFormat.sampleRate,
bitRate,
(float)dc->audioFormat.
sampleRate, bitRate,
NULL);
if(dc->stop) break;
if (dc->stop)
break;
}
}
......@@ -127,38 +133,40 @@ static int audiofile_decode(OutputBuffer * cb, DecoderControl * dc, char * path)
/*if(dc->seek) {
dc->seekError = 1;
dc->seek = 0;
}*/
} */
if(dc->stop) {
if (dc->stop) {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
else dc->state = DECODE_STATE_STOP;
} else
dc->state = DECODE_STATE_STOP;
}
afCloseFile(af_fp);
return 0;
}
static MpdTag * audiofileTagDup(char * file) {
MpdTag * ret = NULL;
static MpdTag *audiofileTagDup(char *file)
{
MpdTag *ret = NULL;
int time = getAudiofileTotalTime(file);
if (time>=0) {
if(!ret) ret = newMpdTag();
if (time >= 0) {
if (!ret)
ret = newMpdTag();
ret->time = time;
}
else {
DEBUG("audiofileTagDup: Failed to get total song time from: %s\n", file);
} else {
DEBUG
("audiofileTagDup: Failed to get total song time from: %s\n",
file);
}
return ret;
}
static char * audiofileSuffixes[] = {"wav", "au", "aiff", "aif", NULL};
static char *audiofileSuffixes[] = { "wav", "au", "aiff", "aif", NULL };
InputPlugin audiofilePlugin =
{
InputPlugin audiofilePlugin = {
"audiofile",
NULL,
NULL,
......@@ -173,8 +181,7 @@ InputPlugin audiofilePlugin =
#else
InputPlugin audiofilePlugin =
{
InputPlugin audiofilePlugin = {
NULL,
NULL,
NULL,
......
......@@ -43,111 +43,126 @@ static void flacError(const FLAC__SeekableStreamDecoder *,
static void flacPrintErroredState(FLAC__SeekableStreamDecoderState state);
static void flacMetadata(const FLAC__SeekableStreamDecoder *,
const FLAC__StreamMetadata *, void *);
static FLAC__StreamDecoderWriteStatus flacWrite(const FLAC__SeekableStreamDecoder *,
const FLAC__Frame *, const FLAC__int32 * const buf[], void *);
static FLAC__SeekableStreamDecoderReadStatus flacRead(
const FLAC__SeekableStreamDecoder *, FLAC__byte buf[],
static FLAC__StreamDecoderWriteStatus flacWrite(const
FLAC__SeekableStreamDecoder *,
const FLAC__Frame *,
const FLAC__int32 * const buf[],
void *);
static FLAC__SeekableStreamDecoderReadStatus flacRead(const
FLAC__SeekableStreamDecoder
*, FLAC__byte buf[],
unsigned *, void *);
static FLAC__SeekableStreamDecoderSeekStatus flacSeek(
const FLAC__SeekableStreamDecoder *, FLAC__uint64, void *);
static FLAC__SeekableStreamDecoderTellStatus flacTell(
const FLAC__SeekableStreamDecoder *, FLAC__uint64 *, void *);
static FLAC__SeekableStreamDecoderLengthStatus flacLength(
const FLAC__SeekableStreamDecoder *, FLAC__uint64 *, void *);
static FLAC__SeekableStreamDecoderSeekStatus flacSeek(const
FLAC__SeekableStreamDecoder
*, FLAC__uint64, void *);
static FLAC__SeekableStreamDecoderTellStatus flacTell(const
FLAC__SeekableStreamDecoder
*, FLAC__uint64 *,
void *);
static FLAC__SeekableStreamDecoderLengthStatus flacLength(const
FLAC__SeekableStreamDecoder
*, FLAC__uint64 *,
void *);
static FLAC__bool flacEOF(const FLAC__SeekableStreamDecoder *, void *);
static int flac_decode(OutputBuffer * cb, DecoderControl * dc, InputStream * inStream)
static int flac_decode(OutputBuffer * cb, DecoderControl * dc,
InputStream * inStream)
{
FLAC__SeekableStreamDecoder * flacDec = NULL;
FLAC__SeekableStreamDecoder *flacDec = NULL;
FlacData data;
int status = 1;
int ret =0;
int ret = 0;
init_FlacData(&data, cb, dc, inStream);
if(!(flacDec = FLAC__seekable_stream_decoder_new())) {
if (!(flacDec = FLAC__seekable_stream_decoder_new())) {
ret = -1;
goto fail;
}
/*status&=FLAC__file_decoder_set_md5_checking(flacDec,1);*/
status&=FLAC__seekable_stream_decoder_set_read_callback(flacDec,
/*status&=FLAC__file_decoder_set_md5_checking(flacDec,1); */
status &= FLAC__seekable_stream_decoder_set_read_callback(flacDec,
flacRead);
status&=FLAC__seekable_stream_decoder_set_seek_callback(flacDec,
status &= FLAC__seekable_stream_decoder_set_seek_callback(flacDec,
flacSeek);
status&=FLAC__seekable_stream_decoder_set_tell_callback(flacDec,
status &= FLAC__seekable_stream_decoder_set_tell_callback(flacDec,
flacTell);
status&=FLAC__seekable_stream_decoder_set_length_callback(flacDec,
status &= FLAC__seekable_stream_decoder_set_length_callback(flacDec,
flacLength);
status&=FLAC__seekable_stream_decoder_set_eof_callback(flacDec,flacEOF);
status&=FLAC__seekable_stream_decoder_set_write_callback(flacDec,
status &=
FLAC__seekable_stream_decoder_set_eof_callback(flacDec, flacEOF);
status &=
FLAC__seekable_stream_decoder_set_write_callback(flacDec,
flacWrite);
status&=FLAC__seekable_stream_decoder_set_metadata_callback(flacDec,
status &=
FLAC__seekable_stream_decoder_set_metadata_callback(flacDec,
flacMetadata);
status&=FLAC__seekable_stream_decoder_set_metadata_respond(flacDec,
status &=
FLAC__seekable_stream_decoder_set_metadata_respond(flacDec,
FLAC__METADATA_TYPE_VORBIS_COMMENT);
status&=FLAC__seekable_stream_decoder_set_error_callback(flacDec,
status &=
FLAC__seekable_stream_decoder_set_error_callback(flacDec,
flacError);
status&=FLAC__seekable_stream_decoder_set_client_data(flacDec,
status &=
FLAC__seekable_stream_decoder_set_client_data(flacDec,
(void *)&data);
if(!status) {
if (!status) {
ERROR("flac problem before init()\n");
flacPrintErroredState(
FLAC__seekable_stream_decoder_get_state(flacDec));
flacPrintErroredState(FLAC__seekable_stream_decoder_get_state
(flacDec));
ret = -1;
goto fail;
}
if(FLAC__seekable_stream_decoder_init(flacDec)!=
FLAC__SEEKABLE_STREAM_DECODER_OK)
{
if (FLAC__seekable_stream_decoder_init(flacDec) !=
FLAC__SEEKABLE_STREAM_DECODER_OK) {
ERROR("flac problem doing init()\n");
flacPrintErroredState(
FLAC__seekable_stream_decoder_get_state(flacDec));
flacPrintErroredState(FLAC__seekable_stream_decoder_get_state
(flacDec));
ret = -1;
goto fail;
}
if(!FLAC__seekable_stream_decoder_process_until_end_of_metadata(flacDec)) {
if (!FLAC__seekable_stream_decoder_process_until_end_of_metadata
(flacDec)) {
ERROR("flac problem reading metadata\n");
flacPrintErroredState(
FLAC__seekable_stream_decoder_get_state(flacDec));
flacPrintErroredState(FLAC__seekable_stream_decoder_get_state
(flacDec));
ret = -1;
goto fail;
}
dc->state = DECODE_STATE_DECODE;
while(1) {
while (1) {
FLAC__seekable_stream_decoder_process_single(flacDec);
if(FLAC__seekable_stream_decoder_get_state(flacDec)!=
FLAC__SEEKABLE_STREAM_DECODER_OK)
{
if (FLAC__seekable_stream_decoder_get_state(flacDec) !=
FLAC__SEEKABLE_STREAM_DECODER_OK) {
break;
}
if(dc->seek) {
FLAC__uint64 sampleToSeek = dc->seekWhere*
dc->audioFormat.sampleRate+0.5;
if(FLAC__seekable_stream_decoder_seek_absolute(flacDec,
if (dc->seek) {
FLAC__uint64 sampleToSeek = dc->seekWhere *
dc->audioFormat.sampleRate + 0.5;
if (FLAC__seekable_stream_decoder_seek_absolute(flacDec,
sampleToSeek))
{
clearOutputBuffer(cb);
data.time = ((float)sampleToSeek)/
data.time = ((float)sampleToSeek) /
dc->audioFormat.sampleRate;
data.position = 0;
}
else dc->seekError = 1;
} else
dc->seekError = 1;
dc->seek = 0;
}
}
/* I don't think we need this bit here! -shank */
/*FLAC__file_decoder_process_until_end_of_file(flacDec);*/
if(!dc->stop) {
flacPrintErroredState(
FLAC__seekable_stream_decoder_get_state(flacDec));
/*FLAC__file_decoder_process_until_end_of_file(flacDec); */
if (!dc->stop) {
flacPrintErroredState(FLAC__seekable_stream_decoder_get_state
(flacDec));
FLAC__seekable_stream_decoder_finish(flacDec);
}
/* send last little bit */
if(data.chunk_length>0 && !dc->stop) {
if (data.chunk_length > 0 && !dc->stop) {
flacSendChunk(&data);
flushOutputBuffer(data.cb);
}
......@@ -160,24 +175,30 @@ static int flac_decode(OutputBuffer * cb, DecoderControl * dc, InputStream * inS
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
fail:
if(data.replayGainInfo) freeReplayGainInfo(data.replayGainInfo);
fail:
if (data.replayGainInfo)
freeReplayGainInfo(data.replayGainInfo);
if(flacDec) FLAC__seekable_stream_decoder_delete(flacDec);
if (flacDec)
FLAC__seekable_stream_decoder_delete(flacDec);
closeInputStream(inStream);
return ret;
}
static FLAC__SeekableStreamDecoderReadStatus flacRead(
const FLAC__SeekableStreamDecoder * flacDec, FLAC__byte buf[],
unsigned * bytes, void * fdata) {
FlacData * data = (FlacData *) fdata;
static FLAC__SeekableStreamDecoderReadStatus flacRead(const
FLAC__SeekableStreamDecoder
* flacDec,
FLAC__byte buf[],
unsigned *bytes,
void *fdata)
{
FlacData *data = (FlacData *) fdata;
size_t r;
while (1) {
r = readFromInputStream(data->inStream,(void *)buf,1,*bytes);
r = readFromInputStream(data->inStream, (void *)buf, 1, *bytes);
if (r == 0 && !inputStreamAtEOF(data->inStream) &&
!data->dc->stop)
my_usleep(10000);
......@@ -186,64 +207,72 @@ static FLAC__SeekableStreamDecoderReadStatus flacRead(
}
*bytes = r;
if (*bytes==0 && !inputStreamAtEOF(data->inStream) && !data->dc->stop)
if (*bytes == 0 && !inputStreamAtEOF(data->inStream) && !data->dc->stop)
return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR;
return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK;
}
static FLAC__SeekableStreamDecoderSeekStatus flacSeek(
const FLAC__SeekableStreamDecoder * flacDec,
FLAC__uint64 offset, void * fdata)
static FLAC__SeekableStreamDecoderSeekStatus flacSeek(const
FLAC__SeekableStreamDecoder
* flacDec,
FLAC__uint64 offset,
void *fdata)
{
FlacData * data = (FlacData *) fdata;
FlacData *data = (FlacData *) fdata;
if(seekInputStream(data->inStream,offset,SEEK_SET)<0) {
if (seekInputStream(data->inStream, offset, SEEK_SET) < 0) {
return FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR;
}
return FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK;
}
static FLAC__SeekableStreamDecoderTellStatus flacTell(
const FLAC__SeekableStreamDecoder * flacDec,
FLAC__uint64 * offset, void * fdata)
static FLAC__SeekableStreamDecoderTellStatus flacTell(const
FLAC__SeekableStreamDecoder
* flacDec,
FLAC__uint64 * offset,
void *fdata)
{
FlacData * data = (FlacData *) fdata;
FlacData *data = (FlacData *) fdata;
*offset = (long)(data->inStream->offset);
return FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK;
}
static FLAC__SeekableStreamDecoderLengthStatus flacLength(
const FLAC__SeekableStreamDecoder * flacDec,
FLAC__uint64 * length, void * fdata)
static FLAC__SeekableStreamDecoderLengthStatus flacLength(const
FLAC__SeekableStreamDecoder
* flacDec,
FLAC__uint64 * length,
void *fdata)
{
FlacData * data = (FlacData *) fdata;
FlacData *data = (FlacData *) fdata;
*length = (size_t)(data->inStream->size);
*length = (size_t) (data->inStream->size);
return FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK;
}
static FLAC__bool flacEOF(const FLAC__SeekableStreamDecoder * flacDec, void * fdata) {
FlacData * data = (FlacData *) fdata;
static FLAC__bool flacEOF(const FLAC__SeekableStreamDecoder * flacDec,
void *fdata)
{
FlacData *data = (FlacData *) fdata;
if (inputStreamAtEOF(data->inStream) == 1)
return true;
return false;
}
static void flacError(const FLAC__SeekableStreamDecoder *dec,
static void flacError(const FLAC__SeekableStreamDecoder * dec,
FLAC__StreamDecoderErrorStatus status, void *fdata)
{
flac_error_common_cb("flac",status,(FlacData *) fdata);
flac_error_common_cb("flac", status, (FlacData *) fdata);
}
static void flacPrintErroredState(FLAC__SeekableStreamDecoderState state)
{
switch(state) {
switch (state) {
case FLAC__SEEKABLE_STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
ERROR("flac allocation error\n");
break;
......@@ -272,48 +301,53 @@ static void flacPrintErroredState(FLAC__SeekableStreamDecoderState state)
}
}
static void flacMetadata(const FLAC__SeekableStreamDecoder *dec,
const FLAC__StreamMetadata *block, void *vdata)
static void flacMetadata(const FLAC__SeekableStreamDecoder * dec,
const FLAC__StreamMetadata * block, void *vdata)
{
flac_metadata_common_cb(block, (FlacData *)vdata);
flac_metadata_common_cb(block, (FlacData *) vdata);
}
static FLAC__StreamDecoderWriteStatus flacWrite(const FLAC__SeekableStreamDecoder *dec,
const FLAC__Frame *frame, const FLAC__int32 * const buf[],
void * vdata)
static FLAC__StreamDecoderWriteStatus flacWrite(const
FLAC__SeekableStreamDecoder *
dec, const FLAC__Frame * frame,
const FLAC__int32 * const buf[],
void *vdata)
{
FlacData * data = (FlacData *)vdata;
FlacData *data = (FlacData *) vdata;
FLAC__uint32 samples = frame->header.blocksize;
FLAC__uint16 u16;
unsigned char * uc;
unsigned char *uc;
int c_samp, c_chan, d_samp;
int i;
float timeChange;
FLAC__uint64 newPosition = 0;
timeChange = ((float)samples)/frame->header.sample_rate;
data->time+= timeChange;
timeChange = ((float)samples) / frame->header.sample_rate;
data->time += timeChange;
FLAC__seekable_stream_decoder_get_decode_position(dec,&newPosition);
if(data->position) {
data->bitRate = ((newPosition-data->position)*8.0/timeChange)
/1000+0.5;
FLAC__seekable_stream_decoder_get_decode_position(dec, &newPosition);
if (data->position) {
data->bitRate =
((newPosition - data->position) * 8.0 / timeChange)
/ 1000 + 0.5;
}
data->position = newPosition;
for(c_samp = d_samp = 0; c_samp < frame->header.blocksize; c_samp++) {
for(c_chan = 0; c_chan < frame->header.channels;
for (c_samp = d_samp = 0; c_samp < frame->header.blocksize; c_samp++) {
for (c_chan = 0; c_chan < frame->header.channels;
c_chan++, d_samp++) {
u16 = buf[c_chan][c_samp];
uc = (unsigned char *)&u16;
for(i=0;i<(data->dc->audioFormat.bits/8);i++) {
if(data->chunk_length>=FLAC_CHUNK_SIZE) {
if(flacSendChunk(data)<0) {
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
for (i = 0; i < (data->dc->audioFormat.bits / 8); i++) {
if (data->chunk_length >= FLAC_CHUNK_SIZE) {
if (flacSendChunk(data) < 0) {
return
FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
data->chunk_length = 0;
if(data->dc->seek) {
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
if (data->dc->seek) {
return
FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}
}
data->chunk[data->chunk_length++] = *(uc++);
......@@ -324,27 +358,35 @@ static FLAC__StreamDecoderWriteStatus flacWrite(const FLAC__SeekableStreamDecode
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}
static MpdTag * flacMetadataDup(char * file, int * vorbisCommentFound) {
MpdTag * ret = NULL;
FLAC__Metadata_SimpleIterator * it;
FLAC__StreamMetadata * block = NULL;
static MpdTag *flacMetadataDup(char *file, int *vorbisCommentFound)
{
MpdTag *ret = NULL;
FLAC__Metadata_SimpleIterator *it;
FLAC__StreamMetadata *block = NULL;
*vorbisCommentFound = 0;
it = FLAC__metadata_simple_iterator_new();
if(!FLAC__metadata_simple_iterator_init(it, file ,1,0)) {
switch(FLAC__metadata_simple_iterator_status(it)) {
if (!FLAC__metadata_simple_iterator_init(it, file, 1, 0)) {
switch (FLAC__metadata_simple_iterator_status(it)) {
case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT:
DEBUG("flacMetadataDup: Reading '%s' metadata gave the following error: Illegal Input\n",file);
DEBUG
("flacMetadataDup: Reading '%s' metadata gave the following error: Illegal Input\n",
file);
break;
case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE:
DEBUG("flacMetadataDup: Reading '%s' metadata gave the following error: Error Opening File\n",file);
DEBUG
("flacMetadataDup: Reading '%s' metadata gave the following error: Error Opening File\n",
file);
break;
case FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE:
DEBUG("flacMetadataDup: Reading '%s' metadata gave the following error: Not A Flac File\n",file);
DEBUG
("flacMetadataDup: Reading '%s' metadata gave the following error: Not A Flac File\n",
file);
break;
default:
DEBUG("flacMetadataDup: Reading '%s' metadata failed\n",file);
DEBUG("flacMetadataDup: Reading '%s' metadata failed\n",
file);
}
FLAC__metadata_simple_iterator_delete(it);
return ret;
......@@ -352,38 +394,41 @@ static MpdTag * flacMetadataDup(char * file, int * vorbisCommentFound) {
do {
block = FLAC__metadata_simple_iterator_get_block(it);
if(!block) break;
if(block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
if (!block)
break;
if (block->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
ret = copyVorbisCommentBlockToMpdTag(block, ret);
if(ret) *vorbisCommentFound = 1;
}
else if(block->type == FLAC__METADATA_TYPE_STREAMINFO) {
if(!ret) ret = newMpdTag();
if (ret)
*vorbisCommentFound = 1;
} else if (block->type == FLAC__METADATA_TYPE_STREAMINFO) {
if (!ret)
ret = newMpdTag();
ret->time = ((float)block->data.stream_info.
total_samples) /
block->data.stream_info.sample_rate +
0.5;
block->data.stream_info.sample_rate + 0.5;
}
FLAC__metadata_object_delete(block);
} while(FLAC__metadata_simple_iterator_next(it));
} while (FLAC__metadata_simple_iterator_next(it));
FLAC__metadata_simple_iterator_delete(it);
return ret;
}
static MpdTag * flacTagDup(char * file) {
MpdTag * ret = NULL;
static MpdTag *flacTagDup(char *file)
{
MpdTag *ret = NULL;
int foundVorbisComment = 0;
ret = flacMetadataDup(file, &foundVorbisComment);
if(!ret) {
DEBUG("flacTagDup: Failed to grab information from: %s\n", file);
if (!ret) {
DEBUG("flacTagDup: Failed to grab information from: %s\n",
file);
return NULL;
}
if(!foundVorbisComment) {
MpdTag * temp = id3Dup(file);
if(temp) {
if (!foundVorbisComment) {
MpdTag *temp = id3Dup(file);
if (temp) {
temp->time = ret->time;
freeMpdTag(ret);
ret = temp;
......@@ -393,11 +438,10 @@ static MpdTag * flacTagDup(char * file) {
return ret;
}
static char * flacSuffixes[] = {"flac", NULL};
static char * flac_mime_types[] = {"application/x-flac", NULL};
static char *flacSuffixes[] = { "flac", NULL };
static char *flac_mime_types[] = { "application/x-flac", NULL };
InputPlugin flacPlugin =
{
InputPlugin flacPlugin = {
"flac",
NULL,
NULL,
......@@ -412,8 +456,7 @@ InputPlugin flacPlugin =
#else /* !HAVE_FLAC */
InputPlugin flacPlugin =
{
InputPlugin flacPlugin = {
NULL,
NULL,
NULL,
......
......@@ -39,23 +39,26 @@
#define MIKMOD_FRAME_SIZE 4096
static BOOL mod_mpd_Init(void) {
static BOOL mod_mpd_Init(void)
{
return VC_Init();
}
static void mod_mpd_Exit(void) {
static void mod_mpd_Exit(void)
{
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;
}
static MDRIVER drv_mpd =
{
static MDRIVER drv_mpd = {
NULL,
"MPD",
"MPD Output Driver v0.1",
......@@ -92,10 +95,12 @@ static MDRIVER drv_mpd =
static int mod_mikModInitiated = 0;
static int mod_mikModInitError = 0;
static int mod_initMikMod(void) {
if(mod_mikModInitError) return -1;
static int mod_initMikMod(void)
{
if (mod_mikModInitError)
return -1;
if(!mod_mikModInitiated) {
if (!mod_mikModInitiated) {
mod_mikModInitiated = 1;
md_device = 0;
......@@ -110,7 +115,7 @@ static int mod_initMikMod(void) {
md_mode = (DMODE_SOFT_MUSIC | DMODE_INTERP | DMODE_STEREO |
DMODE_16BITS);
if(MikMod_Init("")) {
if (MikMod_Init("")) {
ERROR("Could not init MikMod: %s\n",
MikMod_strerror(MikMod_errno));
mod_mikModInitError = 1;
......@@ -120,20 +125,23 @@ static int mod_initMikMod(void) {
return 0;
}
static void mod_finishMikMod(void) {
static void mod_finishMikMod(void)
{
MikMod_Exit();
}
typedef struct _mod_Data {
MODULE * moduleHandle;
SBYTE * audio_buffer;
MODULE *moduleHandle;
SBYTE *audio_buffer;
} mod_Data;
static mod_Data * mod_open(char * path) {
MODULE * moduleHandle;
mod_Data * data;
static mod_Data *mod_open(char *path)
{
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));
......@@ -145,22 +153,25 @@ static mod_Data * mod_open(char * path) {
return data;
}
static void mod_close(mod_Data * data) {
static void mod_close(mod_Data * data)
{
Player_Stop();
Player_Free(data->moduleHandle);
free(data->audio_buffer);
free(data);
}
static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
mod_Data * data;
static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char *path)
{
mod_Data *data;
float time = 0.0;
int ret;
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);
MikMod_Exit();
return -1;
......@@ -169,24 +180,27 @@ static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
dc->audioFormat.bits = 16;
dc->audioFormat.sampleRate = 44100;
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);
dc->state = DECODE_STATE_DECODE;
while(1) {
if(dc->seek) {
while (1) {
if (dc->seek) {
dc->seekError = 1;
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);
time += ret*secPerByte;
time += ret * secPerByte;
sendDataToOutputBuffer(cb, NULL, dc, 0,
(char *)data->audio_buffer, ret, time,
0, NULL);
......@@ -198,27 +212,28 @@ static int mod_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
MikMod_Exit();
if(dc->stop) {
if (dc->stop) {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
else dc->state = DECODE_STATE_STOP;
} else
dc->state = DECODE_STATE_STOP;
return 0;
}
static MpdTag * modTagDup(char * file) {
MpdTag * ret = NULL;
MODULE * moduleHandle;
char * title;
static MpdTag *modTagDup(char *file)
{
MpdTag *ret = NULL;
MODULE *moduleHandle;
char *title;
if(mod_initMikMod() < 0) {
if (mod_initMikMod() < 0) {
DEBUG("modTagDup: Failed to initialize MikMod\n");
return NULL;
}
if(!(moduleHandle = Player_Load(file, 128, 0))) {
DEBUG("modTagDup: Failed to open file: %s\n",file);
if (!(moduleHandle = Player_Load(file, 128, 0))) {
DEBUG("modTagDup: Failed to open file: %s\n", file);
MikMod_Exit();
return NULL;
......@@ -229,14 +244,15 @@ static MpdTag * modTagDup(char * file) {
ret->time = 0;
title = strdup(Player_LoadTitle(file));
if(title) addItemToMpdTag(ret, TAG_ITEM_TITLE, title);
if (title)
addItemToMpdTag(ret, TAG_ITEM_TITLE, title);
MikMod_Exit();
return ret;
}
static char * modSuffixes[] = {"amf",
static char *modSuffixes[] = { "amf",
"dsm",
"far",
"gdm",
......@@ -251,10 +267,10 @@ static char * modSuffixes[] = {"amf",
"ult",
"uni",
"xm",
NULL};
NULL
};
InputPlugin modPlugin =
{
InputPlugin modPlugin = {
"mod",
NULL,
mod_finishMikMod,
......@@ -269,8 +285,7 @@ InputPlugin modPlugin =
#else
InputPlugin modPlugin =
{
InputPlugin modPlugin = {
NULL,
NULL,
NULL,
......
......@@ -58,11 +58,14 @@ struct audio_dither {
mad_fixed_t random;
};
static unsigned long prng(unsigned long state) {
static unsigned long prng(unsigned long state)
{
return (state * 0x0019660dL + 0x3c6ef35fL) & 0xffffffffL;
}
static signed long audio_linear_dither(unsigned int bits, mad_fixed_t sample, struct audio_dither *dither) {
static signed long audio_linear_dither(unsigned int bits, mad_fixed_t sample,
struct audio_dither *dither)
{
unsigned int scalebits;
mad_fixed_t output, mask, random;
......@@ -91,8 +94,7 @@ static signed long audio_linear_dither(unsigned int bits, mad_fixed_t sample, st
if (sample > MAX)
sample = MAX;
}
else if (output < MIN) {
} else if (output < MIN) {
output = MIN;
if (sample < MIN)
......@@ -105,6 +107,7 @@ static signed long audio_linear_dither(unsigned int bits, mad_fixed_t sample, st
return output >> scalebits;
}
/* end of stolen stuff from mpg321 */
/* decoder stuff is based on madlld */
......@@ -118,25 +121,27 @@ typedef struct _mp3DecodeData {
mad_timer_t timer;
unsigned char readBuffer[READ_BUFFER_SIZE];
char outputBuffer[MP3_DATA_OUTPUT_BUFFER_SIZE];
char * outputPtr;
char * outputBufferEnd;
char *outputPtr;
char *outputBufferEnd;
float totalTime;
float elapsedTime;
int muteFrame;
long * frameOffset;
mad_timer_t * times;
long *frameOffset;
mad_timer_t *times;
long highestFrame;
long maxFrames;
long currentFrame;
int flush;
unsigned long bitRate;
InputStream * inStream;
InputStream *inStream;
struct audio_dither dither;
} mp3DecodeData;
static void initMp3DecodeData(mp3DecodeData * data, InputStream * inStream) {
static void initMp3DecodeData(mp3DecodeData * data, InputStream * inStream)
{
data->outputPtr = data->outputBuffer;
data->outputBufferEnd = data->outputBuffer+MP3_DATA_OUTPUT_BUFFER_SIZE;
data->outputBufferEnd =
data->outputBuffer + MP3_DATA_OUTPUT_BUFFER_SIZE;
data->muteFrame = 0;
data->highestFrame = 0;
data->maxFrames = 0;
......@@ -154,84 +159,91 @@ static void initMp3DecodeData(mp3DecodeData * data, InputStream * inStream) {
mad_timer_reset(&data->timer);
}
static int seekMp3InputBuffer(mp3DecodeData * data, long offset) {
if(seekInputStream(data->inStream,offset,SEEK_SET) < 0) {
static int seekMp3InputBuffer(mp3DecodeData * data, long offset)
{
if (seekInputStream(data->inStream, offset, SEEK_SET) < 0) {
return -1;
}
mad_stream_buffer(&data->stream,data->readBuffer,0);
mad_stream_buffer(&data->stream, data->readBuffer, 0);
(data->stream).error = 0;
return 0;
}
static int fillMp3InputBuffer(mp3DecodeData * data) {
static int fillMp3InputBuffer(mp3DecodeData * data)
{
size_t readSize;
size_t remaining;
size_t readed;
unsigned char * readStart;
if((data->stream).next_frame!=NULL) {
remaining = (data->stream).bufend-(data->stream).next_frame;
memmove(data->readBuffer,(data->stream).next_frame,remaining);
readStart = (data->readBuffer)+remaining;
readSize = READ_BUFFER_SIZE-remaining;
}
else {
unsigned char *readStart;
if ((data->stream).next_frame != NULL) {
remaining = (data->stream).bufend - (data->stream).next_frame;
memmove(data->readBuffer, (data->stream).next_frame, remaining);
readStart = (data->readBuffer) + remaining;
readSize = READ_BUFFER_SIZE - remaining;
} else {
readSize = READ_BUFFER_SIZE;
readStart = data->readBuffer,
remaining = 0;
readStart = data->readBuffer, remaining = 0;
}
/* we've exhausted the read buffer, so give up!, these potential
* mp3 frames are way too big, and thus unlikely to be mp3 frames */
if(readSize == 0) return -1;
if (readSize == 0)
return -1;
readed = readFromInputStream(data->inStream, readStart, (size_t)1,
readed = readFromInputStream(data->inStream, readStart, (size_t) 1,
readSize);
if(readed <= 0 && inputStreamAtEOF(data->inStream)) return -1;
if (readed <= 0 && inputStreamAtEOF(data->inStream))
return -1;
/* sleep for a fraction of a second! */
else if(readed <= 0) {
else if (readed <= 0) {
readed = 0;
my_usleep(10000);
}
mad_stream_buffer(&data->stream,data->readBuffer,readed+remaining);
mad_stream_buffer(&data->stream, data->readBuffer, readed + remaining);
(data->stream).error = 0;
return 0;
}
#ifdef HAVE_ID3TAG
static ReplayGainInfo * parseId3ReplayGainInfo(struct id3_tag * tag) {
static ReplayGainInfo *parseId3ReplayGainInfo(struct id3_tag *tag)
{
int i;
char * key;
char * value;
struct id3_frame * frame;
char *key;
char *value;
struct id3_frame *frame;
int found = 0;
ReplayGainInfo * replayGainInfo;
ReplayGainInfo *replayGainInfo;
replayGainInfo = newReplayGainInfo();
for(i=0;(frame = id3_tag_findframe(tag, "TXXX", i));i++) {
if(frame->nfields < 3) continue;
for (i = 0; (frame = id3_tag_findframe(tag, "TXXX", i)); i++) {
if (frame->nfields < 3)
continue;
key = (char *) id3_ucs4_latin1duplicate(id3_field_getstring(&frame->fields[1]));
value = (char *) id3_ucs4_latin1duplicate(id3_field_getstring(&frame->fields[2]));
key =
(char *)
id3_ucs4_latin1duplicate(id3_field_getstring
(&frame->fields[1]));
value =
(char *)
id3_ucs4_latin1duplicate(id3_field_getstring
(&frame->fields[2]));
if(strcmp(key, "replaygain_track_gain") == 0) {
if (strcmp(key, "replaygain_track_gain") == 0) {
replayGainInfo->trackGain = atof(value);
found = 1;
}
else if(strcmp(key, "replaygain_album_gain") == 0) {
} else if (strcmp(key, "replaygain_album_gain") == 0) {
replayGainInfo->albumGain = atof(value);
found = 1;
}
else if(strcmp(key, "replaygain_track_peak") == 0) {
} else if (strcmp(key, "replaygain_track_peak") == 0) {
replayGainInfo->trackPeak = atof(value);
found = 1;
}
else if(strcmp(key, "replaygain_album_peak") == 0) {
} else if (strcmp(key, "replaygain_album_peak") == 0) {
replayGainInfo->albumPeak = atof(value);
found = 1;
}
......@@ -240,48 +252,52 @@ static ReplayGainInfo * parseId3ReplayGainInfo(struct id3_tag * tag) {
free(value);
}
if(found) return replayGainInfo;
if (found)
return replayGainInfo;
freeReplayGainInfo(replayGainInfo);
return NULL;
}
#endif
#ifdef HAVE_ID3TAG
static void mp3_parseId3Tag(mp3DecodeData * data, signed long tagsize, MpdTag ** mpdTag, ReplayGainInfo ** replayGainInfo) {
struct id3_tag * id3Tag = NULL;
static void mp3_parseId3Tag(mp3DecodeData * data, signed long tagsize,
MpdTag ** mpdTag, ReplayGainInfo ** replayGainInfo)
{
struct id3_tag *id3Tag = NULL;
id3_length_t count;
id3_byte_t const *id3_data;
id3_byte_t * allocated = NULL;
MpdTag * tmpMpdTag;
ReplayGainInfo * tmpReplayGainInfo;
id3_byte_t *allocated = NULL;
MpdTag *tmpMpdTag;
ReplayGainInfo *tmpReplayGainInfo;
count = data->stream.bufend - data->stream.this_frame;
if(tagsize <= count) {
if (tagsize <= count) {
id3_data = data->stream.this_frame;
mad_stream_skip(&(data->stream), tagsize);
}
else {
} else {
allocated = malloc(tagsize);
if(!allocated) goto fail;
if (!allocated)
goto fail;
memcpy(allocated, data->stream.this_frame, count);
mad_stream_skip(&(data->stream), count);
while(count < tagsize) {
while (count < tagsize) {
int len;
len = readFromInputStream(data->inStream,
allocated+count, (size_t)1,
tagsize-count);
if(len <= 0 && inputStreamAtEOF(data->inStream)) {
allocated + count, (size_t) 1,
tagsize - count);
if (len <= 0 && inputStreamAtEOF(data->inStream)) {
break;
}
else if(len <= 0) my_usleep(10000);
else count += len;
} else if (len <= 0)
my_usleep(10000);
else
count += len;
}
if(count != tagsize) {
if (count != tagsize) {
DEBUG("mp3_decode: error parsing ID3 tag\n");
goto fail;
}
......@@ -290,51 +306,59 @@ static void mp3_parseId3Tag(mp3DecodeData * data, signed long tagsize, MpdTag **
}
id3Tag = id3_tag_parse(id3_data, tagsize);
if(!id3Tag) goto fail;
if (!id3Tag)
goto fail;
if(mpdTag) {
if (mpdTag) {
tmpMpdTag = parseId3Tag(id3Tag);
if(tmpMpdTag) {
if(*mpdTag) freeMpdTag(*mpdTag);
if (tmpMpdTag) {
if (*mpdTag)
freeMpdTag(*mpdTag);
*mpdTag = tmpMpdTag;
}
}
if(replayGainInfo) {
if (replayGainInfo) {
tmpReplayGainInfo = parseId3ReplayGainInfo(id3Tag);
if(tmpReplayGainInfo) {
if(*replayGainInfo) freeReplayGainInfo(*replayGainInfo);
if (tmpReplayGainInfo) {
if (*replayGainInfo)
freeReplayGainInfo(*replayGainInfo);
*replayGainInfo = tmpReplayGainInfo;
}
}
id3_tag_delete(id3Tag);
fail:
if(allocated) free(allocated);
fail:
if (allocated)
free(allocated);
}
#endif
static int decodeNextFrameHeader(mp3DecodeData * data, MpdTag ** tag, ReplayGainInfo ** replayGainInfo) {
if((data->stream).buffer==NULL || (data->stream).error==MAD_ERROR_BUFLEN) {
if(fillMp3InputBuffer(data) < 0) {
static int decodeNextFrameHeader(mp3DecodeData * data, MpdTag ** tag,
ReplayGainInfo ** replayGainInfo)
{
if ((data->stream).buffer == NULL
|| (data->stream).error == MAD_ERROR_BUFLEN) {
if (fillMp3InputBuffer(data) < 0) {
return DECODE_BREAK;
}
}
if(mad_header_decode(&data->frame.header,&data->stream)) {
if (mad_header_decode(&data->frame.header, &data->stream)) {
#ifdef HAVE_ID3TAG
if((data->stream).error==MAD_ERROR_LOSTSYNC &&
(data->stream).this_frame)
{
signed long tagsize = id3_tag_query(
(data->stream).this_frame,
(data->stream).bufend-
(data->stream).this_frame);
if(tagsize>0) {
if(tag && !(*tag)) {
mp3_parseId3Tag(data, tagsize, tag, replayGainInfo);
}
else {
if ((data->stream).error == MAD_ERROR_LOSTSYNC &&
(data->stream).this_frame) {
signed long tagsize = id3_tag_query((data->stream).
this_frame,
(data->stream).
bufend -
(data->stream).
this_frame);
if (tagsize > 0) {
if (tag && !(*tag)) {
mp3_parseId3Tag(data, tagsize, tag,
replayGainInfo);
} else {
mad_stream_skip(&(data->stream),
tagsize);
}
......@@ -342,13 +366,12 @@ static int decodeNextFrameHeader(mp3DecodeData * data, MpdTag ** tag, ReplayGain
}
}
#endif
if(MAD_RECOVERABLE((data->stream).error)) {
if (MAD_RECOVERABLE((data->stream).error)) {
return DECODE_SKIP;
}
} else {
if ((data->stream).error == MAD_ERROR_BUFLEN)
return DECODE_CONT;
else {
if((data->stream).error==MAD_ERROR_BUFLEN) return DECODE_CONT;
else
{
ERROR("unrecoverable frame level error "
"(%s).\n",
mad_stream_errorstr(&data->stream));
......@@ -357,39 +380,42 @@ static int decodeNextFrameHeader(mp3DecodeData * data, MpdTag ** tag, ReplayGain
}
}
}
if(data->frame.header.layer != MAD_LAYER_III) {
if (data->frame.header.layer != MAD_LAYER_III) {
return DECODE_SKIP;
}
return DECODE_OK;
}
static int decodeNextFrame(mp3DecodeData * data) {
if((data->stream).buffer==NULL || (data->stream).error==MAD_ERROR_BUFLEN) {
if(fillMp3InputBuffer(data) < 0) {
static int decodeNextFrame(mp3DecodeData * data)
{
if ((data->stream).buffer == NULL
|| (data->stream).error == MAD_ERROR_BUFLEN) {
if (fillMp3InputBuffer(data) < 0) {
return DECODE_BREAK;
}
}
if(mad_frame_decode(&data->frame,&data->stream)) {
if (mad_frame_decode(&data->frame, &data->stream)) {
#ifdef HAVE_ID3TAG
if((data->stream).error==MAD_ERROR_LOSTSYNC) {
signed long tagsize = id3_tag_query(
(data->stream).this_frame,
(data->stream).bufend-
(data->stream).this_frame);
if(tagsize>0) {
mad_stream_skip(&(data->stream),tagsize);
if ((data->stream).error == MAD_ERROR_LOSTSYNC) {
signed long tagsize = id3_tag_query((data->stream).
this_frame,
(data->stream).
bufend -
(data->stream).
this_frame);
if (tagsize > 0) {
mad_stream_skip(&(data->stream), tagsize);
return DECODE_CONT;
}
}
#endif
if(MAD_RECOVERABLE((data->stream).error)) {
if (MAD_RECOVERABLE((data->stream).error)) {
return DECODE_SKIP;
}
} else {
if ((data->stream).error == MAD_ERROR_BUFLEN)
return DECODE_CONT;
else {
if((data->stream).error==MAD_ERROR_BUFLEN) return DECODE_CONT;
else
{
ERROR("unrecoverable frame level error "
"(%s).\n",
mad_stream_errorstr(&data->stream));
......@@ -438,64 +464,78 @@ static int parse_xing(struct xing *xing, struct mad_bitptr *ptr, int bitlen)
oldbitlen = bitlen;
if (bitlen < 16) goto fail;
if (bitlen < 16)
goto fail;
bits = mad_bit_read(ptr, 16);
bitlen -= 16;
if (bits == XI_MAGIC) {
if (bitlen < 16) goto fail;
if (mad_bit_read(ptr, 16) != NG_MAGIC) goto fail;
if (bitlen < 16)
goto fail;
if (mad_bit_read(ptr, 16) != NG_MAGIC)
goto fail;
bitlen -= 16;
xing->magic = XING_MAGIC_XING;
} else if (bits == IN_MAGIC) {
if (bitlen < 16) goto fail;
if (mad_bit_read(ptr, 16) != FO_MAGIC) goto fail;
if (bitlen < 16)
goto fail;
if (mad_bit_read(ptr, 16) != FO_MAGIC)
goto fail;
bitlen -= 16;
xing->magic = XING_MAGIC_INFO;
}
else if (bits == NG_MAGIC) xing->magic = XING_MAGIC_XING;
else if (bits == FO_MAGIC) xing->magic = XING_MAGIC_INFO;
else goto fail;
} else if (bits == NG_MAGIC)
xing->magic = XING_MAGIC_XING;
else if (bits == FO_MAGIC)
xing->magic = XING_MAGIC_INFO;
else
goto fail;
if (bitlen < 32) goto fail;
if (bitlen < 32)
goto fail;
xing->flags = mad_bit_read(ptr, 32);
bitlen -= 32;
if (xing->flags & XING_FRAMES) {
if (bitlen < 32) goto fail;
if (bitlen < 32)
goto fail;
xing->frames = mad_bit_read(ptr, 32);
bitlen -= 32;
}
if (xing->flags & XING_BYTES) {
if (bitlen < 32) goto fail;
if (bitlen < 32)
goto fail;
xing->bytes = mad_bit_read(ptr, 32);
bitlen -= 32;
}
if (xing->flags & XING_TOC) {
if (bitlen < 800) goto fail;
for (i = 0; i < 100; ++i) xing->toc[i] = mad_bit_read(ptr, 8);
if (bitlen < 800)
goto fail;
for (i = 0; i < 100; ++i)
xing->toc[i] = mad_bit_read(ptr, 8);
bitlen -= 800;
}
if (xing->flags & XING_SCALE) {
if (bitlen < 32) goto fail;
if (bitlen < 32)
goto fail;
xing->scale = mad_bit_read(ptr, 32);
bitlen -= 32;
}
/* Make sure we consume no less than 120 bytes (960 bits) in hopes that
* the LAME tag is found there, and not right after the Xing header */
bitsleft = 960-(oldbitlen-bitlen);
if (bitsleft < 0) goto fail;
bitsleft = 960 - (oldbitlen - bitlen);
if (bitsleft < 0)
goto fail;
else if (bitsleft > 0) {
mad_bit_read(ptr, bitsleft);
bitlen -= bitsleft;
}
return bitlen;
fail:
fail:
xing->flags = 0;
return -1;
}
......@@ -504,7 +544,8 @@ static int parse_extension_headers(struct xing *xing, struct mad_bitptr ptr,
int bitlen)
{
bitlen = parse_xing(xing, &ptr, bitlen);
if (bitlen < 0) return 0;
if (bitlen < 0)
return 0;
return 1;
}
......@@ -516,80 +557,93 @@ static int decodeFirstFrame(mp3DecodeData * data, DecoderControl * dc,
int ret;
int skip;
memset(&xing,0,sizeof(struct xing));
memset(&xing, 0, sizeof(struct xing));
xing.flags = 0;
while(1) {
while (1) {
skip = 0;
while((ret = decodeNextFrameHeader(data, tag, replayGainInfo))==DECODE_CONT &&
(!dc || !dc->stop));
if(ret==DECODE_SKIP) skip = 1;
else if(ret==DECODE_BREAK || (dc && dc->stop)) return -1;
while((ret = decodeNextFrame(data))==DECODE_CONT &&
(!dc || !dc->stop));
if(ret==DECODE_BREAK || (dc && dc->stop)) return -1;
if(!skip && ret==DECODE_OK) break;
while ((ret =
decodeNextFrameHeader(data, tag,
replayGainInfo)) == DECODE_CONT
&& (!dc || !dc->stop)) ;
if (ret == DECODE_SKIP)
skip = 1;
else if (ret == DECODE_BREAK || (dc && dc->stop))
return -1;
while ((ret = decodeNextFrame(data)) == DECODE_CONT &&
(!dc || !dc->stop)) ;
if (ret == DECODE_BREAK || (dc && dc->stop))
return -1;
if (!skip && ret == DECODE_OK)
break;
}
if(parse_extension_headers(&xing, data->stream.anc_ptr,
if (parse_extension_headers(&xing, data->stream.anc_ptr,
(int)data->stream.anc_bitlen)) {
if(xing.flags & XING_FRAMES) {
if (xing.flags & XING_FRAMES) {
mad_timer_t duration = data->frame.header.duration;
mad_timer_multiply(&duration,xing.frames);
mad_timer_multiply(&duration, xing.frames);
data->muteFrame = MUTEFRAME_SKIP;
data->totalTime = ((float)mad_timer_count(duration,
MAD_UNITS_MILLISECONDS))/1000;
MAD_UNITS_MILLISECONDS))
/ 1000;
data->maxFrames = xing.frames;
}
}
else {
} else {
size_t offset = data->inStream->offset;
mad_timer_t duration = data->frame.header.duration;
float frameTime = ((float)mad_timer_count(duration,
MAD_UNITS_MILLISECONDS))/1000;
if(data->stream.this_frame!=NULL) {
offset-= data->stream.bufend-data->stream.this_frame;
}
else {
offset-= data->stream.bufend-data->stream.buffer;
}
if(data->inStream->size >= offset) {
data->totalTime = ((data->inStream->size-offset)*8.0)/
(data->frame).header.bitrate;
MAD_UNITS_MILLISECONDS))
/ 1000;
if (data->stream.this_frame != NULL) {
offset -= data->stream.bufend - data->stream.this_frame;
} else {
offset -= data->stream.bufend - data->stream.buffer;
}
if (data->inStream->size >= offset) {
data->totalTime =
((data->inStream->size -
offset) * 8.0) / (data->frame).header.bitrate;
data->maxFrames =
data->totalTime/frameTime+FRAMES_CUSHION;
}
else {
data->totalTime / frameTime + FRAMES_CUSHION;
} else {
data->maxFrames = FRAMES_CUSHION;
data->totalTime = 0;
}
}
data->frameOffset = malloc(sizeof(long)*data->maxFrames);
data->times = malloc(sizeof(mad_timer_t)*data->maxFrames);
data->frameOffset = malloc(sizeof(long) * data->maxFrames);
data->times = malloc(sizeof(mad_timer_t) * data->maxFrames);
return 0;
}
static void mp3DecodeDataFinalize(mp3DecodeData * data) {
static void mp3DecodeDataFinalize(mp3DecodeData * data)
{
mad_synth_finish(&data->synth);
mad_frame_finish(&data->frame);
mad_stream_finish(&data->stream);
if(data->frameOffset) free(data->frameOffset);
if(data->times) free(data->times);
if (data->frameOffset)
free(data->frameOffset);
if (data->times)
free(data->times);
}
/* this is primarily used for getting total time for tags */
static int getMp3TotalTime(char * file) {
static int getMp3TotalTime(char *file)
{
InputStream inStream;
mp3DecodeData data;
int ret;
if(openInputStream(&inStream, file) < 0) return -1;
initMp3DecodeData(&data,&inStream);
if(decodeFirstFrame(&data, NULL, NULL,NULL)<0) ret = -1;
else ret = data.totalTime+0.5;
if (openInputStream(&inStream, file) < 0)
return -1;
initMp3DecodeData(&data, &inStream);
if (decodeFirstFrame(&data, NULL, NULL, NULL) < 0)
ret = -1;
else
ret = data.totalTime + 0.5;
mp3DecodeDataFinalize(&data);
closeInputStream(&inStream);
......@@ -597,53 +651,57 @@ static int getMp3TotalTime(char * file) {
}
static int openMp3FromInputStream(InputStream * inStream, mp3DecodeData * data,
DecoderControl * dc, MpdTag ** tag, ReplayGainInfo ** replayGainInfo)
DecoderControl * dc, MpdTag ** tag,
ReplayGainInfo ** replayGainInfo)
{
initMp3DecodeData(data, inStream);
*tag = NULL;
if(decodeFirstFrame(data, dc, tag, replayGainInfo)<0) {
if (decodeFirstFrame(data, dc, tag, replayGainInfo) < 0) {
mp3DecodeDataFinalize(data);
if(tag && *tag) freeMpdTag(*tag);
if (tag && *tag)
freeMpdTag(*tag);
return -1;
}
return 0;
}
static int mp3Read(mp3DecodeData * data, OutputBuffer * cb, DecoderControl * dc, ReplayGainInfo ** replayGainInfo) {
static int mp3Read(mp3DecodeData * data, OutputBuffer * cb, DecoderControl * dc,
ReplayGainInfo ** replayGainInfo)
{
int i;
int ret;
int skip;
if(data->currentFrame>=data->highestFrame) {
mad_timer_add(&data->timer,(data->frame).header.duration);
if (data->currentFrame >= data->highestFrame) {
mad_timer_add(&data->timer, (data->frame).header.duration);
data->bitRate = (data->frame).header.bitrate;
if(data->currentFrame>=data->maxFrames) {
if (data->currentFrame >= data->maxFrames) {
data->currentFrame = data->maxFrames - 1;
}
else data->highestFrame++;
} else
data->highestFrame++;
data->frameOffset[data->currentFrame] = data->inStream->offset;
if(data->stream.this_frame!=NULL) {
data->frameOffset[data->currentFrame]-=
data->stream.bufend-
data->stream.this_frame;
}
else {
data->frameOffset[data->currentFrame]-=
data->stream.bufend-data->stream.buffer;
if (data->stream.this_frame != NULL) {
data->frameOffset[data->currentFrame] -=
data->stream.bufend - data->stream.this_frame;
} else {
data->frameOffset[data->currentFrame] -=
data->stream.bufend - data->stream.buffer;
}
data->times[data->currentFrame] = data->timer;
}
else data->timer = data->times[data->currentFrame];
} else
data->timer = data->times[data->currentFrame];
data->currentFrame++;
data->elapsedTime = ((float)mad_timer_count(data->timer,MAD_UNITS_MILLISECONDS))/1000;
data->elapsedTime =
((float)mad_timer_count(data->timer, MAD_UNITS_MILLISECONDS)) /
1000;
switch(data->muteFrame) {
switch (data->muteFrame) {
case MUTEFRAME_SKIP:
data->muteFrame = 0;
break;
case MUTEFRAME_SEEK:
if(dc->seekWhere<=data->elapsedTime) {
if (dc->seekWhere <= data->elapsedTime) {
data->outputPtr = data->outputBuffer;
clearOutputBuffer(cb);
data->muteFrame = 0;
......@@ -651,11 +709,11 @@ static int mp3Read(mp3DecodeData * data, OutputBuffer * cb, DecoderControl * dc,
}
break;
default:
mad_synth_frame(&data->synth,&data->frame);
mad_synth_frame(&data->synth, &data->frame);
if(data->inStream->metaTitle) {
MpdTag * tag = newMpdTag();
if(data->inStream->metaName) {
if (data->inStream->metaTitle) {
MpdTag *tag = newMpdTag();
if (data->inStream->metaName) {
addItemToMpdTag(tag,
TAG_ITEM_NAME,
data->inStream->metaName);
......@@ -668,111 +726,139 @@ static int mp3Read(mp3DecodeData * data, OutputBuffer * cb, DecoderControl * dc,
freeMpdTag(tag);
}
for(i=0;i<(data->synth).pcm.length;i++) {
mpd_sint16 * sample;
for (i = 0; i < (data->synth).pcm.length; i++) {
mpd_sint16 *sample;
sample = (mpd_sint16 *)data->outputPtr;
sample = (mpd_sint16 *) data->outputPtr;
*sample = (mpd_sint16) audio_linear_dither(16,
(data->synth).pcm.samples[0][i],
&(data->dither));
data->outputPtr+=2;
if(MAD_NCHANNELS(&(data->frame).header)==2) {
sample = (mpd_sint16 *)data->outputPtr;
(data->
synth).pcm.
samples[0]
[i],
&(data->
dither));
data->outputPtr += 2;
if (MAD_NCHANNELS(&(data->frame).header) == 2) {
sample = (mpd_sint16 *) data->outputPtr;
*sample = (mpd_sint16) audio_linear_dither(16,
(data->synth).pcm.samples[1][i],
&(data->dither));
data->outputPtr+=2;
}
if(data->outputPtr>=data->outputBufferEnd) {
(data->
synth).
pcm.
samples
[1]
[i],
&
(data->
dither));
data->outputPtr += 2;
}
if (data->outputPtr >= data->outputBufferEnd) {
long ret;
ret = sendDataToOutputBuffer(cb,
data->inStream,
dc,
data->inStream->seekable,
data->inStream->
seekable,
data->outputBuffer,
data->outputPtr-
data->outputPtr -
data->outputBuffer,
data->elapsedTime,
data->bitRate/1000,
(replayGainInfo != NULL) ? *replayGainInfo : NULL);
if(ret == OUTPUT_BUFFER_DC_STOP) {
data->bitRate /
1000,
(replayGainInfo !=
NULL) ?
*replayGainInfo :
NULL);
if (ret == OUTPUT_BUFFER_DC_STOP) {
data->flush = 0;
return DECODE_BREAK;
}
data->outputPtr = data->outputBuffer;
if(ret == OUTPUT_BUFFER_DC_SEEK) break;
if (ret == OUTPUT_BUFFER_DC_SEEK)
break;
}
}
if(dc->seek && data->inStream->seekable) {
if (dc->seek && data->inStream->seekable) {
long i = 0;
data->muteFrame = MUTEFRAME_SEEK;
while(i<data->highestFrame && dc->seekWhere >
while (i < data->highestFrame && dc->seekWhere >
((float)mad_timer_count(data->times[i],
MAD_UNITS_MILLISECONDS))/1000)
{
MAD_UNITS_MILLISECONDS))
/ 1000) {
i++;
}
if(i<data->highestFrame) {
if(seekMp3InputBuffer(data,
data->frameOffset[i]) == 0)
{
if (i < data->highestFrame) {
if (seekMp3InputBuffer(data,
data->frameOffset[i]) ==
0) {
data->outputPtr = data->outputBuffer;
clearOutputBuffer(cb);
data->currentFrame = i;
}
else dc->seekError = 1;
} else
dc->seekError = 1;
data->muteFrame = 0;
dc->seek = 0;
}
}
else if(dc->seek && !data->inStream->seekable) {
} else if (dc->seek && !data->inStream->seekable) {
dc->seek = 0;
dc->seekError = 1;
}
}
while(1) {
while (1) {
skip = 0;
while((ret = decodeNextFrameHeader(data, NULL, replayGainInfo))==DECODE_CONT &&
!dc->stop);
if(ret==DECODE_BREAK || dc->stop || dc->seek) break;
else if(ret==DECODE_SKIP) skip = 1;
if(!data->muteFrame) {
while((ret = decodeNextFrame(data))==DECODE_CONT &&
!dc->stop && !dc->seek);
if(ret==DECODE_BREAK || dc->stop || dc->seek) break;
while ((ret =
decodeNextFrameHeader(data, NULL,
replayGainInfo)) == DECODE_CONT
&& !dc->stop) ;
if (ret == DECODE_BREAK || dc->stop || dc->seek)
break;
else if (ret == DECODE_SKIP)
skip = 1;
if (!data->muteFrame) {
while ((ret = decodeNextFrame(data)) == DECODE_CONT &&
!dc->stop && !dc->seek) ;
if (ret == DECODE_BREAK || dc->stop || dc->seek)
break;
}
if(!skip && ret==DECODE_OK) break;
if (!skip && ret == DECODE_OK)
break;
}
if(dc->stop) return DECODE_BREAK;
if (dc->stop)
return DECODE_BREAK;
return ret;
}
static void initAudioFormatFromMp3DecodeData(mp3DecodeData * data, AudioFormat * af) {
static void initAudioFormatFromMp3DecodeData(mp3DecodeData * data,
AudioFormat * af)
{
af->bits = 16;
af->sampleRate = (data->frame).header.samplerate;
af->channels = MAD_NCHANNELS(&(data->frame).header);
}
static int mp3_decode(OutputBuffer * cb, DecoderControl * dc, InputStream * inStream) {
static int mp3_decode(OutputBuffer * cb, DecoderControl * dc,
InputStream * inStream)
{
mp3DecodeData data;
MpdTag * tag = NULL;
ReplayGainInfo * replayGainInfo = NULL;
MpdTag *tag = NULL;
ReplayGainInfo *replayGainInfo = NULL;
if(openMp3FromInputStream(inStream, &data, dc, &tag, &replayGainInfo) < 0) {
if (openMp3FromInputStream(inStream, &data, dc, &tag, &replayGainInfo) <
0) {
closeInputStream(inStream);
if(!dc->stop) {
ERROR("Input does not appear to be a mp3 bit stream.\n");
if (!dc->stop) {
ERROR
("Input does not appear to be a mp3 bit stream.\n");
return -1;
}
else {
} else {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
......@@ -784,33 +870,29 @@ static int mp3_decode(OutputBuffer * cb, DecoderControl * dc, InputStream * inSt
dc->totalTime = data.totalTime;
if(inStream->metaTitle) {
if(tag) freeMpdTag(tag);
if (inStream->metaTitle) {
if (tag)
freeMpdTag(tag);
tag = newMpdTag();
addItemToMpdTag(tag, TAG_ITEM_TITLE, inStream->metaTitle);
free(inStream->metaTitle);
inStream->metaTitle = NULL;
if(inStream->metaName) {
addItemToMpdTag(tag, TAG_ITEM_NAME,
inStream->metaName);
if (inStream->metaName) {
addItemToMpdTag(tag, TAG_ITEM_NAME, inStream->metaName);
}
copyMpdTagToOutputBuffer(cb, tag);
freeMpdTag(tag);
}
else if(tag) {
if(inStream->metaName) {
} else if (tag) {
if (inStream->metaName) {
clearItemsFromMpdTag(tag, TAG_ITEM_NAME);
addItemToMpdTag(tag, TAG_ITEM_NAME,
inStream->metaName);
addItemToMpdTag(tag, TAG_ITEM_NAME, inStream->metaName);
}
copyMpdTagToOutputBuffer(cb, tag);
freeMpdTag(tag);
}
else if(inStream->metaName) {
} else if (inStream->metaName) {
tag = newMpdTag();
if(inStream->metaName) {
addItemToMpdTag(tag, TAG_ITEM_NAME,
inStream->metaName);
if (inStream->metaName) {
addItemToMpdTag(tag, TAG_ITEM_NAME, inStream->metaName);
}
copyMpdTagToOutputBuffer(cb, tag);
freeMpdTag(tag);
......@@ -818,22 +900,23 @@ static int mp3_decode(OutputBuffer * cb, DecoderControl * dc, InputStream * inSt
dc->state = DECODE_STATE_DECODE;
while(mp3Read(&data,cb,dc, &replayGainInfo)!=DECODE_BREAK);
while (mp3Read(&data, cb, dc, &replayGainInfo) != DECODE_BREAK) ;
/* send last little bit if not dc->stop */
if(!dc->stop && data.outputPtr!=data.outputBuffer && data.flush) {
if (!dc->stop && data.outputPtr != data.outputBuffer && data.flush) {
sendDataToOutputBuffer(cb, NULL, dc,
data.inStream->seekable,
data.outputBuffer,
data.outputPtr-data.outputBuffer,
data.elapsedTime,data.bitRate/1000,
data.outputPtr - data.outputBuffer,
data.elapsedTime, data.bitRate / 1000,
replayGainInfo);
}
if (replayGainInfo) freeReplayGainInfo(replayGainInfo);
if (replayGainInfo)
freeReplayGainInfo(replayGainInfo);
closeInputStream(inStream);
if(dc->seek && data.muteFrame == MUTEFRAME_SEEK) {
if (dc->seek && data.muteFrame == MUTEFRAME_SEEK) {
clearOutputBuffer(cb);
dc->seek = 0;
}
......@@ -841,39 +924,40 @@ static int mp3_decode(OutputBuffer * cb, DecoderControl * dc, InputStream * inSt
flushOutputBuffer(cb);
mp3DecodeDataFinalize(&data);
if(dc->stop) {
if (dc->stop) {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
else dc->state = DECODE_STATE_STOP;
} else
dc->state = DECODE_STATE_STOP;
return 0;
}
static MpdTag * mp3_tagDup(char * file) {
MpdTag * ret = NULL;
static MpdTag *mp3_tagDup(char *file)
{
MpdTag *ret = NULL;
int time;
ret = id3Dup(file);
time = getMp3TotalTime(file);
if(time>=0) {
if(!ret) ret = newMpdTag();
if (time >= 0) {
if (!ret)
ret = newMpdTag();
ret->time = time;
}
else {
DEBUG("mp3_tagDup: Failed to get total song time from: %s\n", file);
} else {
DEBUG("mp3_tagDup: Failed to get total song time from: %s\n",
file);
}
return ret;
}
static char * mp3_suffixes[] = {"mp3", NULL};
static char * mp3_mimeTypes[] = {"audio/mpeg", NULL};
static char *mp3_suffixes[] = { "mp3", NULL };
static char *mp3_mimeTypes[] = { "audio/mpeg", NULL };
InputPlugin mp3Plugin =
{
InputPlugin mp3Plugin = {
"mp3",
NULL,
NULL,
......@@ -887,8 +971,7 @@ InputPlugin mp3Plugin =
};
#else
InputPlugin mp3Plugin =
{
InputPlugin mp3Plugin = {
NULL,
NULL,
NULL,
......
......@@ -37,7 +37,8 @@
/* all code here is either based on or copied from FAAD2's frontend code */
static int mp4_getAACTrack(mp4ff_t *infile) {
static int mp4_getAACTrack(mp4ff_t * infile)
{
/* find AAC track */
int i, rc;
int numTracks = mp4ff_total_tracks(infile);
......@@ -60,11 +61,13 @@ static int mp4_getAACTrack(mp4ff_t *infile) {
rc = AudioSpecificConfig(buff, *buff_size, &mp4ASC);
#else
rc = AudioSpecificConfig(buff, &dummy1_32, &dummy2_8,
&dummy3_8, &dummy4_8, &dummy5_8,
&dummy6_8, &dummy7_8, &dummy8_8);
&dummy3_8, &dummy4_8,
&dummy5_8, &dummy6_8,
&dummy7_8, &dummy8_8);
#endif
free(buff);
if (rc < 0) continue;
if (rc < 0)
continue;
return i;
}
}
......@@ -76,14 +79,16 @@ static int mp4_getAACTrack(mp4ff_t *infile) {
static uint32_t mp4_inputStreamReadCallback(void *inStream, void *buffer,
uint32_t length)
{
return readFromInputStream((InputStream*) inStream, buffer, 1, length);
return readFromInputStream((InputStream *) inStream, buffer, 1, length);
}
static uint32_t mp4_inputStreamSeekCallback(void *inStream, uint64_t position) {
static uint32_t mp4_inputStreamSeekCallback(void *inStream, uint64_t position)
{
return seekInputStream((InputStream *) inStream, position, SEEK_SET);
}
static faacDecHandle * openConfigureFaad() {
static faacDecHandle *openConfigureFaad()
{
faacDecConfigurationPtr config;
faacDecHandle decoder = faacDecOpen();
......@@ -95,20 +100,21 @@ static faacDecHandle * openConfigureFaad() {
#ifdef HAVE_FAACDECCONFIGURATION_DONTUPSAMPLEIMPLICITSBR
config->dontUpSampleImplicitSBR = 0;
#endif
faacDecSetConfiguration(decoder,config);
faacDecSetConfiguration(decoder, config);
return decoder;
}
static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
mp4ff_t * mp4fh;
mp4ff_callback_t * mp4cb;
static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char *path)
{
mp4ff_t *mp4fh;
mp4ff_callback_t *mp4cb;
int32_t track;
float time;
int32_t scale;
faacDecHandle * decoder;
faacDecHandle *decoder;
faacDecFrameInfo frameInfo;
unsigned char * mp4Buffer;
unsigned char *mp4Buffer;
unsigned int mp4BufferSize;
uint32_t sampleRate;
unsigned char channels;
......@@ -117,10 +123,10 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
int eof = 0;
long dur;
unsigned int sampleCount;
char * sampleBuffer;
char *sampleBuffer;
size_t sampleBufferLen;
unsigned int initial = 1;
float * seekTable;
float *seekTable;
long seekTableEnd = -1;
int seekPositionFound = 0;
long offset;
......@@ -128,7 +134,7 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
InputStream inStream;
int seeking = 0;
if(openInputStream(&inStream, path) < 0) {
if (openInputStream(&inStream, path) < 0) {
ERROR("failed to open %s\n", path);
return -1;
}
......@@ -139,7 +145,7 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
mp4cb->user_data = &inStream;
mp4fh = mp4ff_open_read(mp4cb);
if(!mp4fh) {
if (!mp4fh) {
ERROR("Input does not appear to be a mp4 stream.\n");
free(mp4cb);
closeInputStream(&inStream);
......@@ -147,7 +153,7 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
}
track = mp4_getAACTrack(mp4fh);
if(track < 0) {
if (track < 0) {
ERROR("No AAC track found in mp4 stream.\n");
mp4ff_close(mp4fh);
closeInputStream(&inStream);
......@@ -161,11 +167,11 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
mp4Buffer = NULL;
mp4BufferSize = 0;
mp4ff_get_decoder_config(mp4fh,track,&mp4Buffer,&mp4BufferSize);
mp4ff_get_decoder_config(mp4fh, track, &mp4Buffer, &mp4BufferSize);
if(faacDecInit2(decoder,mp4Buffer,mp4BufferSize,&sampleRate,&channels)
< 0)
{
if (faacDecInit2
(decoder, mp4Buffer, mp4BufferSize, &sampleRate, &channels)
< 0) {
ERROR("Error not a AAC stream.\n");
faacDecClose(decoder);
mp4ff_close(mp4fh);
......@@ -176,12 +182,13 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
dc->audioFormat.sampleRate = sampleRate;
dc->audioFormat.channels = channels;
time = mp4ff_get_track_duration_use_offsets(mp4fh,track);
scale = mp4ff_time_scale(mp4fh,track);
time = mp4ff_get_track_duration_use_offsets(mp4fh, track);
scale = mp4ff_time_scale(mp4fh, track);
if(mp4Buffer) free(mp4Buffer);
if (mp4Buffer)
free(mp4Buffer);
if(scale < 0) {
if (scale < 0) {
ERROR("Error getting audio format of mp4 AAC track.\n");
faacDecClose(decoder);
mp4ff_close(mp4fh);
......@@ -189,66 +196,71 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
free(mp4cb);
return -1;
}
dc->totalTime = ((float)time)/scale;
dc->totalTime = ((float)time) / scale;
numSamples = mp4ff_num_samples(mp4fh,track);
numSamples = mp4ff_num_samples(mp4fh, track);
time = 0.0;
seekTable = malloc(sizeof(float)*numSamples);
seekTable = malloc(sizeof(float) * numSamples);
for(sampleId=0; sampleId<numSamples && !eof; sampleId++) {
if(dc->seek) seeking = 1;
for (sampleId = 0; sampleId < numSamples && !eof; sampleId++) {
if (dc->seek)
seeking = 1;
if(seeking && seekTableEnd>1 &&
seekTable[seekTableEnd]>=dc->seekWhere)
{
if (seeking && seekTableEnd > 1 &&
seekTable[seekTableEnd] >= dc->seekWhere) {
int i = 2;
while(seekTable[i]<dc->seekWhere) i++;
sampleId = i-1;
while (seekTable[i] < dc->seekWhere)
i++;
sampleId = i - 1;
time = seekTable[sampleId];
}
dur = mp4ff_get_sample_duration(mp4fh,track,sampleId);
offset = mp4ff_get_sample_offset(mp4fh,track,sampleId);
dur = mp4ff_get_sample_duration(mp4fh, track, sampleId);
offset = mp4ff_get_sample_offset(mp4fh, track, sampleId);
if(sampleId>seekTableEnd) {
if (sampleId > seekTableEnd) {
seekTable[sampleId] = time;
seekTableEnd = sampleId;
}
if(sampleId==0) dur = 0;
if(offset>dur) dur = 0;
else dur-=offset;
time+=((float)dur)/scale;
if (sampleId == 0)
dur = 0;
if (offset > dur)
dur = 0;
else
dur -= offset;
time += ((float)dur) / scale;
if(seeking && time>dc->seekWhere) seekPositionFound = 1;
if (seeking && time > dc->seekWhere)
seekPositionFound = 1;
if(seeking && seekPositionFound) {
if (seeking && seekPositionFound) {
seekPositionFound = 0;
clearOutputBuffer(cb);
seeking = 0;
dc->seek = 0;
}
if(seeking) continue;
if (seeking)
continue;
if(mp4ff_read_sample(mp4fh,track,sampleId,&mp4Buffer,
&mp4BufferSize) == 0)
{
if (mp4ff_read_sample(mp4fh, track, sampleId, &mp4Buffer,
&mp4BufferSize) == 0) {
eof = 1;
continue;
}
#ifdef HAVE_FAAD_BUFLEN_FUNCS
sampleBuffer = faacDecDecode(decoder,&frameInfo,mp4Buffer,
sampleBuffer = faacDecDecode(decoder, &frameInfo, mp4Buffer,
mp4BufferSize);
#else
sampleBuffer = faacDecDecode(decoder,&frameInfo,mp4Buffer);
sampleBuffer = faacDecDecode(decoder, &frameInfo, mp4Buffer);
#endif
if(mp4Buffer) free(mp4Buffer);
if(frameInfo.error > 0) {
if (mp4Buffer)
free(mp4Buffer);
if (frameInfo.error > 0) {
ERROR("error decoding MP4 file: %s\n", path);
ERROR("faad2 error: %s\n",
faacDecGetErrorMessage(frameInfo.error));
......@@ -256,7 +268,7 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
break;
}
if(dc->state != DECODE_STATE_DECODE) {
if (dc->state != DECODE_STATE_DECODE) {
channels = frameInfo.channels;
#ifdef HAVE_FAACDECFRAMEINFO_SAMPLERATE
scale = frameInfo.samplerate;
......@@ -268,28 +280,27 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
dc->state = DECODE_STATE_DECODE;
}
if(channels*(dur+offset) > frameInfo.samples) {
dur = frameInfo.samples/channels;
if (channels * (dur + offset) > frameInfo.samples) {
dur = frameInfo.samples / channels;
offset = 0;
}
sampleCount = (unsigned long)(dur*channels);
sampleCount = (unsigned long)(dur * channels);
if(sampleCount>0) {
initial =0;
bitRate = frameInfo.bytesconsumed*8.0*
frameInfo.channels*scale/
frameInfo.samples/1000+0.5;
if (sampleCount > 0) {
initial = 0;
bitRate = frameInfo.bytesconsumed * 8.0 *
frameInfo.channels * scale /
frameInfo.samples / 1000 + 0.5;
}
sampleBufferLen = sampleCount * 2;
sampleBufferLen = sampleCount*2;
sampleBuffer+=offset*channels*2;
sampleBuffer += offset * channels * 2;
sendDataToOutputBuffer(cb, NULL, dc, 1, sampleBuffer,
sampleBufferLen, time, bitRate, NULL);
if(dc->stop) {
if (dc->stop) {
eof = 1;
break;
}
......@@ -301,25 +312,28 @@ static int mp4_decode(OutputBuffer * cb, DecoderControl * dc, char * path) {
closeInputStream(&inStream);
free(mp4cb);
if(dc->state != DECODE_STATE_DECODE) return -1;
if (dc->state != DECODE_STATE_DECODE)
return -1;
if(dc->seek && seeking) {
if (dc->seek && seeking) {
clearOutputBuffer(cb);
dc->seek = 0;
}
flushOutputBuffer(cb);
if(dc->stop) dc->stop = 0;
if (dc->stop)
dc->stop = 0;
dc->state = DECODE_STATE_STOP;
return 0;
}
static MpdTag * mp4DataDup(char * file, int * mp4MetadataFound) {
MpdTag * ret = NULL;
static MpdTag *mp4DataDup(char *file, int *mp4MetadataFound)
{
MpdTag *ret = NULL;
InputStream inStream;
mp4ff_t * mp4fh;
mp4ff_callback_t * cb;
mp4ff_t *mp4fh;
mp4ff_callback_t *cb;
int32_t track;
int32_t time;
int32_t scale;
......@@ -327,7 +341,7 @@ static MpdTag * mp4DataDup(char * file, int * mp4MetadataFound) {
*mp4MetadataFound = 0;
if(openInputStream(&inStream, file) < 0) {
if (openInputStream(&inStream, file) < 0) {
DEBUG("mp4DataDup: Failed to open file: %s\n", file);
return NULL;
}
......@@ -338,14 +352,14 @@ static MpdTag * mp4DataDup(char * file, int * mp4MetadataFound) {
cb->user_data = &inStream;
mp4fh = mp4ff_open_read(cb);
if(!mp4fh) {
if (!mp4fh) {
free(cb);
closeInputStream(&inStream);
return NULL;
}
track = mp4_getAACTrack(mp4fh);
if(track < 0) {
if (track < 0) {
mp4ff_close(mp4fh);
closeInputStream(&inStream);
free(cb);
......@@ -353,48 +367,42 @@ static MpdTag * mp4DataDup(char * file, int * mp4MetadataFound) {
}
ret = newMpdTag();
time = mp4ff_get_track_duration_use_offsets(mp4fh,track);
scale = mp4ff_time_scale(mp4fh,track);
if(scale < 0) {
time = mp4ff_get_track_duration_use_offsets(mp4fh, track);
scale = mp4ff_time_scale(mp4fh, track);
if (scale < 0) {
mp4ff_close(mp4fh);
closeInputStream(&inStream);
free(cb);
freeMpdTag(ret);
return NULL;
}
ret->time = ((float)time)/scale+0.5;
ret->time = ((float)time) / scale + 0.5;
for(i = 0; i < mp4ff_meta_get_num_items(mp4fh); i++) {
char * item;
char * value;
for (i = 0; i < mp4ff_meta_get_num_items(mp4fh); i++) {
char *item;
char *value;
mp4ff_meta_get_by_index(mp4fh, i, &item, &value);
if(0 == strcasecmp("artist", item)) {
if (0 == strcasecmp("artist", item)) {
addItemToMpdTag(ret, TAG_ITEM_ARTIST, value);
*mp4MetadataFound = 1;
}
else if(0 == strcasecmp("title", item)) {
} else if (0 == strcasecmp("title", item)) {
addItemToMpdTag(ret, TAG_ITEM_TITLE, value);
*mp4MetadataFound = 1;
}
else if(0 == strcasecmp("album", item)) {
} else if (0 == strcasecmp("album", item)) {
addItemToMpdTag(ret, TAG_ITEM_ALBUM, value);
*mp4MetadataFound = 1;
}
else if(0 == strcasecmp("track", item)) {
} else if (0 == strcasecmp("track", item)) {
addItemToMpdTag(ret, TAG_ITEM_TRACK, value);
*mp4MetadataFound = 1;
}
else if(0 == strcasecmp("disc", item)) { /* Is that the correct id? */
} else if (0 == strcasecmp("disc", item)) { /* Is that the correct id? */
addItemToMpdTag(ret, TAG_ITEM_DISC, value);
*mp4MetadataFound = 1;
}
else if(0 == strcasecmp("genre", item)) {
} else if (0 == strcasecmp("genre", item)) {
addItemToMpdTag(ret, TAG_ITEM_GENRE, value);
*mp4MetadataFound = 1;
}
else if(0 == strcasecmp("date", item)) {
} else if (0 == strcasecmp("date", item)) {
addItemToMpdTag(ret, TAG_ITEM_DATE, value);
*mp4MetadataFound = 1;
}
......@@ -410,15 +418,17 @@ static MpdTag * mp4DataDup(char * file, int * mp4MetadataFound) {
return ret;
}
static MpdTag * mp4TagDup(char * file) {
MpdTag * ret = NULL;
static MpdTag *mp4TagDup(char *file)
{
MpdTag *ret = NULL;
int mp4MetadataFound = 0;
ret = mp4DataDup(file, &mp4MetadataFound);
if(!ret) return NULL;
if(!mp4MetadataFound) {
MpdTag * temp = id3Dup(file);
if(temp) {
if (!ret)
return NULL;
if (!mp4MetadataFound) {
MpdTag *temp = id3Dup(file);
if (temp) {
temp->time = ret->time;
freeMpdTag(ret);
ret = temp;
......@@ -428,10 +438,9 @@ static MpdTag * mp4TagDup(char * file) {
return ret;
}
static char * mp4Suffixes[] = {"m4a", "mp4", NULL};
static char *mp4Suffixes[] = { "m4a", "mp4", NULL };
InputPlugin mp4Plugin =
{
InputPlugin mp4Plugin = {
"mp4",
NULL,
NULL,
......@@ -446,8 +455,7 @@ InputPlugin mp4Plugin =
#else
InputPlugin mp4Plugin =
{
InputPlugin mp4Plugin = {
NULL,
NULL,
NULL,
......
......@@ -37,53 +37,58 @@
#include <math.h>
typedef struct _MpcCallbackData {
InputStream * inStream;
DecoderControl * dc;
InputStream *inStream;
DecoderControl *dc;
} 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;
MpcCallbackData * data = (MpcCallbackData *)vdata;
MpcCallbackData *data = (MpcCallbackData *) vdata;
while(1) {
while (1) {
ret = readFromInputStream(data->inStream, ptr, 1, size);
if(ret == 0 && !inputStreamAtEOF(data->inStream) &&
(data->dc && !data->dc->stop))
{
if (ret == 0 && !inputStreamAtEOF(data->inStream) &&
(data->dc && !data->dc->stop)) {
my_usleep(10000);
}
else break;
} else
break;
}
return ret;
}
static mpc_bool_t mpc_seek_cb(void * vdata, mpc_int32_t offset) {
MpcCallbackData * data = (MpcCallbackData *)vdata;
static mpc_bool_t mpc_seek_cb(void *vdata, mpc_int32_t offset)
{
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) {
MpcCallbackData * data = (MpcCallbackData *)vdata;
static mpc_int32_t mpc_tell_cb(void *vdata)
{
MpcCallbackData *data = (MpcCallbackData *) vdata;
return (long)(data->inStream->offset);
}
static mpc_bool_t mpc_canseek_cb(void * vdata) {
MpcCallbackData * data = (MpcCallbackData *)vdata;
static mpc_bool_t mpc_canseek_cb(void *vdata)
{
MpcCallbackData *data = (MpcCallbackData *) vdata;
return data->inStream->seekable;
}
static mpc_int32_t mpc_getsize_cb(void * vdata) {
MpcCallbackData * data = (MpcCallbackData *)vdata;
static mpc_int32_t mpc_getsize_cb(void *vdata)
{
MpcCallbackData *data = (MpcCallbackData *) vdata;
return data->inStream->size;
}
/* 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 */
mpd_sint32 val;
......@@ -93,10 +98,9 @@ static inline mpd_sint16 convertSample(MPC_SAMPLE_FORMAT sample) {
#ifdef MPC_FIXED_POINT
const int shift = 16 - MPC_FIXED_POINT_SCALE_SHIFT;
if( ssample > 0 ) {
if (ssample > 0) {
sample <<= shift;
}
else if ( shift < 0 ) {
} else if (shift < 0) {
sample >>= -shift;
}
val = sample;
......@@ -106,8 +110,10 @@ static inline mpd_sint16 convertSample(MPC_SAMPLE_FORMAT sample) {
val = sample * float_scale;
#endif
if( val < clip_min) val = clip_min;
else if ( val > clip_max ) val = clip_max;
if (val < clip_min)
val = clip_min;
else if (val > clip_max)
val = clip_max;
return val;
}
......@@ -129,13 +135,13 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
char chunk[MPC_CHUNK_SIZE];
int chunkpos = 0;
long bitRate = 0;
mpd_sint16 * s16 = (mpd_sint16 *) chunk;
mpd_sint16 *s16 = (mpd_sint16 *) chunk;
unsigned long samplePos = 0;
mpc_uint32_t vbrUpdateAcc;
mpc_uint32_t vbrUpdateBits;
float time;
int i;
ReplayGainInfo * replayGainInfo = NULL;
ReplayGainInfo *replayGainInfo = NULL;
data.inStream = inStream;
data.dc = dc;
......@@ -149,13 +155,12 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
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);
if(!dc->stop) {
if (!dc->stop) {
ERROR("Not a valid musepack stream");
return -1;
}
else {
} else {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
......@@ -164,12 +169,11 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
mpc_decoder_setup(&decoder, &reader);
if(!mpc_decoder_initialize(&decoder, &info)) {
if (!mpc_decoder_initialize(&decoder, &info)) {
closeInputStream(inStream);
if(!dc->stop) {
if (!dc->stop) {
ERROR("Not a valid musepack stream");
}
else {
} else {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
......@@ -191,14 +195,14 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
dc->state = DECODE_STATE_DECODE;
while(!eof) {
if(dc->seek) {
while (!eof) {
if (dc->seek) {
samplePos = dc->seekWhere * dc->audioFormat.sampleRate;
if(mpc_decoder_seek_sample(&decoder, samplePos)) {
if (mpc_decoder_seek_sample(&decoder, samplePos)) {
clearOutputBuffer(cb);
chunkpos = 0;
}
else dc->seekError = 1;
} else
dc->seekError = 1;
dc->seek = 0;
}
......@@ -207,7 +211,7 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
ret = mpc_decoder_decode(&decoder, sample_buffer,
&vbrUpdateAcc, &vbrUpdateBits);
if(ret <= 0 || dc->stop ) {
if (ret <= 0 || dc->stop) {
eof = 1;
break;
}
......@@ -217,30 +221,28 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
/* ret is in samples, and we have stereo */
ret *= 2;
for(i = 0; i < ret; i++) {
for (i = 0; i < ret; i++) {
/* 16 bit audio again */
*s16 = convertSample(sample_buffer[i]);
chunkpos += 2;
s16++;
if(chunkpos >= MPC_CHUNK_SIZE) {
if (chunkpos >= MPC_CHUNK_SIZE) {
time = ((float)samplePos) /
dc->audioFormat.sampleRate;
bitRate = vbrUpdateBits *
dc->audioFormat.sampleRate /
1152 / 1000;
dc->audioFormat.sampleRate / 1152 / 1000;
sendDataToOutputBuffer(cb, inStream, dc,
inStream->seekable,
chunk, chunkpos,
time,
bitRate,
replayGainInfo);
bitRate, replayGainInfo);
chunkpos = 0;
s16 = (mpd_sint16 *)chunk;
if(dc->stop) {
s16 = (mpd_sint16 *) chunk;
if (dc->stop) {
eof = 1;
break;
}
......@@ -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;
bitRate = vbrUpdateBits * dc->audioFormat.sampleRate / 1152 / 1000;
bitRate =
vbrUpdateBits * dc->audioFormat.sampleRate / 1152 / 1000;
sendDataToOutputBuffer(cb, NULL, dc, inStream->seekable,
chunk, chunkpos, time, bitRate,
......@@ -264,18 +267,18 @@ static int mpc_decode(OutputBuffer * cb, DecoderControl * dc,
freeReplayGainInfo(replayGainInfo);
if(dc->stop) {
if (dc->stop) {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
else {
} else {
dc->state = DECODE_STATE_STOP;
}
return 0;
}
static float mpcGetTime(char * file) {
static float mpcGetTime(char *file)
{
InputStream inStream;
float time = -1;
......@@ -295,12 +298,12 @@ static float mpcGetTime(char * file) {
mpc_streaminfo_init(&info);
if(openInputStream(&inStream, file) < 0) {
if (openInputStream(&inStream, file) < 0) {
DEBUG("mpcGetTime: Failed to open file: %s\n", file);
return -1;
}
if(mpc_streaminfo_read(&info, &reader) != ERROR_CODE_OK) {
if (mpc_streaminfo_read(&info, &reader) != ERROR_CODE_OK) {
closeInputStream(&inStream);
return -1;
}
......@@ -312,28 +315,31 @@ static float mpcGetTime(char * file) {
return time;
}
static MpdTag * mpcTagDup(char * file) {
MpdTag * ret = NULL;
static MpdTag *mpcTagDup(char *file)
{
MpdTag *ret = NULL;
float time = mpcGetTime(file);
if(time < 0) {
DEBUG("mpcTagDup: Failed to get Songlength of file: %s\n",file);
if (time < 0) {
DEBUG("mpcTagDup: Failed to get Songlength of file: %s\n",
file);
return NULL;
}
ret = apeDup(file);
if(!ret) ret = id3Dup(file);
if(!ret) ret = newMpdTag();
if (!ret)
ret = id3Dup(file);
if (!ret)
ret = newMpdTag();
ret->time = time;
return ret;
}
static char * mpcSuffixes[] = {"mpc", NULL};
static char * mpcMimeTypes[] = {NULL};
static char *mpcSuffixes[] = { "mpc", NULL };
static char *mpcMimeTypes[] = { NULL };
InputPlugin mpcPlugin =
{
InputPlugin mpcPlugin = {
"mpc",
NULL,
NULL,
......@@ -348,8 +354,7 @@ InputPlugin mpcPlugin =
#else
InputPlugin mpcPlugin =
{
InputPlugin mpcPlugin = {
NULL,
NULL,
NULL,
......
......@@ -51,14 +51,18 @@ static void oggflac_cleanup(InputStream * inStream,
closeInputStream(inStream);
}
static OggFLAC__SeekableStreamDecoderReadStatus of_read_cb(
const OggFLAC__SeekableStreamDecoder * decoder,
FLAC__byte buf[], unsigned * bytes, void * fdata) {
FlacData * data = (FlacData *) fdata;
static OggFLAC__SeekableStreamDecoderReadStatus of_read_cb(const
OggFLAC__SeekableStreamDecoder
* decoder,
FLAC__byte buf[],
unsigned *bytes,
void *fdata)
{
FlacData *data = (FlacData *) fdata;
size_t r;
while (1) {
r = readFromInputStream(data->inStream,(void *)buf,1,*bytes);
r = readFromInputStream(data->inStream, (void *)buf, 1, *bytes);
if (r == 0 && !inputStreamAtEOF(data->inStream) &&
!data->dc->stop)
my_usleep(10000);
......@@ -73,44 +77,52 @@ static OggFLAC__SeekableStreamDecoderReadStatus of_read_cb(
return OggFLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK;
}
static OggFLAC__SeekableStreamDecoderSeekStatus of_seek_cb(
const OggFLAC__SeekableStreamDecoder * decoder,
FLAC__uint64 offset, void * fdata)
static OggFLAC__SeekableStreamDecoderSeekStatus of_seek_cb(const
OggFLAC__SeekableStreamDecoder
* decoder,
FLAC__uint64 offset,
void *fdata)
{
FlacData * data = (FlacData *) fdata;
FlacData *data = (FlacData *) fdata;
if(seekInputStream(data->inStream,offset,SEEK_SET)<0) {
if (seekInputStream(data->inStream, offset, SEEK_SET) < 0) {
return OggFLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR;
}
return OggFLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK;
}
static OggFLAC__SeekableStreamDecoderTellStatus of_tell_cb(
const OggFLAC__SeekableStreamDecoder * decoder,
FLAC__uint64 * offset, void * fdata)
static OggFLAC__SeekableStreamDecoderTellStatus of_tell_cb(const
OggFLAC__SeekableStreamDecoder
* decoder,
FLAC__uint64 *
offset, void *fdata)
{
FlacData * data = (FlacData *) fdata;
FlacData *data = (FlacData *) fdata;
*offset = (long)(data->inStream->offset);
return OggFLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK;
}
static OggFLAC__SeekableStreamDecoderLengthStatus of_length_cb(
const OggFLAC__SeekableStreamDecoder * decoder,
FLAC__uint64 * length, void * fdata)
static OggFLAC__SeekableStreamDecoderLengthStatus of_length_cb(const
OggFLAC__SeekableStreamDecoder
* decoder,
FLAC__uint64 *
length,
void *fdata)
{
FlacData * data = (FlacData *) fdata;
FlacData *data = (FlacData *) fdata;
*length = (size_t)(data->inStream->size);
*length = (size_t) (data->inStream->size);
return OggFLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK;
}
static FLAC__bool of_EOF_cb(const OggFLAC__SeekableStreamDecoder * decoder,
void * fdata) {
FlacData * data = (FlacData *) fdata;
void *fdata)
{
FlacData *data = (FlacData *) fdata;
if (inputStreamAtEOF(data->inStream) == 1)
return true;
......@@ -120,12 +132,12 @@ static FLAC__bool of_EOF_cb(const OggFLAC__SeekableStreamDecoder * decoder,
static void of_error_cb(const OggFLAC__SeekableStreamDecoder * decoder,
FLAC__StreamDecoderErrorStatus status, void *fdata)
{
flac_error_common_cb("oggflac",status,(FlacData *) fdata);
flac_error_common_cb("oggflac", status, (FlacData *) fdata);
}
static void oggflacPrintErroredState(OggFLAC__SeekableStreamDecoderState state)
{
switch(state) {
switch (state) {
case OggFLAC__SEEKABLE_STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
ERROR("oggflac allocation error\n");
break;
......@@ -154,21 +166,23 @@ static void oggflacPrintErroredState(OggFLAC__SeekableStreamDecoderState state)
}
}
static FLAC__StreamDecoderWriteStatus oggflacWrite(
const OggFLAC__SeekableStreamDecoder *decoder,
const FLAC__Frame *frame, const FLAC__int32 * const buf[],
void * vdata)
static FLAC__StreamDecoderWriteStatus oggflacWrite(const
OggFLAC__SeekableStreamDecoder
* decoder,
const FLAC__Frame * frame,
const FLAC__int32 *
const buf[], void *vdata)
{
FlacData * data = (FlacData *)vdata;
FlacData *data = (FlacData *) vdata;
FLAC__uint32 samples = frame->header.blocksize;
FLAC__uint16 u16;
unsigned char * uc;
unsigned char *uc;
int c_samp, c_chan, d_samp;
int i;
float timeChange;
timeChange = ((float)samples)/frame->header.sample_rate;
data->time+= timeChange;
timeChange = ((float)samples) / frame->header.sample_rate;
data->time += timeChange;
/* ogg123 uses a complicated method of calculating bitrate
* with averaging which I'm not too fond of.
......@@ -182,19 +196,21 @@ static FLAC__StreamDecoderWriteStatus oggflacWrite(
/((float)samples * 1000)) + 0.5;
*/
for(c_samp = d_samp = 0; c_samp < frame->header.blocksize; c_samp++) {
for(c_chan = 0; c_chan < frame->header.channels;
for (c_samp = d_samp = 0; c_samp < frame->header.blocksize; c_samp++) {
for (c_chan = 0; c_chan < frame->header.channels;
c_chan++, d_samp++) {
u16 = buf[c_chan][c_samp];
uc = (unsigned char *)&u16;
for(i=0;i<(data->dc->audioFormat.bits/8);i++) {
if(data->chunk_length>=FLAC_CHUNK_SIZE) {
if(flacSendChunk(data)<0) {
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
for (i = 0; i < (data->dc->audioFormat.bits / 8); i++) {
if (data->chunk_length >= FLAC_CHUNK_SIZE) {
if (flacSendChunk(data) < 0) {
return
FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
data->chunk_length = 0;
if(data->dc->seek) {
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
if (data->dc->seek) {
return
FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}
}
data->chunk[data->chunk_length++] = *(uc++);
......@@ -206,22 +222,21 @@ static FLAC__StreamDecoderWriteStatus oggflacWrite(
}
/* used by TagDup */
static void of_metadata_dup_cb(
const OggFLAC__SeekableStreamDecoder * decoder,
const FLAC__StreamMetadata *block, void *vdata)
static void of_metadata_dup_cb(const OggFLAC__SeekableStreamDecoder * decoder,
const FLAC__StreamMetadata * block, void *vdata)
{
FlacData * data = (FlacData *)vdata;
FlacData *data = (FlacData *) vdata;
switch(block->type) {
switch (block->type) {
case FLAC__METADATA_TYPE_STREAMINFO:
if (!data->tag) data->tag = newMpdTag();
if (!data->tag)
data->tag = newMpdTag();
data->tag->time = ((float)block->data.stream_info.
total_samples) /
block->data.stream_info.sample_rate +
0.5;
block->data.stream_info.sample_rate + 0.5;
return;
case FLAC__METADATA_TYPE_VORBIS_COMMENT:
copyVorbisCommentBlockToMpdTag(block,data->tag);
copyVorbisCommentBlockToMpdTag(block, data->tag);
default:
break;
}
......@@ -229,30 +244,30 @@ static void of_metadata_dup_cb(
/* used by decode */
static void of_metadata_decode_cb(const OggFLAC__SeekableStreamDecoder * dec,
const FLAC__StreamMetadata *block, void *vdata)
const FLAC__StreamMetadata * block,
void *vdata)
{
flac_metadata_common_cb(block, (FlacData *)vdata);
flac_metadata_common_cb(block, (FlacData *) vdata);
}
static OggFLAC__SeekableStreamDecoder * full_decoder_init_and_read_metadata(
FlacData * data,
static OggFLAC__SeekableStreamDecoder
*full_decoder_init_and_read_metadata(FlacData * data,
unsigned int metadata_only)
{
OggFLAC__SeekableStreamDecoder * decoder = NULL;
OggFLAC__SeekableStreamDecoder *decoder = NULL;
unsigned int s = 1;
if (!(decoder = OggFLAC__seekable_stream_decoder_new()))
return NULL;
if (metadata_only) {
s &= OggFLAC__seekable_stream_decoder_set_metadata_callback(
decoder, of_metadata_dup_cb);
s &= OggFLAC__seekable_stream_decoder_set_metadata_respond(
decoder,
FLAC__METADATA_TYPE_STREAMINFO);
s &= OggFLAC__seekable_stream_decoder_set_metadata_callback
(decoder, of_metadata_dup_cb);
s &= OggFLAC__seekable_stream_decoder_set_metadata_respond
(decoder, FLAC__METADATA_TYPE_STREAMINFO);
} else {
s &= OggFLAC__seekable_stream_decoder_set_metadata_callback(
decoder, of_metadata_decode_cb);
s &= OggFLAC__seekable_stream_decoder_set_metadata_callback
(decoder, of_metadata_decode_cb);
}
s &= OggFLAC__seekable_stream_decoder_set_read_callback(decoder,
......@@ -279,31 +294,30 @@ static OggFLAC__SeekableStreamDecoder * full_decoder_init_and_read_metadata(
goto fail;
}
if (OggFLAC__seekable_stream_decoder_init(decoder) !=
OggFLAC__SEEKABLE_STREAM_DECODER_OK)
{
OggFLAC__SEEKABLE_STREAM_DECODER_OK) {
ERROR("oggflac problem doing init()\n");
goto fail;
}
if (!OggFLAC__seekable_stream_decoder_process_until_end_of_metadata(
decoder)) {
if (!OggFLAC__seekable_stream_decoder_process_until_end_of_metadata
(decoder)) {
ERROR("oggflac problem reading metadata\n");
goto fail;
}
return decoder;
fail:
oggflacPrintErroredState(
OggFLAC__seekable_stream_decoder_get_state(decoder));
fail:
oggflacPrintErroredState(OggFLAC__seekable_stream_decoder_get_state
(decoder));
OggFLAC__seekable_stream_decoder_delete(decoder);
return NULL;
}
/* public functions: */
static MpdTag * oggflac_TagDup(char * file)
static MpdTag *oggflac_TagDup(char *file)
{
InputStream inStream;
OggFLAC__SeekableStreamDecoder * decoder;
OggFLAC__SeekableStreamDecoder *decoder;
FlacData data;
if (openInputStream(&inStream, file) < 0)
......@@ -317,7 +331,7 @@ static MpdTag * oggflac_TagDup(char * file)
/* errors here won't matter,
* data.tag will be set or unset, that's all we care about */
decoder = full_decoder_init_and_read_metadata(&data,1);
decoder = full_decoder_init_and_read_metadata(&data, 1);
oggflac_cleanup(&inStream, &data, decoder);
......@@ -332,49 +346,47 @@ static unsigned int oggflac_try_decode(InputStream * inStream)
static int oggflac_decode(OutputBuffer * cb, DecoderControl * dc,
InputStream * inStream)
{
OggFLAC__SeekableStreamDecoder * decoder = NULL;
OggFLAC__SeekableStreamDecoder *decoder = NULL;
FlacData data;
int ret = 0;
init_FlacData(&data, cb, dc, inStream);
if(!(decoder = full_decoder_init_and_read_metadata(&data,0))){
if (!(decoder = full_decoder_init_and_read_metadata(&data, 0))) {
ret = -1;
goto fail;
}
dc->state = DECODE_STATE_DECODE;
while(1) {
while (1) {
OggFLAC__seekable_stream_decoder_process_single(decoder);
if(OggFLAC__seekable_stream_decoder_get_state(decoder)!=
OggFLAC__SEEKABLE_STREAM_DECODER_OK)
{
if (OggFLAC__seekable_stream_decoder_get_state(decoder) !=
OggFLAC__SEEKABLE_STREAM_DECODER_OK) {
break;
}
if(dc->seek) {
FLAC__uint64 sampleToSeek = dc->seekWhere*
dc->audioFormat.sampleRate+0.5;
if(OggFLAC__seekable_stream_decoder_seek_absolute(
decoder, sampleToSeek))
{
if (dc->seek) {
FLAC__uint64 sampleToSeek = dc->seekWhere *
dc->audioFormat.sampleRate + 0.5;
if (OggFLAC__seekable_stream_decoder_seek_absolute
(decoder, sampleToSeek)) {
clearOutputBuffer(cb);
data.time = ((float)sampleToSeek)/
data.time = ((float)sampleToSeek) /
dc->audioFormat.sampleRate;
data.position = 0;
}
else dc->seekError = 1;
} else
dc->seekError = 1;
dc->seek = 0;
}
}
if(!dc->stop) {
oggflacPrintErroredState(
OggFLAC__seekable_stream_decoder_get_state(decoder));
if (!dc->stop) {
oggflacPrintErroredState
(OggFLAC__seekable_stream_decoder_get_state(decoder));
OggFLAC__seekable_stream_decoder_finish(decoder);
}
/* send last little bit */
if(data.chunk_length>0 && !dc->stop) {
if (data.chunk_length > 0 && !dc->stop) {
flacSendChunk(&data);
flushOutputBuffer(data.cb);
}
......@@ -382,17 +394,16 @@ static int oggflac_decode(OutputBuffer * cb, DecoderControl * dc,
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
fail:
fail:
oggflac_cleanup(inStream, &data, decoder);
return ret;
}
static char * oggflac_Suffixes[] = {"ogg", NULL};
static char * oggflac_mime_types[] = {"application/ogg", NULL};
static char *oggflac_Suffixes[] = { "ogg", NULL };
static char *oggflac_mime_types[] = { "application/ogg", NULL };
InputPlugin oggflacPlugin =
{
InputPlugin oggflacPlugin = {
"oggflac",
NULL,
NULL,
......@@ -407,8 +418,7 @@ InputPlugin oggflacPlugin =
#else /* !HAVE_FLAC */
InputPlugin oggflacPlugin =
{
InputPlugin oggflacPlugin = {
NULL,
NULL,
NULL,
......@@ -422,4 +432,3 @@ InputPlugin oggflacPlugin =
};
#endif /* HAVE_OGGFLAC */
......@@ -61,86 +61,85 @@
#endif
typedef struct _OggCallbackData {
InputStream * inStream;
DecoderControl * dc;
InputStream *inStream;
DecoderControl *dc;
} OggCallbackData;
static size_t ogg_read_cb(void * ptr, size_t size, size_t nmemb, void * vdata)
static size_t ogg_read_cb(void *ptr, size_t size, size_t nmemb, void *vdata)
{
size_t ret = 0;
OggCallbackData * data = (OggCallbackData *)vdata;
OggCallbackData *data = (OggCallbackData *) vdata;
while(1) {
ret = readFromInputStream(data->inStream,ptr,size,nmemb);
if(ret == 0 && !inputStreamAtEOF(data->inStream) &&
!data->dc->stop)
{
while (1) {
ret = readFromInputStream(data->inStream, ptr, size, nmemb);
if (ret == 0 && !inputStreamAtEOF(data->inStream) &&
!data->dc->stop) {
my_usleep(10000);
}
else break;
} else
break;
}
errno = 0;
/*if(ret<0) errno = ((InputStream *)inStream)->error;*/
/*if(ret<0) errno = ((InputStream *)inStream)->error; */
return ret;
}
static int ogg_seek_cb(void * vdata, ogg_int64_t offset, int whence) {
OggCallbackData * data = (OggCallbackData *)vdata;
static int ogg_seek_cb(void *vdata, ogg_int64_t offset, int whence)
{
OggCallbackData *data = (OggCallbackData *) vdata;
return seekInputStream(data->inStream,offset,whence);
return seekInputStream(data->inStream, offset, whence);
}
static int ogg_close_cb(void * vdata) {
OggCallbackData * data = (OggCallbackData *)vdata;
static int ogg_close_cb(void *vdata)
{
OggCallbackData *data = (OggCallbackData *) vdata;
return closeInputStream(data->inStream);
}
static long ogg_tell_cb(void * vdata) {
OggCallbackData * data = (OggCallbackData *)vdata;
static long ogg_tell_cb(void *vdata)
{
OggCallbackData *data = (OggCallbackData *) vdata;
return (long)(data->inStream->offset);
}
static char * ogg_parseComment(char * comment, char * needle) {
static char *ogg_parseComment(char *comment, char *needle)
{
int len = strlen(needle);
if(strncasecmp(comment, needle, len) == 0 && *(comment+len) == '=') {
return comment+len+1;
if (strncasecmp(comment, needle, len) == 0 && *(comment + len) == '=') {
return comment + len + 1;
}
return NULL;
}
static void ogg_getReplayGainInfo(char ** comments, ReplayGainInfo ** infoPtr) {
char * temp;
static void ogg_getReplayGainInfo(char **comments, ReplayGainInfo ** infoPtr)
{
char *temp;
int found = 0;
if(*infoPtr) freeReplayGainInfo(*infoPtr);
if (*infoPtr)
freeReplayGainInfo(*infoPtr);
*infoPtr = newReplayGainInfo();
while(*comments) {
if((temp = ogg_parseComment(*comments,"replaygain_track_gain")))
{
while (*comments) {
if ((temp =
ogg_parseComment(*comments, "replaygain_track_gain"))) {
(*infoPtr)->trackGain = atof(temp);
found = 1;
}
else if((temp = ogg_parseComment(*comments,
"replaygain_album_gain")))
{
} else if ((temp = ogg_parseComment(*comments,
"replaygain_album_gain"))) {
(*infoPtr)->albumGain = atof(temp);
found = 1;
}
else if((temp = ogg_parseComment(*comments,
"replaygain_track_peak")))
{
} else if ((temp = ogg_parseComment(*comments,
"replaygain_track_peak"))) {
(*infoPtr)->trackPeak = atof(temp);
found = 1;
}
else if((temp = ogg_parseComment(*comments,
"replaygain_album_peak")))
{
} else if ((temp = ogg_parseComment(*comments,
"replaygain_album_peak"))) {
(*infoPtr)->albumPeak = atof(temp);
found = 1;
}
......@@ -148,32 +147,38 @@ static void ogg_getReplayGainInfo(char ** comments, ReplayGainInfo ** infoPtr) {
comments++;
}
if(!found) {
if (!found) {
freeReplayGainInfo(*infoPtr);
*infoPtr = NULL;
}
}
static const char * VORBIS_COMMENT_TRACK_KEY = "tracknumber";
static const char * VORBIS_COMMENT_DISC_KEY = "discnumber";
static const char *VORBIS_COMMENT_TRACK_KEY = "tracknumber";
static const char *VORBIS_COMMENT_DISC_KEY = "discnumber";
static unsigned int ogg_parseCommentAddToTag(char * comment,
unsigned int itemType, MpdTag ** tag)
static unsigned int ogg_parseCommentAddToTag(char *comment,
unsigned int itemType,
MpdTag ** tag)
{
const char * needle;
const char *needle;
unsigned int len;
switch (itemType) {
case TAG_ITEM_TRACK: needle = VORBIS_COMMENT_TRACK_KEY; break;
case TAG_ITEM_DISC: needle = VORBIS_COMMENT_DISC_KEY; break;
default: needle = mpdTagItemKeys[itemType];
case TAG_ITEM_TRACK:
needle = VORBIS_COMMENT_TRACK_KEY;
break;
case TAG_ITEM_DISC:
needle = VORBIS_COMMENT_DISC_KEY;
break;
default:
needle = mpdTagItemKeys[itemType];
}
len = strlen(needle);
if(strncasecmp(comment, needle, len) == 0 && *(comment+len) == '=') {
if (strncasecmp(comment, needle, len) == 0 && *(comment + len) == '=') {
if (!*tag)
*tag = newMpdTag();
addItemToMpdTag(*tag, itemType, comment+len+1);
addItemToMpdTag(*tag, itemType, comment + len + 1);
return 1;
}
......@@ -181,12 +186,13 @@ static unsigned int ogg_parseCommentAddToTag(char * comment,
return 0;
}
static MpdTag * oggCommentsParse(char ** comments) {
MpdTag * tag = NULL;
static MpdTag *oggCommentsParse(char **comments)
{
MpdTag *tag = NULL;
while(*comments) {
while (*comments) {
int j;
for (j = TAG_NUM_OF_ITEM_TYPES; --j >= 0; ) {
for (j = TAG_NUM_OF_ITEM_TYPES; --j >= 0;) {
if (ogg_parseCommentAddToTag(*comments, j, &tag))
break;
}
......@@ -196,23 +202,24 @@ static MpdTag * oggCommentsParse(char ** comments) {
return tag;
}
static void putOggCommentsIntoOutputBuffer(OutputBuffer * cb, char * streamName,
char ** comments)
static void putOggCommentsIntoOutputBuffer(OutputBuffer * cb, char *streamName,
char **comments)
{
MpdTag * tag;
MpdTag *tag;
tag = oggCommentsParse(comments);
if(!tag && streamName) {
if (!tag && streamName) {
tag = newMpdTag();
}
if(!tag) return;
if (!tag)
return;
/*if(tag->artist) printf("Artist: %s\n", tag->artist);
if(tag->album) printf("Album: %s\n", tag->album);
if(tag->track) printf("Track: %s\n", tag->track);
if(tag->title) printf("Title: %s\n", tag->title);*/
if(tag->title) printf("Title: %s\n", tag->title); */
if(streamName) {
if (streamName) {
clearItemsFromMpdTag(tag, TAG_ITEM_NAME);
addItemToMpdTag(tag, TAG_ITEM_NAME, streamName);
}
......@@ -238,9 +245,9 @@ static int oggvorbis_decode(OutputBuffer * cb, DecoderControl * dc,
int chunkpos = 0;
long bitRate = 0;
long test;
ReplayGainInfo * replayGainInfo = NULL;
char ** comments;
char * errorStr;
ReplayGainInfo *replayGainInfo = NULL;
char **comments;
char *errorStr;
data.inStream = inStream;
data.dc = dc;
......@@ -250,10 +257,10 @@ static int oggvorbis_decode(OutputBuffer * cb, DecoderControl * dc,
callbacks.close_func = ogg_close_cb;
callbacks.tell_func = ogg_tell_cb;
if((ret = ov_open_callbacks(&data, &vf, NULL, 0, callbacks)) < 0) {
if ((ret = ov_open_callbacks(&data, &vf, NULL, 0, callbacks)) < 0) {
closeInputStream(inStream);
if(!dc->stop) {
switch(ret) {
if (!dc->stop) {
switch (ret) {
case OV_EREAD:
errorStr = "read error";
break;
......@@ -276,39 +283,38 @@ static int oggvorbis_decode(OutputBuffer * cb, DecoderControl * dc,
ERROR("Error decoding Ogg Vorbis stream: %s\n",
errorStr);
return -1;
}
else {
} else {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
return 0;
}
dc->totalTime = ov_time_total(&vf,-1);
if(dc->totalTime < 0) dc->totalTime = 0;
dc->totalTime = ov_time_total(&vf, -1);
if (dc->totalTime < 0)
dc->totalTime = 0;
dc->audioFormat.bits = 16;
while(!eof) {
if(dc->seek) {
if(0 == ov_time_seek_page(&vf,dc->seekWhere)) {
while (!eof) {
if (dc->seek) {
if (0 == ov_time_seek_page(&vf, dc->seekWhere)) {
clearOutputBuffer(cb);
chunkpos = 0;
}
else dc->seekError = 1;
} else
dc->seekError = 1;
dc->seek = 0;
}
ret = ov_read(&vf, chunk+chunkpos,
OGG_CHUNK_SIZE-chunkpos,
OGG_DECODE_USE_BIGENDIAN,
2, 1, &current_section);
if(current_section!=prev_section) {
/*printf("new song!\n");*/
vorbis_info *vi=ov_info(&vf,-1);
ret = ov_read(&vf, chunk + chunkpos,
OGG_CHUNK_SIZE - chunkpos,
OGG_DECODE_USE_BIGENDIAN, 2, 1, &current_section);
if (current_section != prev_section) {
/*printf("new song!\n"); */
vorbis_info *vi = ov_info(&vf, -1);
dc->audioFormat.channels = vi->channels;
dc->audioFormat.sampleRate = vi->rate;
if(dc->state == DECODE_STATE_START) {
if (dc->state == DECODE_STATE_START) {
getOutputAudioFormat(&(dc->audioFormat),
&(cb->audioFormat));
dc->state = DECODE_STATE_DECODE;
......@@ -321,71 +327,76 @@ static int oggvorbis_decode(OutputBuffer * cb, DecoderControl * dc,
prev_section = current_section;
if(ret <= 0 && ret != OV_HOLE) {
if (ret <= 0 && ret != OV_HOLE) {
eof = 1;
break;
}
if(ret == OV_HOLE) ret = 0;
if (ret == OV_HOLE)
ret = 0;
chunkpos+=ret;
chunkpos += ret;
if(chunkpos >= OGG_CHUNK_SIZE) {
if((test = ov_bitrate_instant(&vf))>0) {
bitRate = test/1000;
if (chunkpos >= OGG_CHUNK_SIZE) {
if ((test = ov_bitrate_instant(&vf)) > 0) {
bitRate = test / 1000;
}
sendDataToOutputBuffer(cb, inStream, dc,
inStream->seekable,
chunk, chunkpos,
ov_pcm_tell(&vf)/
ov_pcm_tell(&vf) /
dc->audioFormat.sampleRate,
bitRate,
replayGainInfo);
bitRate, replayGainInfo);
chunkpos = 0;
if(dc->stop) break;
if (dc->stop)
break;
}
}
if(!dc->stop && chunkpos > 0) {
if (!dc->stop && chunkpos > 0) {
sendDataToOutputBuffer(cb, NULL, dc, inStream->seekable,
chunk, chunkpos,
ov_time_tell(&vf), bitRate, replayGainInfo);
ov_time_tell(&vf), bitRate,
replayGainInfo);
}
if(replayGainInfo) freeReplayGainInfo(replayGainInfo);
if (replayGainInfo)
freeReplayGainInfo(replayGainInfo);
ov_clear(&vf);
flushOutputBuffer(cb);
if(dc->stop) {
if (dc->stop) {
dc->state = DECODE_STATE_STOP;
dc->stop = 0;
}
else dc->state = DECODE_STATE_STOP;
} else
dc->state = DECODE_STATE_STOP;
return 0;
}
static MpdTag * oggvorbis_TagDup(char * file) {
MpdTag * ret = NULL;
FILE * fp;
static MpdTag *oggvorbis_TagDup(char *file)
{
MpdTag *ret = NULL;
FILE *fp;
OggVorbis_File vf;
fp = fopen(file,"r");
if(!fp)
{
DEBUG("oggTagDup: Failed to open file: '%s', %s\n", file, strerror(errno));
fp = fopen(file, "r");
if (!fp) {
DEBUG("oggTagDup: Failed to open file: '%s', %s\n", file,
strerror(errno));
return NULL;
}
if(ov_open(fp,&vf,NULL,0)<0) {
if (ov_open(fp, &vf, NULL, 0) < 0) {
fclose(fp);
return NULL;
}
ret = oggCommentsParse(ov_comment(&vf,-1)->user_comments);
ret = oggCommentsParse(ov_comment(&vf, -1)->user_comments);
if(!ret) ret = newMpdTag();
ret->time = (int)(ov_time_total(&vf,-1)+0.5);
if (!ret)
ret = newMpdTag();
ret->time = (int)(ov_time_total(&vf, -1) + 0.5);
ov_clear(&vf);
......@@ -397,12 +408,10 @@ static unsigned int oggvorbis_try_decode(InputStream * inStream)
return (ogg_stream_type_detect(inStream) == VORBIS) ? 1 : 0;
}
static char *oggvorbis_Suffixes[] = { "ogg", NULL };
static char *oggvorbis_MimeTypes[] = { "application/ogg", NULL };
static char * oggvorbis_Suffixes[] = {"ogg", NULL};
static char * oggvorbis_MimeTypes[] = {"application/ogg", NULL};
InputPlugin oggvorbisPlugin =
{
InputPlugin oggvorbisPlugin = {
"oggvorbis",
NULL,
NULL,
......@@ -417,8 +426,7 @@ InputPlugin oggvorbisPlugin =
#else /* !HAVE_OGGVORBIS */
InputPlugin oggvorbisPlugin =
{
InputPlugin oggvorbisPlugin = {
NULL,
NULL,
NULL,
......
......@@ -25,12 +25,14 @@
#include <sys/types.h>
#include <unistd.h>
void initInputStream(void) {
void initInputStream(void)
{
inputStream_initFile();
inputStream_initHttp();
}
int openInputStream(InputStream * inStream, char * url) {
int openInputStream(InputStream * inStream, char *url)
{
inStream->offset = 0;
inStream->size = 0;
inStream->error = 0;
......@@ -39,34 +41,43 @@ int openInputStream(InputStream * inStream, char * url) {
inStream->metaName = NULL;
inStream->metaTitle = NULL;
if(inputStream_fileOpen(inStream,url) == 0) return 0;
if(inputStream_httpOpen(inStream,url) == 0) return 0;
if (inputStream_fileOpen(inStream, url) == 0)
return 0;
if (inputStream_httpOpen(inStream, url) == 0)
return 0;
return -1;
}
int seekInputStream(InputStream * inStream, long offset, int whence) {
return inStream->seekFunc(inStream,offset,whence);
int seekInputStream(InputStream * inStream, long offset, int 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)
{
return inStream->readFunc(inStream,ptr,size,nmemb);
return inStream->readFunc(inStream, ptr, size, nmemb);
}
int closeInputStream(InputStream * inStream) {
if(inStream->mime) free(inStream->mime);
if(inStream->metaName) free(inStream->metaName);
if(inStream->metaTitle) free(inStream->metaTitle);
int closeInputStream(InputStream * inStream)
{
if (inStream->mime)
free(inStream->mime);
if (inStream->metaName)
free(inStream->metaName);
if (inStream->metaTitle)
free(inStream->metaTitle);
return inStream->closeFunc(inStream);
}
int inputStreamAtEOF(InputStream * inStream) {
int inputStreamAtEOF(InputStream * inStream)
{
return inStream->atEOFFunc(inStream);
}
int bufferInputStream(InputStream * inStream) {
int bufferInputStream(InputStream * inStream)
{
return inStream->bufferFunc(inStream);
}
......@@ -23,19 +23,19 @@
typedef struct _InputStream InputStream;
typedef int (* InputStreamSeekFunc) (InputStream * inStream, long offset,
typedef int (*InputStreamSeekFunc) (InputStream * inStream, long offset,
int whence);
typedef size_t (* InputStreamReadFunc) (InputStream * inStream, void * ptr, size_t size,
size_t nmemb);
typedef int (* InputStreamCloseFunc) (InputStream * inStream);
typedef int (* InputStreamAtEOFFunc) (InputStream * inStream);
typedef int (* InputStreamBufferFunc) (InputStream * inStream);
typedef size_t(*InputStreamReadFunc) (InputStream * inStream, void *ptr,
size_t size, size_t nmemb);
typedef int (*InputStreamCloseFunc) (InputStream * inStream);
typedef int (*InputStreamAtEOFFunc) (InputStream * inStream);
typedef int (*InputStreamBufferFunc) (InputStream * inStream);
struct _InputStream {
int error;
long offset;
size_t size;
char * mime;
char *mime;
int seekable;
/* don't touc this stuff */
......@@ -44,18 +44,18 @@ struct _InputStream {
InputStreamCloseFunc closeFunc;
InputStreamAtEOFFunc atEOFFunc;
InputStreamBufferFunc bufferFunc;
void * data;
char * metaName;
char * metaTitle;
void *data;
char *metaName;
char *metaTitle;
};
void initInputStream();
int isUrlSaneForInputStream(char * url);
int isUrlSaneForInputStream(char *url);
/* if an error occurs for these 3 functions, then -1 is returned and errno
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 closeInputStream(InputStream * inStream);
int inputStreamAtEOF(InputStream * inStream);
......@@ -64,7 +64,7 @@ int inputStreamAtEOF(InputStream * inStream);
was buffered */
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);
#endif
......@@ -26,23 +26,25 @@
#include <unistd.h>
#include <errno.h>
void inputStream_initFile(void) {
void inputStream_initFile(void)
{
}
int inputStream_fileOpen(InputStream * inStream, char * filename) {
FILE * fp;
int inputStream_fileOpen(InputStream * inStream, char *filename)
{
FILE *fp;
fp = fopen(filename,"r");
if(!fp) {
fp = fopen(filename, "r");
if (!fp) {
inStream->error = errno;
return -1;
}
inStream->seekable = 1;
fseek(fp,0,SEEK_END);
fseek(fp, 0, SEEK_END);
inStream->size = ftell(fp);
fseek(fp,0,SEEK_SET);
fseek(fp, 0, SEEK_SET);
inStream->data = fp;
inStream->seekFunc = inputStream_fileSeek;
......@@ -54,11 +56,11 @@ int inputStream_fileOpen(InputStream * inStream, char * filename) {
return 0;
}
int inputStream_fileSeek(InputStream * inStream, long offset, int whence) {
if(fseek((FILE *)inStream->data,offset,whence)==0) {
inStream->offset = ftell((FILE *)inStream->data);
}
else {
int inputStream_fileSeek(InputStream * inStream, long offset, int whence)
{
if (fseek((FILE *) inStream->data, offset, whence) == 0) {
inStream->offset = ftell((FILE *) inStream->data);
} else {
inStream->error = errno;
return -1;
}
......@@ -66,25 +68,26 @@ int inputStream_fileSeek(InputStream * inStream, long offset, int whence) {
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 readSize;
readSize = fread(ptr,size,nmemb,(FILE *)inStream->data);
if(readSize <=0 && ferror((FILE *)inStream->data)) {
readSize = fread(ptr, size, nmemb, (FILE *) inStream->data);
if (readSize <= 0 && ferror((FILE *) inStream->data)) {
inStream->error = errno;
DEBUG("inputStream_fileRead: error reading: %s\n",
strerror(inStream->error));
}
inStream->offset = ftell((FILE *)inStream->data);
inStream->offset = ftell((FILE *) inStream->data);
return readSize;
}
int inputStream_fileClose(InputStream * inStream) {
if(fclose((FILE *)inStream->data)<0) {
int inputStream_fileClose(InputStream * inStream)
{
if (fclose((FILE *) inStream->data) < 0) {
inStream->error = errno;
return -1;
}
......@@ -92,16 +95,19 @@ int inputStream_fileClose(InputStream * inStream) {
return 0;
}
int inputStream_fileAtEOF(InputStream * inStream) {
if(feof((FILE *)inStream->data)) return 1;
int inputStream_fileAtEOF(InputStream * inStream)
{
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 0;
}
int inputStream_fileBuffer(InputStream * inStream) {
int inputStream_fileBuffer(InputStream * inStream)
{
return 0;
}
......@@ -23,11 +23,11 @@
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);
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);
int inputStream_fileClose(InputStream * inStream);
......
......@@ -47,39 +47,40 @@
#define HTTP_REDIRECT_MAX 10
static char * proxyHost = NULL;
static char * proxyPort = NULL;
static char * proxyUser = NULL;
static char * proxyPassword = NULL;
static char *proxyHost = NULL;
static char *proxyPort = NULL;
static char *proxyUser = NULL;
static char *proxyPassword = NULL;
static int bufferSize = HTTP_BUFFER_SIZE_DEFAULT;
static int prebufferSize = HTTP_PREBUFFER_SIZE_DEFAULT;
typedef struct _InputStreemHTTPData {
char * host;
char * path;
char *host;
char *path;
char *port;
int sock;
int connState;
char * buffer;
char *buffer;
size_t buflen;
int timesRedirected;
int icyMetaint;
int prebuffer;
int icyOffset;
char * proxyAuth;
char * httpAuth;
char *proxyAuth;
char *httpAuth;
} InputStreamHTTPData;
void inputStream_initHttp(void) {
ConfigParam * param = getConfigParam(CONF_HTTP_PROXY_HOST);
char * test;
void inputStream_initHttp(void)
{
ConfigParam *param = getConfigParam(CONF_HTTP_PROXY_HOST);
char *test;
if(param) {
if (param) {
proxyHost = param->value;
param = getConfigParam(CONF_HTTP_PROXY_PORT);
if(!param) {
if (!param) {
ERROR("%s specified but not %s", CONF_HTTP_PROXY_HOST,
CONF_HTTP_PROXY_PORT);
exit(EXIT_FAILURE);
......@@ -88,12 +89,12 @@ void inputStream_initHttp(void) {
param = getConfigParam(CONF_HTTP_PROXY_USER);
if(param) {
if (param) {
proxyUser = param->value;
param = getConfigParam(CONF_HTTP_PROXY_PASSWORD);
if(!param) {
if (!param) {
ERROR("%s specified but not %s\n",
CONF_HTTP_PROXY_USER,
CONF_HTTP_PROXY_PASSWORD);
......@@ -105,25 +106,20 @@ void inputStream_initHttp(void) {
param = getConfigParam(CONF_HTTP_PROXY_PASSWORD);
if(param) {
if (param) {
ERROR("%s specified but not %s\n",
CONF_HTTP_PROXY_PASSWORD, CONF_HTTP_PROXY_USER);
exit(EXIT_FAILURE);
}
}
else if((param = getConfigParam(CONF_HTTP_PROXY_PORT))) {
} else if ((param = getConfigParam(CONF_HTTP_PROXY_PORT))) {
ERROR("%s specified but not %s, line %i\n",
CONF_HTTP_PROXY_PORT, CONF_HTTP_PROXY_HOST,
param->line);
CONF_HTTP_PROXY_PORT, CONF_HTTP_PROXY_HOST, param->line);
exit(EXIT_FAILURE);
}
else if((param = getConfigParam(CONF_HTTP_PROXY_USER))) {
} else if ((param = getConfigParam(CONF_HTTP_PROXY_USER))) {
ERROR("%s specified but not %s, line %i\n",
CONF_HTTP_PROXY_USER, CONF_HTTP_PROXY_HOST,
param->line);
CONF_HTTP_PROXY_USER, CONF_HTTP_PROXY_HOST, param->line);
exit(EXIT_FAILURE);
}
else if((param = getConfigParam(CONF_HTTP_PROXY_PASSWORD))) {
} else if ((param = getConfigParam(CONF_HTTP_PROXY_PASSWORD))) {
ERROR("%s specified but not %s, line %i\n",
CONF_HTTP_PROXY_PASSWORD, CONF_HTTP_PROXY_HOST,
param->line);
......@@ -132,28 +128,28 @@ void inputStream_initHttp(void) {
param = getConfigParam(CONF_HTTP_BUFFER_SIZE);
if(param) {
if (param) {
bufferSize = strtol(param->value, &test, 10);
if(bufferSize <= 0 || *test != '\0') {
if (bufferSize <= 0 || *test != '\0') {
ERROR("\"%s\" specified for %s at line %i is not a "
"positive integer\n",
param->value, CONF_HTTP_BUFFER_SIZE,
param->line);
param->value, CONF_HTTP_BUFFER_SIZE, param->line);
exit(EXIT_FAILURE);
}
bufferSize *= 1024;
if(prebufferSize > bufferSize) prebufferSize = bufferSize;
if (prebufferSize > bufferSize)
prebufferSize = bufferSize;
}
param = getConfigParam(CONF_HTTP_PREBUFFER_SIZE);
if(param) {
if (param) {
prebufferSize = strtol(param->value, &test, 10);
if(prebufferSize <= 0 || *test != '\0') {
if (prebufferSize <= 0 || *test != '\0') {
ERROR("\"%s\" specified for %s at line %i is not a "
"positive integer\n",
param->value, CONF_HTTP_PREBUFFER_SIZE,
......@@ -164,32 +160,34 @@ void inputStream_initHttp(void) {
prebufferSize *= 1024;
}
if(prebufferSize > bufferSize) prebufferSize = bufferSize;
if (prebufferSize > bufferSize)
prebufferSize = bufferSize;
}
/* base64 code taken from xmms */
#define BASE64_LENGTH(len) (4 * (((len) + 2) / 3))
static char * base64Dup(char * s) {
static char *base64Dup(char *s)
{
int i;
int len = strlen(s);
char * ret = calloc(BASE64_LENGTH(len)+1, 1);
unsigned char * p = (unsigned char *)ret;
char *ret = calloc(BASE64_LENGTH(len) + 1, 1);
unsigned char *p = (unsigned char *)ret;
char tbl[64] = {
'A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X',
'Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3',
'4','5','6','7','8','9','+','/'
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
/* Transform the 3x8 bits to 4x6 bits, as required by base64. */
for(i = 0; i < len; i += 3) {
for (i = 0; i < len; i += 3) {
*p++ = tbl[s[0] >> 2];
*p++ = tbl[((s[0] & 3) << 4) + (s[1] >> 4)];
*p++ = tbl[((s[1] & 0xf) << 2) + (s[2] >> 6)];
......@@ -207,13 +205,15 @@ static char * base64Dup(char * s) {
return ret;
}
static char * authString(char * header, char * user, char * password) {
char * ret = NULL;
static char *authString(char *header, char *user, char *password)
{
char *ret = NULL;
int templen;
char * temp;
char * temp64;
char *temp;
char *temp64;
if(!user || !password) return NULL;
if (!user || !password)
return NULL;
templen = strlen(user) + strlen(password) + 2;
temp = malloc(templen);
......@@ -223,7 +223,7 @@ static char * authString(char * header, char * user, char * password) {
temp64 = base64Dup(temp);
free(temp);
ret = malloc(strlen(temp64)+strlen(header)+3);
ret = malloc(strlen(temp64) + strlen(header) + 3);
strcpy(ret, header);
strcat(ret, temp64);
strcat(ret, "\r\n");
......@@ -238,13 +238,14 @@ static char * authString(char * header, char * user, char * password) {
#define proxyAuthString(x, y) authString(PROXY_AUTH_HEADER, x, y)
#define httpAuthString(x, y) authString(HTTP_AUTH_HEADER, x, y)
static InputStreamHTTPData * newInputStreamHTTPData(void) {
InputStreamHTTPData * ret = malloc(sizeof(InputStreamHTTPData));
static InputStreamHTTPData *newInputStreamHTTPData(void)
{
InputStreamHTTPData *ret = malloc(sizeof(InputStreamHTTPData));
if(proxyHost) {
if (proxyHost) {
ret->proxyAuth = proxyAuthString(proxyUser, proxyPassword);
}
else ret->proxyAuth = NULL;
} else
ret->proxyAuth = NULL;
ret->httpAuth = NULL;
ret->host = NULL;
......@@ -260,54 +261,61 @@ static InputStreamHTTPData * newInputStreamHTTPData(void) {
return ret;
}
static void freeInputStreamHTTPData(InputStreamHTTPData * data) {
if(data->host) free(data->host);
if(data->path) free(data->path);
if(data->port) free(data->port);
if(data->proxyAuth) free(data->proxyAuth);
if(data->httpAuth) free(data->httpAuth);
static void freeInputStreamHTTPData(InputStreamHTTPData * data)
{
if (data->host)
free(data->host);
if (data->path)
free(data->path);
if (data->port)
free(data->port);
if (data->proxyAuth)
free(data->proxyAuth);
if (data->httpAuth)
free(data->httpAuth);
free(data->buffer);
free(data);
}
static int parseUrl(InputStreamHTTPData * data, char * url) {
char * temp;
char * colon;
char * slash;
char * at;
static int parseUrl(InputStreamHTTPData * data, char *url)
{
char *temp;
char *colon;
char *slash;
char *at;
int len;
if(strncmp("http://",url,strlen("http://"))!=0) return -1;
if (strncmp("http://", url, strlen("http://")) != 0)
return -1;
temp = url+strlen("http://");
temp = url + strlen("http://");
colon = strchr(temp, ':');
at = strchr(temp, '@');
if(data->httpAuth) {
if (data->httpAuth) {
free(data->httpAuth);
data->httpAuth = NULL;
}
if(at) {
char * user;
char * passwd;
if (at) {
char *user;
char *passwd;
if(colon && colon < at) {
user = malloc(colon-temp+1);
strncpy(user, temp, colon-temp);
user[colon-temp] = '\0';
if (colon && colon < at) {
user = malloc(colon - temp + 1);
strncpy(user, temp, colon - temp);
user[colon - temp] = '\0';
passwd = malloc(at-colon);
strncpy(passwd, colon+1, at-colon-1);
passwd[at-colon-1] = '\0';
}
else {
user = malloc(at-temp+1);
strncpy(user, temp, at-temp);
user[at-temp] = '\0';
passwd = malloc(at - colon);
strncpy(passwd, colon + 1, at - colon - 1);
passwd[at - colon - 1] = '\0';
} else {
user = malloc(at - temp + 1);
strncpy(user, temp, at - temp);
user[at - temp] = '\0';
passwd = strdup("");
}
......@@ -317,52 +325,60 @@ static int parseUrl(InputStreamHTTPData * data, char * url) {
free(user);
free(passwd);
temp = at+1;
temp = at + 1;
colon = strchr(temp, ':');
}
slash = strchr(temp, '/');
if(slash && colon && slash <= colon) return -1;
if (slash && colon && slash <= colon)
return -1;
/* fetch the host portion */
if(colon) len = colon-temp+1;
else if(slash) len = slash-temp+1;
else len = strlen(temp)+1;
if(len<=1) return -1;
if (colon)
len = colon - temp + 1;
else if (slash)
len = slash - temp + 1;
else
len = strlen(temp) + 1;
if (len <= 1)
return -1;
data->host = malloc(len);
strncpy(data->host,temp,len-1);
data->host[len-1] = '\0';
strncpy(data->host, temp, len - 1);
data->host[len - 1] = '\0';
/* fetch the port */
if(colon && (!slash || slash != colon+1)) {
len = strlen(colon)-1;
if(slash) len -= strlen(slash);
data->port = malloc(len+1);
strncpy(data->port, colon+1, len);
if (colon && (!slash || slash != colon + 1)) {
len = strlen(colon) - 1;
if (slash)
len -= strlen(slash);
data->port = malloc(len + 1);
strncpy(data->port, colon + 1, len);
data->port[len] = '\0';
DEBUG(__FILE__ ": Port: %s\n", data->port);
}
else {
} else {
data->port = strdup("80");
}
/* fetch the path */
if(proxyHost) data->path = strdup(url);
else data->path = strdup(slash ? slash : "/");
if (proxyHost)
data->path = strdup(url);
else
data->path = strdup(slash ? slash : "/");
return 0;
}
static int initHTTPConnection(InputStream * inStream) {
static int initHTTPConnection(InputStream * inStream)
{
char *connHost;
char *connPort;
struct addrinfo *ans = NULL;
struct addrinfo *ap = NULL;
struct addrinfo hints;
int error, flags;
InputStreamHTTPData * data = (InputStreamHTTPData *)inStream->data;
InputStreamHTTPData *data = (InputStreamHTTPData *) inStream->data;
/**
* Setup hints
*/
......@@ -375,29 +391,27 @@ static int initHTTPConnection(InputStream * inStream) {
hints.ai_canonname = NULL;
hints.ai_next = NULL;
if(proxyHost) {
if (proxyHost) {
connHost = proxyHost;
connPort = proxyPort;
}
else {
} else {
connHost = data->host;
connPort = data->port;
}
error = getaddrinfo(connHost, connPort, &hints, &ans);
if(error) {
DEBUG(__FILE__ ": Error getting address info: %s\n", gai_strerror(error));
if (error) {
DEBUG(__FILE__ ": Error getting address info: %s\n",
gai_strerror(error));
return -1;
}
/* loop through possible addresses */
for(ap = ans; ap != NULL; ap = ap->ai_next) {
if((data->sock = socket(ap->ai_family, ap->ai_socktype,
for (ap = ans; ap != NULL; ap = ap->ai_next) {
if ((data->sock = socket(ap->ai_family, ap->ai_socktype,
ap->ai_protocol)) < 0) {
DEBUG(__FILE__ ": unable to connect: %s\n", strerror(errno));
DEBUG(__FILE__ ": unable to connect: %s\n",
strerror(errno));
freeaddrinfo(ans);
return -1;
}
......@@ -405,9 +419,8 @@ static int initHTTPConnection(InputStream * inStream) {
flags = fcntl(data->sock, F_GETFL, 0);
fcntl(data->sock, F_SETFL, flags | O_NONBLOCK);
if(connect(data->sock, ap->ai_addr, ap->ai_addrlen) >= 0
|| errno == EINPROGRESS
) {
if (connect(data->sock, ap->ai_addr, ap->ai_addrlen) >= 0
|| errno == EINPROGRESS) {
data->connState = HTTP_CONN_STATE_INIT;
data->buflen = 0;
freeaddrinfo(ans);
......@@ -424,8 +437,9 @@ static int initHTTPConnection(InputStream * inStream) {
return -1; /* failed */
}
static int finishHTTPInit(InputStream * inStream) {
InputStreamHTTPData * data = (InputStreamHTTPData *)inStream->data;
static int finishHTTPInit(InputStream * inStream)
{
InputStreamHTTPData *data = (InputStreamHTTPData *) inStream->data;
struct timeval tv;
fd_set writeSet;
fd_set errorSet;
......@@ -442,19 +456,20 @@ static int finishHTTPInit(InputStream * inStream) {
FD_SET(data->sock, &writeSet);
FD_SET(data->sock, &errorSet);
ret = select(data->sock+1, NULL, &writeSet, &errorSet, &tv);
ret = select(data->sock + 1, NULL, &writeSet, &errorSet, &tv);
if(ret == 0 || (ret < 0 && errno==EINTR)) return 0;
if (ret == 0 || (ret < 0 && errno == EINTR))
return 0;
if(ret < 0) {
DEBUG(__FILE__ ": problem select'ing: %s\n",strerror(errno));
if (ret < 0) {
DEBUG(__FILE__ ": problem select'ing: %s\n", strerror(errno));
close(data->sock);
data->connState = HTTP_CONN_STATE_CLOSED;
return -1;
}
getsockopt(data->sock, SOL_SOCKET, SO_ERROR, &error, &error_len);
if(error) {
if (error) {
close(data->sock);
data->connState = HTTP_CONN_STATE_CLOSED;
return -1;
......@@ -462,26 +477,20 @@ static int finishHTTPInit(InputStream * inStream) {
memset(request, 0, 2049);
/* deal with ICY metadata later, for now its fucking up stuff! */
snprintf(request, 2048, "GET %s HTTP/1.0\r\n"
"Host: %s\r\n"
/*"Connection: close\r\n"*/
snprintf(request, 2048, "GET %s HTTP/1.0\r\n" "Host: %s\r\n"
/*"Connection: close\r\n" */
"User-Agent: %s/%s\r\n"
/*"Range: bytes=%ld-\r\n"*/
/*"Range: bytes=%ld-\r\n" */
"%s" /* authorization */
"Icy-Metadata:1\r\n"
"\r\n",
data->path,
data->host,
PACKAGE_NAME,
PACKAGE_VERSION,
/*inStream->offset,*/
"\r\n", data->path, data->host, PACKAGE_NAME, PACKAGE_VERSION,
/*inStream->offset, */
data->proxyAuth ? data->proxyAuth :
(data->httpAuth ? data->httpAuth : "")
);
ret = write(data->sock, request, strlen(request));
if(ret!=strlen(request)) {
if (ret != strlen(request)) {
close(data->sock);
data->connState = HTTP_CONN_STATE_CLOSED;
return -1;
......@@ -492,13 +501,14 @@ static int finishHTTPInit(InputStream * inStream) {
return 0;
}
static int getHTTPHello(InputStream * inStream) {
InputStreamHTTPData * data = (InputStreamHTTPData *)inStream->data;
static int getHTTPHello(InputStream * inStream)
{
InputStreamHTTPData *data = (InputStreamHTTPData *) inStream->data;
fd_set readSet;
struct timeval tv;
int ret;
char * needle;
char * cur = data->buffer;
char *needle;
char *cur = data->buffer;
int rc;
long readed;
......@@ -508,84 +518,86 @@ static int getHTTPHello(InputStream * inStream) {
tv.tv_sec = 0;
tv.tv_usec = 0;
ret = select(data->sock+1,&readSet,NULL,NULL,&tv);
ret = select(data->sock + 1, &readSet, NULL, NULL, &tv);
if(ret == 0 || (ret < 0 && errno==EINTR)) return 0;
if (ret == 0 || (ret < 0 && errno == EINTR))
return 0;
if(ret < 0) {
if (ret < 0) {
data->connState = HTTP_CONN_STATE_CLOSED;
close(data->sock);
data->buflen = 0;
return -1;
}
if(data->buflen >= bufferSize-1) {
if (data->buflen >= bufferSize - 1) {
data->connState = HTTP_CONN_STATE_CLOSED;
close(data->sock);
return -1;
}
readed = recv(data->sock, data->buffer+data->buflen,
bufferSize-1-data->buflen, 0);
readed = recv(data->sock, data->buffer + data->buflen,
bufferSize - 1 - data->buflen, 0);
if(readed < 0 && (errno == EAGAIN || errno == EINTR)) return 0;
if (readed < 0 && (errno == EAGAIN || errno == EINTR))
return 0;
if(readed <= 0) {
if (readed <= 0) {
data->connState = HTTP_CONN_STATE_CLOSED;
close(data->sock);
data->buflen = 0;
return -1;
}
data->buffer[data->buflen+readed] = '\0';
data->buffer[data->buflen + readed] = '\0';
data->buflen += readed;
needle = strstr(data->buffer,"\r\n\r\n");
needle = strstr(data->buffer, "\r\n\r\n");
if(!needle) return 0;
if (!needle)
return 0;
if(0 == strncmp(cur, "HTTP/1.0 ", 9)) {
if (0 == strncmp(cur, "HTTP/1.0 ", 9)) {
inStream->seekable = 0;
rc = atoi(cur+9);
}
else if(0 == strncmp(cur, "HTTP/1.1 ", 9)) {
rc = atoi(cur + 9);
} else if (0 == strncmp(cur, "HTTP/1.1 ", 9)) {
inStream->seekable = 1;
rc = atoi(cur+9);
}
else if(0 == strncmp(cur, "ICY 200 OK", 10)) {
rc = atoi(cur + 9);
} else if (0 == strncmp(cur, "ICY 200 OK", 10)) {
inStream->seekable = 0;
rc = 200;
}
else if(0 == strncmp(cur, "ICY 400 Server Full", 19)) rc = 400;
else if(0 == strncmp(cur, "ICY 404", 7)) rc = 404;
} else if (0 == strncmp(cur, "ICY 400 Server Full", 19))
rc = 400;
else if (0 == strncmp(cur, "ICY 404", 7))
rc = 404;
else {
close(data->sock);
data->connState = HTTP_CONN_STATE_CLOSED;
return -1;
}
switch(rc) {
switch (rc) {
case 200:
case 206:
break;
case 301:
case 302:
cur = strstr(cur, "Location: ");
if(cur) {
char * url;
if (cur) {
char *url;
int curlen = 0;
cur+= strlen("Location: ");
while(*(cur+curlen)!='\0' && *(cur+curlen)!='\r') {
cur += strlen("Location: ");
while (*(cur + curlen) != '\0'
&& *(cur + curlen) != '\r') {
curlen++;
}
url = malloc(curlen+1);
memcpy(url,cur,curlen);
url = malloc(curlen + 1);
memcpy(url, cur, curlen);
url[curlen] = '\0';
ret = parseUrl(data,url);
ret = parseUrl(data, url);
free(url);
if(ret == 0 && data->timesRedirected <
HTTP_REDIRECT_MAX)
{
if (ret == 0 && data->timesRedirected <
HTTP_REDIRECT_MAX) {
data->timesRedirected++;
close(data->sock);
data->connState = HTTP_CONN_STATE_REOPEN;
......@@ -604,82 +616,89 @@ static int getHTTPHello(InputStream * inStream) {
return -1;
}
cur = strstr(data->buffer,"\r\n");
while(cur && cur!=needle) {
if(0 == strncmp(cur,"\r\nContent-Length: ",18)) {
if(!inStream->size) inStream->size = atol(cur+18);
}
else if(0 == strncmp(cur, "\r\nicy-metaint:", 14)) {
data->icyMetaint = atoi(cur+14);
}
else if(0 == strncmp(cur, "\r\nicy-name:", 11) ||
0 == strncmp(cur, "\r\nice-name:", 11))
{
cur = strstr(data->buffer, "\r\n");
while (cur && cur != needle) {
if (0 == strncmp(cur, "\r\nContent-Length: ", 18)) {
if (!inStream->size)
inStream->size = atol(cur + 18);
} else if (0 == strncmp(cur, "\r\nicy-metaint:", 14)) {
data->icyMetaint = atoi(cur + 14);
} else if (0 == strncmp(cur, "\r\nicy-name:", 11) ||
0 == strncmp(cur, "\r\nice-name:", 11)) {
int incr = 11;
char * temp = strstr(cur+incr,"\r\n");
if(!temp) break;
char *temp = strstr(cur + incr, "\r\n");
if (!temp)
break;
*temp = '\0';
if(inStream->metaName) free(inStream->metaName);
while(*(incr+cur) == ' ') incr++;
inStream->metaName = strdup(cur+incr);
if (inStream->metaName)
free(inStream->metaName);
while (*(incr + cur) == ' ')
incr++;
inStream->metaName = strdup(cur + incr);
*temp = '\r';
DEBUG("inputStream_http: metaName: %s\n",
inStream->metaName);
}
else if(0 == strncmp(cur, "\r\nx-audiocast-name:", 19)) {
} else if (0 == strncmp(cur, "\r\nx-audiocast-name:", 19)) {
int incr = 19;
char * temp = strstr(cur+incr,"\r\n");
if(!temp) break;
char *temp = strstr(cur + incr, "\r\n");
if (!temp)
break;
*temp = '\0';
if(inStream->metaName) free(inStream->metaName);
while(*(incr+cur) == ' ') incr++;
inStream->metaName = strdup(cur+incr);
if (inStream->metaName)
free(inStream->metaName);
while (*(incr + cur) == ' ')
incr++;
inStream->metaName = strdup(cur + incr);
*temp = '\r';
DEBUG("inputStream_http: metaName: %s\n",
inStream->metaName);
}
else if(0 == strncmp(cur, "\r\nContent-Type:", 15)) {
} else if (0 == strncmp(cur, "\r\nContent-Type:", 15)) {
int incr = 15;
char * temp = strstr(cur+incr,"\r\n");
if(!temp) break;
char *temp = strstr(cur + incr, "\r\n");
if (!temp)
break;
*temp = '\0';
if(inStream->mime) free(inStream->mime);
while(*(incr+cur) == ' ') incr++;
inStream->mime = strdup(cur+incr);
if (inStream->mime)
free(inStream->mime);
while (*(incr + cur) == ' ')
incr++;
inStream->mime = strdup(cur + incr);
*temp = '\r';
}
cur = strstr(cur+2,"\r\n");
cur = strstr(cur + 2, "\r\n");
}
if(inStream->size <= 0) inStream->seekable = 0;
if (inStream->size <= 0)
inStream->seekable = 0;
needle += 4; /* 4 == strlen("\r\n\r\n") */
data->buflen -= (needle-data->buffer);
/*fwrite(data->buffer, 1, data->buflen, stdout);*/
data->buflen -= (needle - data->buffer);
/*fwrite(data->buffer, 1, data->buflen, stdout); */
memmove(data->buffer, needle, data->buflen);
data->connState = HTTP_CONN_STATE_OPEN;
data->prebuffer = 1;
/*mark as unseekable till we actually implement seeking*/
/*mark as unseekable till we actually implement seeking */
inStream->seekable = 0;
return 0;
}
int inputStream_httpOpen(InputStream * inStream, char * url) {
InputStreamHTTPData * data = newInputStreamHTTPData();
int inputStream_httpOpen(InputStream * inStream, char *url)
{
InputStreamHTTPData *data = newInputStreamHTTPData();
inStream->data = data;
if(parseUrl(data,url) < 0) {
if (parseUrl(data, url) < 0) {
freeInputStreamHTTPData(data);
return -1;
}
if(initHTTPConnection(inStream) < 0) {
if (initHTTPConnection(inStream) < 0) {
freeInputStreamHTTPData(data);
return -1;
}
......@@ -693,13 +712,14 @@ int inputStream_httpOpen(InputStream * inStream, char * url) {
return 0;
}
int inputStream_httpSeek(InputStream * inStream, long offset, int whence) {
int inputStream_httpSeek(InputStream * inStream, long offset, int whence)
{
/* hack to reopen an HTTP stream if we're trying to seek to
* the beginning */
if ((whence == SEEK_SET) && (offset == 0)) {
InputStreamHTTPData * data;
InputStreamHTTPData *data;
data = (InputStreamHTTPData*)inStream->data;
data = (InputStreamHTTPData *) inStream->data;
close(data->sock);
data->connState = HTTP_CONN_STATE_REOPEN;
data->buflen = 0;
......@@ -711,24 +731,25 @@ int inputStream_httpSeek(InputStream * inStream, long offset, int whence) {
return -1;
}
static void parseIcyMetadata(InputStream * inStream, char * metadata,
int size)
static void parseIcyMetadata(InputStream * inStream, char *metadata, int size)
{
char * r;
char * s;
char * temp = malloc(size+1);
char *r;
char *s;
char *temp = malloc(size + 1);
memcpy(temp, metadata, size);
temp[size] = '\0';
s = strtok_r(temp, ";", &r);
while(s) {
if(0 == strncmp(s, "StreamTitle=", 12)) {
while (s) {
if (0 == strncmp(s, "StreamTitle=", 12)) {
int cur = 12;
if(inStream->metaTitle) free(inStream->metaTitle);
if(*(s+cur) == '\'') cur++;
if(s[strlen(s)-1] == '\'') {
s[strlen(s)-1] = '\0';
}
inStream->metaTitle = strdup(s+cur);
if (inStream->metaTitle)
free(inStream->metaTitle);
if (*(s + cur) == '\'')
cur++;
if (s[strlen(s) - 1] == '\'') {
s[strlen(s) - 1] = '\0';
}
inStream->metaTitle = strdup(s + cur);
DEBUG("inputStream_http: metaTitle: %s\n",
inStream->metaTitle);
}
......@@ -737,35 +758,38 @@ static void parseIcyMetadata(InputStream * inStream, char * metadata,
free(temp);
}
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)
{
InputStreamHTTPData * data = (InputStreamHTTPData *)inStream->data;
InputStreamHTTPData *data = (InputStreamHTTPData *) inStream->data;
long tosend = 0;
long inlen = size*nmemb;
long inlen = size * nmemb;
long maxToSend = data->buflen;
inputStream_httpBuffer(inStream);
switch(data->connState) {
switch (data->connState) {
case HTTP_CONN_STATE_OPEN:
if(data->prebuffer || data->buflen < data->icyMetaint) return 0;
if (data->prebuffer || data->buflen < data->icyMetaint)
return 0;
break;
case HTTP_CONN_STATE_CLOSED:
if(data->buflen) break;
if (data->buflen)
break;
default:
return 0;
}
if(data->icyMetaint > 0) {
if(data->icyOffset >= data->icyMetaint) {
if (data->icyMetaint > 0) {
if (data->icyOffset >= data->icyMetaint) {
int metalen = *(data->buffer);
metalen <<= 4;
if(metalen < 0) metalen = 0;
if(metalen+1 > data->buflen) {
if (metalen < 0)
metalen = 0;
if (metalen + 1 > data->buflen) {
/* damn that's some fucking big metadata! */
if(bufferSize < metalen+1) {
if (bufferSize < metalen + 1) {
data->connState =
HTTP_CONN_STATE_CLOSED;
close(data->sock);
......@@ -773,40 +797,41 @@ size_t inputStream_httpRead(InputStream * inStream, void * ptr, size_t size,
}
return 0;
}
if(metalen > 0) {
parseIcyMetadata(inStream, data->buffer+1,
if (metalen > 0) {
parseIcyMetadata(inStream, data->buffer + 1,
metalen);
}
data->buflen -= metalen+1;
memmove(data->buffer, data->buffer+metalen+1,
data->buflen -= metalen + 1;
memmove(data->buffer, data->buffer + metalen + 1,
data->buflen);
data->icyOffset = 0;
}
maxToSend = data->icyMetaint-data->icyOffset;
maxToSend = data->icyMetaint - data->icyOffset;
maxToSend = maxToSend > data->buflen ? data->buflen : maxToSend;
}
if(data->buflen > 0) {
if (data->buflen > 0) {
tosend = inlen > maxToSend ? maxToSend : inlen;
tosend = (tosend/size)*size;
tosend = (tosend / size) * size;
memcpy(ptr, data->buffer, tosend);
/*fwrite(ptr,1,readed,stdout);*/
/*fwrite(ptr,1,readed,stdout); */
data->buflen -= tosend;
data->icyOffset+= tosend;
/*fwrite(data->buffer,1,readed,stdout);*/
memmove(data->buffer, data->buffer+tosend, data->buflen);
data->icyOffset += tosend;
/*fwrite(data->buffer,1,readed,stdout); */
memmove(data->buffer, data->buffer + tosend, data->buflen);
inStream->offset += tosend;
}
return tosend/size;
return tosend / size;
}
int inputStream_httpClose(InputStream * inStream) {
InputStreamHTTPData * data = (InputStreamHTTPData *)inStream->data;
int inputStream_httpClose(InputStream * inStream)
{
InputStreamHTTPData *data = (InputStreamHTTPData *) inStream->data;
switch(data->connState) {
switch (data->connState) {
case HTTP_CONN_STATE_CLOSED:
break;
default:
......@@ -818,33 +843,39 @@ int inputStream_httpClose(InputStream * inStream) {
return 0;
}
int inputStream_httpAtEOF(InputStream * inStream) {
InputStreamHTTPData * data = (InputStreamHTTPData *)inStream->data;
switch(data->connState) {
int inputStream_httpAtEOF(InputStream * inStream)
{
InputStreamHTTPData *data = (InputStreamHTTPData *) inStream->data;
switch (data->connState) {
case HTTP_CONN_STATE_CLOSED:
if(data->buflen == 0) return 1;
if (data->buflen == 0)
return 1;
default:
return 0;
}
}
int inputStream_httpBuffer(InputStream * inStream) {
InputStreamHTTPData * data = (InputStreamHTTPData *)inStream->data;
int inputStream_httpBuffer(InputStream * inStream)
{
InputStreamHTTPData *data = (InputStreamHTTPData *) inStream->data;
ssize_t readed = 0;
if(data->connState == HTTP_CONN_STATE_REOPEN) {
if(initHTTPConnection(inStream) < 0) return -1;
if (data->connState == HTTP_CONN_STATE_REOPEN) {
if (initHTTPConnection(inStream) < 0)
return -1;
}
if(data->connState == HTTP_CONN_STATE_INIT) {
if(finishHTTPInit(inStream) < 0) return -1;
if (data->connState == HTTP_CONN_STATE_INIT) {
if (finishHTTPInit(inStream) < 0)
return -1;
}
if(data->connState == HTTP_CONN_STATE_HELLO) {
if(getHTTPHello(inStream) < 0) return -1;
if (data->connState == HTTP_CONN_STATE_HELLO) {
if (getHTTPHello(inStream) < 0)
return -1;
}
switch(data->connState) {
switch (data->connState) {
case HTTP_CONN_STATE_OPEN:
case HTTP_CONN_STATE_CLOSED:
break;
......@@ -852,30 +883,29 @@ int inputStream_httpBuffer(InputStream * inStream) {
return -1;
}
if(data->buflen == 0 || data->buflen < data->icyMetaint) {
if (data->buflen == 0 || data->buflen < data->icyMetaint) {
data->prebuffer = 1;
}
else if(data->buflen > prebufferSize) data->prebuffer = 0;
} else if (data->buflen > prebufferSize)
data->prebuffer = 0;
if(data->connState == HTTP_CONN_STATE_OPEN &&
data->buflen < bufferSize-1)
{
readed = read(data->sock, data->buffer+data->buflen,
(size_t)(bufferSize-1-data->buflen));
if (data->connState == HTTP_CONN_STATE_OPEN &&
data->buflen < bufferSize - 1) {
readed = read(data->sock, data->buffer + data->buflen,
(size_t) (bufferSize - 1 - data->buflen));
if(readed < 0 && (errno == EAGAIN || errno == EINTR)) {
if (readed < 0 && (errno == EAGAIN || errno == EINTR)) {
readed = 0;
}
else if(readed <= 0) {
} else if (readed <= 0) {
close(data->sock);
data->connState = HTTP_CONN_STATE_CLOSED;
readed = 0;
}
/*fwrite(data->buffer+data->buflen,1,readed,stdout);*/
/*fwrite(data->buffer+data->buflen,1,readed,stdout); */
data->buflen += readed;
}
if(data->buflen > prebufferSize) data->prebuffer = 0;
if (data->buflen > prebufferSize)
data->prebuffer = 0;
return (readed ? 1 : 0);
}
......@@ -23,11 +23,11 @@
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);
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);
int inputStream_httpClose(InputStream * inStream);
......
......@@ -54,7 +54,7 @@
#define INTERFACE_MAX_OUTPUT_BUFFER_SIZE_DEFAULT (8192*1024)
/* set this to zero to indicate we have no possible interfaces */
static int interface_max_connections = 0; /*INTERFACE_MAX_CONNECTIONS_DEFAULT;*/
static int interface_max_connections = 0; /*INTERFACE_MAX_CONNECTIONS_DEFAULT; */
static int interface_timeout = INTERFACE_TIMEOUT_DEFAULT;
static size_t interface_max_command_list_size =
INTERFACE_MAX_COMMAND_LIST_DEFAULT;
......@@ -66,42 +66,43 @@ typedef struct _Interface {
int bufferLength;
int bufferPos;
int fd; /* file descriptor */
FILE * fp; /* file pointer */
FILE *fp; /* file pointer */
int open; /* open/used */
int permission;
time_t lastTime;
List * commandList; /* for when in list mode */
List *commandList; /* for when in list mode */
int commandListOK; /* print OK after each command execution */
size_t commandListSize; /* mem commandList consumes */
List * bufferList; /* for output if client is slow */
List *bufferList; /* for output if client is slow */
size_t outputBufferSize; /* mem bufferList consumes */
int expired; /* set whether this interface should be closed on next
check of old interfaces */
int num; /* interface number */
char * outBuffer;
char *outBuffer;
int outBuflen;
int outBufSize;
} Interface;
static Interface * interfaces = NULL;
static Interface *interfaces = NULL;
static void flushInterfaceBuffer(Interface * interface);
static void printInterfaceOutBuffer(Interface * interface);
static void openInterface(Interface * interface, int fd) {
static void openInterface(Interface * interface, int fd)
{
int flags;
assert(interface->open==0);
assert(interface->open == 0);
interface->bufferLength = 0;
interface->bufferPos = 0;
interface->fd = fd;
/* fcntl(interface->fd,F_SETOWN,(int)getpid()); */
while((flags = fcntl(fd,F_GETFL))<0 && errno==EINTR);
flags|=O_NONBLOCK;
while(fcntl(interface->fd,F_SETFL,flags)<0 && errno==EINTR);
while((interface->fp = fdopen(fd,"rw"))==NULL && errno==EINTR);
while ((flags = fcntl(fd, F_GETFL)) < 0 && errno == EINTR) ;
flags |= O_NONBLOCK;
while (fcntl(interface->fd, F_SETFL, flags) < 0 && errno == EINTR) ;
while ((interface->fp = fdopen(fd, "rw")) == NULL && errno == EINTR) ;
interface->open = 1;
interface->lastTime = time(NULL);
interface->commandList = NULL;
......@@ -118,15 +119,13 @@ static void openInterface(Interface * interface, int fd) {
int getSize;
unsigned int sockOptLen = sizeof(int);
if(getsockopt(interface->fd,SOL_SOCKET,SO_SNDBUF,
(char *)&getSize,&sockOptLen) < 0)
{
if (getsockopt(interface->fd, SOL_SOCKET, SO_SNDBUF,
(char *)&getSize, &sockOptLen) < 0) {
DEBUG("problem getting sockets send buffer size\n");
}
else if(getSize<=0) {
} else if (getSize <= 0) {
DEBUG("sockets send buffer size is not positive\n");
}
else interface->outBufSize = getSize;
} else
interface->outBufSize = getSize;
}
#endif
interface->outBuffer = malloc(interface->outBufSize);
......@@ -135,42 +134,44 @@ static void openInterface(Interface * interface, int fd) {
printInterfaceOutBuffer(interface);
}
static void closeInterface(Interface * interface) {
if (!interface->open) return;
static void closeInterface(Interface * interface)
{
if (!interface->open)
return;
interface->open = 0;
while(fclose(interface->fp) && errno==EINTR);
while (fclose(interface->fp) && errno == EINTR) ;
if(interface->commandList) freeList(interface->commandList);
if(interface->bufferList) freeList(interface->bufferList);
if (interface->commandList)
freeList(interface->commandList);
if (interface->bufferList)
freeList(interface->bufferList);
free(interface->outBuffer);
SECURE("interface %i: closed\n",interface->num);
SECURE("interface %i: closed\n", interface->num);
}
void openAInterface(int fd, struct sockaddr * addr) {
void openAInterface(int fd, struct sockaddr *addr)
{
int i;
for(i=0;i<interface_max_connections && interfaces[i].open;i++);
for (i = 0; i < interface_max_connections && interfaces[i].open; i++) ;
if(i==interface_max_connections) {
if (i == interface_max_connections) {
ERROR("Max Connections Reached!\n");
while(close(fd) && errno==EINTR);
}
else {
SECURE("interface %i: opened from ",i);
switch(addr->sa_family) {
while (close(fd) && errno == EINTR) ;
} else {
SECURE("interface %i: opened from ", i);
switch (addr->sa_family) {
case AF_INET:
{
char * host = inet_ntoa(
((struct sockaddr_in *)addr)->
sin_addr);
if(host) {
SECURE("%s\n",host);
}
else {
char *host = inet_ntoa(((struct sockaddr_in *)
addr)->sin_addr);
if (host) {
SECURE("%s\n", host);
} else {
SECURE("error getting ipv4 address\n");
}
}
......@@ -178,15 +179,14 @@ void openAInterface(int fd, struct sockaddr * addr) {
#ifdef HAVE_IPV6
case AF_INET6:
{
char host[INET6_ADDRSTRLEN+1];
memset(host,0,INET6_ADDRSTRLEN+1);
if(inet_ntop(AF_INET6,(void *)
char host[INET6_ADDRSTRLEN + 1];
memset(host, 0, INET6_ADDRSTRLEN + 1);
if (inet_ntop(AF_INET6, (void *)
&(((struct sockaddr_in6 *)addr)->
sin6_addr),host,INET6_ADDRSTRLEN))
{
SECURE("%s\n",host);
}
else {
sin6_addr), host,
INET6_ADDRSTRLEN)) {
SECURE("%s\n", host);
} else {
SECURE("error getting ipv6 address\n");
}
}
......@@ -198,37 +198,36 @@ void openAInterface(int fd, struct sockaddr * addr) {
default:
SECURE("unknown\n");
}
openInterface(&(interfaces[i]),fd);
openInterface(&(interfaces[i]), fd);
}
}
static int processLineOfInput(Interface * interface) {
static int processLineOfInput(Interface * interface)
{
int ret = 1;
char * line = interface->buffer+interface->bufferPos;
char *line = interface->buffer + interface->bufferPos;
if(interface->bufferLength - interface->bufferPos > 1) {
if(interface->buffer[interface->bufferLength-2] == '\r') {
interface->buffer[interface->bufferLength-2] = '\0';
if (interface->bufferLength - interface->bufferPos > 1) {
if (interface->buffer[interface->bufferLength - 2] == '\r') {
interface->buffer[interface->bufferLength - 2] = '\0';
}
}
if(interface->commandList) {
if(strcmp(line, INTERFACE_LIST_MODE_END)==0) {
if (interface->commandList) {
if (strcmp(line, INTERFACE_LIST_MODE_END) == 0) {
DEBUG("interface %i: process command "
"list\n",interface->num);
ret = processListOfCommands(
interface->fp,
"list\n", interface->num);
ret = processListOfCommands(interface->fp,
&(interface->permission),
&(interface->expired),
interface->commandListOK,
interface->commandList);
DEBUG("interface %i: process command "
"list returned %i\n",
interface->num,
ret);
if(ret==0) commandSuccess(interface->fp);
else if(ret==COMMAND_RETURN_CLOSE || interface->expired)
{
"list returned %i\n", interface->num, ret);
if (ret == 0)
commandSuccess(interface->fp);
else if (ret == COMMAND_RETURN_CLOSE
|| interface->expired) {
closeInterface(interface);
}
......@@ -236,56 +235,48 @@ static int processLineOfInput(Interface * interface) {
freeList(interface->commandList);
interface->commandList = NULL;
}
else {
interface->commandListSize+= sizeof(ListNode);
interface->commandListSize+= strlen(line)+1;
if(interface->commandListSize >
interface_max_command_list_size)
{
} else {
interface->commandListSize += sizeof(ListNode);
interface->commandListSize += strlen(line) + 1;
if (interface->commandListSize >
interface_max_command_list_size) {
ERROR("interface %i: command "
"list size (%lli) is "
"larger than the max "
"(%lli)\n",
interface->num,
(long long)interface->
commandListSize,
(long long)
interface_max_command_list_size)
;
commandListSize, (long long)
interface_max_command_list_size);
closeInterface(interface);
ret = COMMAND_RETURN_CLOSE;
}
else {
} else {
insertInListWithoutKey(interface->commandList,
strdup(line));
}
}
}
else {
if(strcmp(line, INTERFACE_LIST_MODE_BEGIN) == 0) {
} else {
if (strcmp(line, INTERFACE_LIST_MODE_BEGIN) == 0) {
interface->commandList = makeList(free, 1);
interface->commandListSize = sizeof(List);
interface->commandListOK = 0;
ret = 1;
}
else if(strcmp(line, INTERFACE_LIST_OK_MODE_BEGIN) == 0) {
} else if (strcmp(line, INTERFACE_LIST_OK_MODE_BEGIN) == 0) {
interface->commandList = makeList(free, 1);
interface->commandListSize = sizeof(List);
interface->commandListOK = 1;
ret = 1;
}
else {
} else {
DEBUG("interface %i: process command \"%s\"\n",
interface->num, line);
ret = processCommand(interface->fp,
&(interface->permission),
line);
&(interface->permission), line);
DEBUG("interface %i: command returned %i\n",
interface->num, ret);
if(ret==0) commandSuccess(interface->fp);
else if(ret==COMMAND_RETURN_CLOSE || interface->expired)
{
if (ret == 0)
commandSuccess(interface->fp);
else if (ret == COMMAND_RETURN_CLOSE
|| interface->expired) {
closeInterface(interface);
}
printInterfaceOutBuffer(interface);
......@@ -295,33 +286,32 @@ static int processLineOfInput(Interface * interface) {
return ret;
}
static int processBytesRead(Interface * interface, int bytesRead) {
static int processBytesRead(Interface * interface, int bytesRead)
{
int ret = 0;
while(bytesRead > 0) {
while (bytesRead > 0) {
interface->bufferLength++;
bytesRead--;
if(interface->buffer[interface->bufferLength-1]=='\n') {
interface->buffer[interface->bufferLength-1] = '\0';
if (interface->buffer[interface->bufferLength - 1] == '\n') {
interface->buffer[interface->bufferLength - 1] = '\0';
ret = processLineOfInput(interface);
interface->bufferPos = interface->bufferLength;
}
if(interface->bufferLength==INTERFACE_MAX_BUFFER_LENGTH)
{
if(interface->bufferPos == 0) {
if (interface->bufferLength == INTERFACE_MAX_BUFFER_LENGTH) {
if (interface->bufferPos == 0) {
ERROR("interface %i: buffer overflow\n",
interface->num);
closeInterface(interface);
return 1;
}
interface->bufferLength-= interface->bufferPos;
interface->bufferLength -= interface->bufferPos;
memmove(interface->buffer,
interface->buffer+interface->bufferPos,
interface->buffer + interface->bufferPos,
interface->bufferLength);
interface->bufferPos = 0;
}
if(ret == COMMAND_RETURN_KILL || ret == COMMAND_RETURN_CLOSE)
{
if (ret == COMMAND_RETURN_KILL || ret == COMMAND_RETURN_CLOSE) {
return ret;
}
......@@ -330,50 +320,60 @@ static int processBytesRead(Interface * interface, int bytesRead) {
return ret;
}
static int interfaceReadInput(Interface * interface) {
static int interfaceReadInput(Interface * interface)
{
int bytesRead;
bytesRead = read(interface->fd,
interface->buffer+interface->bufferLength,
INTERFACE_MAX_BUFFER_LENGTH-interface->bufferLength);
interface->buffer + interface->bufferLength,
INTERFACE_MAX_BUFFER_LENGTH - interface->bufferLength);
if(bytesRead > 0) return processBytesRead(interface, bytesRead);
else if(bytesRead == 0 || (bytesRead < 0 && errno != EINTR)) {
if (bytesRead > 0)
return processBytesRead(interface, bytesRead);
else if (bytesRead == 0 || (bytesRead < 0 && errno != EINTR)) {
closeInterface(interface);
}
else return 0;
} else
return 0;
return 1;
}
static void addInterfacesReadyToReadAndListenSocketToFdSet(fd_set * fds, int * fdmax) {
static void addInterfacesReadyToReadAndListenSocketToFdSet(fd_set * fds,
int *fdmax)
{
int i;
FD_ZERO(fds);
addListenSocketsToFdSet(fds, fdmax);
for(i=0;i<interface_max_connections;i++) {
if(interfaces[i].open && !interfaces[i].expired && !interfaces[i].bufferList) {
FD_SET(interfaces[i].fd,fds);
if(*fdmax<interfaces[i].fd) *fdmax = interfaces[i].fd;
for (i = 0; i < interface_max_connections; i++) {
if (interfaces[i].open && !interfaces[i].expired
&& !interfaces[i].bufferList) {
FD_SET(interfaces[i].fd, fds);
if (*fdmax < interfaces[i].fd)
*fdmax = interfaces[i].fd;
}
}
}
static void addInterfacesForBufferFlushToFdSet(fd_set * fds, int * fdmax) {
static void addInterfacesForBufferFlushToFdSet(fd_set * fds, int *fdmax)
{
int i;
FD_ZERO(fds);
for(i=0;i<interface_max_connections;i++) {
if(interfaces[i].open && !interfaces[i].expired && interfaces[i].bufferList) {
FD_SET(interfaces[i].fd,fds);
if(*fdmax<interfaces[i].fd) *fdmax = interfaces[i].fd;
for (i = 0; i < interface_max_connections; i++) {
if (interfaces[i].open && !interfaces[i].expired
&& interfaces[i].bufferList) {
FD_SET(interfaces[i].fd, fds);
if (*fdmax < interfaces[i].fd)
*fdmax = interfaces[i].fd;
}
}
}
static void closeNextErroredInterface(void) {
static void closeNextErroredInterface(void)
{
fd_set fds;
struct timeval tv;
int i;
......@@ -381,11 +381,11 @@ static void closeNextErroredInterface(void) {
tv.tv_sec = 0;
tv.tv_usec = 0;
for(i=0;i<interface_max_connections;i++) {
if(interfaces[i].open) {
for (i = 0; i < interface_max_connections; i++) {
if (interfaces[i].open) {
FD_ZERO(&fds);
FD_SET(interfaces[i].fd,&fds);
if(select(FD_SETSIZE,&fds,NULL,NULL,&tv)<0) {
FD_SET(interfaces[i].fd, &fds);
if (select(FD_SETSIZE, &fds, NULL, NULL, &tv) < 0) {
closeInterface(&interfaces[i]);
return;
}
......@@ -393,7 +393,8 @@ static void closeNextErroredInterface(void) {
}
}
int doIOForInterfaces(void) {
int doIOForInterfaces(void)
{
fd_set rfds;
fd_set wfds;
struct timeval tv;
......@@ -404,31 +405,35 @@ int doIOForInterfaces(void) {
tv.tv_sec = 1;
tv.tv_usec = 0;
while(1) {
while (1) {
fdmax = 0;
addInterfacesReadyToReadAndListenSocketToFdSet(&rfds,&fdmax);
addInterfacesForBufferFlushToFdSet(&wfds,&fdmax);
addInterfacesReadyToReadAndListenSocketToFdSet(&rfds, &fdmax);
addInterfacesForBufferFlushToFdSet(&wfds, &fdmax);
selret = select(fdmax+1,&rfds,&wfds,NULL,&tv);
selret = select(fdmax + 1, &rfds, &wfds, NULL, &tv);
if(selret == 0 || (selret<0 && errno==EINTR)) break;
if (selret == 0 || (selret < 0 && errno == EINTR))
break;
if(selret<0) {
if (selret < 0) {
closeNextErroredInterface();
continue;
}
getConnections(&rfds);
for(i=0;i<interface_max_connections;i++) {
if(interfaces[i].open && FD_ISSET(interfaces[i].fd,&rfds)) {
if(COMMAND_RETURN_KILL==interfaceReadInput(&(interfaces[i]))) {
for (i = 0; i < interface_max_connections; i++) {
if (interfaces[i].open
&& FD_ISSET(interfaces[i].fd, &rfds)) {
if (COMMAND_RETURN_KILL ==
interfaceReadInput(&(interfaces[i]))) {
return COMMAND_RETURN_KILL;
}
interfaces[i].lastTime = time(NULL);
}
if(interfaces[i].open && FD_ISSET(interfaces[i].fd,&wfds)) {
if (interfaces[i].open
&& FD_ISSET(interfaces[i].fd, &wfds)) {
flushInterfaceBuffer(&interfaces[i]);
interfaces[i].lastTime = time(NULL);
}
......@@ -441,16 +446,17 @@ int doIOForInterfaces(void) {
return 1;
}
void initInterfaces(void) {
void initInterfaces(void)
{
int i;
char * test;
ConfigParam * param;
char *test;
ConfigParam *param;
param = getConfigParam(CONF_CONN_TIMEOUT);
if(param) {
interface_timeout = strtol(param->value,&test,10);
if(*test!='\0' || interface_timeout<=0) {
if (param) {
interface_timeout = strtol(param->value, &test, 10);
if (*test != '\0' || interface_timeout <= 0) {
ERROR("connection timeout \"%s\" is not a positive "
"integer, line %i\n", CONF_CONN_TIMEOUT,
param->line);
......@@ -460,65 +466,65 @@ void initInterfaces(void) {
param = getConfigParam(CONF_MAX_CONN);
if(param) {
if (param) {
interface_max_connections = strtol(param->value, &test, 10);
if(*test!='\0' || interface_max_connections<=0) {
if (*test != '\0' || interface_max_connections <= 0) {
ERROR("max connections \"%s\" is not a positive integer"
", line %i\n", param->value, param->line);
exit(EXIT_FAILURE);
}
}
else interface_max_connections = INTERFACE_MAX_CONNECTIONS_DEFAULT;
} else
interface_max_connections = INTERFACE_MAX_CONNECTIONS_DEFAULT;
param = getConfigParam(CONF_MAX_COMMAND_LIST_SIZE);
if(param) {
if (param) {
interface_max_command_list_size = strtoll(param->value,
&test, 10);
if(*test!='\0' || interface_max_command_list_size<=0) {
if (*test != '\0' || interface_max_command_list_size <= 0) {
ERROR("max command list size \"%s\" is not a positive "
"integer, line %i\n", param->value,
param->line);
"integer, line %i\n", param->value, param->line);
exit(EXIT_FAILURE);
}
interface_max_command_list_size*=1024;
interface_max_command_list_size *= 1024;
}
param = getConfigParam(CONF_MAX_OUTPUT_BUFFER_SIZE);
if(param) {
if (param) {
interface_max_output_buffer_size = strtoll(param->value, &test,
10);
if(*test!='\0' || interface_max_output_buffer_size<=0) {
if (*test != '\0' || interface_max_output_buffer_size <= 0) {
ERROR("max output buffer size \"%s\" is not a positive "
"integer, line %i\n", param->value,
param->line);
"integer, line %i\n", param->value, param->line);
exit(EXIT_FAILURE);
}
interface_max_output_buffer_size*=1024;
interface_max_output_buffer_size *= 1024;
}
interfaces = malloc(sizeof(Interface)*interface_max_connections);
interfaces = malloc(sizeof(Interface) * interface_max_connections);
for(i=0;i<interface_max_connections;i++) {
for (i = 0; i < interface_max_connections; i++) {
interfaces[i].open = 0;
interfaces[i].num = i;
}
}
static void closeAllInterfaces(void) {
static void closeAllInterfaces(void)
{
int i;
fflush(NULL);
for(i=0;i<interface_max_connections;i++) {
if(interfaces[i].open) {
for (i = 0; i < interface_max_connections; i++) {
if (interfaces[i].open) {
closeInterface(&(interfaces[i]));
}
}
}
void freeAllInterfaces(void) {
void freeAllInterfaces(void)
{
closeAllInterfaces();
free(interfaces);
......@@ -526,53 +532,52 @@ void freeAllInterfaces(void) {
interface_max_connections = 0;
}
void closeOldInterfaces(void) {
void closeOldInterfaces(void)
{
int i;
for(i=0;i<interface_max_connections;i++) {
if(interfaces[i].open) {
if(interfaces[i].expired) {
DEBUG("interface %i: expired\n",i);
for (i = 0; i < interface_max_connections; i++) {
if (interfaces[i].open) {
if (interfaces[i].expired) {
DEBUG("interface %i: expired\n", i);
closeInterface(&(interfaces[i]));
}
else if(time(NULL)-interfaces[i].lastTime >
interface_timeout)
{
DEBUG("interface %i: timeout\n",i);
} else if (time(NULL) - interfaces[i].lastTime >
interface_timeout) {
DEBUG("interface %i: timeout\n", i);
closeInterface(&(interfaces[i]));
}
}
}
}
static void flushInterfaceBuffer(Interface * interface) {
ListNode * node = NULL;
char * str;
static void flushInterfaceBuffer(Interface * interface)
{
ListNode *node = NULL;
char *str;
int ret = 0;
while((node = interface->bufferList->firstNode)) {
while ((node = interface->bufferList->firstNode)) {
str = (char *)node->data;
if((ret = write(interface->fd,str,strlen(str)))<0) break;
else if(ret<strlen(str)) {
interface->outputBufferSize-=ret;
if ((ret = write(interface->fd, str, strlen(str))) < 0)
break;
else if (ret < strlen(str)) {
interface->outputBufferSize -= ret;
str = strdup(&str[ret]);
free(node->data);
node->data = str;
}
else {
interface->outputBufferSize-= strlen(str)+1;
interface->outputBufferSize-= sizeof(ListNode);
deleteNodeFromList(interface->bufferList,node);
} else {
interface->outputBufferSize -= strlen(str) + 1;
interface->outputBufferSize -= sizeof(ListNode);
deleteNodeFromList(interface->bufferList, node);
}
interface->lastTime = time(NULL);
}
if(!interface->bufferList->firstNode) {
DEBUG("interface %i: buffer empty\n",interface->num);
if (!interface->bufferList->firstNode) {
DEBUG("interface %i: buffer empty\n", interface->num);
freeList(interface->bufferList);
interface->bufferList = NULL;
}
else if(ret<0 && errno!=EAGAIN && errno!=EINTR) {
} else if (ret < 0 && errno != EAGAIN && errno != EINTR) {
/* cause interface to close */
DEBUG("interface %i: problems flushing buffer\n",
interface->num);
......@@ -582,36 +587,38 @@ static void flushInterfaceBuffer(Interface * interface) {
}
}
int interfacePrintWithFD(int fd, char * buffer, int buflen) {
int interfacePrintWithFD(int fd, char *buffer, int buflen)
{
static int i = 0;
int copylen;
Interface * interface;
Interface *interface;
if(i>=interface_max_connections ||
!interfaces[i].open || interfaces[i].fd!=fd)
{
for(i=0;i<interface_max_connections;i++) {
if(interfaces[i].open && interfaces[i].fd==fd) break;
if (i >= interface_max_connections ||
!interfaces[i].open || interfaces[i].fd != fd) {
for (i = 0; i < interface_max_connections; i++) {
if (interfaces[i].open && interfaces[i].fd == fd)
break;
}
if(i==interface_max_connections) return -1;
if (i == interface_max_connections)
return -1;
}
/* if fd isn't found or interfaces is going to be closed, do nothing */
if(interfaces[i].expired) return 0;
if (interfaces[i].expired)
return 0;
interface = interfaces+i;
interface = interfaces + i;
while(buflen>0 && !interface->expired) {
copylen = buflen>
interface->outBufSize-interface->outBuflen?
interface->outBufSize-interface->outBuflen:
buflen;
memcpy(interface->outBuffer+interface->outBuflen,buffer,
while (buflen > 0 && !interface->expired) {
copylen = buflen >
interface->outBufSize - interface->outBuflen ?
interface->outBufSize - interface->outBuflen : buflen;
memcpy(interface->outBuffer + interface->outBuflen, buffer,
copylen);
buflen-=copylen;
interface->outBuflen+=copylen;
buffer+=copylen;
if(interface->outBuflen>=interface->outBufSize) {
buflen -= copylen;
interface->outBuflen += copylen;
buffer += copylen;
if (interface->outBuflen >= interface->outBufSize) {
printInterfaceOutBuffer(interface);
}
}
......@@ -619,20 +626,20 @@ int interfacePrintWithFD(int fd, char * buffer, int buflen) {
return 0;
}
static void printInterfaceOutBuffer(Interface * interface) {
char * buffer;
static void printInterfaceOutBuffer(Interface * interface)
{
char *buffer;
int ret;
if(!interface->open || interface->expired || !interface->outBuflen) {
if (!interface->open || interface->expired || !interface->outBuflen) {
return;
}
if(interface->bufferList) {
interface->outputBufferSize+=sizeof(ListNode);
interface->outputBufferSize+=interface->outBuflen+1;
if(interface->outputBufferSize>
interface_max_output_buffer_size)
{
if (interface->bufferList) {
interface->outputBufferSize += sizeof(ListNode);
interface->outputBufferSize += interface->outBuflen + 1;
if (interface->outputBufferSize >
interface_max_output_buffer_size) {
ERROR("interface %i: output buffer size (%lli) is "
"larger than the max (%lli)\n",
interface->num,
......@@ -642,51 +649,50 @@ static void printInterfaceOutBuffer(Interface * interface) {
freeList(interface->bufferList);
interface->bufferList = NULL;
interface->expired = 1;
}
else {
buffer = malloc(interface->outBuflen+1);
memcpy(buffer,interface->outBuffer,interface->outBuflen);
} else {
buffer = malloc(interface->outBuflen + 1);
memcpy(buffer, interface->outBuffer,
interface->outBuflen);
buffer[interface->outBuflen] = '\0';
insertInListWithoutKey(interface->bufferList,(void *)buffer);
insertInListWithoutKey(interface->bufferList,
(void *)buffer);
flushInterfaceBuffer(interface);
}
}
else {
if((ret = write(interface->fd,interface->outBuffer,
interface->outBuflen))<0)
{
if(errno==EAGAIN || errno==EINTR) {
buffer = malloc(interface->outBuflen+1);
memcpy(buffer,interface->outBuffer,
} else {
if ((ret = write(interface->fd, interface->outBuffer,
interface->outBuflen)) < 0) {
if (errno == EAGAIN || errno == EINTR) {
buffer = malloc(interface->outBuflen + 1);
memcpy(buffer, interface->outBuffer,
interface->outBuflen);
buffer[interface->outBuflen] = '\0';
interface->bufferList = makeList(free, 1);
insertInListWithoutKey(interface->bufferList,
(void *)buffer);
}
else {
} else {
DEBUG("interface %i: problems writing\n",
interface->num);
interface->expired = 1;
return;
}
}
else if(ret<interface->outBuflen) {
buffer = malloc(interface->outBuflen-ret+1);
memcpy(buffer,interface->outBuffer+ret,
interface->outBuflen-ret);
buffer[interface->outBuflen-ret] = '\0';
} else if (ret < interface->outBuflen) {
buffer = malloc(interface->outBuflen - ret + 1);
memcpy(buffer, interface->outBuffer + ret,
interface->outBuflen - ret);
buffer[interface->outBuflen - ret] = '\0';
interface->bufferList = makeList(free, 1);
insertInListWithoutKey(interface->bufferList,buffer);
insertInListWithoutKey(interface->bufferList, buffer);
}
/* if we needed to create buffer, initialize bufferSize info */
if(interface->bufferList) {
DEBUG("interface %i: buffer created\n",interface->num);
if (interface->bufferList) {
DEBUG("interface %i: buffer created\n", interface->num);
interface->outputBufferSize = sizeof(List);
interface->outputBufferSize+=sizeof(ListNode);
interface->outputBufferSize+=strlen(
(char *)interface->bufferList->
firstNode->data)+1;
interface->outputBufferSize += sizeof(ListNode);
interface->outputBufferSize += strlen((char *)
interface->
bufferList->
firstNode->data) +
1;
}
}
......
......@@ -27,10 +27,10 @@
#include <sys/socket.h>
void initInterfaces();
void openAInterface(int fd, struct sockaddr * addr);
void openAInterface(int fd, struct sockaddr *addr);
void freeAllInterfaces();
void closeOldInterfaces();
int interfacePrintWithFD(int fd, char * buffer, int len);
int interfacePrintWithFD(int fd, char *buffer, int len);
int doIOForInterfaces();
......
......@@ -16,7 +16,6 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "list.h"
#include <stdlib.h>
......@@ -25,31 +24,36 @@
#include <time.h>
#include <stdio.h>
static void makeListNodesArray(List * list) {
ListNode * node = list->firstNode;
static void makeListNodesArray(List * list)
{
ListNode *node = list->firstNode;
long i;
if(!list->numberOfNodes) return;
if (!list->numberOfNodes)
return;
list->nodesArray = realloc(list->nodesArray,
sizeof(ListNode *)*list->numberOfNodes);
sizeof(ListNode *) * list->numberOfNodes);
for(i=0;i<list->numberOfNodes;i++) {
for (i = 0; i < list->numberOfNodes; i++) {
list->nodesArray[i] = node;
node = node->nextNode;
}
}
static void freeListNodesArray(List * list) {
if(!list->nodesArray) return;
static void freeListNodesArray(List * list)
{
if (!list->nodesArray)
return;
free(list->nodesArray);
list->nodesArray = NULL;
}
List * makeList(ListFreeDataFunc * freeDataFunc, int strdupKeys) {
List * list = malloc(sizeof(List));
List *makeList(ListFreeDataFunc * freeDataFunc, int strdupKeys)
{
List *list = malloc(sizeof(List));
assert(list!=NULL);
assert(list != NULL);
list->sorted = 0;
list->firstNode = NULL;
......@@ -62,61 +66,63 @@ List * makeList(ListFreeDataFunc * freeDataFunc, int strdupKeys) {
return list;
}
ListNode * insertInListBeforeNode(List * list, ListNode * beforeNode, int pos, char * key, void * data)
ListNode *insertInListBeforeNode(List * list, ListNode * beforeNode, int pos,
char *key, void *data)
{
ListNode * node;
ListNode *node;
assert(list!=NULL);
assert(key!=NULL);
/*assert(data!=NULL);*/
assert(list != NULL);
assert(key != NULL);
/*assert(data!=NULL); */
node = malloc(sizeof(ListNode));
assert(node!=NULL);
assert(node != NULL);
node->nextNode = beforeNode;
if(beforeNode==list->firstNode) {
if(list->firstNode==NULL) {
assert(list->lastNode==NULL);
if (beforeNode == list->firstNode) {
if (list->firstNode == NULL) {
assert(list->lastNode == NULL);
list->lastNode = node;
}
else {
assert(list->lastNode!=NULL);
assert(list->lastNode->nextNode==NULL);
} else {
assert(list->lastNode != NULL);
assert(list->lastNode->nextNode == NULL);
list->firstNode->prevNode = node;
}
node->prevNode = NULL;
list->firstNode = node;
}
else {
if(beforeNode) {
} else {
if (beforeNode) {
node->prevNode = beforeNode->prevNode;
beforeNode->prevNode = node;
}
else {
} else {
node->prevNode = list->lastNode;
list->lastNode = node;
}
node->prevNode->nextNode = node;
}
if(list->strdupKeys) node->key = strdup(key);
else node->key = key;
if (list->strdupKeys)
node->key = strdup(key);
else
node->key = key;
node->data = data;
list->numberOfNodes++;
if(list->sorted) {
if (list->sorted) {
list->nodesArray = realloc(list->nodesArray,
list->numberOfNodes*sizeof(ListNode *));
if(node == list->lastNode) {
list->nodesArray[list->numberOfNodes-1] = node;
}
else if(pos < 0) makeListNodesArray(list);
list->numberOfNodes *
sizeof(ListNode *));
if (node == list->lastNode) {
list->nodesArray[list->numberOfNodes - 1] = node;
} else if (pos < 0)
makeListNodesArray(list);
else {
memmove(list->nodesArray+pos+1, list->nodesArray+pos,
sizeof(ListNode *)*
(list->numberOfNodes-pos-1));
memmove(list->nodesArray + pos + 1,
list->nodesArray + pos,
sizeof(ListNode *) * (list->numberOfNodes -
pos - 1));
list->nodesArray[pos] = node;
}
}
......@@ -124,30 +130,33 @@ ListNode * insertInListBeforeNode(List * list, ListNode * beforeNode, int po
return node;
}
ListNode * insertInList(List * list, char * key, void * data) {
ListNode * node;
ListNode *insertInList(List * list, char *key, void *data)
{
ListNode *node;
assert(list!=NULL);
assert(key!=NULL);
/*assert(data!=NULL);*/
assert(list != NULL);
assert(key != NULL);
/*assert(data!=NULL); */
node = malloc(sizeof(ListNode));
assert(node!=NULL);
assert(node != NULL);
if(list->nodesArray) freeListNodesArray(list);
if (list->nodesArray)
freeListNodesArray(list);
if(list->firstNode==NULL) {
assert(list->lastNode==NULL);
if (list->firstNode == NULL) {
assert(list->lastNode == NULL);
list->firstNode = node;
}
else {
assert(list->lastNode!=NULL);
assert(list->lastNode->nextNode==NULL);
} else {
assert(list->lastNode != NULL);
assert(list->lastNode->nextNode == NULL);
list->lastNode->nextNode = node;
}
if(list->strdupKeys) node->key = strdup(key);
else node->key = key;
if (list->strdupKeys)
node->key = strdup(key);
else
node->key = key;
node->data = data;
node->nextNode = NULL;
......@@ -160,24 +169,25 @@ ListNode * insertInList(List * list, char * key, void * data) {
return node;
}
int insertInListWithoutKey(List * list, void * data) {
ListNode * node;
int insertInListWithoutKey(List * list, void *data)
{
ListNode *node;
assert(list!=NULL);
assert(data!=NULL);
assert(list != NULL);
assert(data != NULL);
node = malloc(sizeof(ListNode));
assert(node!=NULL);
assert(node != NULL);
if(list->nodesArray) freeListNodesArray(list);
if (list->nodesArray)
freeListNodesArray(list);
if(list->firstNode==NULL) {
assert(list->lastNode==NULL);
if (list->firstNode == NULL) {
assert(list->lastNode == NULL);
list->firstNode = node;
}
else {
assert(list->lastNode!=NULL);
assert(list->lastNode->nextNode==NULL);
} else {
assert(list->lastNode != NULL);
assert(list->lastNode->nextNode == NULL);
list->lastNode->nextNode = node;
}
......@@ -195,147 +205,157 @@ int insertInListWithoutKey(List * list, void * data) {
/* if _key_ is not found, *_node_ is assigned to the node before which
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)
{
long high;
long low;
long cur;
ListNode * tmpNode;
ListNode *tmpNode;
int cmp;
assert(list!=NULL);
assert(list != NULL);
if(list->sorted && list->nodesArray) {
high = list->numberOfNodes-1;
if (list->sorted && list->nodesArray) {
high = list->numberOfNodes - 1;
low = 0;
cur = high;
while(high>low) {
cur = (high+low)/2;
while (high > low) {
cur = (high + low) / 2;
tmpNode = list->nodesArray[cur];
cmp = strcmp(tmpNode->key,key);
if(cmp==0) {
cmp = strcmp(tmpNode->key, key);
if (cmp == 0) {
*node = tmpNode;
*pos = cur;
return 1;
}
else if(cmp>0) high = cur;
} else if (cmp > 0)
high = cur;
else {
if(low==cur) break;
if (low == cur)
break;
low = cur;
}
}
cur = high;
if(cur>=0) {
if (cur >= 0) {
tmpNode = list->nodesArray[cur];
*node = tmpNode;
*pos = high;
cmp = tmpNode ? strcmp(tmpNode->key,key) : -1;
if( 0 == cmp ) return 1;
else if( cmp > 0) return 0;
cmp = tmpNode ? strcmp(tmpNode->key, key) : -1;
if (0 == cmp)
return 1;
else if (cmp > 0)
return 0;
else {
*pos = -1;
*node = NULL;
return 0;
}
}
else {
} else {
*pos = 0;
*node = list->firstNode;
return 0;
}
}
else {
} else {
tmpNode = list->firstNode;
while(tmpNode!=NULL && strcmp(tmpNode->key,key)!=0) {
while (tmpNode != NULL && strcmp(tmpNode->key, key) != 0) {
tmpNode = tmpNode->nextNode;
}
*node = tmpNode;
if(tmpNode) return 1;
if (tmpNode)
return 1;
}
return 0;
}
int findInList(List * list, char * key, void ** data) {
ListNode * node;
int findInList(List * list, char *key, void **data)
{
ListNode *node;
int pos;
if(findNodeInList(list, key, &node, &pos)) {
if(data) *data = node->data;
if (findNodeInList(list, key, &node, &pos)) {
if (data)
*data = node->data;
return 1;
}
return 0;
}
int deleteFromList(List * list,char * key) {
ListNode * tmpNode;
int deleteFromList(List * list, char *key)
{
ListNode *tmpNode;
assert(list!=NULL);
assert(list != NULL);
tmpNode = list->firstNode;
while(tmpNode!=NULL && strcmp(tmpNode->key,key)!=0) {
while (tmpNode != NULL && strcmp(tmpNode->key, key) != 0) {
tmpNode = tmpNode->nextNode;
}
if(tmpNode!=NULL)
deleteNodeFromList(list,tmpNode);
if (tmpNode != NULL)
deleteNodeFromList(list, tmpNode);
else
return 0;
return 1;
}
void deleteNodeFromList(List * list,ListNode * node) {
assert(list!=NULL);
assert(node!=NULL);
void deleteNodeFromList(List * list, ListNode * node)
{
assert(list != NULL);
assert(node != NULL);
if(node->prevNode==NULL) {
if (node->prevNode == NULL) {
list->firstNode = node->nextNode;
}
else {
} else {
node->prevNode->nextNode = node->nextNode;
}
if(node->nextNode==NULL) {
if (node->nextNode == NULL) {
list->lastNode = node->prevNode;
}
else {
} else {
node->nextNode->prevNode = node->prevNode;
}
if(list->freeDataFunc) {
if (list->freeDataFunc) {
list->freeDataFunc(node->data);
}
if(list->strdupKeys) free(node->key);
if (list->strdupKeys)
free(node->key);
free(node);
list->numberOfNodes--;
if(list->nodesArray) {
if (list->nodesArray) {
freeListNodesArray(list);
if(list->sorted) makeListNodesArray(list);
if (list->sorted)
makeListNodesArray(list);
}
}
void freeList(void * list) {
ListNode * tmpNode;
ListNode * tmpNode2;
void freeList(void *list)
{
ListNode *tmpNode;
ListNode *tmpNode2;
assert(list!=NULL);
assert(list != NULL);
tmpNode = ((List *)list)->firstNode;
tmpNode = ((List *) list)->firstNode;
if(((List *)list)->nodesArray) free(((List *)list)->nodesArray);
if (((List *) list)->nodesArray)
free(((List *) list)->nodesArray);
while(tmpNode!=NULL) {
while (tmpNode != NULL) {
tmpNode2 = tmpNode->nextNode;
if(((List *)list)->strdupKeys) free(tmpNode->key);
if(((List *)list)->freeDataFunc) {
((List *)list)->freeDataFunc(tmpNode->data);
if (((List *) list)->strdupKeys)
free(tmpNode->key);
if (((List *) list)->freeDataFunc) {
((List *) list)->freeDataFunc(tmpNode->data);
}
free(tmpNode);
tmpNode = tmpNode2;
......@@ -344,12 +364,13 @@ void freeList(void * list) {
free(list);
}
static void swapNodes(ListNode * nodeA, ListNode * nodeB) {
char * key;
void * data;
static void swapNodes(ListNode * nodeA, ListNode * nodeB)
{
char *key;
void *data;
assert(nodeA!=NULL);
assert(nodeB!=NULL);
assert(nodeA != NULL);
assert(nodeB != NULL);
key = nodeB->key;
data = nodeB->data;
......@@ -361,98 +382,116 @@ static void swapNodes(ListNode * nodeA, ListNode * nodeB) {
nodeA->data = data;
}
static void bubbleSort(ListNode ** nodesArray, long start, long end) {
static void bubbleSort(ListNode ** nodesArray, long start, long end)
{
long i;
long j;
ListNode * node;
ListNode *node;
if(start>=end) return;
if (start >= end)
return;
for(j=start;j<end;j++) {
for(i=end-1;i>=start;i--) {
for (j = start; j < end; j++) {
for (i = end - 1; i >= start; i--) {
node = nodesArray[i];
if(strcmp(node->key,node->nextNode->key)>0) {
swapNodes(node,node->nextNode);
if (strcmp(node->key, node->nextNode->key) > 0) {
swapNodes(node, node->nextNode);
}
}
}
}
static void quickSort(ListNode ** nodesArray, long start, long end) {
if(start>=end) return;
else if(end-start<5) bubbleSort(nodesArray,start,end);
static void quickSort(ListNode ** nodesArray, long start, long end)
{
if (start >= end)
return;
else if (end - start < 5)
bubbleSort(nodesArray, start, end);
else {
long i;
ListNode * node;
ListNode *node;
long pivot;
ListNode * pivotNode;
char * pivotKey;
ListNode *pivotNode;
char *pivotKey;
List * startList = makeList(free, 0);
List * endList = makeList(free, 0);
long * startPtr = malloc(sizeof(long));
long * endPtr = malloc(sizeof(long));
List *startList = makeList(free, 0);
List *endList = makeList(free, 0);
long *startPtr = malloc(sizeof(long));
long *endPtr = malloc(sizeof(long));
*startPtr = start;
*endPtr = end;
insertInListWithoutKey(startList,(void *)startPtr);
insertInListWithoutKey(endList,(void *)endPtr);
insertInListWithoutKey(startList, (void *)startPtr);
insertInListWithoutKey(endList, (void *)endPtr);
while(startList->numberOfNodes) {
while (startList->numberOfNodes) {
start = *((long *)startList->lastNode->data);
end = *((long *)endList->lastNode->data);
if(end-start<5) {
bubbleSort(nodesArray,start,end);
deleteNodeFromList(startList,startList->lastNode);
deleteNodeFromList(endList,endList->lastNode);
}
else {
pivot = (start+end)/2;
if (end - start < 5) {
bubbleSort(nodesArray, start, end);
deleteNodeFromList(startList,
startList->lastNode);
deleteNodeFromList(endList, endList->lastNode);
} else {
pivot = (start + end) / 2;
pivotNode = nodesArray[pivot];
pivotKey = pivotNode->key;
for(i=pivot-1;i>=start;i--) {
for (i = pivot - 1; i >= start; i--) {
node = nodesArray[i];
if(strcmp(node->key,pivotKey)>0) {
if (strcmp(node->key, pivotKey) > 0) {
pivot--;
if(pivot>i) {
swapNodes(node,nodesArray[pivot]);
if (pivot > i) {
swapNodes(node,
nodesArray
[pivot]);
}
swapNodes(pivotNode,nodesArray[pivot]);
swapNodes(pivotNode,
nodesArray[pivot]);
pivotNode = nodesArray[pivot];
}
}
for(i=pivot+1;i<=end;i++) {
for (i = pivot + 1; i <= end; i++) {
node = nodesArray[i];
if(strcmp(pivotKey,node->key)>0) {
if (strcmp(pivotKey, node->key) > 0) {
pivot++;
if(pivot<i) {
swapNodes(node,nodesArray[pivot]);
if (pivot < i) {
swapNodes(node,
nodesArray
[pivot]);
}
swapNodes(pivotNode,nodesArray[pivot]);
swapNodes(pivotNode,
nodesArray[pivot]);
pivotNode = nodesArray[pivot];
}
}
deleteNodeFromList(startList,startList->lastNode);
deleteNodeFromList(endList,endList->lastNode);
deleteNodeFromList(startList,
startList->lastNode);
deleteNodeFromList(endList, endList->lastNode);
if(pivot-1-start>0) {
if (pivot - 1 - start > 0) {
startPtr = malloc(sizeof(long));
endPtr = malloc(sizeof(long));
*startPtr = start;
*endPtr = pivot-1;
insertInListWithoutKey(startList,(void *)startPtr);
insertInListWithoutKey(endList,(void *)endPtr);
*endPtr = pivot - 1;
insertInListWithoutKey(startList,
(void *)
startPtr);
insertInListWithoutKey(endList,
(void *)endPtr);
}
if(end-pivot-1>0) {
if (end - pivot - 1 > 0) {
startPtr = malloc(sizeof(long));
endPtr = malloc(sizeof(long));
*startPtr = pivot+1;
*startPtr = pivot + 1;
*endPtr = end;
insertInListWithoutKey(startList,(void *)startPtr);
insertInListWithoutKey(endList,(void *)endPtr);
insertInListWithoutKey(startList,
(void *)
startPtr);
insertInListWithoutKey(endList,
(void *)endPtr);
}
}
}
......@@ -462,15 +501,18 @@ static void quickSort(ListNode ** nodesArray, long start, long end) {
}
}
void sortList(List * list) {
assert(list!=NULL);
void sortList(List * list)
{
assert(list != NULL);
list->sorted = 1;
if(list->numberOfNodes<2) return;
if (list->numberOfNodes < 2)
return;
if(list->nodesArray) freeListNodesArray(list);
if (list->nodesArray)
freeListNodesArray(list);
makeListNodesArray(list);
quickSort(list->nodesArray,0,list->numberOfNodes-1);
quickSort(list->nodesArray, 0, list->numberOfNodes - 1);
}
......@@ -16,7 +16,6 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef LIST_H
#define LIST_H
......@@ -32,26 +31,26 @@ typedef void ListFreeDataFunc(void *);
typedef struct _ListNode {
/* used to identify node (ie. when using findInList) */
char * key;
char *key;
/* data store in node */
void * data;
void *data;
/* next node in list */
struct _ListNode * nextNode;
struct _ListNode *nextNode;
/* previous node in list */
struct _ListNode * prevNode;
struct _ListNode *prevNode;
} ListNode;
typedef struct _List {
/* first node in list */
ListNode * firstNode;
ListNode *firstNode;
/* last node in list */
ListNode * lastNode;
ListNode *lastNode;
/* function used to free data stored in nodes of the list */
ListFreeDataFunc * freeDataFunc;
ListFreeDataFunc *freeDataFunc;
/* number of nodes */
long numberOfNodes;
/* array for searching when list is sorted */
ListNode ** nodesArray;
ListNode **nodesArray;
/* sorted */
int sorted;
/* weather to strdup() key's on insertion */
......@@ -63,7 +62,7 @@ typedef struct _List {
* DEFAULT_FREE_DATAFUNC to use free()
* 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_
* _list_ -> list the data will be inserted in
......@@ -71,21 +70,21 @@ List * makeList(ListFreeDataFunc * freeDataFunc, int strdupKeys);
* _data_ -> data to be inserted in list
* 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,
int pos, char * key, void * data);
ListNode *insertInListBeforeNode(List * list, ListNode * beforeNode,
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_
* _list_ -> list the node will be deleted from
* _key_ -> key used to identify node to delete
* 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
* _list_ -> list to search for _key_ in
......@@ -95,16 +94,16 @@ void deleteNodeFromList(List * list,ListNode * node);
* _data_ can be NULL
* 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
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
* _list_ -> List to be free'd
*/
void freeList(void * list);
void freeList(void *list);
void sortList(List * list);
......
......@@ -40,18 +40,17 @@
#define DEFAULT_PORT 6600
int * listenSockets = NULL;
int *listenSockets = NULL;
int numberOfListenSockets = 0;
static void establishListen(unsigned int port,
struct sockaddr * addrp,
socklen_t addrlen)
struct sockaddr *addrp, socklen_t addrlen)
{
int pf;
int sock;
int allowReuse = ALLOW_REUSE;
switch(addrp->sa_family) {
switch (addrp->sa_family) {
case AF_INET:
pf = PF_INET;
break;
......@@ -64,49 +63,49 @@ static void establishListen(unsigned int port,
pf = PF_UNIX;
break;
default:
ERROR("unknown address family: %i\n",addrp->sa_family);
ERROR("unknown address family: %i\n", addrp->sa_family);
exit(EXIT_FAILURE);
}
if((sock = socket(pf,SOCK_STREAM,0)) < 0) {
if ((sock = socket(pf, SOCK_STREAM, 0)) < 0) {
ERROR("socket < 0\n");
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",
strerror(errno));
exit(EXIT_FAILURE);
}
if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&allowReuse,
sizeof(allowReuse))<0)
{
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&allowReuse,
sizeof(allowReuse)) < 0) {
ERROR("problems setsockopt'ing: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if(bind(sock,addrp,addrlen)<0) {
if (bind(sock, addrp, addrlen) < 0) {
ERROR("unable to bind port %u", port);
ERROR(": %s\n", strerror(errno));
ERROR("maybe MPD is still running?\n");
exit(EXIT_FAILURE);
}
if(listen(sock,5)<0) {
if (listen(sock, 5) < 0) {
ERROR("problems listen'ing: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
numberOfListenSockets++;
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) {
struct sockaddr * addrp;
static void parseListenConfigParam(unsigned int port, ConfigParam * param)
{
struct sockaddr *addrp;
socklen_t addrlen;
struct sockaddr_in sin;
#ifdef HAVE_IPV6
......@@ -120,54 +119,52 @@ static void parseListenConfigParam(unsigned int port, ConfigParam * param) {
sin.sin_port = htons(port);
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");
#ifdef HAVE_IPV6
if(ipv6Supported()) {
if (ipv6Supported()) {
sin6.sin6_addr = in6addr_any;
addrp = (struct sockaddr *) &sin6;
addrp = (struct sockaddr *)&sin6;
addrlen = sizeof(struct sockaddr_in6);
establishListen(port, addrp, addrlen);
}
#endif
sin.sin_addr.s_addr = INADDR_ANY;
addrp = (struct sockaddr *) &sin;
addrp = (struct sockaddr *)&sin;
addrlen = sizeof(struct sockaddr_in);
establishListen(port, addrp, addrlen);
}
else {
struct hostent * he;
} else {
struct hostent *he;
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",
param->value, param->line);
exit(EXIT_FAILURE);
}
switch(he->h_addrtype) {
switch (he->h_addrtype) {
#ifdef HAVE_IPV6
case AF_INET6:
if(!ipv6Supported()) {
if (!ipv6Supported()) {
ERROR("no IPv6 support, but a IPv6 address "
"found for \"%s\" at line %i\n",
param->value, param->line);
exit(EXIT_FAILURE);
}
bcopy((char *)he->h_addr,(char *)
&sin6.sin6_addr.s6_addr,he->h_length);
addrp = (struct sockaddr *) &sin6;
bcopy((char *)he->h_addr, (char *)
&sin6.sin6_addr.s6_addr, he->h_length);
addrp = (struct sockaddr *)&sin6;
addrlen = sizeof(struct sockaddr_in6);
break;
#endif
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);
addrp = (struct sockaddr *) &sin;
addrp = (struct sockaddr *)&sin;
addrlen = sizeof(struct sockaddr_in);
break;
default:
ERROR("address type for \"%s\" is not IPv4 or IPv6 "
"at line %i\n",
param->value, param->line);
"at line %i\n", param->value, param->line);
exit(EXIT_FAILURE);
}
......@@ -175,21 +172,21 @@ static void parseListenConfigParam(unsigned int port, ConfigParam * param) {
}
}
void listenOnPort(void) {
void listenOnPort(void)
{
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) {
char * test;
if (portParam) {
char *test;
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 "
"positive integer", CONF_PORT,
portParam->value,
portParam->line);
portParam->value, portParam->line);
exit(EXIT_FAILURE);
}
}
......@@ -200,47 +197,51 @@ void listenOnPort(void) {
} while ((param = getNextConfigParam(CONF_BIND_TO_ADDRESS, param)));
}
void addListenSocketsToFdSet(fd_set * fds, int * fdmax) {
void addListenSocketsToFdSet(fd_set * fds, int *fdmax)
{
int i;
for(i=0; i<numberOfListenSockets; i++) {
for (i = 0; i < numberOfListenSockets; i++) {
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;
DEBUG("closeAllListenSockets called\n");
for(i=0; i<numberOfListenSockets; i++) {
for (i = 0; i < numberOfListenSockets; i++) {
DEBUG("closing listen socket %i\n", i);
while(close(listenSockets[i]) < 0 && errno==EINTR);
while (close(listenSockets[i]) < 0 && errno == EINTR) ;
}
freeAllListenSockets();
}
void freeAllListenSockets(void) {
void freeAllListenSockets(void)
{
numberOfListenSockets = 0;
free(listenSockets);
listenSockets = NULL;
}
void getConnections(fd_set * fds) {
void getConnections(fd_set * fds)
{
int i;
int fd = 0;
struct sockaddr sockAddr;
socklen_t socklen = sizeof(sockAddr);
for(i=0; i<numberOfListenSockets; i++) {
if(FD_ISSET(listenSockets[i], fds)) {
if((fd = accept(listenSockets[i], &sockAddr, &socklen))
>= 0)
{
openAInterface(fd,&sockAddr);
}
else if(fd<0 && (errno!=EAGAIN && errno!=EINTR)) {
for (i = 0; i < numberOfListenSockets; i++) {
if (FD_ISSET(listenSockets[i], fds)) {
if ((fd = accept(listenSockets[i], &sockAddr, &socklen))
>= 0) {
openAInterface(fd, &sockAddr);
} else if (fd < 0
&& (errno != EAGAIN && errno != EINTR)) {
ERROR("Problems accept()'ing\n");
}
}
......
......@@ -34,6 +34,6 @@ void closeAllListenSockets();
void freeAllListenSockets();
/* fdmax should be initialized to something */
void addListenSocketsToFdSet(fd_set * fds, int * fdmax);
void addListenSocketsToFdSet(fd_set * fds, int *fdmax);
#endif
......@@ -29,23 +29,25 @@
int logLevel = LOG_LEVEL_LOW;
short warningFlushed = 0;
static char * warningBuffer = NULL;
void initLog(void) {
ConfigParam * param = getConfigParam(CONF_LOG_LEVEL);
if(!param) return;
if(0 == strcmp(param->value, "default")) {
if(logLevel<LOG_LEVEL_LOW) logLevel = LOG_LEVEL_LOW;
}
else if(0 == strcmp(param->value, "secure")) {
if(logLevel<LOG_LEVEL_SECURE) logLevel = LOG_LEVEL_SECURE;
}
else if(0 == strcmp(param->value, "verbose")) {
if(logLevel<LOG_LEVEL_DEBUG) logLevel = LOG_LEVEL_DEBUG;
}
else {
static char *warningBuffer = NULL;
void initLog(void)
{
ConfigParam *param = getConfigParam(CONF_LOG_LEVEL);
if (!param)
return;
if (0 == strcmp(param->value, "default")) {
if (logLevel < LOG_LEVEL_LOW)
logLevel = LOG_LEVEL_LOW;
} else if (0 == strcmp(param->value, "secure")) {
if (logLevel < LOG_LEVEL_SECURE)
logLevel = LOG_LEVEL_SECURE;
} else if (0 == strcmp(param->value, "verbose")) {
if (logLevel < LOG_LEVEL_DEBUG)
logLevel = LOG_LEVEL_DEBUG;
} else {
ERROR("unknown log level \"%s\" at line %i\n",
param->value, param->line);
exit(EXIT_FAILURE);
......@@ -54,11 +56,12 @@ void initLog(void) {
#define BUFFER_LENGTH 4096
void bufferWarning(char * format, ... ) {
void bufferWarning(char *format, ...)
{
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);
......@@ -69,15 +72,17 @@ void bufferWarning(char * format, ... ) {
va_end(arglist);
}
void flushWarningLog(void) {
char * s;
void flushWarningLog(void)
{
char *s;
DEBUG("flushing warning messages\n");
if(warningBuffer == NULL) return;
if (warningBuffer == NULL)
return;
s = strtok(warningBuffer, "\n");
while ( s != NULL ) {
while (s != NULL) {
myfprintf(stderr, "%s\n", s);
s = strtok(NULL, "\n");
......
......@@ -37,7 +37,6 @@ extern short warningFlushed;
#define SECURE(...) if(logLevel>=LOG_LEVEL_SECURE) \
myfprintf(stdout, __VA_ARGS__)
#define DEBUG(...) if(logLevel>=LOG_LEVEL_DEBUG) \
myfprintf(stdout, __VA_ARGS__)
......@@ -48,7 +47,7 @@ extern short warningFlushed;
void initLog();
void bufferWarning(char * format, ... );
void bufferWarning(char *format, ...);
void flushWarningLog();
......
......@@ -27,33 +27,34 @@
#include <stdio.h>
#include <errno.h>
static char * remoteUrlPrefixes[] =
{
static char *remoteUrlPrefixes[] = {
"http://",
NULL
};
int printRemoteUrlHandlers(FILE * fp) {
char ** prefixes = remoteUrlPrefixes;
int printRemoteUrlHandlers(FILE * fp)
{
char **prefixes = remoteUrlPrefixes;
while (*prefixes) {
myfprintf(fp,"handler: %s\n", *prefixes);
myfprintf(fp, "handler: %s\n", *prefixes);
prefixes++;
}
return 0;
}
int isValidRemoteUtf8Url(char * utf8url) {
int isValidRemoteUtf8Url(char *utf8url)
{
int ret = 0;
char * temp;
char *temp;
switch(isRemoteUrl(utf8url)) {
switch (isRemoteUrl(utf8url)) {
case 1:
ret = 1;
temp = utf8url;
while(*temp) {
if((*temp >= 'a' && *temp <= 'z') ||
while (*temp) {
if ((*temp >= 'a' && *temp <= 'z') ||
(*temp >= 'A' && *temp <= 'Z') ||
(*temp >= '0' && *temp <= '9') ||
*temp == '$' ||
......@@ -70,12 +71,8 @@ int isValidRemoteUtf8Url(char * utf8url) {
*temp == '/' ||
*temp == ':' ||
*temp == '?' ||
*temp == ';' ||
*temp == '&' ||
*temp == '=')
{
}
else {
*temp == ';' || *temp == '&' || *temp == '=') {
} else {
ret = 1;
break;
}
......@@ -87,13 +84,14 @@ int isValidRemoteUtf8Url(char * utf8url) {
return ret;
}
int isRemoteUrl(char * url) {
int isRemoteUrl(char *url)
{
int count = 0;
char ** urlPrefixes = remoteUrlPrefixes;
char **urlPrefixes = remoteUrlPrefixes;
while(*urlPrefixes) {
while (*urlPrefixes) {
count++;
if(strncmp(*urlPrefixes,url,strlen(*urlPrefixes)) == 0) {
if (strncmp(*urlPrefixes, url, strlen(*urlPrefixes)) == 0) {
return count;
}
urlPrefixes++;
......@@ -102,46 +100,47 @@ int isRemoteUrl(char * url) {
return 0;
}
int lsPlaylists(FILE * fp, char * utf8path) {
DIR * dir;
int lsPlaylists(FILE * fp, char *utf8path)
{
DIR *dir;
struct stat st;
struct dirent * ent;
char * dup;
char * utf8;
char s[MAXPATHLEN+1];
List * list = NULL;
ListNode * node = NULL;
char * path = utf8ToFsCharset(utf8path);
char * actualPath = rpp2app(path);
int actlen = strlen(actualPath)+1;
int maxlen = MAXPATHLEN-actlen;
int suflen = strlen(PLAYLIST_FILE_SUFFIX)+1;
struct dirent *ent;
char *dup;
char *utf8;
char s[MAXPATHLEN + 1];
List *list = NULL;
ListNode *node = NULL;
char *path = utf8ToFsCharset(utf8path);
char *actualPath = rpp2app(path);
int actlen = strlen(actualPath) + 1;
int maxlen = MAXPATHLEN - actlen;
int suflen = strlen(PLAYLIST_FILE_SUFFIX) + 1;
int suff;
if(actlen>MAXPATHLEN-1 || (dir = opendir(actualPath))==NULL) {
if (actlen > MAXPATHLEN - 1 || (dir = opendir(actualPath)) == NULL) {
free(path);
return 0;
}
s[MAXPATHLEN] = '\0';
/* this is safe, notice actlen > MAXPATHLEN-1 above */
strcpy(s,actualPath);
strcat(s,"/");
strcpy(s, actualPath);
strcat(s, "/");
while((ent = readdir(dir))) {
while ((ent = readdir(dir))) {
dup = ent->d_name;
if(dup[0]!='.' &&
(suff=strlen(dup)-suflen)>0 &&
dup[suff]=='.' &&
strcmp(dup+suff+1,PLAYLIST_FILE_SUFFIX)==0)
{
strncpy(s+actlen,ent->d_name,maxlen);
if(stat(s,&st)==0) {
if(S_ISREG(st.st_mode)) {
if(list==NULL) list = makeList(NULL, 1);
if (dup[0] != '.' &&
(suff = strlen(dup) - suflen) > 0 &&
dup[suff] == '.' &&
strcmp(dup + suff + 1, PLAYLIST_FILE_SUFFIX) == 0) {
strncpy(s + actlen, ent->d_name, maxlen);
if (stat(s, &st) == 0) {
if (S_ISREG(st.st_mode)) {
if (list == NULL)
list = makeList(NULL, 1);
dup[suff] = '\0';
if((utf8 = fsCharsetToUtf8(dup))) {
insertInList(list,utf8,NULL);
if ((utf8 = fsCharsetToUtf8(dup))) {
insertInList(list, utf8, NULL);
free(utf8);
}
}
......@@ -152,21 +151,23 @@ int lsPlaylists(FILE * fp, char * utf8path) {
closedir(dir);
free(path);
if(list) {
if (list) {
int i;
sortList(list);
dup = malloc(strlen(utf8path)+2);
strcpy(dup,utf8path);
for(i = strlen(dup)-1; i >= 0 && dup[i]=='/'; i--) {
dup = malloc(strlen(utf8path) + 2);
strcpy(dup, utf8path);
for (i = strlen(dup) - 1; i >= 0 && dup[i] == '/'; i--) {
dup[i] = '\0';
}
if(strlen(dup)) strcat(dup,"/");
if (strlen(dup))
strcat(dup, "/");
node = list->firstNode;
while(node!=NULL) {
if(!strchr(node->key, '\n')) {
myfprintf(fp,"playlist: %s%s\n",dup,node->key);
while (node != NULL) {
if (!strchr(node->key, '\n')) {
myfprintf(fp, "playlist: %s%s\n", dup,
node->key);
}
node = node->nextNode;
}
......@@ -178,71 +179,79 @@ int lsPlaylists(FILE * fp, char * utf8path) {
return 0;
}
int myStat(char * utf8file, struct stat * st) {
char * file = utf8ToFsCharset(utf8file);
char * actualFile = file;
int myStat(char *utf8file, struct stat *st)
{
char *file = utf8ToFsCharset(utf8file);
char *actualFile = file;
int ret;
if(actualFile[0]!='/') actualFile = rmp2amp(file);
if (actualFile[0] != '/')
actualFile = rmp2amp(file);
ret = stat(actualFile,st);
ret = stat(actualFile, st);
free(file);
return ret;
}
static int isFile(char * utf8file, time_t * mtime) {
static int isFile(char *utf8file, time_t * mtime)
{
struct stat st;
if(myStat(utf8file,&st)==0) {
if(S_ISREG(st.st_mode)) {
if(mtime) *mtime = st.st_mtime;
if (myStat(utf8file, &st) == 0) {
if (S_ISREG(st.st_mode)) {
if (mtime)
*mtime = st.st_mtime;
return 1;
}
else
{
DEBUG("isFile: %s is not a regular file\n",utf8file);
} else {
DEBUG("isFile: %s is not a regular file\n", utf8file);
return 0;
}
}
else {
DEBUG("isFile: failed to stat: %s: %s\n", utf8file, strerror(errno));
} else {
DEBUG("isFile: failed to stat: %s: %s\n", utf8file,
strerror(errno));
}
return 0;
}
/* suffixes should be ascii only characters */
char * getSuffix(char * utf8file) {
char * ret = NULL;
char *getSuffix(char *utf8file)
{
char *ret = NULL;
while(*utf8file) {
if(*utf8file == '.') ret = utf8file+1;
while (*utf8file) {
if (*utf8file == '.')
ret = utf8file + 1;
utf8file++;
}
return ret;
}
int hasSuffix(char * utf8file, char * suffix) {
char * s = getSuffix(utf8file);
if(s && 0==strcmp(s,suffix)) return 1;
int hasSuffix(char *utf8file, char *suffix)
{
char *s = getSuffix(utf8file);
if (s && 0 == strcmp(s, suffix))
return 1;
return 0;
}
int isPlaylist(char * utf8file) {
if(isFile(utf8file,NULL)) {
return hasSuffix(utf8file,PLAYLIST_FILE_SUFFIX);
int isPlaylist(char *utf8file)
{
if (isFile(utf8file, NULL)) {
return hasSuffix(utf8file, PLAYLIST_FILE_SUFFIX);
}
return 0;
}
int isDir(char * utf8name) {
int isDir(char *utf8name)
{
struct stat st;
if(myStat(utf8name,&st)==0) {
if(S_ISDIR(st.st_mode)) {
if (myStat(utf8name, &st) == 0) {
if (S_ISDIR(st.st_mode)) {
return 1;
}
}
......@@ -250,26 +259,28 @@ int isDir(char * utf8name) {
return 0;
}
InputPlugin * hasMusicSuffix(char * utf8file, unsigned int next) {
InputPlugin * ret = NULL;
InputPlugin *hasMusicSuffix(char *utf8file, unsigned int next)
{
InputPlugin *ret = NULL;
char * s = getSuffix(utf8file);
if(s) {
char *s = getSuffix(utf8file);
if (s) {
ret = getInputPluginFromSuffix(s, next);
}
else {
DEBUG("hasMusicSuffix: The file: %s has no valid suffix\n",utf8file);
} else {
DEBUG("hasMusicSuffix: The file: %s has no valid suffix\n",
utf8file);
}
return ret;
}
InputPlugin * isMusic(char * utf8file, time_t * mtime, unsigned int next) {
if(isFile(utf8file,mtime)) {
InputPlugin * plugin = hasMusicSuffix(utf8file, next);
InputPlugin *isMusic(char *utf8file, time_t * mtime, unsigned int next)
{
if (isFile(utf8file, mtime)) {
InputPlugin *plugin = hasMusicSuffix(utf8file, next);
if (plugin != NULL)
return plugin;
}
DEBUG("isMusic: %s is not a valid file\n",utf8file);
DEBUG("isMusic: %s is not a valid file\n", utf8file);
return NULL;
}
......@@ -29,23 +29,23 @@
#include <unistd.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);
......
......@@ -20,7 +20,8 @@
#include <string.h>
static void initMetadataChunk(MetadataChunk * chunk) {
static void initMetadataChunk(MetadataChunk * chunk)
{
memset(chunk, 0, sizeof(MetadataChunk));
chunk->name = -1;
......@@ -35,10 +36,11 @@ static void initMetadataChunk(MetadataChunk * chunk) {
} \
}
MpdTag * metadataChunkToMpdTagDup(MetadataChunk * chunk) {
MpdTag * ret = newMpdTag();
MpdTag *metadataChunkToMpdTagDup(MetadataChunk * chunk)
{
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_TITLE, chunk->title);
......@@ -59,17 +61,19 @@ MpdTag * metadataChunkToMpdTagDup(MetadataChunk * chunk) {
} \
}
void copyMpdTagToMetadataChunk(MpdTag * tag, MetadataChunk * chunk) {
void copyMpdTagToMetadataChunk(MpdTag * tag, MetadataChunk * chunk)
{
int pos = 0;
int slen;
int i;
initMetadataChunk(chunk);
if(!tag) return;
if (!tag)
return;
for(i = 0; i < tag->numOfItems; i++) {
switch(tag->items[i].type) {
for (i = 0; i < tag->numOfItems; i++) {
switch (tag->items[i].type) {
case TAG_ITEM_NAME:
copyStringToChunk(tag->items[i].value, chunk->name);
break;
......
......@@ -31,7 +31,7 @@ typedef struct _MetadataChunk {
char buffer[METADATA_BUFFER_LENGTH];
} MetadataChunk;
MpdTag * metadataChunkToMpdTagDup(MetadataChunk * chunk);
MpdTag *metadataChunkToMpdTagDup(MetadataChunk * chunk);
void copyMpdTagToMetadataChunk(MpdTag * tag, MetadataChunk * chunk);
......
......@@ -33,19 +33,21 @@
#define BUFFER_LENGTH MAXPATHLEN+1024
static int myfprintf_stdLogMode = 0;
static FILE * myfprintf_out;
static FILE * myfprintf_err;
static char * myfprintf_outFilename;
static char * myfprintf_errFilename;
static FILE *myfprintf_out;
static FILE *myfprintf_err;
static char *myfprintf_outFilename;
static char *myfprintf_errFilename;
static void blockingWrite(int fd, char * string, int len) {
static void blockingWrite(int fd, char *string, int len)
{
int ret;
while(len) {
ret = write(fd,string,len);
if(ret==0) return;
if(ret<0) {
switch(errno) {
while (len) {
ret = write(fd, string, len);
if (ret == 0)
return;
if (ret < 0) {
switch (errno) {
case EAGAIN:
case EINTR:
continue;
......@@ -53,12 +55,13 @@ static void blockingWrite(int fd, char * string, int len) {
return;
}
}
len-= ret;
string+= ret;
len -= ret;
string += ret;
}
}
void myfprintfStdLogMode(FILE * out, FILE * err) {
void myfprintfStdLogMode(FILE * out, FILE * err)
{
myfprintf_stdLogMode = 1;
myfprintf_out = out;
myfprintf_err = err;
......@@ -66,64 +69,68 @@ void myfprintfStdLogMode(FILE * out, FILE * err) {
myfprintf_errFilename = getConfigParamValue(CONF_ERROR_FILE);
}
void myfprintf(FILE * fp, char * format, ... ) {
static char buffer[BUFFER_LENGTH+1];
void myfprintf(FILE * fp, char *format, ...)
{
static char buffer[BUFFER_LENGTH + 1];
va_list arglist;
int fd = fileno(fp);
va_start(arglist,format);
if(fd==1 || fd==2) {
if(myfprintf_stdLogMode) {
va_start(arglist, format);
if (fd == 1 || fd == 2) {
if (myfprintf_stdLogMode) {
time_t t = time(NULL);
if(fd==1) fp = myfprintf_out;
else fp = myfprintf_err;
strftime(buffer,14,"%b %e %R",localtime(&t));
blockingWrite(fd,buffer,strlen(buffer));
blockingWrite(fd," : ",3);
}
vsnprintf(buffer,BUFFER_LENGTH,format,arglist);
blockingWrite(fd,buffer,strlen(buffer));
if (fd == 1)
fp = myfprintf_out;
else
fp = myfprintf_err;
strftime(buffer, 14, "%b %e %R", localtime(&t));
blockingWrite(fd, buffer, strlen(buffer));
blockingWrite(fd, " : ", 3);
}
else {
vsnprintf(buffer, BUFFER_LENGTH, format, arglist);
blockingWrite(fd, buffer, strlen(buffer));
} else {
int len;
vsnprintf(buffer,BUFFER_LENGTH,format,arglist);
vsnprintf(buffer, BUFFER_LENGTH, format, arglist);
len = strlen(buffer);
if(interfacePrintWithFD(fd,buffer,len)<0) {
blockingWrite(fd,buffer,len);
if (interfacePrintWithFD(fd, buffer, len) < 0) {
blockingWrite(fd, buffer, len);
}
}
va_end(arglist);
}
int myfprintfCloseAndOpenLogFile(void) {
if(myfprintf_stdLogMode) {
while(fclose(myfprintf_out)<0 && errno==EINTR);
while(fclose(myfprintf_err)<0 && errno==EINTR);
while((myfprintf_out = fopen(myfprintf_outFilename,"a+"))==NULL
&& errno==EINTR);
if(!myfprintf_out) {
ERROR("error re-opening log file: %s\n",
myfprintf_out);
int myfprintfCloseAndOpenLogFile(void)
{
if (myfprintf_stdLogMode) {
while (fclose(myfprintf_out) < 0 && errno == EINTR) ;
while (fclose(myfprintf_err) < 0 && errno == EINTR) ;
while ((myfprintf_out =
fopen(myfprintf_outFilename, "a+")) == NULL
&& errno == EINTR) ;
if (!myfprintf_out) {
ERROR("error re-opening log file: %s\n", myfprintf_out);
return -1;
}
while((myfprintf_err = fopen(myfprintf_errFilename,"a+"))==NULL
&& errno==EINTR);
if(!myfprintf_out) {
ERROR("error re-opening log file: %s\n",
myfprintf_out);
while ((myfprintf_err =
fopen(myfprintf_errFilename, "a+")) == NULL
&& errno == EINTR) ;
if (!myfprintf_out) {
ERROR("error re-opening log file: %s\n", myfprintf_out);
return -1;
}
while(dup2(fileno(myfprintf_out),1)<0 && errno==EINTR);
while(dup2(fileno(myfprintf_err),2)<0 && errno==EINTR);
while (dup2(fileno(myfprintf_out), 1) < 0 && errno == EINTR) ;
while (dup2(fileno(myfprintf_err), 2) < 0 && errno == EINTR) ;
}
return 0;
}
void myfprintfCloseLogFile(void) {
if(myfprintf_stdLogMode) {
while(fclose(myfprintf_out)<0 && errno==EINTR);
while(fclose(myfprintf_err)<0 && errno==EINTR);
void myfprintfCloseLogFile(void)
{
if (myfprintf_stdLogMode) {
while (fclose(myfprintf_out) < 0 && errno == EINTR) ;
while (fclose(myfprintf_err) < 0 && errno == EINTR) ;
}
}
......@@ -25,7 +25,7 @@
void myfprintfStdLogMode(FILE * out, FILE * err);
void myfprintf(FILE * fp, char * format, ... );
void myfprintf(FILE * fp, char *format, ...);
int myfprintfCloseAndOpenLogFile();
......
......@@ -30,11 +30,13 @@ static mpd_sint16 currentChunk = -1;
static mpd_sint8 currentMetaChunk = -1;
static mpd_sint8 sendMetaChunk = 0;
void clearAllMetaChunkSets(OutputBuffer * cb) {
void clearAllMetaChunkSets(OutputBuffer * cb)
{
memset(cb->metaChunkSet, 0, BUFFERED_METACHUNKS);
}
void clearOutputBuffer(OutputBuffer * cb) {
void clearOutputBuffer(OutputBuffer * cb)
{
int currentSet = 1;
currentChunk = -1;
......@@ -42,19 +44,20 @@ void clearOutputBuffer(OutputBuffer * cb) {
/* be sure to reset metaChunkSets cause we are skipping over audio
* audio chunks, and thus skipping over metadata */
if(sendMetaChunk == 0 && currentMetaChunk >= 0) {
if (sendMetaChunk == 0 && currentMetaChunk >= 0) {
currentSet = cb->metaChunkSet[currentChunk];
}
clearAllMetaChunkSets(cb);
if(sendMetaChunk == 0 && currentMetaChunk >= 0) {
if (sendMetaChunk == 0 && currentMetaChunk >= 0) {
cb->metaChunkSet[currentChunk] = currentSet;
}
}
void flushOutputBuffer(OutputBuffer * cb) {
if(currentChunk == cb->end) {
int next = cb->end+1;
if(next>=buffered_chunks) {
void flushOutputBuffer(OutputBuffer * cb)
{
if (currentChunk == cb->end) {
int next = cb->end + 1;
if (next >= buffered_chunks) {
next = 0;
}
cb->end = next;
......@@ -63,85 +66,85 @@ void flushOutputBuffer(OutputBuffer * cb) {
}
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,
ReplayGainInfo * replayGainInfo)
{
mpd_uint16 dataToSend;
mpd_uint16 chunkLeft;
char * data;
char *data;
size_t datalen;
static char * convBuffer = NULL;
static char *convBuffer = NULL;
static long convBufferLen = 0;
if(cmpAudioFormat(&(cb->audioFormat),&(dc->audioFormat))==0)
{
if (cmpAudioFormat(&(cb->audioFormat), &(dc->audioFormat)) == 0) {
data = dataIn;
datalen = dataInLen;
}
else {
datalen = pcm_sizeOfOutputBufferForAudioFormatConversion(
&(dc->audioFormat), dataInLen,
&(cb->audioFormat));
if(datalen > convBufferLen) {
convBuffer = realloc(convBuffer,datalen);
} else {
datalen =
pcm_sizeOfOutputBufferForAudioFormatConversion(&
(dc->
audioFormat),
dataInLen,
&(cb->
audioFormat));
if (datalen > convBufferLen) {
convBuffer = realloc(convBuffer, datalen);
convBufferLen = datalen;
}
data = convBuffer;
pcm_convertAudioFormat(&(dc->audioFormat), dataIn, dataInLen,
&(cb->audioFormat),data);
&(cb->audioFormat), data);
}
if(replayGainInfo) {
if (replayGainInfo) {
doReplayGain(replayGainInfo, data, datalen, &cb->audioFormat);
}
while(datalen) {
if(currentChunk != cb->end) {
int next = cb->end+1;
if(next>=buffered_chunks) {
while (datalen) {
if (currentChunk != cb->end) {
int next = cb->end + 1;
if (next >= buffered_chunks) {
next = 0;
}
while(cb->begin==next && !dc->stop) {
if(dc->seek) {
if(seekable) {
while (cb->begin == next && !dc->stop) {
if (dc->seek) {
if (seekable) {
return OUTPUT_BUFFER_DC_SEEK;
}
else {
} else {
dc->seekError = 1;
dc->seek = 0;
}
}
if(!inStream ||
bufferInputStream(inStream) <= 0)
{
if (!inStream ||
bufferInputStream(inStream) <= 0) {
my_usleep(10000);
}
}
if(dc->stop) return OUTPUT_BUFFER_DC_STOP;
if (dc->stop)
return OUTPUT_BUFFER_DC_STOP;
currentChunk = cb->end;
cb->chunkSize[currentChunk] = 0;
if(sendMetaChunk) {
if (sendMetaChunk) {
cb->metaChunk[currentChunk] = currentMetaChunk;
}
else cb->metaChunk[currentChunk] = -1;
} else
cb->metaChunk[currentChunk] = -1;
cb->bitRate[currentChunk] = bitRate;
cb->times[currentChunk] = time;
}
chunkLeft = CHUNK_SIZE-cb->chunkSize[currentChunk];
chunkLeft = CHUNK_SIZE - cb->chunkSize[currentChunk];
dataToSend = datalen > chunkLeft ? chunkLeft : datalen;
memcpy(cb->chunks+currentChunk*CHUNK_SIZE+
cb->chunkSize[currentChunk],
data, dataToSend);
cb->chunkSize[currentChunk]+= dataToSend;
datalen-= dataToSend;
data+= dataToSend;
memcpy(cb->chunks + currentChunk * CHUNK_SIZE +
cb->chunkSize[currentChunk], data, dataToSend);
cb->chunkSize[currentChunk] += dataToSend;
datalen -= dataToSend;
data += dataToSend;
if(cb->chunkSize[currentChunk] == CHUNK_SIZE) {
if (cb->chunkSize[currentChunk] == CHUNK_SIZE) {
flushOutputBuffer(cb);
}
}
......@@ -149,30 +152,34 @@ int sendDataToOutputBuffer(OutputBuffer * cb, InputStream * inStream,
return 0;
}
int copyMpdTagToOutputBuffer(OutputBuffer * cb, MpdTag * tag) {
int copyMpdTagToOutputBuffer(OutputBuffer * cb, MpdTag * tag)
{
int nextChunk;
static MpdTag * last = NULL;
static MpdTag *last = NULL;
if(!cb->acceptMetadata || !tag) {
if (!cb->acceptMetadata || !tag) {
sendMetaChunk = 0;
if(last) freeMpdTag(last);
if (last)
freeMpdTag(last);
last = NULL;
DEBUG("copyMpdTagToOB: !acceptMetadata || !tag\n");
return 0;
}
if(last && mpdTagsAreEqual(last, tag)) {
if (last && mpdTagsAreEqual(last, tag)) {
DEBUG("copyMpdTagToOB: same as last\n");
return 0;
}
if(last) freeMpdTag(last);
if (last)
freeMpdTag(last);
last = NULL;
nextChunk = currentMetaChunk+1;
if(nextChunk >= BUFFERED_METACHUNKS) nextChunk = 0;
nextChunk = currentMetaChunk + 1;
if (nextChunk >= BUFFERED_METACHUNKS)
nextChunk = 0;
if(cb->metaChunkSet[nextChunk]) {
if (cb->metaChunkSet[nextChunk]) {
sendMetaChunk = 0;
DEBUG("copyMpdTagToOB: metachunk in use!\n");
return -1;
......
......@@ -32,16 +32,16 @@
#define BUFFERED_METACHUNKS 25
typedef struct _OutputBuffer {
char * volatile chunks;
mpd_uint16 * volatile chunkSize;
mpd_uint16 * volatile bitRate;
float * volatile times;
char *volatile chunks;
mpd_uint16 *volatile chunkSize;
mpd_uint16 *volatile bitRate;
float *volatile times;
mpd_sint16 volatile begin;
mpd_sint16 volatile end;
AudioFormat audioFormat;
MetadataChunk metadataChunks[BUFFERED_METACHUNKS];
mpd_sint8 metaChunkSet[BUFFERED_METACHUNKS];
mpd_sint8 * volatile metaChunk;
mpd_sint8 *volatile metaChunk;
volatile mpd_sint8 acceptMetadata;
} OutputBuffer;
......@@ -51,16 +51,14 @@ void flushOutputBuffer(OutputBuffer * cb);
/* we send inStream for buffering the inputStream while waiting to
send the next chunk */
int sendDataToOutputBuffer(
OutputBuffer * cb,
int sendDataToOutputBuffer(OutputBuffer * cb,
InputStream * inStream,
DecoderControl * dc,
int seekable,
void * data,
void *data,
long datalen,
float time,
mpd_uint16 bitRate,
ReplayGainInfo * replayGainInfo);
mpd_uint16 bitRate, ReplayGainInfo * replayGainInfo);
int copyMpdTagToOutputBuffer(OutputBuffer * cb, MpdTag * tag);
......
......@@ -37,23 +37,25 @@
#endif
#endif
char * musicDir;
char * playlistDir;
char *musicDir;
char *playlistDir;
char * fsCharset = NULL;
char *fsCharset = NULL;
static char * pathConvCharset(char * to, char * from, char * str) {
if(setCharSetConversion(to,from)==0) {
static char *pathConvCharset(char *to, char *from, char *str)
{
if (setCharSetConversion(to, from) == 0) {
return convStrDup(str);
}
return NULL;
}
char * fsCharsetToUtf8(char * str) {
char * ret = pathConvCharset("UTF-8",fsCharset,str);
char *fsCharsetToUtf8(char *str)
{
char *ret = pathConvCharset("UTF-8", fsCharset, str);
if(ret && !validUtf8String(ret)) {
if (ret && !validUtf8String(ret)) {
free(ret);
ret = NULL;
}
......@@ -61,54 +63,60 @@ char * fsCharsetToUtf8(char * str) {
return ret;
}
char * utf8ToFsCharset(char * str) {
char * ret = pathConvCharset(fsCharset,"UTF-8",str);
char *utf8ToFsCharset(char *str)
{
char *ret = pathConvCharset(fsCharset, "UTF-8", str);
if(!ret) ret = strdup(str);
if (!ret)
ret = strdup(str);
return ret;
}
void setFsCharset(char * charset) {
void setFsCharset(char *charset)
{
int error = 0;
if(fsCharset) free(fsCharset);
if (fsCharset)
free(fsCharset);
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: "
"not able to convert from \"%s\" to \"%s\"\n",
fsCharset,"UTF-8");
fsCharset, "UTF-8");
error = 1;
}
if(setCharSetConversion(fsCharset,"UTF-8")!=0) {
if (setCharSetConversion(fsCharset, "UTF-8") != 0) {
WARNING("fs charset conversion problem: "
"not able to convert from \"%s\" to \"%s\"\n",
"UTF-8",fsCharset);
"UTF-8", fsCharset);
error = 1;
}
if(error) {
if (error) {
free(fsCharset);
WARNING("setting fs charset to ISO-8859-1!\n");
fsCharset = strdup("ISO-8859-1");
}
}
char * getFsCharset(void) {
char *getFsCharset(void)
{
return fsCharset;
}
static char * appendSlash(char ** path) {
char * temp = *path;
static char *appendSlash(char **path)
{
char *temp = *path;
int len = strlen(temp);
if(temp[len-1] != '/') {
temp = malloc(len+2);
memset(temp, 0, len+2);
if (temp[len - 1] != '/') {
temp = malloc(len + 2);
memset(temp, 0, len + 2);
memcpy(temp, *path, len);
temp[len] = '/';
free(*path);
......@@ -118,19 +126,20 @@ static char * appendSlash(char ** path) {
return temp;
}
void initPaths(void) {
ConfigParam * musicParam = parseConfigFilePath(CONF_MUSIC_DIR, 1);
ConfigParam * playlistParam = parseConfigFilePath(CONF_PLAYLIST_DIR, 1);
ConfigParam * fsCharsetParam = getConfigParam(CONF_FS_CHARSET);
void initPaths(void)
{
ConfigParam *musicParam = parseConfigFilePath(CONF_MUSIC_DIR, 1);
ConfigParam *playlistParam = parseConfigFilePath(CONF_PLAYLIST_DIR, 1);
ConfigParam *fsCharsetParam = getConfigParam(CONF_FS_CHARSET);
char * charset = NULL;
char * originalLocale;
DIR * dir;
char *charset = NULL;
char *originalLocale;
DIR *dir;
musicDir = appendSlash(&(musicParam->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",
CONF_PLAYLIST_DIR, playlistParam->value,
playlistParam->line, strerror(errno));
......@@ -138,7 +147,7 @@ void initPaths(void) {
}
closedir(dir);
if((dir = opendir(musicDir)) == NULL) {
if ((dir = opendir(musicDir)) == NULL) {
ERROR("cannot open %s \"%s\" (config line %i): %s\n",
CONF_MUSIC_DIR, musicParam->value,
musicParam->line, strerror(errno));
......@@ -146,132 +155,136 @@ void initPaths(void) {
}
closedir(dir);
if(fsCharsetParam) {
if (fsCharsetParam) {
charset = strdup(fsCharsetParam->value);
}
#ifdef HAVE_LOCALE
#ifdef HAVE_LANGINFO_CODESET
else if((originalLocale = setlocale(LC_CTYPE,NULL))) {
char * temp;
char * currentLocale;
else if ((originalLocale = setlocale(LC_CTYPE, NULL))) {
char *temp;
char *currentLocale;
originalLocale = strdup(originalLocale);
if(!(currentLocale = setlocale(LC_CTYPE,""))) {
if (!(currentLocale = setlocale(LC_CTYPE, ""))) {
WARNING("problems setting current locale with "
"setlocale()\n");
}
else {
if(strcmp(currentLocale,"C")==0 ||
strcmp(currentLocale,"POSIX")==0)
{
} else {
if (strcmp(currentLocale, "C") == 0 ||
strcmp(currentLocale, "POSIX") == 0) {
WARNING("current locale is \"%s\"\n",
currentLocale);
}
else if((temp = nl_langinfo(CODESET))) {
} else if ((temp = nl_langinfo(CODESET))) {
charset = strdup(temp);
}
else WARNING("problems getting charset for locale\n");
if(!setlocale(LC_CTYPE,originalLocale)) {
WARNING("problems resetting locale with setlocale()\n");
} else
WARNING
("problems getting charset for locale\n");
if (!setlocale(LC_CTYPE, originalLocale)) {
WARNING
("problems resetting locale with setlocale()\n");
}
}
free(originalLocale);
}
else WARNING("problems getting locale with setlocale()\n");
} else
WARNING("problems getting locale with setlocale()\n");
#endif
#endif
if(charset) {
if (charset) {
setFsCharset(charset);
free(charset);
}
else {
} else {
WARNING("setting filesystem charset to ISO-8859-1\n");
setFsCharset("ISO-8859-1");
}
}
void finishPaths(void) {
void finishPaths(void)
{
free(fsCharset);
fsCharset = NULL;
}
char * rmp2amp(char * relativePath) {
static char absolutePath[MAXPATHLEN+1];
char *rmp2amp(char *relativePath)
{
static char absolutePath[MAXPATHLEN + 1];
memset(absolutePath,0,MAXPATHLEN+1);
memset(absolutePath, 0, MAXPATHLEN + 1);
strncpy(absolutePath,musicDir,MAXPATHLEN);
strncat(absolutePath,relativePath,MAXPATHLEN-strlen(musicDir));
strncpy(absolutePath, musicDir, MAXPATHLEN);
strncat(absolutePath, relativePath, MAXPATHLEN - strlen(musicDir));
return absolutePath;
}
char * rpp2app(char * relativePath) {
static char absolutePath[MAXPATHLEN+1];
char *rpp2app(char *relativePath)
{
static char absolutePath[MAXPATHLEN + 1];
memset(absolutePath,0,MAXPATHLEN+1);
memset(absolutePath, 0, MAXPATHLEN + 1);
strncpy(absolutePath,playlistDir,MAXPATHLEN);
strncat(absolutePath,relativePath,MAXPATHLEN-strlen(musicDir));
strncpy(absolutePath, playlistDir, MAXPATHLEN);
strncat(absolutePath, relativePath, MAXPATHLEN - strlen(musicDir));
return absolutePath;
}
char * parentPath(char * path) {
static char parentPath[MAXPATHLEN+1];
char * c;
char *parentPath(char *path)
{
static char parentPath[MAXPATHLEN + 1];
char *c;
memset(parentPath,0,MAXPATHLEN+1);
strncpy(parentPath,path,MAXPATHLEN);
memset(parentPath, 0, MAXPATHLEN + 1);
strncpy(parentPath, path, MAXPATHLEN);
c = strrchr(parentPath,'/');
c = strrchr(parentPath, '/');
if (c == NULL)
parentPath[0] = '\0';
else {
while ((parentPath <= c) && *(--c) == '/') /* nothing */;
while ((parentPath <= c) && *(--c) == '/') /* nothing */
;
c[1] = '\0';
}
return parentPath;
}
char * sanitizePathDup(char * path) {
int len = strlen(path)+1;
char * ret = malloc(len);
char * cp = ret;
char *sanitizePathDup(char *path)
{
int len = strlen(path) + 1;
char *ret = malloc(len);
char *cp = ret;
memset(ret,0,len);
memset(ret, 0, len);
len = 0;
/* illeminate more than one '/' in a row, like "///" */
while(*path) {
while(*path=='/') path++;
if(*path=='.') {
while (*path) {
while (*path == '/')
path++;
if (*path == '.') {
/* we dont want to have hidden directoires, or '.' or
".." in our path */
free(ret);
return NULL;
}
while(*path && *path!='/') {
while (*path && *path != '/') {
*(cp++) = *(path++);
len++;
}
if(*path=='/') {
if (*path == '/') {
*(cp++) = *(path++);
len++;
}
}
if(len && ret[len-1]=='/') {
if (len && ret[len - 1] == '/') {
len--;
ret[len] = '\0';
}
DEBUG("sanitized: %s\n", ret);
return realloc(ret,len+1);
return realloc(ret, len + 1);
}
......@@ -23,32 +23,32 @@
#include <sys/param.h>
extern char * musicDir;
extern char *musicDir;
void initPaths();
void finishPaths();
char * utf8ToFsCharset(char * str);
char *utf8ToFsCharset(char *str);
char * fsCharsetToUtf8(char * str);
char *fsCharsetToUtf8(char *str);
void setFsCharset(char * charset);
void setFsCharset(char *charset);
char * getFsCharset();
char *getFsCharset();
/* relative music path to absolute music path
* char * passed is a static variable, so don't free it
*/
char * rmp2amp(char * file);
char *rmp2amp(char *file);
/* static char * returned */
char * rpp2app(char * file);
char *rpp2app(char *file);
/* static char * returned */
char * parentPath(char * path);
char *parentPath(char *path);
/* strips extra "///" and leading "/" and trailing "/" */
char * sanitizePathDup(char * path);
char *sanitizePathDup(char *path);
#endif
......@@ -16,7 +16,6 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "pcm_utils.h"
#include "mpd_types.h"
......@@ -26,39 +25,40 @@
#include <math.h>
#include <assert.h>
void pcm_volumeChange(char * buffer, int bufferSize, AudioFormat * format,
void pcm_volumeChange(char *buffer, int bufferSize, AudioFormat * format,
int volume)
{
mpd_sint32 temp32;
mpd_sint8 * buffer8 = (mpd_sint8 *)buffer;
mpd_sint16 * buffer16 = (mpd_sint16 *)buffer;
mpd_sint8 *buffer8 = (mpd_sint8 *) buffer;
mpd_sint16 *buffer16 = (mpd_sint16 *) buffer;
if(volume>=1000) return;
if (volume >= 1000)
return;
if(volume<=0) {
memset(buffer,0,bufferSize);
if (volume <= 0) {
memset(buffer, 0, bufferSize);
return;
}
switch(format->bits) {
switch (format->bits) {
case 16:
while(bufferSize>0) {
while (bufferSize > 0) {
temp32 = *buffer16;
temp32*= volume;
temp32/=1000;
*buffer16 = temp32>32767 ? 32767 :
(temp32<-32768 ? -32768 : temp32);
temp32 *= volume;
temp32 /= 1000;
*buffer16 = temp32 > 32767 ? 32767 :
(temp32 < -32768 ? -32768 : temp32);
buffer16++;
bufferSize-=2;
bufferSize -= 2;
}
break;
case 8:
while(bufferSize>0) {
while (bufferSize > 0) {
temp32 = *buffer8;
temp32*= volume;
temp32/=1000;
*buffer8 = temp32>127 ? 127 :
(temp32<-128 ? -128 : temp32);
temp32 *= volume;
temp32 /= 1000;
*buffer8 = temp32 > 127 ? 127 :
(temp32 < -128 ? -128 : temp32);
buffer8++;
bufferSize--;
}
......@@ -70,90 +70,98 @@ void pcm_volumeChange(char * buffer, int bufferSize, AudioFormat * format,
}
}
static void pcm_add(char * buffer1, char * buffer2, size_t bufferSize1,
size_t bufferSize2, int vol1, int vol2, AudioFormat * format)
static void pcm_add(char *buffer1, char *buffer2, size_t bufferSize1,
size_t bufferSize2, int vol1, int vol2,
AudioFormat * format)
{
mpd_sint32 temp32;
mpd_sint8 * buffer8_1 = (mpd_sint8 *)buffer1;
mpd_sint8 * buffer8_2 = (mpd_sint8 *)buffer2;
mpd_sint16 * buffer16_1 = (mpd_sint16 *)buffer1;
mpd_sint16 * buffer16_2 = (mpd_sint16 *)buffer2;
mpd_sint8 *buffer8_1 = (mpd_sint8 *) buffer1;
mpd_sint8 *buffer8_2 = (mpd_sint8 *) buffer2;
mpd_sint16 *buffer16_1 = (mpd_sint16 *) buffer1;
mpd_sint16 *buffer16_2 = (mpd_sint16 *) buffer2;
switch(format->bits) {
switch (format->bits) {
case 16:
while(bufferSize1>0 && bufferSize2>0) {
temp32 = (vol1*(*buffer16_1)+vol2*(*buffer16_2))/1000;
*buffer16_1 = temp32>32767 ? 32767 :
(temp32<-32768 ? -32768 : temp32);
while (bufferSize1 > 0 && bufferSize2 > 0) {
temp32 =
(vol1 * (*buffer16_1) +
vol2 * (*buffer16_2)) / 1000;
*buffer16_1 =
temp32 > 32767 ? 32767 : (temp32 <
-32768 ? -32768 : temp32);
buffer16_1++;
buffer16_2++;
bufferSize1-=2;
bufferSize2-=2;
bufferSize1 -= 2;
bufferSize2 -= 2;
}
if(bufferSize2>0) memcpy(buffer16_1,buffer16_2,bufferSize2);
if (bufferSize2 > 0)
memcpy(buffer16_1, buffer16_2, bufferSize2);
break;
case 8:
while(bufferSize1>0 && bufferSize2>0) {
temp32 = (vol1*(*buffer8_1)+vol2*(*buffer8_2))/1000;
*buffer8_1 = temp32>127 ? 127 :
(temp32<-128 ? -128 : temp32);
while (bufferSize1 > 0 && bufferSize2 > 0) {
temp32 =
(vol1 * (*buffer8_1) + vol2 * (*buffer8_2)) / 1000;
*buffer8_1 =
temp32 > 127 ? 127 : (temp32 <
-128 ? -128 : temp32);
buffer8_1++;
buffer8_2++;
bufferSize1--;
bufferSize2--;
}
if(bufferSize2>0) memcpy(buffer8_1,buffer8_2,bufferSize2);
if (bufferSize2 > 0)
memcpy(buffer8_1, buffer8_2, bufferSize2);
break;
default:
ERROR("%i bits not supported by pcm_add!\n",format->bits);
ERROR("%i bits not supported by pcm_add!\n", format->bits);
exit(EXIT_FAILURE);
}
}
void pcm_mix(char * buffer1, char * buffer2, size_t bufferSize1,
void pcm_mix(char *buffer1, char *buffer2, size_t bufferSize1,
size_t bufferSize2, AudioFormat * format, float portion1)
{
int vol1;
float s = sin(M_PI_2*portion1);
s*=s;
float s = sin(M_PI_2 * portion1);
s *= s;
vol1 = s*1000+0.5;
vol1 = vol1>1000 ? 1000 : ( vol1<0 ? 0 : vol1 );
vol1 = s * 1000 + 0.5;
vol1 = vol1 > 1000 ? 1000 : (vol1 < 0 ? 0 : vol1);
pcm_add(buffer1,buffer2,bufferSize1,bufferSize2,vol1,1000-vol1,format);
pcm_add(buffer1, buffer2, bufferSize1, bufferSize2, vol1, 1000 - vol1,
format);
}
/* outFormat bits must be 16 and channels must be 2! */
void pcm_convertAudioFormat(AudioFormat * inFormat, char * inBuffer, size_t
inSize, AudioFormat * outFormat, char * outBuffer)
void pcm_convertAudioFormat(AudioFormat * inFormat, char *inBuffer, size_t
inSize, AudioFormat * outFormat, char *outBuffer)
{
static char * bitConvBuffer = NULL;
static char *bitConvBuffer = NULL;
static int bitConvBufferLength = 0;
static char * channelConvBuffer = NULL;
static char *channelConvBuffer = NULL;
static int channelConvBufferLength = 0;
char * dataChannelConv;
char *dataChannelConv;
int dataChannelLen;
char * dataBitConv;
char *dataBitConv;
int dataBitLen;
assert(outFormat->bits==16);
assert(outFormat->channels==2 || outFormat->channels==1);
assert(outFormat->bits == 16);
assert(outFormat->channels == 2 || outFormat->channels == 1);
/* converts */
switch(inFormat->bits) {
switch (inFormat->bits) {
case 8:
dataBitLen = inSize << 1;
if(dataBitLen > bitConvBufferLength) {
if (dataBitLen > bitConvBufferLength) {
bitConvBuffer = realloc(bitConvBuffer, dataBitLen);
bitConvBufferLength = dataBitLen;
}
dataBitConv = bitConvBuffer;
{
mpd_sint8 * in = (mpd_sint8 *)inBuffer;
mpd_sint16 * out = (mpd_sint16 *)dataBitConv;
mpd_sint8 *in = (mpd_sint8 *) inBuffer;
mpd_sint16 *out = (mpd_sint16 *) dataBitConv;
int i;
for(i=0; i<inSize; i++) {
for (i = 0; i < inSize; i++) {
*out++ = (*in++) << 8;
}
}
......@@ -170,27 +178,26 @@ void pcm_convertAudioFormat(AudioFormat * inFormat, char * inBuffer, size_t
}
/* converts only between 16 bit audio between mono and stereo */
if(inFormat->channels == outFormat->channels)
{
if (inFormat->channels == outFormat->channels) {
dataChannelConv = dataBitConv;
dataChannelLen = dataBitLen;
}
else {
switch(inFormat->channels) {
} else {
switch (inFormat->channels) {
/* convert from 1 -> 2 channels */
case 1:
dataChannelLen = (dataBitLen >> 1) << 2;
if(dataChannelLen > channelConvBufferLength) {
if (dataChannelLen > channelConvBufferLength) {
channelConvBuffer = realloc(channelConvBuffer,
dataChannelLen);
channelConvBufferLength = dataChannelLen;
}
dataChannelConv = channelConvBuffer;
{
mpd_sint16 * in = (mpd_sint16 *)dataBitConv;
mpd_sint16 * out = (mpd_sint16 *)dataChannelConv;
mpd_sint16 *in = (mpd_sint16 *) dataBitConv;
mpd_sint16 *out =
(mpd_sint16 *) dataChannelConv;
int i, inSamples = dataBitLen >> 1;
for(i=0;i<inSamples;i++) {
for (i = 0; i < inSamples; i++) {
*out++ = *in;
*out++ = *in++;
}
......@@ -199,67 +206,68 @@ void pcm_convertAudioFormat(AudioFormat * inFormat, char * inBuffer, size_t
/* convert from 2 -> 1 channels */
case 2:
dataChannelLen = dataBitLen >> 1;
if(dataChannelLen > channelConvBufferLength) {
if (dataChannelLen > channelConvBufferLength) {
channelConvBuffer = realloc(channelConvBuffer,
dataChannelLen);
channelConvBufferLength = dataChannelLen;
}
dataChannelConv = channelConvBuffer;
{
mpd_sint16 * in = (mpd_sint16 *)dataBitConv;
mpd_sint16 * out = (mpd_sint16 *)dataChannelConv;
mpd_sint16 *in = (mpd_sint16 *) dataBitConv;
mpd_sint16 *out =
(mpd_sint16 *) dataChannelConv;
int i, inSamples = dataBitLen >> 2;
for(i=0;i<inSamples;i++) {
*out = (*in++)/2;
*out++ += (*in++)/2;
for (i = 0; i < inSamples; i++) {
*out = (*in++) / 2;
*out++ += (*in++) / 2;
}
}
break;
default:
ERROR("only 1 or 2 channels are supported for conversion!\n");
ERROR
("only 1 or 2 channels are supported for conversion!\n");
exit(EXIT_FAILURE);
}
}
if(inFormat->sampleRate == outFormat->sampleRate) {
memcpy(outBuffer,dataChannelConv,dataChannelLen);
}
else {
if (inFormat->sampleRate == outFormat->sampleRate) {
memcpy(outBuffer, dataChannelConv, dataChannelLen);
} else {
/* only works if outFormat is 16-bit stereo! */
/* resampling code blatantly ripped from ESD */
mpd_uint32 rd_dat = 0;
mpd_uint32 wr_dat = 0;
mpd_sint16 lsample, rsample;
mpd_sint16 * out = (mpd_sint16 *)outBuffer;
mpd_sint16 * in = (mpd_sint16 *)dataChannelConv;
const int shift = sizeof(mpd_sint16)*outFormat->channels;
mpd_uint32 nlen = ((( dataChannelLen / shift) *
(mpd_uint32)(outFormat->sampleRate)) /
mpd_sint16 *out = (mpd_sint16 *) outBuffer;
mpd_sint16 *in = (mpd_sint16 *) dataChannelConv;
const int shift = sizeof(mpd_sint16) * outFormat->channels;
mpd_uint32 nlen = (((dataChannelLen / shift) *
(mpd_uint32) (outFormat->sampleRate)) /
inFormat->sampleRate);
nlen *= outFormat->channels;
switch(outFormat->channels) {
switch (outFormat->channels) {
case 1:
while( wr_dat < nlen) {
while (wr_dat < nlen) {
rd_dat = wr_dat * inFormat->sampleRate /
outFormat->sampleRate;
lsample = in[ rd_dat++ ];
lsample = in[rd_dat++];
out[ wr_dat++ ] = lsample;
out[wr_dat++] = lsample;
}
break;
case 2:
while( wr_dat < nlen) {
while (wr_dat < nlen) {
rd_dat = wr_dat * inFormat->sampleRate /
outFormat->sampleRate;
rd_dat &= ~1;
lsample = in[ rd_dat++ ];
rsample = in[ rd_dat++ ];
lsample = in[rd_dat++];
rsample = in[rd_dat++];
out[ wr_dat++ ] = lsample;
out[ wr_dat++ ] = rsample;
out[wr_dat++] = lsample;
out[wr_dat++] = rsample;
}
break;
}
......@@ -269,12 +277,13 @@ void pcm_convertAudioFormat(AudioFormat * inFormat, char * inBuffer, size_t
}
size_t pcm_sizeOfOutputBufferForAudioFormatConversion(AudioFormat * inFormat,
size_t inSize, AudioFormat * outFormat)
size_t inSize,
AudioFormat * outFormat)
{
const int shift = sizeof(mpd_sint16)*outFormat->channels;
const int shift = sizeof(mpd_sint16) * outFormat->channels;
size_t outSize = inSize;
switch(inFormat->bits) {
switch (inFormat->bits) {
case 8:
outSize = outSize << 1;
break;
......@@ -285,8 +294,8 @@ size_t pcm_sizeOfOutputBufferForAudioFormatConversion(AudioFormat * inFormat,
exit(EXIT_FAILURE);
}
if(inFormat->channels != outFormat->channels) {
switch(inFormat->channels) {
if (inFormat->channels != outFormat->channels) {
switch (inFormat->channels) {
case 1:
outSize = (outSize >> 1) << 2;
break;
......@@ -296,7 +305,7 @@ size_t pcm_sizeOfOutputBufferForAudioFormatConversion(AudioFormat * inFormat,
}
}
outSize = (((outSize / shift) * (mpd_uint32)(outFormat->sampleRate)) /
outSize = (((outSize / shift) * (mpd_uint32) (outFormat->sampleRate)) /
inFormat->sampleRate);
outSize *= shift;
......
......@@ -25,15 +25,16 @@
#include <stdlib.h>
void pcm_volumeChange(char * buffer, int bufferSize, AudioFormat * format,
void pcm_volumeChange(char *buffer, int bufferSize, AudioFormat * format,
int volume);
void pcm_mix(char * buffer1, char * buffer2, size_t bufferSize1,
void pcm_mix(char *buffer1, char *buffer2, size_t bufferSize1,
size_t bufferSize2, AudioFormat * format, float portion1);
void pcm_convertAudioFormat(AudioFormat * inFormat, char * inBuffer, size_t
inSize, AudioFormat * outFormat, char * outBuffer);
void pcm_convertAudioFormat(AudioFormat * inFormat, char *inBuffer, size_t
inSize, AudioFormat * outFormat, char *outBuffer);
size_t pcm_sizeOfOutputBufferForAudioFormatConversion(AudioFormat * inFormat,
size_t inSize, AudioFormat * outFormat);
size_t inSize,
AudioFormat * outFormat);
#endif
......@@ -32,48 +32,47 @@
#define PERMISSION_CONTROL_STRING "control"
#define PERMISSION_ADMIN_STRING "admin"
static List * permission_passwords;
static List *permission_passwords;
static int permission_default;
static int parsePermissions(char * string) {
static int parsePermissions(char *string)
{
int permission = 0;
char * temp;
char * tok;
char *temp;
char *tok;
if(!string) return 0;
if (!string)
return 0;
temp = strtok_r(string,PERMISSION_SEPERATOR,&tok);
while(temp) {
if(strcmp(temp,PERMISSION_READ_STRING)==0) {
temp = strtok_r(string, PERMISSION_SEPERATOR, &tok);
while (temp) {
if (strcmp(temp, PERMISSION_READ_STRING) == 0) {
permission |= PERMISSION_READ;
}
else if(strcmp(temp,PERMISSION_ADD_STRING)==0) {
} else if (strcmp(temp, PERMISSION_ADD_STRING) == 0) {
permission |= PERMISSION_ADD;
}
else if(strcmp(temp,PERMISSION_CONTROL_STRING)==0) {
} else if (strcmp(temp, PERMISSION_CONTROL_STRING) == 0) {
permission |= PERMISSION_CONTROL;
}
else if(strcmp(temp,PERMISSION_ADMIN_STRING)==0) {
} else if (strcmp(temp, PERMISSION_ADMIN_STRING) == 0) {
permission |= PERMISSION_ADMIN;
}
else {
ERROR("unknown permission \"%s\"\n",temp);
} else {
ERROR("unknown permission \"%s\"\n", temp);
exit(EXIT_FAILURE);
}
temp = strtok_r(NULL,PERMISSION_SEPERATOR,&tok);
temp = strtok_r(NULL, PERMISSION_SEPERATOR, &tok);
}
return permission;
}
void initPermissions(void) {
char * temp;
char * cp2;
char * password;
int * permission;
ConfigParam * param;
void initPermissions(void)
{
char *temp;
char *cp2;
char *password;
int *permission;
ConfigParam *param;
permission_passwords = makeList(free, 1);
......@@ -82,46 +81,50 @@ void initPermissions(void) {
param = getNextConfigParam(CONF_PASSWORD, NULL);
if(param) {
if (param) {
permission_default = 0;
do {
if(!strstr(param->value, PERMISSION_PASSWORD_CHAR)) {
if (!strstr(param->value, PERMISSION_PASSWORD_CHAR)) {
ERROR("\"%s\" not found in password string "
"\"%s\", line %i\n",
PERMISSION_PASSWORD_CHAR,
param->value,
param->line);
param->value, param->line);
exit(EXIT_FAILURE);
}
if(!(temp = strtok_r(param->value,
PERMISSION_PASSWORD_CHAR,&cp2))) {
ERROR("something weird just happened in permission.c\n");
if (!(temp = strtok_r(param->value,
PERMISSION_PASSWORD_CHAR,
&cp2))) {
ERROR
("something weird just happened in permission.c\n");
exit(EXIT_FAILURE);
}
password = temp;
permission = malloc(sizeof(int));
*permission = parsePermissions(strtok_r(NULL,"",&cp2));
*permission =
parsePermissions(strtok_r(NULL, "", &cp2));
insertInList(permission_passwords,password,permission);
} while((param = getNextConfigParam(CONF_PASSWORD, param)));
insertInList(permission_passwords, password,
permission);
} while ((param = getNextConfigParam(CONF_PASSWORD, param)));
}
param = getConfigParam(CONF_DEFAULT_PERMS);
if(param) permission_default = parsePermissions(param->value);
if (param)
permission_default = parsePermissions(param->value);
sortList(permission_passwords);
}
int getPermissionFromPassword(char * password, int * permission) {
void * foundPermission;
int getPermissionFromPassword(char *password, int *permission)
{
void *foundPermission;
if(findInList(permission_passwords,password,&foundPermission)) {
if (findInList(permission_passwords, password, &foundPermission)) {
*permission = *((int *)foundPermission);
return 0;
}
......@@ -129,10 +132,12 @@ int getPermissionFromPassword(char * password, int * permission) {
return -1;
}
void finishPermissions(void) {
void finishPermissions(void)
{
freeList(permission_passwords);
}
int getDefaultPermissions(void) {
int getDefaultPermissions(void)
{
return permission_default;
}
......@@ -28,7 +28,7 @@
void initPermissions();
int getPermissionFromPassword(char * password, int * permission);
int getPermissionFromPassword(char *password, int *permission);
void finishPermissions();
......
......@@ -45,15 +45,17 @@
extern int masterPid;
static void resetPlayerMetadata() {
PlayerControl * pc = &(getPlayerData()->playerControl);
static void resetPlayerMetadata()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(pc->metadataState == PLAYER_METADATA_STATE_READ) {
if (pc->metadataState == PLAYER_METADATA_STATE_READ) {
pc->metadataState = PLAYER_METADATA_STATE_WRITE;
}
}
void resetPlayer() {
void resetPlayer()
{
int pid;
setPlayerPid(0);
......@@ -68,85 +70,85 @@ void resetPlayer() {
getPlayerData()->playerControl.metadataState =
PLAYER_METADATA_STATE_WRITE;
pid = getPlayerData()->playerControl.decode_pid;
if(pid>0) kill(pid,SIGTERM);
if (pid > 0)
kill(pid, SIGTERM);
getPlayerData()->playerControl.decode_pid = 0;
}
void player_sigChldHandler(int pid, int status) {
if(getPlayerPid()==pid) {
void player_sigChldHandler(int pid, int status)
{
if (getPlayerPid() == pid) {
DEBUG("SIGCHLD caused by player process\n");
if(WIFSIGNALED(status) && WTERMSIG(status)!=SIGTERM &&
WTERMSIG(status)!=SIGINT)
{
if (WIFSIGNALED(status) && WTERMSIG(status) != SIGTERM &&
WTERMSIG(status) != SIGINT) {
ERROR("player process died from signal: %i\n",
WTERMSIG(status));
}
resetPlayer();
}
else if(pid==getPlayerData()->playerControl.decode_pid && getPlayerPid()<=0)
{
if(WIFSIGNALED(status) && WTERMSIG(status)!=SIGTERM) {
} else if (pid == getPlayerData()->playerControl.decode_pid
&& getPlayerPid() <= 0) {
if (WIFSIGNALED(status) && WTERMSIG(status) != SIGTERM) {
ERROR("(caught by master parent) "
"decode process died from a "
"non-TERM signal: %i\n",
WTERMSIG(status));
"non-TERM signal: %i\n", WTERMSIG(status));
}
getPlayerData()->playerControl.decode_pid = 0;
}
}
int playerInit() {
int playerInit()
{
kill(masterPid, SIGUSR2);
/* we need to wait for the signal to take effect: */
while (getPlayerPid()==0) my_usleep(10000);
while (getPlayerPid() == 0)
my_usleep(10000);
return 0;
}
int playerInitReal() {
int playerInitReal()
{
int player_pid;
blockSignals();
player_pid = fork();
if(player_pid==0) {
PlayerControl * pc = &(getPlayerData()->playerControl);
if (player_pid == 0) {
PlayerControl *pc = &(getPlayerData()->playerControl);
unblockSignals();
setSigHandlersForDecoder();
while(1) {
if(pc->play) decode();
else if(pc->stop) pc->stop = 0;
else if(pc->pause) pc->pause = 0;
else if(pc->closeAudio) {
while (1) {
if (pc->play)
decode();
else if (pc->stop)
pc->stop = 0;
else if (pc->pause)
pc->pause = 0;
else if (pc->closeAudio) {
closeAudioDevice();
pc->closeAudio = 0;
kill(getppid(),SIGUSR1);
}
else if(pc->lockQueue) {
kill(getppid(), SIGUSR1);
} else if (pc->lockQueue) {
pc->queueLockState = PLAYER_QUEUE_LOCKED;
pc->lockQueue = 0;
}
else if(pc->unlockQueue) {
} else if (pc->unlockQueue) {
pc->queueLockState = PLAYER_QUEUE_UNLOCKED;
pc->unlockQueue = 0;
}
else if(pc->cycleLogFiles) {
} else if (pc->cycleLogFiles) {
myfprintfCloseAndOpenLogFile();
pc->cycleLogFiles = 0;
}
else my_usleep(10000);
} else
my_usleep(10000);
}
exit(EXIT_SUCCESS);
}
else if(player_pid<0) {
} else if (player_pid < 0) {
unblockSignals();
ERROR("player Problems fork()'ing\n");
setPlayerPid(0);
player_pid = 0;
return -1;
}
else
} else
setPlayerPid(player_pid);
unblockSignals();
......@@ -154,15 +156,20 @@ int playerInitReal() {
return 0;
}
int playerPlay(FILE * fp, Song * song) {
PlayerControl * pc = &(getPlayerData()->playerControl);
int playerPlay(FILE * fp, Song * song)
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(fp==NULL) fp = stderr;
if (fp == NULL)
fp = stderr;
if(playerStop(fp)<0) return -1;
if (playerStop(fp) < 0)
return -1;
if(song->tag) pc->fileTime = song->tag->time;
else pc->fileTime = 0;
if (song->tag)
pc->fileTime = song->tag->time;
else
pc->fileTime = 0;
copyMpdTagToMetadataChunk(song->tag, &(pc->fileMetadataChunk));
......@@ -170,23 +177,26 @@ int playerPlay(FILE * fp, Song * song) {
pc->utf8url[MAXPATHLEN] = '\0';
pc->play = 1;
if(getPlayerPid()==0 && playerInit()<0) {
if (getPlayerPid() == 0 && playerInit() < 0) {
pc->play = 0;
return -1;
}
resetPlayerMetadata();
while(getPlayerPid()>0 && pc->play) my_usleep(1000);
while (getPlayerPid() > 0 && pc->play)
my_usleep(1000);
return 0;
}
int playerStop(FILE * fp) {
PlayerControl * pc = &(getPlayerData()->playerControl);
int playerStop(FILE * fp)
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(getPlayerPid()>0 && pc->state!=PLAYER_STATE_STOP) {
if (getPlayerPid() > 0 && pc->state != PLAYER_STATE_STOP) {
pc->stop = 1;
while(getPlayerPid()>0 && pc->stop) my_usleep(1000);
while (getPlayerPid() > 0 && pc->stop)
my_usleep(1000);
}
pc->queueState = PLAYER_QUEUE_BLANK;
......@@ -195,127 +205,148 @@ int playerStop(FILE * fp) {
return 0;
}
void playerKill() {
void playerKill()
{
int pid;
/*PlayerControl * pc = &(getPlayerData()->playerControl);
playerStop(stderr);
playerCloseAudio(stderr);
if(player_pid>0 && pc->closeAudio) sleep(1);*/
if(player_pid>0 && pc->closeAudio) sleep(1); */
pid = getPlayerPid();
if(pid>0) kill(pid,SIGTERM);
if (pid > 0)
kill(pid, SIGTERM);
}
int playerPause(FILE * fp) {
PlayerControl * pc = &(getPlayerData()->playerControl);
int playerPause(FILE * fp)
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(getPlayerPid()>0 && pc->state!=PLAYER_STATE_STOP) {
if (getPlayerPid() > 0 && pc->state != PLAYER_STATE_STOP) {
pc->pause = 1;
while(getPlayerPid()>0 && pc->pause) my_usleep(1000);
while (getPlayerPid() > 0 && pc->pause)
my_usleep(1000);
}
return 0;
}
int playerSetPause(FILE * fp, int pause) {
PlayerControl * pc = &(getPlayerData()->playerControl);
int playerSetPause(FILE * fp, int pause)
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(getPlayerPid()<=0) return 0;
if (getPlayerPid() <= 0)
return 0;
switch(pc->state) {
switch (pc->state) {
case PLAYER_STATE_PLAY:
if(pause) playerPause(fp);
if (pause)
playerPause(fp);
break;
case PLAYER_STATE_PAUSE:
if(!pause) playerPause(fp);
if (!pause)
playerPause(fp);
break;
}
return 0;
}
int getPlayerElapsedTime() {
return (int)(getPlayerData()->playerControl.elapsedTime+0.5);
int getPlayerElapsedTime()
{
return (int)(getPlayerData()->playerControl.elapsedTime + 0.5);
}
unsigned long getPlayerBitRate() {
unsigned long getPlayerBitRate()
{
return getPlayerData()->playerControl.bitRate;
}
int getPlayerTotalTime() {
return (int)(getPlayerData()->playerControl.totalTime+0.5);
int getPlayerTotalTime()
{
return (int)(getPlayerData()->playerControl.totalTime + 0.5);
}
int getPlayerState() {
int getPlayerState()
{
return getPlayerData()->playerControl.state;
}
void clearPlayerError() {
void clearPlayerError()
{
getPlayerData()->playerControl.error = 0;
}
int getPlayerError() {
int getPlayerError()
{
return getPlayerData()->playerControl.error;
}
char * getPlayerErrorStr() {
static char * error = NULL;
int errorlen = MAXPATHLEN+1024;
PlayerControl * pc = &(getPlayerData()->playerControl);
char *getPlayerErrorStr()
{
static char *error = NULL;
int errorlen = MAXPATHLEN + 1024;
PlayerControl *pc = &(getPlayerData()->playerControl);
error = realloc(error,errorlen+1);
memset(error,0,errorlen+1);
error = realloc(error, errorlen + 1);
memset(error, 0, errorlen + 1);
switch(pc->error) {
switch (pc->error) {
case PLAYER_ERROR_FILENOTFOUND:
snprintf(error,errorlen,
snprintf(error, errorlen,
"file \"%s\" does not exist or is inaccesible",
pc->erroredUrl);
break;
case PLAYER_ERROR_FILE:
snprintf(error,errorlen,"problems decoding \"%s\"",
snprintf(error, errorlen, "problems decoding \"%s\"",
pc->erroredUrl);
break;
case PLAYER_ERROR_AUDIO:
snprintf(error,errorlen,"problems opening audio device");
snprintf(error, errorlen, "problems opening audio device");
break;
case PLAYER_ERROR_SYSTEM:
snprintf(error,errorlen,"system error occured");
snprintf(error, errorlen, "system error occured");
break;
case PLAYER_ERROR_UNKTYPE:
snprintf(error,errorlen,"file type of \"%s\" is unknown",
snprintf(error, errorlen, "file type of \"%s\" is unknown",
pc->erroredUrl);
default:
break;
}
errorlen = strlen(error);
error = realloc(error,errorlen+1);
error = realloc(error, errorlen + 1);
if(errorlen) return error;
if (errorlen)
return error;
return NULL;
}
void playerCloseAudio() {
PlayerControl * pc = &(getPlayerData()->playerControl);
void playerCloseAudio()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(getPlayerPid()>0) {
if(playerStop(stderr)<0) return;
if (getPlayerPid() > 0) {
if (playerStop(stderr) < 0)
return;
pc->closeAudio = 1;
}
}
int queueSong(Song * song) {
PlayerControl * pc = &(getPlayerData()->playerControl);
int queueSong(Song * song)
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(pc->queueState==PLAYER_QUEUE_BLANK) {
if (pc->queueState == PLAYER_QUEUE_BLANK) {
strncpy(pc->utf8url, getSongUrl(song), MAXPATHLEN);
pc->utf8url[MAXPATHLEN] = '\0';
if(song->tag) pc->fileTime = song->tag->time;
else pc->fileTime = 0;
if (song->tag)
pc->fileTime = song->tag->time;
else
pc->fileTime = 0;
copyMpdTagToMetadataChunk(song->tag, &(pc->fileMetadataChunk));
......@@ -326,50 +357,57 @@ int queueSong(Song * song) {
return -1;
}
int getPlayerQueueState() {
PlayerControl * pc = &(getPlayerData()->playerControl);
int getPlayerQueueState()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
return pc->queueState;
}
void setQueueState(int queueState) {
PlayerControl * pc = &(getPlayerData()->playerControl);
void setQueueState(int queueState)
{
PlayerControl *pc = &(getPlayerData()->playerControl);
pc->queueState = queueState;
}
void playerQueueLock() {
PlayerControl * pc = &(getPlayerData()->playerControl);
void playerQueueLock()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(getPlayerPid()>0 && pc->queueLockState==PLAYER_QUEUE_UNLOCKED)
{
if (getPlayerPid() > 0 && pc->queueLockState == PLAYER_QUEUE_UNLOCKED) {
pc->lockQueue = 1;
while(getPlayerPid()>0 && pc->lockQueue) my_usleep(1000);
while (getPlayerPid() > 0 && pc->lockQueue)
my_usleep(1000);
}
}
void playerQueueUnlock() {
PlayerControl * pc = &(getPlayerData()->playerControl);
void playerQueueUnlock()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(getPlayerPid()>0 && pc->queueLockState==PLAYER_QUEUE_LOCKED)
{
if (getPlayerPid() > 0 && pc->queueLockState == PLAYER_QUEUE_LOCKED) {
pc->unlockQueue = 1;
while(getPlayerPid()>0 && pc->unlockQueue) my_usleep(1000);
while (getPlayerPid() > 0 && pc->unlockQueue)
my_usleep(1000);
}
}
int playerSeek(FILE * fp, Song * song, float time) {
PlayerControl * pc = &(getPlayerData()->playerControl);
int playerSeek(FILE * fp, Song * song, float time)
{
PlayerControl *pc = &(getPlayerData()->playerControl);
if(pc->state==PLAYER_STATE_STOP) {
if (pc->state == PLAYER_STATE_STOP) {
commandError(fp, ACK_ERROR_PLAYER_SYNC,
"player not currently playing", NULL);
return -1;
}
if(strcmp(pc->utf8url, getSongUrl(song))!=0) {
if(song->tag) pc->fileTime = song->tag->time;
else pc->fileTime = 0;
if (strcmp(pc->utf8url, getSongUrl(song)) != 0) {
if (song->tag)
pc->fileTime = song->tag->time;
else
pc->fileTime = 0;
copyMpdTagToMetadataChunk(song->tag, &(pc->fileMetadataChunk));
......@@ -377,85 +415,98 @@ int playerSeek(FILE * fp, Song * song, float time) {
pc->utf8url[MAXPATHLEN] = '\0';
}
if(pc->error==PLAYER_ERROR_NOERROR) {
if (pc->error == PLAYER_ERROR_NOERROR) {
resetPlayerMetadata();
pc->seekWhere = time;
pc->seek = 1;
while(getPlayerPid()>0 && pc->seek) my_usleep(1000);
while (getPlayerPid() > 0 && pc->seek)
my_usleep(1000);
}
return 0;
}
float getPlayerCrossFade() {
PlayerControl * pc = &(getPlayerData()->playerControl);
float getPlayerCrossFade()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
return pc->crossFade;
}
void setPlayerCrossFade(float crossFadeInSeconds) {
PlayerControl * pc;
if(crossFadeInSeconds<0) crossFadeInSeconds = 0;
void setPlayerCrossFade(float crossFadeInSeconds)
{
PlayerControl *pc;
if (crossFadeInSeconds < 0)
crossFadeInSeconds = 0;
pc = &(getPlayerData()->playerControl);
pc->crossFade = crossFadeInSeconds;
}
void setPlayerSoftwareVolume(int volume) {
PlayerControl * pc;
volume = (volume>1000) ? 1000 : (volume<0 ? 0 : volume);
void setPlayerSoftwareVolume(int volume)
{
PlayerControl *pc;
volume = (volume > 1000) ? 1000 : (volume < 0 ? 0 : volume);
pc = &(getPlayerData()->playerControl);
pc->softwareVolume = volume;
}
double getPlayerTotalPlayTime() {
PlayerControl * pc = &(getPlayerData()->playerControl);
double getPlayerTotalPlayTime()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
return pc->totalPlayTime;
}
unsigned int getPlayerSampleRate() {
PlayerControl * pc = &(getPlayerData()->playerControl);
unsigned int getPlayerSampleRate()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
return pc->sampleRate;
}
int getPlayerBits() {
PlayerControl * pc = &(getPlayerData()->playerControl);
int getPlayerBits()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
return pc->bits;
}
int getPlayerChannels() {
PlayerControl * pc = &(getPlayerData()->playerControl);
int getPlayerChannels()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
return pc->channels;
}
void playerCycleLogFiles() {
PlayerControl * pc = &(getPlayerData()->playerControl);
DecoderControl * dc = &(getPlayerData()->decoderControl);
void playerCycleLogFiles()
{
PlayerControl *pc = &(getPlayerData()->playerControl);
DecoderControl *dc = &(getPlayerData()->decoderControl);
pc->cycleLogFiles = 1;
dc->cycleLogFiles = 1;
}
/* this actually creates a dupe of the current metadata */
Song * playerCurrentDecodeSong() {
static Song * song = NULL;
static MetadataChunk * prev = NULL;
Song * ret = NULL;
PlayerControl * pc = &(getPlayerData()->playerControl);
if(pc->metadataState == PLAYER_METADATA_STATE_READ) {
Song *playerCurrentDecodeSong()
{
static Song *song = NULL;
static MetadataChunk *prev = NULL;
Song *ret = NULL;
PlayerControl *pc = &(getPlayerData()->playerControl);
if (pc->metadataState == PLAYER_METADATA_STATE_READ) {
DEBUG("playerCurrentDecodeSong: caught new metadata!\n");
if(prev) free(prev);
if (prev)
free(prev);
prev = malloc(sizeof(MetadataChunk));
memcpy(prev, &(pc->metadataChunk), sizeof(MetadataChunk));
if(song) freeJustSong(song);
if (song)
freeJustSong(song);
song = newNullSong();
song->url = strdup(pc->currentUrl);
song->tag = metadataChunkToMpdTagDup(prev);
......
......@@ -70,9 +70,9 @@ typedef struct _PlayerControl {
volatile float totalTime;
volatile float elapsedTime;
volatile float fileTime;
char utf8url[MAXPATHLEN+1];
char currentUrl[MAXPATHLEN+1];
char erroredUrl[MAXPATHLEN+1];
char utf8url[MAXPATHLEN + 1];
char currentUrl[MAXPATHLEN + 1];
char erroredUrl[MAXPATHLEN + 1];
volatile mpd_sint8 queueState;
volatile mpd_sint8 queueLockState;
volatile mpd_sint8 lockQueue;
......@@ -115,7 +115,7 @@ int getPlayerState();
void clearPlayerError();
char * getPlayerErrorStr();
char *getPlayerErrorStr();
int getPlayerError();
......@@ -149,6 +149,6 @@ int getPlayerChannels();
void playerCycleLogFiles();
Song * playerCurrentDecodeSong();
Song *playerCurrentDecodeSong();
#endif
......@@ -33,44 +33,45 @@ int buffered_chunks;
#define DEFAULT_BUFFER_SIZE 2048
#define DEFAULT_BUFFER_BEFORE_PLAY 0
static PlayerData * playerData_pd;
int * player_pid;
static PlayerData *playerData_pd;
int *player_pid;
void initPlayerData(void) {
void initPlayerData(void)
{
float perc = DEFAULT_BUFFER_BEFORE_PLAY;
char * test;
char *test;
int shmid;
int crossfade = 0;
size_t bufferSize = DEFAULT_BUFFER_SIZE;
size_t allocationSize;
OutputBuffer * buffer;
ConfigParam * param;
OutputBuffer *buffer;
ConfigParam *param;
param = getConfigParam(CONF_AUDIO_BUFFER_SIZE);
if(param) {
if (param) {
bufferSize = strtol(param->value, &test, 10);
if(*test!='\0' || bufferSize<=0) {
if (*test != '\0' || bufferSize <= 0) {
ERROR("buffer size \"%s\" is not a positive integer, "
"line %i\n", param->value, param->line);
exit(EXIT_FAILURE);
}
}
bufferSize*=1024;
bufferSize *= 1024;
buffered_chunks = bufferSize/CHUNK_SIZE;
buffered_chunks = bufferSize / CHUNK_SIZE;
if(buffered_chunks >= 1<<15) {
ERROR("buffer size \"%i\" is too big\n",bufferSize);
if (buffered_chunks >= 1 << 15) {
ERROR("buffer size \"%i\" is too big\n", bufferSize);
exit(EXIT_FAILURE);
}
param = getConfigParam(CONF_BUFFER_BEFORE_PLAY);
if(param) {
if (param) {
perc = strtod(param->value, &test);
if(*test!='%' || perc<0 || perc>100) {
if (*test != '%' || perc < 0 || perc > 100) {
ERROR("buffered before play \"%s\" is not a positive "
"percentage and less than 100 percent, line %i"
"\n", param->value, param->line);
......@@ -78,28 +79,28 @@ void initPlayerData(void) {
}
}
buffered_before_play = (perc/100)*buffered_chunks;
if(buffered_before_play>buffered_chunks) {
buffered_before_play = (perc / 100) * buffered_chunks;
if (buffered_before_play > buffered_chunks) {
buffered_before_play = buffered_chunks;
}
else if(buffered_before_play<0) buffered_before_play = 0;
} else if (buffered_before_play < 0)
buffered_before_play = 0;
allocationSize = buffered_chunks*CHUNK_SIZE; /*actual buffer*/
allocationSize+= buffered_chunks*sizeof(float); /*for times*/
allocationSize+= buffered_chunks*sizeof(mpd_sint16); /*for chunkSize*/
allocationSize+= buffered_chunks*sizeof(mpd_sint16); /*for bitRate*/
allocationSize+= buffered_chunks*sizeof(mpd_sint8); /*for metaChunk*/
allocationSize+= sizeof(PlayerData); /*for playerData struct*/
allocationSize = buffered_chunks * CHUNK_SIZE; /*actual buffer */
allocationSize += buffered_chunks * sizeof(float); /*for times */
allocationSize += buffered_chunks * sizeof(mpd_sint16); /*for chunkSize */
allocationSize += buffered_chunks * sizeof(mpd_sint16); /*for bitRate */
allocationSize += buffered_chunks * sizeof(mpd_sint8); /*for metaChunk */
allocationSize += sizeof(PlayerData); /*for playerData struct */
if((shmid = shmget(IPC_PRIVATE,allocationSize,IPC_CREAT|0600))<0) {
if ((shmid = shmget(IPC_PRIVATE, allocationSize, IPC_CREAT | 0600)) < 0) {
ERROR("problems shmget'ing\n");
exit(EXIT_FAILURE);
}
if((playerData_pd = shmat(shmid,NULL,0))<0) {
if ((playerData_pd = shmat(shmid, NULL, 0)) < 0) {
ERROR("problems shmat'ing\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, NULL)<0) {
if (shmctl(shmid, IPC_RMID, NULL) < 0) {
ERROR("problems shmctl'ing\n");
exit(EXIT_FAILURE);
}
......@@ -107,30 +108,32 @@ void initPlayerData(void) {
* or maybe even made a part of the playerData struct
*/
allocationSize = sizeof(int);
if((shmid = shmget(IPC_PRIVATE,allocationSize,IPC_CREAT|0600))<0) {
if ((shmid = shmget(IPC_PRIVATE, allocationSize, IPC_CREAT | 0600)) < 0) {
ERROR("problems shmget'ing\n");
exit(EXIT_FAILURE);
}
if((player_pid = shmat(shmid,NULL,0))<0) {
if ((player_pid = shmat(shmid, NULL, 0)) < 0) {
ERROR("problems shmat'ing\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, NULL)<0) {
if (shmctl(shmid, IPC_RMID, NULL) < 0) {
ERROR("problems shmctl'ing\n");
exit(EXIT_FAILURE);
}
buffer = &(playerData_pd->buffer);
buffer->chunks = ((char *)playerData_pd)+sizeof(PlayerData);
buffer->chunkSize = (mpd_uint16 *)(((char *)buffer->chunks)+
buffered_chunks*CHUNK_SIZE);
buffer->bitRate = (mpd_uint16 *)(((char *)buffer->chunkSize)+
buffered_chunks*sizeof(mpd_sint16));
buffer->metaChunk = (mpd_sint8 *)(((char *)buffer->bitRate)+
buffered_chunks*sizeof(mpd_sint16));
buffer->times = (float *)(((char *)buffer->metaChunk)+
buffered_chunks*sizeof(mpd_sint8));
buffer->chunks = ((char *)playerData_pd) + sizeof(PlayerData);
buffer->chunkSize = (mpd_uint16 *) (((char *)buffer->chunks) +
buffered_chunks * CHUNK_SIZE);
buffer->bitRate = (mpd_uint16 *) (((char *)buffer->chunkSize) +
buffered_chunks * sizeof(mpd_sint16));
buffer->metaChunk = (mpd_sint8 *) (((char *)buffer->bitRate) +
buffered_chunks *
sizeof(mpd_sint16));
buffer->times =
(float *)(((char *)buffer->metaChunk) +
buffered_chunks * sizeof(mpd_sint8));
buffer->acceptMetadata = 0;
playerData_pd->playerControl.stop = 0;
......@@ -144,9 +147,9 @@ void initPlayerData(void) {
playerData_pd->playerControl.queueLockState = PLAYER_QUEUE_UNLOCKED;
playerData_pd->playerControl.seek = 0;
playerData_pd->playerControl.closeAudio = 0;
memset(playerData_pd->playerControl.utf8url, 0, MAXPATHLEN+1);
memset(playerData_pd->playerControl.erroredUrl, 0, MAXPATHLEN+1);
memset(playerData_pd->playerControl.currentUrl, 0, MAXPATHLEN+1);
memset(playerData_pd->playerControl.utf8url, 0, MAXPATHLEN + 1);
memset(playerData_pd->playerControl.erroredUrl, 0, MAXPATHLEN + 1);
memset(playerData_pd->playerControl.currentUrl, 0, MAXPATHLEN + 1);
playerData_pd->playerControl.crossFade = crossfade;
playerData_pd->playerControl.softwareVolume = 1000;
playerData_pd->playerControl.totalPlayTime = 0;
......@@ -159,22 +162,26 @@ void initPlayerData(void) {
playerData_pd->decoderControl.state = DECODE_STATE_STOP;
playerData_pd->decoderControl.seek = 0;
playerData_pd->decoderControl.error = DECODE_ERROR_NOERROR;
memset(playerData_pd->decoderControl.utf8url, 0, MAXPATHLEN+1);
memset(playerData_pd->decoderControl.utf8url, 0, MAXPATHLEN + 1);
}
PlayerData * getPlayerData(void) {
PlayerData *getPlayerData(void)
{
return playerData_pd;
}
int getPlayerPid(void) {
int getPlayerPid(void)
{
return *player_pid;
}
void setPlayerPid(int pid) {
void setPlayerPid(int pid)
{
*player_pid = pid;
}
void freePlayerData(void) {
void freePlayerData(void)
{
shmdt(playerData_pd);
shmdt(player_pid);
}
......@@ -42,7 +42,7 @@ typedef struct _PlayerData {
void initPlayerData();
PlayerData * getPlayerData();
PlayerData *getPlayerData();
int getPlayerPid();
void setPlayerPid(int pid);
......
......@@ -64,12 +64,12 @@
#define DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS 0
typedef struct _Playlist {
Song ** songs;
Song **songs;
/* holds version a song was modified on */
mpd_uint32 * songMod;
int * order;
int * positionToId;
int * idToPosition;
mpd_uint32 *songMod;
int *order;
int *positionToId;
int *idToPosition;
int length;
int current;
int queued;
......@@ -92,21 +92,24 @@ static void swapOrder(int a, int b);
static int playPlaylistOrderNumber(FILE * fp, int orderNum);
static void randomizeOrder(int start, int end);
char * getStateFile(void) {
ConfigParam * param = parseConfigFilePath(CONF_STATE_FILE, 0);
char *getStateFile(void)
{
ConfigParam *param = parseConfigFilePath(CONF_STATE_FILE, 0);
if(!param) return NULL;
if (!param)
return NULL;
return param->value;
}
static void incrPlaylistVersion(void) {
static unsigned long max = ((mpd_uint32)1<<31)-1;
static void incrPlaylistVersion(void)
{
static unsigned long max = ((mpd_uint32) 1 << 31) - 1;
playlist.version++;
if(playlist.version>=max) {
if (playlist.version >= max) {
int i;
for(i=0; i<playlist.length; i++) {
for (i = 0; i < playlist.length; i++) {
playlist.songMod[i] = 0;
}
......@@ -114,30 +117,36 @@ static void incrPlaylistVersion(void) {
}
}
void playlistVersionChange(void) {
void playlistVersionChange(void)
{
int i = 0;
for(i=0; i<playlist.length; i++) {
for (i = 0; i < playlist.length; i++) {
playlist.songMod[i] = playlist.version;
}
incrPlaylistVersion();
}
static void incrPlaylistCurrent(void) {
if(playlist.current < 0) return;
static void incrPlaylistCurrent(void)
{
if (playlist.current < 0)
return;
if(playlist.current >= playlist.length-1) {
if(playlist.repeat) playlist.current = 0;
else playlist.current = -1;
}
else playlist.current++;
if (playlist.current >= playlist.length - 1) {
if (playlist.repeat)
playlist.current = 0;
else
playlist.current = -1;
} else
playlist.current++;
}
void initPlaylist(void) {
char * test;
void initPlaylist(void)
{
char *test;
int i;
ConfigParam * param;
ConfigParam *param;
playlist.length = 0;
playlist.repeat = 0;
......@@ -148,9 +157,9 @@ void initPlaylist(void) {
param = getConfigParam(CONF_MAX_PLAYLIST_LENGTH);
if(param) {
if (param) {
playlist_max_length = strtol(param->value, &test, 10);
if(*test!='\0') {
if (*test != '\0') {
ERROR("max playlist length \"%s\" is not an integer, "
"line %i\n", param->value, param->line);
exit(EXIT_FAILURE);
......@@ -159,14 +168,12 @@ void initPlaylist(void) {
param = getConfigParam(CONF_SAVE_ABSOLUTE_PATHS);
if(param) {
if(0 == strcmp("yes", param->value) ) {
if (param) {
if (0 == strcmp("yes", param->value)) {
playlist_saveAbsolutePaths = 1;
}
else if(0 == strcmp("no", param->value) ) {
} else if (0 == strcmp("no", param->value)) {
playlist_saveAbsolutePaths = 0;
}
else {
} else {
ERROR("%s \"%s\" is not yes or no, line %i"
CONF_SAVE_ABSOLUTE_PATHS,
param->value, param->line);
......@@ -174,39 +181,41 @@ void initPlaylist(void) {
}
}
playlist.songs = malloc(sizeof(Song *)*playlist_max_length);
playlist.songMod = malloc(sizeof(mpd_uint32)*playlist_max_length);
playlist.order = malloc(sizeof(int)*playlist_max_length);
playlist.idToPosition = malloc(sizeof(int)*playlist_max_length*
playlist.songs = malloc(sizeof(Song *) * playlist_max_length);
playlist.songMod = malloc(sizeof(mpd_uint32) * playlist_max_length);
playlist.order = malloc(sizeof(int) * playlist_max_length);
playlist.idToPosition = malloc(sizeof(int) * playlist_max_length *
PLAYLIST_HASH_MULT);
playlist.positionToId = malloc(sizeof(int)*playlist_max_length);
playlist.positionToId = malloc(sizeof(int) * playlist_max_length);
memset(playlist.songs,0,sizeof(char *)*playlist_max_length);
memset(playlist.songs, 0, sizeof(char *) * playlist_max_length);
srandom(time(NULL));
for(i=0; i<playlist_max_length*PLAYLIST_HASH_MULT; i++) {
for (i = 0; i < playlist_max_length * PLAYLIST_HASH_MULT; i++) {
playlist.idToPosition[i] = -1;
}
}
static int getNextId(void) {
static int getNextId(void)
{
static int cur = -1;
do {
cur++;
if(cur >= playlist_max_length*PLAYLIST_HASH_MULT) {
if (cur >= playlist_max_length * PLAYLIST_HASH_MULT) {
cur = 0;
}
} while(playlist.idToPosition[cur] != -1);
} while (playlist.idToPosition[cur] != -1);
return cur;
}
void finishPlaylist(void) {
void finishPlaylist(void)
{
int i;
for(i=0;i<playlist.length;i++) {
if(playlist.songs[i]->type == SONG_TYPE_URL) {
for (i = 0; i < playlist.length; i++) {
if (playlist.songs[i]->type == SONG_TYPE_URL) {
freeJustSong(playlist.songs[i]);
}
}
......@@ -225,13 +234,15 @@ void finishPlaylist(void) {
playlist.positionToId = NULL;
}
int clearPlaylist(FILE * fp) {
int clearPlaylist(FILE * fp)
{
int i;
if(stopPlaylist(fp)<0) return -1;
if (stopPlaylist(fp) < 0)
return -1;
for(i=0;i<playlist.length;i++) {
if(playlist.songs[i]->type == SONG_TYPE_URL) {
for (i = 0; i < playlist.length; i++) {
if (playlist.songs[i]->type == SONG_TYPE_URL) {
freeJustSong(playlist.songs[i]);
}
playlist.idToPosition[playlist.positionToId[i]] = -1;
......@@ -245,191 +256,208 @@ int clearPlaylist(FILE * fp) {
return 0;
}
int showPlaylist(FILE * fp) {
int showPlaylist(FILE * fp)
{
int i;
for(i=0;i<playlist.length;i++) {
myfprintf(fp,"%i:%s\n", i, getSongUrl(playlist.songs[i]));
for (i = 0; i < playlist.length; i++) {
myfprintf(fp, "%i:%s\n", i, getSongUrl(playlist.songs[i]));
}
return 0;
}
void savePlaylistState(void) {
char * stateFile = getStateFile();
void savePlaylistState(void)
{
char *stateFile = getStateFile();
if(stateFile) {
FILE * fp;
if (stateFile) {
FILE *fp;
while(!(fp = fopen(stateFile,"w")) && errno==EINTR);
if(!fp) {
while (!(fp = fopen(stateFile, "w")) && errno == EINTR) ;
if (!fp) {
ERROR("problems opening state file \"%s\" for "
"writing: %s\n", stateFile,
strerror(errno));
"writing: %s\n", stateFile, strerror(errno));
return;
}
myfprintf(fp,"%s",PLAYLIST_STATE_FILE_STATE);
switch(playlist_state) {
myfprintf(fp, "%s", PLAYLIST_STATE_FILE_STATE);
switch (playlist_state) {
case PLAYLIST_STATE_PLAY:
switch(getPlayerState()) {
switch (getPlayerState()) {
case PLAYER_STATE_PAUSE:
myfprintf(fp,"%s\n",
myfprintf(fp, "%s\n",
PLAYLIST_STATE_FILE_STATE_PAUSE);
break;
default:
myfprintf(fp,"%s\n",
myfprintf(fp, "%s\n",
PLAYLIST_STATE_FILE_STATE_PLAY);
}
myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_CURRENT,
myfprintf(fp, "%s%i\n", PLAYLIST_STATE_FILE_CURRENT,
playlist.order[playlist.current]);
myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_TIME,
myfprintf(fp, "%s%i\n", PLAYLIST_STATE_FILE_TIME,
getPlayerElapsedTime());
break;
default:
myfprintf(fp,"%s\n",PLAYLIST_STATE_FILE_STATE_STOP);
myfprintf(fp, "%s\n", PLAYLIST_STATE_FILE_STATE_STOP);
break;
}
myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_RANDOM,
myfprintf(fp, "%s%i\n", PLAYLIST_STATE_FILE_RANDOM,
playlist.random);
myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_REPEAT,
myfprintf(fp, "%s%i\n", PLAYLIST_STATE_FILE_REPEAT,
playlist.repeat);
myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_CROSSFADE,
myfprintf(fp, "%s%i\n", PLAYLIST_STATE_FILE_CROSSFADE,
(int)(getPlayerCrossFade()));
myfprintf(fp,"%s\n",PLAYLIST_STATE_FILE_PLAYLIST_BEGIN);
myfprintf(fp, "%s\n", PLAYLIST_STATE_FILE_PLAYLIST_BEGIN);
showPlaylist(fp);
myfprintf(fp,"%s\n",PLAYLIST_STATE_FILE_PLAYLIST_END);
myfprintf(fp, "%s\n", PLAYLIST_STATE_FILE_PLAYLIST_END);
while(fclose(fp) && errno==EINTR);
while (fclose(fp) && errno == EINTR) ;
}
}
void loadPlaylistFromStateFile(FILE * fp, char * buffer, int state, int current,
void loadPlaylistFromStateFile(FILE * fp, char *buffer, int state, int current,
int time)
{
char * temp;
char *temp;
int song;
char * stateFile = getStateFile();
char *stateFile = getStateFile();
if(!myFgets(buffer,PLAYLIST_BUFFER_SIZE,fp)) {
if (!myFgets(buffer, PLAYLIST_BUFFER_SIZE, fp)) {
ERROR("error parsing state file \"%s\"\n", stateFile);
exit(EXIT_FAILURE);
}
while(strcmp(buffer,PLAYLIST_STATE_FILE_PLAYLIST_END)) {
song = atoi(strtok(buffer,":"));
if(!(temp = strtok(NULL,""))) {
while (strcmp(buffer, PLAYLIST_STATE_FILE_PLAYLIST_END)) {
song = atoi(strtok(buffer, ":"));
if (!(temp = strtok(NULL, ""))) {
ERROR("error parsing state file \"%s\"\n", stateFile);
exit(EXIT_FAILURE);
}
if(addToPlaylist(stderr, temp, 0)==0 && current==song) {
if(state!=PLAYER_STATE_STOP) {
playPlaylist(stderr,playlist.length-1,0);
if (addToPlaylist(stderr, temp, 0) == 0 && current == song) {
if (state != PLAYER_STATE_STOP) {
playPlaylist(stderr, playlist.length - 1, 0);
}
if(state==PLAYER_STATE_PAUSE) {
if (state == PLAYER_STATE_PAUSE) {
playerPause(stderr);
}
if(state!=PLAYER_STATE_STOP) {
seekSongInPlaylist(stderr,playlist.length-1,
if (state != PLAYER_STATE_STOP) {
seekSongInPlaylist(stderr, playlist.length - 1,
time);
}
}
if(!myFgets(buffer,PLAYLIST_BUFFER_SIZE,fp)) {
if (!myFgets(buffer, PLAYLIST_BUFFER_SIZE, fp)) {
ERROR("error parsing state file \"%s\"\n", stateFile);
exit(EXIT_FAILURE);
}
}
}
void readPlaylistState(void) {
char * stateFile = getStateFile();
void readPlaylistState(void)
{
char *stateFile = getStateFile();
if(stateFile) {
FILE * fp;
if (stateFile) {
FILE *fp;
struct stat st;
int current = -1;
int time = 0;
int state = PLAYER_STATE_STOP;
char buffer[PLAYLIST_BUFFER_SIZE];
if(stat(stateFile,&st)<0) {
if (stat(stateFile, &st) < 0) {
DEBUG("failed to stat state file\n");
return;
}
if(!S_ISREG(st.st_mode)) {
if (!S_ISREG(st.st_mode)) {
ERROR("state file \"%s\" is not a regular "
"file\n",stateFile);
"file\n", stateFile);
exit(EXIT_FAILURE);
}
fp = fopen(stateFile,"r");
if(!fp) {
fp = fopen(stateFile, "r");
if (!fp) {
ERROR("problems opening state file \"%s\" for "
"reading: %s\n", stateFile,
strerror(errno));
"reading: %s\n", stateFile, strerror(errno));
exit(EXIT_FAILURE);
}
while(myFgets(buffer,PLAYLIST_BUFFER_SIZE,fp)) {
if(strncmp(buffer,PLAYLIST_STATE_FILE_STATE,
strlen(PLAYLIST_STATE_FILE_STATE))==0) {
if(strcmp(&(buffer
[strlen(PLAYLIST_STATE_FILE_STATE)]),
PLAYLIST_STATE_FILE_STATE_PLAY)==0) {
while (myFgets(buffer, PLAYLIST_BUFFER_SIZE, fp)) {
if (strncmp(buffer, PLAYLIST_STATE_FILE_STATE,
strlen(PLAYLIST_STATE_FILE_STATE)) == 0) {
if (strcmp(&(buffer
[strlen
(PLAYLIST_STATE_FILE_STATE)]),
PLAYLIST_STATE_FILE_STATE_PLAY) ==
0) {
state = PLAYER_STATE_PLAY;
}
else if(strcmp(&(buffer
[strlen(PLAYLIST_STATE_FILE_STATE)]),
PLAYLIST_STATE_FILE_STATE_PAUSE)==0) {
} else if (strcmp(&(buffer
[strlen
(PLAYLIST_STATE_FILE_STATE)]),
PLAYLIST_STATE_FILE_STATE_PAUSE)
== 0) {
state = PLAYER_STATE_PAUSE;
}
}
else if(strncmp(buffer,PLAYLIST_STATE_FILE_TIME,
strlen(PLAYLIST_STATE_FILE_TIME))==0) {
time = atoi(&(buffer
} else if (strncmp(buffer, PLAYLIST_STATE_FILE_TIME,
strlen(PLAYLIST_STATE_FILE_TIME)) ==
0) {
time =
atoi(&
(buffer
[strlen(PLAYLIST_STATE_FILE_TIME)]));
}
else if(strncmp(buffer,PLAYLIST_STATE_FILE_REPEAT,
strlen(PLAYLIST_STATE_FILE_REPEAT))==0) {
if(strcmp(&(buffer
} else
if (strncmp
(buffer, PLAYLIST_STATE_FILE_REPEAT,
strlen(PLAYLIST_STATE_FILE_REPEAT)) == 0) {
if (strcmp
(&
(buffer
[strlen(PLAYLIST_STATE_FILE_REPEAT)]),
"1")==0) {
setPlaylistRepeatStatus(stderr,1);
}
else setPlaylistRepeatStatus(stderr,0);
}
else if(strncmp(buffer,PLAYLIST_STATE_FILE_CROSSFADE,
strlen(PLAYLIST_STATE_FILE_CROSSFADE))==0) {
setPlayerCrossFade(atoi(&(buffer[strlen(
PLAYLIST_STATE_FILE_CROSSFADE)])));
}
else if(strncmp(buffer,PLAYLIST_STATE_FILE_RANDOM,
strlen(PLAYLIST_STATE_FILE_RANDOM))==0) {
if(strcmp(&(buffer
"1") == 0) {
setPlaylistRepeatStatus(stderr, 1);
} else
setPlaylistRepeatStatus(stderr, 0);
} else
if (strncmp
(buffer, PLAYLIST_STATE_FILE_CROSSFADE,
strlen(PLAYLIST_STATE_FILE_CROSSFADE)) == 0) {
setPlayerCrossFade(atoi
(&
(buffer
[strlen
(PLAYLIST_STATE_FILE_CROSSFADE)])));
} else
if (strncmp
(buffer, PLAYLIST_STATE_FILE_RANDOM,
strlen(PLAYLIST_STATE_FILE_RANDOM)) == 0) {
if (strcmp
(&
(buffer
[strlen(PLAYLIST_STATE_FILE_RANDOM)]),
"1")==0) {
setPlaylistRandomStatus(stderr,1);
}
else setPlaylistRandomStatus(stderr,0);
}
else if(strncmp(buffer,PLAYLIST_STATE_FILE_CURRENT,
strlen(PLAYLIST_STATE_FILE_CURRENT))==0) {
if(strlen(buffer)==
"1") == 0) {
setPlaylistRandomStatus(stderr, 1);
} else
setPlaylistRandomStatus(stderr, 0);
} else if (strncmp(buffer, PLAYLIST_STATE_FILE_CURRENT,
strlen(PLAYLIST_STATE_FILE_CURRENT))
== 0) {
if (strlen(buffer) ==
strlen(PLAYLIST_STATE_FILE_CURRENT)) {
ERROR("error parsing state "
"file \"%s\"\n",
stateFile);
"file \"%s\"\n", stateFile);
exit(EXIT_FAILURE);
}
current = atoi(&(buffer
[strlen(PLAYLIST_STATE_FILE_CURRENT)]));
}
else if(strncmp(buffer,
PLAYLIST_STATE_FILE_PLAYLIST_BEGIN,
[strlen
(PLAYLIST_STATE_FILE_CURRENT)]));
} else
if (strncmp
(buffer, PLAYLIST_STATE_FILE_PLAYLIST_BEGIN,
strlen(PLAYLIST_STATE_FILE_PLAYLIST_BEGIN)
)==0) {
if(state==PLAYER_STATE_STOP) current = -1;
loadPlaylistFromStateFile(fp,buffer,state,
current,time);
) == 0) {
if (state == PLAYER_STATE_STOP)
current = -1;
loadPlaylistFromStateFile(fp, buffer, state,
current, time);
}
}
......@@ -437,20 +465,21 @@ void readPlaylistState(void) {
}
}
void printPlaylistSongInfo(FILE * fp, int song) {
void printPlaylistSongInfo(FILE * fp, int song)
{
printSongInfo(fp, playlist.songs[song]);
myfprintf(fp, "Pos: %i\n", song);
myfprintf(fp, "Id: %i\n", playlist.positionToId[song]);
}
int playlistChanges(FILE * fp, mpd_uint32 version) {
int playlistChanges(FILE * fp, mpd_uint32 version)
{
int i;
for(i=0; i<playlist.length; i++) {
if(version > playlist.version ||
for (i = 0; i < playlist.length; i++) {
if (version > playlist.version ||
playlist.songMod[i] >= version ||
playlist.songMod[i] == 0)
{
playlist.songMod[i] == 0) {
printPlaylistSongInfo(fp, i);
}
}
......@@ -458,14 +487,14 @@ int playlistChanges(FILE * fp, mpd_uint32 version) {
return 0;
}
int playlistChangesPosId(FILE * fp, mpd_uint32 version) {
int playlistChangesPosId(FILE * fp, mpd_uint32 version)
{
int i;
for(i=0; i<playlist.length; i++) {
if(version > playlist.version ||
for (i = 0; i < playlist.length; i++) {
if (version > playlist.version ||
playlist.songMod[i] >= version ||
playlist.songMod[i] == 0)
{
playlist.songMod[i] == 0) {
myfprintf(fp, "cpos: %i\n", i);
myfprintf(fp, "Id: %i\n", playlist.positionToId[i]);
}
......@@ -474,26 +503,24 @@ int playlistChangesPosId(FILE * fp, mpd_uint32 version) {
return 0;
}
int playlistInfo(FILE * fp, int song) {
int playlistInfo(FILE * fp, int song)
{
int i;
int begin = 0;
int end = playlist.length;
if(song>=0) {
if (song >= 0) {
begin = song;
end = song+1;
end = song + 1;
}
if(song>=playlist.length) {
if (song >= playlist.length) {
commandError(fp, ACK_ERROR_NO_EXIST,
"song doesn't exist: \"%i\"", song);
return -1;
}
for(i=begin; i<end; i++) printPlaylistSongInfo(fp, i);
for (i = begin; i < end; i++)
printPlaylistSongInfo(fp, i);
return 0;
}
......@@ -508,24 +535,27 @@ int playlistInfo(FILE * fp, int song) {
} \
}
int playlistId(FILE * fp, int id) {
int playlistId(FILE * fp, int id)
{
int i;
int begin = 0;
int end = playlist.length;
if(id>=0) {
if (id >= 0) {
checkSongId(id);
begin = playlist.idToPosition[id];
end = begin+1;
end = begin + 1;
}
for(i=begin; i<end; i++) printPlaylistSongInfo(fp, i);
for (i = begin; i < end; i++)
printPlaylistSongInfo(fp, i);
return 0;
}
void swapSongs(int song1, int song2) {
Song * sTemp;
void swapSongs(int song1, int song2)
{
Song *sTemp;
int iTemp;
sTemp = playlist.songs[song1];
......@@ -543,72 +573,75 @@ void swapSongs(int song1, int song2) {
playlist.positionToId[song2] = iTemp;
}
void queueNextSongInPlaylist(void) {
if(playlist.current<playlist.length-1) {
playlist.queued = playlist.current+1;
void queueNextSongInPlaylist(void)
{
if (playlist.current < playlist.length - 1) {
playlist.queued = playlist.current + 1;
DEBUG("playlist: queue song %i:\"%s\"\n",
playlist.queued,
getSongUrl(playlist.songs[playlist.order[
playlist.queued]]));
if(queueSong(playlist.songs[playlist.order[playlist.queued]]) <
0)
{
getSongUrl(playlist.
songs[playlist.order[playlist.queued]]));
if (queueSong(playlist.songs[playlist.order[playlist.queued]]) <
0) {
playlist.queued = -1;
playlist_queueError = 1;
}
}
else if(playlist.length && playlist.repeat) {
if(playlist.length>1 && playlist.random) {
randomizeOrder(0,playlist.length-1);
} else if (playlist.length && playlist.repeat) {
if (playlist.length > 1 && playlist.random) {
randomizeOrder(0, playlist.length - 1);
}
playlist.queued = 0;
DEBUG("playlist: queue song %i:\"%s\"\n",
playlist.queued,
getSongUrl(playlist.songs[playlist.order[
playlist.queued]]));
if(queueSong(playlist.songs[playlist.order[playlist.queued]]) <
0)
{
getSongUrl(playlist.
songs[playlist.order[playlist.queued]]));
if (queueSong(playlist.songs[playlist.order[playlist.queued]]) <
0) {
playlist.queued = -1;
playlist_queueError = 1;
}
}
}
void syncPlaylistWithQueue(int queue) {
if(queue && getPlayerQueueState()==PLAYER_QUEUE_BLANK) {
void syncPlaylistWithQueue(int queue)
{
if (queue && getPlayerQueueState() == PLAYER_QUEUE_BLANK) {
queueNextSongInPlaylist();
}
else if(getPlayerQueueState()==PLAYER_QUEUE_DECODE) {
if(playlist.queued!=-1) setQueueState(PLAYER_QUEUE_PLAY);
else setQueueState(PLAYER_QUEUE_STOP);
}
else if(getPlayerQueueState()==PLAYER_QUEUE_EMPTY) {
} else if (getPlayerQueueState() == PLAYER_QUEUE_DECODE) {
if (playlist.queued != -1)
setQueueState(PLAYER_QUEUE_PLAY);
else
setQueueState(PLAYER_QUEUE_STOP);
} else if (getPlayerQueueState() == PLAYER_QUEUE_EMPTY) {
setQueueState(PLAYER_QUEUE_BLANK);
if(playlist.queued>=0) {
if (playlist.queued >= 0) {
DEBUG("playlist: now playing queued song\n");
playlist.current = playlist.queued;
}
playlist.queued = -1;
if(queue) queueNextSongInPlaylist();
if (queue)
queueNextSongInPlaylist();
}
}
void lockPlaylistInteraction(void) {
if(getPlayerQueueState()==PLAYER_QUEUE_PLAY ||
getPlayerQueueState()==PLAYER_QUEUE_FULL) {
void lockPlaylistInteraction(void)
{
if (getPlayerQueueState() == PLAYER_QUEUE_PLAY ||
getPlayerQueueState() == PLAYER_QUEUE_FULL) {
playerQueueLock();
syncPlaylistWithQueue(0);
}
}
static void unlockPlaylistInteraction(void) {
static void unlockPlaylistInteraction(void)
{
playerQueueUnlock();
}
void clearPlayerQueue(void) {
void clearPlayerQueue(void)
{
playlist.queued = -1;
switch(getPlayerQueueState()) {
switch (getPlayerQueueState()) {
case PLAYER_QUEUE_FULL:
DEBUG("playlist: dequeue song\n");
setQueueState(PLAYER_QUEUE_BLANK);
......@@ -620,14 +653,14 @@ void clearPlayerQueue(void) {
}
}
int addToPlaylist(FILE * fp, char * url, int printId) {
Song * song;
int addToPlaylist(FILE * fp, char *url, int printId)
{
Song *song;
DEBUG("add to playlist: %s\n",url);
DEBUG("add to playlist: %s\n", url);
if((song = getSongFromDB(url))) {
}
else if(!(isValidRemoteUtf8Url(url) &&
if ((song = getSongFromDB(url))) {
} else if (!(isValidRemoteUtf8Url(url) &&
(song = newSong(url, SONG_TYPE_URL, NULL)))) {
commandError(fp, ACK_ERROR_NO_EXIST,
"\"%s\" is not in the music db or is "
......@@ -635,20 +668,22 @@ int addToPlaylist(FILE * fp, char * url, int printId) {
return -1;
}
return addSongToPlaylist(fp,song, printId);
return addSongToPlaylist(fp, song, printId);
}
int addSongToPlaylist(FILE * fp, Song * song, int printId) {
int addSongToPlaylist(FILE * fp, Song * song, int printId)
{
int id;
if(playlist.length==playlist_max_length) {
if (playlist.length == playlist_max_length) {
commandError(fp, ACK_ERROR_PLAYLIST_MAX,
"playlist is at the max size", NULL);
return -1;
}
if(playlist_state==PLAYLIST_STATE_PLAY) {
if(playlist.queued>=0 && playlist.current==playlist.length-1) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist.queued >= 0
&& playlist.current == playlist.length - 1) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
......@@ -661,74 +696,82 @@ int addSongToPlaylist(FILE * fp, Song * song, int printId) {
playlist.songMod[playlist.length] = playlist.version;
playlist.order[playlist.length] = playlist.length;
playlist.positionToId[playlist.length] = id;
playlist.idToPosition[playlist.positionToId[playlist.length]] = playlist.length;
playlist.idToPosition[playlist.positionToId[playlist.length]] =
playlist.length;
playlist.length++;
if(playlist.random) {
if (playlist.random) {
int swap;
int start;
/*if(playlist_state==PLAYLIST_STATE_STOP) start = 0;
else */if(playlist.queued>=0) start = playlist.queued+1;
else start = playlist.current+1;
if(start < playlist.length) {
swap = random()%(playlist.length-start);
swap+=start;
swapOrder(playlist.length-1,swap);
else */ if (playlist.queued >= 0)
start = playlist.queued + 1;
else
start = playlist.current + 1;
if (start < playlist.length) {
swap = random() % (playlist.length - start);
swap += start;
swapOrder(playlist.length - 1, swap);
}
}
incrPlaylistVersion();
if(printId) myfprintf(fp, "Id: %i\n", id);
if (printId)
myfprintf(fp, "Id: %i\n", id);
return 0;
}
int swapSongsInPlaylist(FILE * fp, int song1, int song2) {
int swapSongsInPlaylist(FILE * fp, int song1, int song2)
{
int queuedSong = -1;
int currentSong = -1;
if(song1<0 || song1>=playlist.length) {
if (song1 < 0 || song1 >= playlist.length) {
commandError(fp, ACK_ERROR_NO_EXIST,
"song doesn't exist: \"%i\"", song1);
return -1;
}
if(song2<0 || song2>=playlist.length) {
if (song2 < 0 || song2 >= playlist.length) {
commandError(fp, ACK_ERROR_NO_EXIST,
"song doesn't exist: \"%i\"", song2);
return -1;
}
if(playlist_state==PLAYLIST_STATE_PLAY) {
if(playlist.queued>=0) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist.queued >= 0) {
queuedSong = playlist.order[playlist.queued];
}
currentSong = playlist.order[playlist.current];
if(queuedSong==song1 || queuedSong==song2 || currentSong==song1
|| currentSong==song2)
{
if (queuedSong == song1 || queuedSong == song2
|| currentSong == song1 || currentSong == song2) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
}
}
swapSongs(song1,song2);
if(playlist.random) {
swapSongs(song1, song2);
if (playlist.random) {
int i;
int k;
int j = -1;
for(i=0;playlist.order[i]!=song1;i++) {
if(playlist.order[i]==song2) j = i;
for (i = 0; playlist.order[i] != song1; i++) {
if (playlist.order[i] == song2)
j = i;
}
k = i;
for(;j==-1;i++) if(playlist.order[i]==song2) j = i;
swapOrder(k,j);
}
else {
if(playlist.current==song1) playlist.current = song2;
else if(playlist.current==song2) playlist.current = song1;
for (; j == -1; i++)
if (playlist.order[i] == song2)
j = i;
swapOrder(k, j);
} else {
if (playlist.current == song1)
playlist.current = song2;
else if (playlist.current == song2)
playlist.current = song1;
}
incrPlaylistVersion();
......@@ -736,7 +779,8 @@ int swapSongsInPlaylist(FILE * fp, int song1, int song2) {
return 0;
}
int swapSongsInPlaylistById(FILE * fp, int id1, int id2) {
int swapSongsInPlaylistById(FILE * fp, int id1, int id2)
{
checkSongId(id1);
checkSongId(id2);
......@@ -751,161 +795,172 @@ int swapSongsInPlaylistById(FILE * fp, int id1, int id2) {
playlist.songMod[to] = playlist.version; \
}
int deleteFromPlaylist(FILE * fp, int song) {
int deleteFromPlaylist(FILE * fp, int song)
{
int i;
int songOrder;
if(song<0 || song>=playlist.length) {
if (song < 0 || song >= playlist.length) {
commandError(fp, ACK_ERROR_NO_EXIST,
"song doesn't exist: \"%i\"", song);
return -1;
}
if(playlist_state==PLAYLIST_STATE_PLAY) {
if(playlist.queued>=0 && (playlist.order[playlist.queued]==song
|| playlist.order[playlist.current]==song))
{
if (playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist.queued >= 0
&& (playlist.order[playlist.queued] == song
|| playlist.order[playlist.current] == song)) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
}
}
if(playlist.songs[song]->type == SONG_TYPE_URL) {
if (playlist.songs[song]->type == SONG_TYPE_URL) {
freeJustSong(playlist.songs[song]);
}
playlist.idToPosition[playlist.positionToId[song]] = -1;
/* delete song from songs array */
for(i=song;i<playlist.length-1;i++) {
moveSongFromTo(i+1, i);
for (i = song; i < playlist.length - 1; i++) {
moveSongFromTo(i + 1, i);
}
/* now find it in the order array */
for(i=0;i<playlist.length-1;i++) {
if(playlist.order[i]==song) break;
for (i = 0; i < playlist.length - 1; i++) {
if (playlist.order[i] == song)
break;
}
songOrder = i;
/* delete the entry from the order array */
for(;i<playlist.length-1;i++) playlist.order[i] = playlist.order[i+1];
for (; i < playlist.length - 1; i++)
playlist.order[i] = playlist.order[i + 1];
/* readjust values in the order array */
for(i=0;i<playlist.length-1;i++) {
if(playlist.order[i]>song) playlist.order[i]--;
for (i = 0; i < playlist.length - 1; i++) {
if (playlist.order[i] > song)
playlist.order[i]--;
}
/* now take care of other misc stuff */
playlist.songs[playlist.length-1] = NULL;
playlist.songs[playlist.length - 1] = NULL;
playlist.length--;
incrPlaylistVersion();
if(playlist_state!=PLAYLIST_STATE_STOP && playlist.current==songOrder) {
if (playlist_state != PLAYLIST_STATE_STOP
&& playlist.current == songOrder) {
/*if(playlist.current>=playlist.length) return playerStop(fp);
else return playPlaylistOrderNumber(fp,playlist.current);*/
else return playPlaylistOrderNumber(fp,playlist.current); */
playerStop(stderr);
playlist_noGoToNext = 1;
}
if(playlist.current>songOrder) {
if (playlist.current > songOrder) {
playlist.current--;
}
else if(playlist.current>=playlist.length) {
} else if (playlist.current >= playlist.length) {
incrPlaylistCurrent();
}
if(playlist.queued>songOrder) {
if (playlist.queued > songOrder) {
playlist.queued--;
}
return 0;
}
int deleteFromPlaylistById(FILE * fp, int id) {
int deleteFromPlaylistById(FILE * fp, int id)
{
checkSongId(id);
return deleteFromPlaylist(fp, playlist.idToPosition[id]);
}
void deleteASongFromPlaylist(Song * song) {
void deleteASongFromPlaylist(Song * song)
{
int i;
if(NULL==playlist.songs) return;
if (NULL == playlist.songs)
return;
for(i=0;i<playlist.length;i++) {
if(song==playlist.songs[i]) {
deleteFromPlaylist(stderr,i);
for (i = 0; i < playlist.length; i++) {
if (song == playlist.songs[i]) {
deleteFromPlaylist(stderr, i);
}
}
}
int stopPlaylist(FILE * fp) {
int stopPlaylist(FILE * fp)
{
DEBUG("playlist: stop\n");
if(playerStop(fp)<0) return -1;
if (playerStop(fp) < 0)
return -1;
playerCloseAudio();
playlist.queued = -1;
playlist_state = PLAYLIST_STATE_STOP;
playlist_noGoToNext = 0;
if(playlist.random) randomizeOrder(0,playlist.length-1);
if (playlist.random)
randomizeOrder(0, playlist.length - 1);
return 0;
}
int playPlaylistOrderNumber(FILE * fp, int orderNum) {
int playPlaylistOrderNumber(FILE * fp, int orderNum)
{
if(playerStop(fp)<0) return -1;
if (playerStop(fp) < 0)
return -1;
playlist_state = PLAYLIST_STATE_PLAY;
playlist_noGoToNext = 0;
playlist.queued = -1;
playlist_queueError = 0;
DEBUG("playlist: play %i:\"%s\"\n",orderNum,
DEBUG("playlist: play %i:\"%s\"\n", orderNum,
getSongUrl(playlist.songs[playlist.order[orderNum]]));
if(playerPlay(fp,(playlist.songs[playlist.order[orderNum]])) < 0) {
if (playerPlay(fp, (playlist.songs[playlist.order[orderNum]])) < 0) {
stopPlaylist(fp);
return -1;
}
else playlist.current++;
} else
playlist.current++;
playlist.current = orderNum;
return 0;
}
int playPlaylist(FILE * fp, int song, int stopOnError) {
int playPlaylist(FILE * fp, int song, int stopOnError)
{
int i = song;
clearPlayerError();
if(song==-1) {
if(playlist.length == 0) return 0;
if (song == -1) {
if (playlist.length == 0)
return 0;
if(playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
return playerSetPause(fp, 0);
}
if(playlist.current >= 0 && playlist.current < playlist.length)
{
if (playlist.current >= 0 && playlist.current < playlist.length) {
i = playlist.current;
}
else {
} else {
i = 0;
}
}
else if(song<0 || song>=playlist.length) {
} else if (song < 0 || song >= playlist.length) {
commandError(fp, ACK_ERROR_NO_EXIST,
"song doesn't exist: \"%i\"", song);
return -1;
}
if(playlist.random) {
if(song == -1 && playlist_state==PLAYLIST_STATE_PLAY) {
randomizeOrder(0,playlist.length-1);
}
else {
if(song>=0) for(i=0;song!=playlist.order[i];i++);
if(playlist_state==PLAYLIST_STATE_STOP) {
if (playlist.random) {
if (song == -1 && playlist_state == PLAYLIST_STATE_PLAY) {
randomizeOrder(0, playlist.length - 1);
} else {
if (song >= 0)
for (i = 0; song != playlist.order[i]; i++) ;
if (playlist_state == PLAYLIST_STATE_STOP) {
playlist.current = 0;
}
swapOrder(i,playlist.current);
swapOrder(i, playlist.current);
i = playlist.current;
}
}
......@@ -913,11 +968,12 @@ int playPlaylist(FILE * fp, int song, int stopOnError) {
playlist_stopOnError = stopOnError;
playlist_errorCount = 0;
return playPlaylistOrderNumber(fp,i);
return playPlaylistOrderNumber(fp, i);
}
int playPlaylistById(FILE * fp, int id, int stopOnError) {
if(id == -1) {
int playPlaylistById(FILE * fp, int id, int stopOnError)
{
if (id == -1) {
return playPlaylist(fp, id, stopOnError);
}
......@@ -926,68 +982,78 @@ int playPlaylistById(FILE * fp, int id, int stopOnError) {
return playPlaylist(fp, playlist.idToPosition[id], stopOnError);
}
void syncCurrentPlayerDecodeMetadata(void) {
Song * songPlayer = playerCurrentDecodeSong();
Song * song;
void syncCurrentPlayerDecodeMetadata(void)
{
Song *songPlayer = playerCurrentDecodeSong();
Song *song;
int songNum;
if(!songPlayer) return;
if (!songPlayer)
return;
if(playlist_state!=PLAYLIST_STATE_PLAY) return;
if (playlist_state != PLAYLIST_STATE_PLAY)
return;
songNum = playlist.order[playlist.current];
song = playlist.songs[songNum];
if(song->type == SONG_TYPE_URL &&
if (song->type == SONG_TYPE_URL &&
0 == strcmp(getSongUrl(song), songPlayer->url) &&
!mpdTagsAreEqual(song->tag, songPlayer->tag))
{
if(song->tag) freeMpdTag(song->tag);
!mpdTagsAreEqual(song->tag, songPlayer->tag)) {
if (song->tag)
freeMpdTag(song->tag);
song->tag = mpdTagDup(songPlayer->tag);
playlist.songMod[songNum] = playlist.version;
incrPlaylistVersion();
}
}
void syncPlayerAndPlaylist(void) {
if(playlist_state!=PLAYLIST_STATE_PLAY) return;
void syncPlayerAndPlaylist(void)
{
if (playlist_state != PLAYLIST_STATE_PLAY)
return;
if(getPlayerState()==PLAYER_STATE_STOP) playPlaylistIfPlayerStopped();
else syncPlaylistWithQueue(!playlist_queueError);
if (getPlayerState() == PLAYER_STATE_STOP)
playPlaylistIfPlayerStopped();
else
syncPlaylistWithQueue(!playlist_queueError);
syncCurrentPlayerDecodeMetadata();
}
int currentSongInPlaylist(FILE * fp) {
if(playlist_state!=PLAYLIST_STATE_PLAY) return 0;
int currentSongInPlaylist(FILE * fp)
{
if (playlist_state != PLAYLIST_STATE_PLAY)
return 0;
playlist_stopOnError = 0;
syncPlaylistWithQueue(0);
if(playlist.current>= 0 && playlist.current<playlist.length) {
return playPlaylistOrderNumber(fp,playlist.current);
}
else return stopPlaylist(fp);;
if (playlist.current >= 0 && playlist.current < playlist.length) {
return playPlaylistOrderNumber(fp, playlist.current);
} else
return stopPlaylist(fp);;
return 0;
}
int nextSongInPlaylist(FILE * fp) {
if(playlist_state!=PLAYLIST_STATE_PLAY) return 0;
int nextSongInPlaylist(FILE * fp)
{
if (playlist_state != PLAYLIST_STATE_PLAY)
return 0;
syncPlaylistWithQueue(0);
playlist_stopOnError = 0;
if(playlist.current<playlist.length-1) {
return playPlaylistOrderNumber(fp,playlist.current+1);
}
else if(playlist.length && playlist.repeat) {
if(playlist.random) randomizeOrder(0,playlist.length-1);
return playPlaylistOrderNumber(fp,0);
}
else {
if (playlist.current < playlist.length - 1) {
return playPlaylistOrderNumber(fp, playlist.current + 1);
} else if (playlist.length && playlist.repeat) {
if (playlist.random)
randomizeOrder(0, playlist.length - 1);
return playPlaylistOrderNumber(fp, 0);
} else {
incrPlaylistCurrent();
return stopPlaylist(fp);;
}
......@@ -995,42 +1061,44 @@ int nextSongInPlaylist(FILE * fp) {
return 0;
}
void playPlaylistIfPlayerStopped(void) {
if(getPlayerState()==PLAYER_STATE_STOP) {
void playPlaylistIfPlayerStopped(void)
{
if (getPlayerState() == PLAYER_STATE_STOP) {
int error = getPlayerError();
if(error==PLAYER_ERROR_NOERROR) playlist_errorCount = 0;
else playlist_errorCount++;
if (error == PLAYER_ERROR_NOERROR)
playlist_errorCount = 0;
else
playlist_errorCount++;
if(playlist_state==PLAYLIST_STATE_PLAY && (
(playlist_stopOnError &&
error!=PLAYER_ERROR_NOERROR) ||
error==PLAYER_ERROR_AUDIO ||
error==PLAYER_ERROR_SYSTEM ||
playlist_errorCount>=playlist.length)) {
if (playlist_state == PLAYLIST_STATE_PLAY && ((playlist_stopOnError && error != PLAYER_ERROR_NOERROR) || error == PLAYER_ERROR_AUDIO || error == PLAYER_ERROR_SYSTEM || playlist_errorCount >= playlist.length)) {
stopPlaylist(stderr);
}
else if(playlist_noGoToNext) currentSongInPlaylist(stderr);
else nextSongInPlaylist(stderr);
} else if (playlist_noGoToNext)
currentSongInPlaylist(stderr);
else
nextSongInPlaylist(stderr);
}
}
int getPlaylistRepeatStatus(void) {
int getPlaylistRepeatStatus(void)
{
return playlist.repeat;
}
int getPlaylistRandomStatus(void) {
int getPlaylistRandomStatus(void)
{
return playlist.random;
}
int setPlaylistRepeatStatus(FILE * fp, int status) {
if(status!=0 && status!=1) {
int setPlaylistRepeatStatus(FILE * fp, int status)
{
if (status != 0 && status != 1) {
commandError(fp, ACK_ERROR_ARG, "\"%i\" is not 0 or 1", status);
return -1;
}
if(playlist_state==PLAYLIST_STATE_PLAY) {
if(playlist.repeat && !status && playlist.queued==0) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist.repeat && !status && playlist.queued == 0) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
......@@ -1042,34 +1110,33 @@ int setPlaylistRepeatStatus(FILE * fp, int status) {
return 0;
}
int moveSongInPlaylist(FILE * fp, int from, int to) {
int moveSongInPlaylist(FILE * fp, int from, int to)
{
int i;
Song * tmpSong;
Song *tmpSong;
int tmpId;
int queuedSong = -1;
int currentSong = -1;
if(from<0 || from>=playlist.length) {
if (from < 0 || from >= playlist.length) {
commandError(fp, ACK_ERROR_NO_EXIST,
"song doesn't exist: \"%i\"", from);
return -1;
}
if(to<0 || to>=playlist.length) {
if (to < 0 || to >= playlist.length) {
commandError(fp, ACK_ERROR_NO_EXIST,
"song doesn't exist: \"%i\"", to);
return -1;
}
if(playlist_state==PLAYLIST_STATE_PLAY) {
if(playlist.queued>=0) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist.queued >= 0) {
queuedSong = playlist.order[playlist.queued];
}
currentSong = playlist.order[playlist.current];
if(queuedSong==from || queuedSong==to || currentSong==from ||
currentSong==to)
{
if (queuedSong == from || queuedSong == to
|| currentSong == from || currentSong == to) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
......@@ -1079,12 +1146,12 @@ int moveSongInPlaylist(FILE * fp, int from, int to) {
tmpSong = playlist.songs[from];
tmpId = playlist.positionToId[from];
/* move songs to one less in from->to */
for(i=from;i<to;i++) {
moveSongFromTo(i+1, i);
for (i = from; i < to; i++) {
moveSongFromTo(i + 1, i);
}
/* move songs to one more in to->from */
for(i=from;i>to;i--) {
moveSongFromTo(i-1, i);
for (i = from; i > to; i--) {
moveSongFromTo(i - 1, i);
}
/* put song at _to_ */
playlist.idToPosition[tmpId] = to;
......@@ -1092,25 +1159,22 @@ int moveSongInPlaylist(FILE * fp, int from, int to) {
playlist.songs[to] = tmpSong;
playlist.songMod[to] = playlist.version;
/* now deal with order */
if(playlist.random) {
for(i=0;i<playlist.length;i++) {
if(playlist.order[i]>from && playlist.order[i]<=to) {
if (playlist.random) {
for (i = 0; i < playlist.length; i++) {
if (playlist.order[i] > from && playlist.order[i] <= to) {
playlist.order[i]--;
}
else if(playlist.order[i]<from &&
playlist.order[i]>=to) {
} else if (playlist.order[i] < from &&
playlist.order[i] >= to) {
playlist.order[i]++;
}
else if(from==playlist.order[i]) {
} else if (from == playlist.order[i]) {
playlist.order[i] = to;
}
}
}
else if(playlist.current==from) playlist.current = to;
else if(playlist.current>from && playlist.current<=to) {
} else if (playlist.current == from)
playlist.current = to;
else if (playlist.current > from && playlist.current <= to) {
playlist.current--;
}
else if(playlist.current>=to && playlist.current<from) {
} else if (playlist.current >= to && playlist.current < from) {
playlist.current++;
}
......@@ -1119,147 +1183,153 @@ int moveSongInPlaylist(FILE * fp, int from, int to) {
return 0;
}
int moveSongInPlaylistById(FILE * fp, int id1, int to) {
int moveSongInPlaylistById(FILE * fp, int id1, int to)
{
checkSongId(id1);
return moveSongInPlaylist(fp, playlist.idToPosition[id1], to);
}
static void orderPlaylist(void) {
static void orderPlaylist(void)
{
int i;
if(playlist.current >= 0 && playlist.current < playlist.length) {
if (playlist.current >= 0 && playlist.current < playlist.length) {
playlist.current = playlist.order[playlist.current];
}
if(playlist_state==PLAYLIST_STATE_PLAY) {
if(playlist.queued>=0) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist.queued >= 0) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
}
}
for(i=0;i<playlist.length;i++) {
for (i = 0; i < playlist.length; i++) {
playlist.order[i] = i;
}
}
static void swapOrder(int a, int b) {
static void swapOrder(int a, int b)
{
int bak = playlist.order[a];
playlist.order[a] = playlist.order[b];
playlist.order[b] = bak;
}
static void randomizeOrder(int start,int end) {
static void randomizeOrder(int start, int end)
{
int i;
int ri;
DEBUG("playlist: randomize from %i to %i\n",start,end);
DEBUG("playlist: randomize from %i to %i\n", start, end);
if(playlist_state==PLAYLIST_STATE_PLAY) {
if(playlist.queued>=start && playlist.queued<=end) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist.queued >= start && playlist.queued <= end) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
}
}
for(i=start;i<=end;i++) {
ri = random()%(end-start+1)+start;
if(ri==playlist.current) playlist.current = i;
else if(i==playlist.current) playlist.current = ri;
swapOrder(i,ri);
for (i = start; i <= end; i++) {
ri = random() % (end - start + 1) + start;
if (ri == playlist.current)
playlist.current = i;
else if (i == playlist.current)
playlist.current = ri;
swapOrder(i, ri);
}
}
int setPlaylistRandomStatus(FILE * fp, int status) {
int setPlaylistRandomStatus(FILE * fp, int status)
{
int statusWas = playlist.random;
if(status!=0 && status!=1) {
if (status != 0 && status != 1) {
commandError(fp, ACK_ERROR_ARG, "\"%i\" is not 0 or 1", status);
return -1;
}
playlist.random = status;
if(status!=statusWas) {
if(playlist.random) {
if (status != statusWas) {
if (playlist.random) {
/*if(playlist_state==PLAYLIST_STATE_PLAY) {
randomizeOrder(playlist.current+1,
playlist.length-1);
}
else */randomizeOrder(0,playlist.length-1);
if(playlist.current >= 0 &&
playlist.current < playlist.length)
{
else */ randomizeOrder(0, playlist.length - 1);
if (playlist.current >= 0 &&
playlist.current < playlist.length) {
swapOrder(playlist.current, 0);
playlist.current = 0;
}
}
else orderPlaylist();
} else
orderPlaylist();
}
return 0;
}
int previousSongInPlaylist(FILE * fp) {
int previousSongInPlaylist(FILE * fp)
{
static time_t lastTime = 0;
time_t diff = time(NULL) - lastTime;
lastTime += diff;
if(playlist_state!=PLAYLIST_STATE_PLAY) return 0;
if (playlist_state != PLAYLIST_STATE_PLAY)
return 0;
syncPlaylistWithQueue(0);
if (diff && getPlayerElapsedTime() > PLAYLIST_PREV_UNLESS_ELAPSED) {
return playPlaylistOrderNumber(fp,playlist.current);
}
else {
if(playlist.current>0) {
return playPlaylistOrderNumber(fp,playlist.current-1);
}
else if(playlist.repeat) {
return playPlaylistOrderNumber(fp,playlist.length-1);
}
else {
return playPlaylistOrderNumber(fp,playlist.current);
return playPlaylistOrderNumber(fp, playlist.current);
} else {
if (playlist.current > 0) {
return playPlaylistOrderNumber(fp,
playlist.current - 1);
} else if (playlist.repeat) {
return playPlaylistOrderNumber(fp, playlist.length - 1);
} else {
return playPlaylistOrderNumber(fp, playlist.current);
}
}
return 0;
}
int shufflePlaylist(FILE * fp) {
int shufflePlaylist(FILE * fp)
{
int i;
int ri;
if(playlist.length>1) {
if(playlist_state==PLAYLIST_STATE_PLAY) {
if (playlist.length > 1) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
/* put current playing song first */
swapSongs(0,playlist.order[playlist.current]);
if(playlist.random) {
swapSongs(0, playlist.order[playlist.current]);
if (playlist.random) {
int j;
for(j=0;0!=playlist.order[j];j++);
for (j = 0; 0 != playlist.order[j]; j++) ;
playlist.current = j;
}
else playlist.current = 0;
} else
playlist.current = 0;
i = 1;
}
else {
} else {
i = 0;
playlist.current = -1;
}
/* shuffle the rest of the list */
for(;i<playlist.length;i++) {
ri = random()%(playlist.length-1)+1;
swapSongs(i,ri);
for (; i < playlist.length; i++) {
ri = random() % (playlist.length - 1) + 1;
swapSongs(i, ri);
}
incrPlaylistVersion();
......@@ -1268,17 +1338,19 @@ int shufflePlaylist(FILE * fp) {
return 0;
}
int deletePlaylist(FILE * fp, char * utf8file) {
char * file = utf8ToFsCharset(utf8file);
char * rfile = malloc(strlen(file)+strlen(".")+
strlen(PLAYLIST_FILE_SUFFIX)+1);
char * actualFile;
int deletePlaylist(FILE * fp, char *utf8file)
{
char *file = utf8ToFsCharset(utf8file);
char *rfile = malloc(strlen(file) + strlen(".") +
strlen(PLAYLIST_FILE_SUFFIX) + 1);
char *actualFile;
strcpy(rfile,file);
strcat(rfile,".");
strcat(rfile,PLAYLIST_FILE_SUFFIX);
strcpy(rfile, file);
strcat(rfile, ".");
strcat(rfile, PLAYLIST_FILE_SUFFIX);
if((actualFile = rpp2app(rfile)) && isPlaylist(actualFile)) free(rfile);
if ((actualFile = rpp2app(rfile)) && isPlaylist(actualFile))
free(rfile);
else {
free(rfile);
commandError(fp, ACK_ERROR_NO_EXIST,
......@@ -1286,7 +1358,7 @@ int deletePlaylist(FILE * fp, char * utf8file) {
return -1;
}
if(unlink(actualFile)<0) {
if (unlink(actualFile) < 0) {
commandError(fp, ACK_ERROR_SYSTEM,
"problems deleting file", NULL);
return -1;
......@@ -1295,16 +1367,17 @@ int deletePlaylist(FILE * fp, char * utf8file) {
return 0;
}
int savePlaylist(FILE * fp, char * utf8file) {
FILE * fileP;
int savePlaylist(FILE * fp, char *utf8file)
{
FILE *fileP;
int i;
struct stat st;
char * file;
char * rfile;
char * actualFile;
char * url;
char *file;
char *rfile;
char *actualFile;
char *url;
if(strstr(utf8file,"/")) {
if (strstr(utf8file, "/")) {
commandError(fp, ACK_ERROR_ARG,
"cannot save \"%s\", saving playlists to "
"subdirectories is not supported", utf8file);
......@@ -1313,12 +1386,12 @@ int savePlaylist(FILE * fp, char * utf8file) {
file = utf8ToFsCharset(utf8file);
rfile = malloc(strlen(file)+strlen(".")+
strlen(PLAYLIST_FILE_SUFFIX)+1);
rfile = malloc(strlen(file) + strlen(".") +
strlen(PLAYLIST_FILE_SUFFIX) + 1);
strcpy(rfile,file);
strcat(rfile,".");
strcat(rfile,PLAYLIST_FILE_SUFFIX);
strcpy(rfile, file);
strcat(rfile, ".");
strcat(rfile, PLAYLIST_FILE_SUFFIX);
free(file);
......@@ -1326,27 +1399,26 @@ int savePlaylist(FILE * fp, char * utf8file) {
free(rfile);
if(0==stat(actualFile,&st)) {
if (0 == stat(actualFile, &st)) {
commandError(fp, ACK_ERROR_EXIST, "a file or directory already "
"exists with the name \"%s\"", utf8file);
return -1;
}
while(!(fileP = fopen(actualFile,"w")) && errno==EINTR);
if(fileP==NULL) {
while (!(fileP = fopen(actualFile, "w")) && errno == EINTR) ;
if (fileP == NULL) {
commandError(fp, ACK_ERROR_SYSTEM, "problems opening file",
NULL);
return -1;
}
for(i=0;i<playlist.length;i++) {
if(playlist_saveAbsolutePaths &&
playlist.songs[i]->type==SONG_TYPE_FILE)
{
myfprintf(fileP,"%s\n",rmp2amp(utf8ToFsCharset((
getSongUrl(playlist.songs[i])))));
}
else {
for (i = 0; i < playlist.length; i++) {
if (playlist_saveAbsolutePaths &&
playlist.songs[i]->type == SONG_TYPE_FILE) {
myfprintf(fileP, "%s\n",
rmp2amp(utf8ToFsCharset
((getSongUrl(playlist.songs[i])))));
} else {
url = utf8ToFsCharset(getSongUrl(playlist.songs[i]));
myfprintf(fileP, "%s\n", url);
free(url);
......@@ -1354,89 +1426,101 @@ int savePlaylist(FILE * fp, char * utf8file) {
}
}
while(fclose(fileP) && errno==EINTR);
while (fclose(fileP) && errno == EINTR) ;
return 0;
}
int getPlaylistCurrentSong(void) {
if(playlist.current >= 0 && playlist.current < playlist.length) {
int getPlaylistCurrentSong(void)
{
if (playlist.current >= 0 && playlist.current < playlist.length) {
return playlist.order[playlist.current];
}
return -1;
}
unsigned long getPlaylistVersion(void) {
unsigned long getPlaylistVersion(void)
{
return playlist.version;
}
int getPlaylistLength(void) {
int getPlaylistLength(void)
{
return playlist.length;
}
int seekSongInPlaylist(FILE * fp, int song, float time) {
int seekSongInPlaylist(FILE * fp, int song, float time)
{
int i = song;
if(song<0 || song>=playlist.length) {
if (song < 0 || song >= playlist.length) {
commandError(fp, ACK_ERROR_NO_EXIST,
"song doesn't exist: \"%i\"", song);
return -1;
}
if(playlist.random) for(i=0;song!=playlist.order[i];i++);
if (playlist.random)
for (i = 0; song != playlist.order[i]; i++) ;
clearPlayerError();
playlist_stopOnError = 1;
playlist_errorCount = 0;
if(playlist_state == PLAYLIST_STATE_PLAY) {
if(playlist.queued>=0) {
if (playlist_state == PLAYLIST_STATE_PLAY) {
if (playlist.queued >= 0) {
lockPlaylistInteraction();
clearPlayerQueue();
unlockPlaylistInteraction();
}
}
else if(playPlaylistOrderNumber(fp,i)<0) return -1;
} else if (playPlaylistOrderNumber(fp, i) < 0)
return -1;
if(playlist.current!=i) {
if(playPlaylistOrderNumber(fp,i)<0) return -1;
if (playlist.current != i) {
if (playPlaylistOrderNumber(fp, i) < 0)
return -1;
}
return playerSeek(fp, playlist.songs[playlist.order[i]], time);
}
int seekSongInPlaylistById(FILE * fp, int id, float time) {
int seekSongInPlaylistById(FILE * fp, int id, float time)
{
checkSongId(id);
return seekSongInPlaylist(fp, playlist.idToPosition[id], time);
}
int getPlaylistSongId(int song) {
int getPlaylistSongId(int song)
{
return playlist.positionToId[song];
}
static int PlaylistIterFunc(FILE * fp, char * utf8file, void (*IterFunc)(FILE *fp, char *utf8_file, char **errored_File)) {
FILE * fileP;
char s[MAXPATHLEN+1];
static int PlaylistIterFunc(FILE * fp, char *utf8file,
void (*IterFunc) (FILE * fp, char *utf8_file,
char **errored_File))
{
FILE *fileP;
char s[MAXPATHLEN + 1];
int slength = 0;
char * temp = utf8ToFsCharset(utf8file);
char * rfile = malloc(strlen(temp)+strlen(".")+
strlen(PLAYLIST_FILE_SUFFIX)+1);
char * actualFile;
char * parent = parentPath(temp);
char *temp = utf8ToFsCharset(utf8file);
char *rfile = malloc(strlen(temp) + strlen(".") +
strlen(PLAYLIST_FILE_SUFFIX) + 1);
char *actualFile;
char *parent = parentPath(temp);
int parentlen = strlen(parent);
char * erroredFile = NULL;
char *erroredFile = NULL;
int tempInt;
int commentCharFound = 0;
strcpy(rfile,temp);
strcat(rfile,".");
strcat(rfile,PLAYLIST_FILE_SUFFIX);
strcpy(rfile, temp);
strcat(rfile, ".");
strcat(rfile, PLAYLIST_FILE_SUFFIX);
free(temp);
if((actualFile = rpp2app(rfile)) && isPlaylist(actualFile)) free(rfile);
if ((actualFile = rpp2app(rfile)) && isPlaylist(actualFile))
free(rfile);
else {
free(rfile);
commandError(fp, ACK_ERROR_NO_EXIST,
......@@ -1444,47 +1528,47 @@ static int PlaylistIterFunc(FILE * fp, char * utf8file, void (*IterFunc)(FILE *f
return -1;
}
while(!(fileP = fopen(actualFile,"r")) && errno==EINTR);
if(fileP==NULL) {
while (!(fileP = fopen(actualFile, "r")) && errno == EINTR) ;
if (fileP == NULL) {
commandError(fp, ACK_ERROR_SYSTEM,
"problems opening file \"%s\"", utf8file);
return -1;
}
while((tempInt = fgetc(fileP))!=EOF) {
while ((tempInt = fgetc(fileP)) != EOF) {
s[slength] = tempInt;
if(s[slength]=='\n' || s[slength]=='\0') {
if (s[slength] == '\n' || s[slength] == '\0') {
commentCharFound = 0;
s[slength] = '\0';
if(s[0]==PLAYLIST_COMMENT) {
if (s[0] == PLAYLIST_COMMENT) {
commentCharFound = 1;
}
if(strncmp(s,musicDir,strlen(musicDir))==0) {
strcpy(s,&(s[strlen(musicDir)]));
}
else if(parentlen) {
if (strncmp(s, musicDir, strlen(musicDir)) == 0) {
strcpy(s, &(s[strlen(musicDir)]));
} else if (parentlen) {
temp = strdup(s);
memset(s,0,MAXPATHLEN+1);
strcpy(s,parent);
strncat(s,"/",MAXPATHLEN-parentlen);
strncat(s,temp,MAXPATHLEN-parentlen-1);
if(strlen(s)>=MAXPATHLEN) {
memset(s, 0, MAXPATHLEN + 1);
strcpy(s, parent);
strncat(s, "/", MAXPATHLEN - parentlen);
strncat(s, temp, MAXPATHLEN - parentlen - 1);
if (strlen(s) >= MAXPATHLEN) {
commandError(fp,
ACK_ERROR_PLAYLIST_LOAD,
"\"%s\" too long",
temp);
"\"%s\" too long", temp);
free(temp);
while(fclose(fileP) && errno==EINTR);
if(erroredFile) free(erroredFile);
while (fclose(fileP)
&& errno == EINTR) ;
if (erroredFile)
free(erroredFile);
return -1;
}
free(temp);
}
slength = 0;
temp = fsCharsetToUtf8(s);
if(!temp) continue;
if(!commentCharFound)
{
if (!temp)
continue;
if (!commentCharFound) {
/* using temp directly should be safe,
* for our current IterFunction set
* but just in case, we copy to s */
......@@ -1492,23 +1576,23 @@ static int PlaylistIterFunc(FILE * fp, char * utf8file, void (*IterFunc)(FILE *f
IterFunc(fp, s, &erroredFile);
}
free(temp);
}
else if(slength==MAXPATHLEN) {
} else if (slength == MAXPATHLEN) {
s[slength] = '\0';
commandError(fp, ACK_ERROR_PLAYLIST_LOAD,
"line in \"%s\" is too long", utf8file);
ERROR("line \"%s\" in playlist \"%s\" is too long\n",
s, utf8file);
while(fclose(fileP) && errno==EINTR);
if(erroredFile) free(erroredFile);
while (fclose(fileP) && errno == EINTR) ;
if (erroredFile)
free(erroredFile);
return -1;
}
else if(s[slength]!='\r') slength++;
} else if (s[slength] != '\r')
slength++;
}
while(fclose(fileP) && errno==EINTR);
while (fclose(fileP) && errno == EINTR) ;
if(erroredFile) {
if (erroredFile) {
commandError(fp, ACK_ERROR_PLAYLIST_LOAD,
"can't add file \"%s\"", erroredFile);
free(erroredFile);
......@@ -1518,35 +1602,35 @@ static int PlaylistIterFunc(FILE * fp, char * utf8file, void (*IterFunc)(FILE *f
return 0;
}
static void PlaylistInfoPrintInfo(FILE *fp, char *utf8file, char **erroredfile) {
Song * song = getSongFromDB(utf8file);
if(song) {
static void PlaylistInfoPrintInfo(FILE * fp, char *utf8file, char **erroredfile)
{
Song *song = getSongFromDB(utf8file);
if (song) {
printSongInfo(fp, song);
}
else {
myfprintf(fp,"file: %s\n",utf8file);
} else {
myfprintf(fp, "file: %s\n", utf8file);
}
}
static void PlaylistInfoPrint(FILE *fp, char *utf8file, char **erroredfile) {
myfprintf(fp,"file: %s\n",utf8file);
static void PlaylistInfoPrint(FILE * fp, char *utf8file, char **erroredfile)
{
myfprintf(fp, "file: %s\n", utf8file);
}
static void PlaylistLoadIterFunc(FILE *fp, char *temp, char **erroredFile) {
if(!getSongFromDB(temp) && !isRemoteUrl(temp))
{
static void PlaylistLoadIterFunc(FILE * fp, char *temp, char **erroredFile)
{
if (!getSongFromDB(temp) && !isRemoteUrl(temp)) {
}
else if((addToPlaylist(stderr, temp, 0))<0) {
} else if ((addToPlaylist(stderr, temp, 0)) < 0) {
/* for windows compatibilit, convert slashes */
char * temp2 = strdup(temp);
char * p = temp2;
while(*p) {
if(*p=='\\') *p = '/';
char *temp2 = strdup(temp);
char *p = temp2;
while (*p) {
if (*p == '\\')
*p = '/';
p++;
}
if((addToPlaylist(stderr, temp2, 0))<0) {
if(!*erroredFile) {
if ((addToPlaylist(stderr, temp2, 0)) < 0) {
if (!*erroredFile) {
*erroredFile = strdup(temp);
}
}
......@@ -1554,13 +1638,15 @@ static void PlaylistLoadIterFunc(FILE *fp, char *temp, char **erroredFile) {
}
}
int PlaylistInfo(FILE * fp, char * utf8file, int detail) {
if(detail) {
int PlaylistInfo(FILE * fp, char *utf8file, int detail)
{
if (detail) {
return PlaylistIterFunc(fp, utf8file, PlaylistInfoPrintInfo);
}
return PlaylistIterFunc(fp, utf8file, PlaylistInfoPrint) ;
return PlaylistIterFunc(fp, utf8file, PlaylistInfoPrint);
}
int loadPlaylist(FILE * fp, char * utf8file) {
int loadPlaylist(FILE * fp, char *utf8file)
{
return PlaylistIterFunc(fp, utf8file, PlaylistLoadIterFunc);
}
......@@ -40,7 +40,7 @@ void savePlaylistState();
int clearPlaylist(FILE * fp);
int addToPlaylist(FILE * fp, char * file, int printId);
int addToPlaylist(FILE * fp, char *file, int printId);
int addSongToPlaylist(FILE * fp, Song * song, int printId);
......@@ -68,11 +68,11 @@ int previousSongInPlaylist(FILE * fp);
int shufflePlaylist(FILE * fp);
int savePlaylist(FILE * fp, char * utf8file);
int savePlaylist(FILE * fp, char *utf8file);
int deletePlaylist(FILE * fp, char * utf8file);
int deletePlaylist(FILE * fp, char *utf8file);
int deletePlaylistById(FILE * fp, char * utf8file);
int deletePlaylistById(FILE * fp, char *utf8file);
void deleteASongFromPlaylist(Song * song);
......@@ -84,7 +84,7 @@ int swapSongsInPlaylist(FILE * fp, int song1, int song2);
int swapSongsInPlaylistById(FILE * fp, int id1, int id2);
int loadPlaylist(FILE * fp, char * utf8file);
int loadPlaylist(FILE * fp, char *utf8file);
int getPlaylistRepeatStatus();
......@@ -114,8 +114,8 @@ int playlistChanges(FILE * fp, mpd_uint32 version);
int playlistChangesPosId(FILE * fp, mpd_uint32 version);
int PlaylistInfo(FILE * fp, char * utf8file, int detail);
int PlaylistInfo(FILE * fp, char *utf8file, int detail);
char * getStateFile();
char *getStateFile();
#endif
......@@ -31,18 +31,18 @@ static int replayGainState = REPLAYGAIN_OFF;
static float replayGainPreamp = 1.0;
void initReplayGainState(void) {
ConfigParam * param = getConfigParam(CONF_REPLAYGAIN);
void initReplayGainState(void)
{
ConfigParam *param = getConfigParam(CONF_REPLAYGAIN);
if(!param) return;
if (!param)
return;
if(strcmp(param->value, "track") == 0) {
if (strcmp(param->value, "track") == 0) {
replayGainState = REPLAYGAIN_TRACK;
}
else if(strcmp(param->value, "album") == 0) {
} else if (strcmp(param->value, "album") == 0) {
replayGainState = REPLAYGAIN_ALBUM;
}
else {
} else {
ERROR("replaygain value \"%s\" at line %i is invalid\n",
param->value, param->line);
exit(EXIT_FAILURE);
......@@ -50,43 +50,46 @@ void initReplayGainState(void) {
param = getConfigParam(CONF_REPLAYGAIN_PREAMP);
if(param) {
char * test;
if (param) {
char *test;
float f = strtod(param->value, &test);
if(*test != '\0') {
if (*test != '\0') {
ERROR("Replaygain preamp \"%s\" is not a number at "
"line %i\n", param->value, param->line);
exit(EXIT_FAILURE);
}
if(f < -15 || f > 15) {
if (f < -15 || f > 15) {
ERROR("Replaygain preamp \"%s\" is not between -15 and"
"15 at line %i\n",
param->value, param->line);
"15 at line %i\n", param->value, param->line);
exit(EXIT_FAILURE);
}
replayGainPreamp = pow(10, f/20.0);
replayGainPreamp = pow(10, f / 20.0);
}
}
static float computeReplayGainScale(float gain, float peak) {
static float computeReplayGainScale(float gain, float peak)
{
float scale;
if(gain == 0.0) return(1);
scale = pow(10.0, gain/20.0);
scale*= replayGainPreamp;
if(scale > 15.0) scale = 15.0;
if (gain == 0.0)
return (1);
scale = pow(10.0, gain / 20.0);
scale *= replayGainPreamp;
if (scale > 15.0)
scale = 15.0;
if (scale * peak > 1.0) {
scale = 1.0 / peak;
}
return(scale);
return (scale);
}
ReplayGainInfo * newReplayGainInfo(void) {
ReplayGainInfo * ret = malloc(sizeof(ReplayGainInfo));
ReplayGainInfo *newReplayGainInfo(void)
{
ReplayGainInfo *ret = malloc(sizeof(ReplayGainInfo));
ret->albumGain = 0.0;
ret->albumPeak = 0.0;
......@@ -100,22 +103,24 @@ ReplayGainInfo * newReplayGainInfo(void) {
return ret;
}
void freeReplayGainInfo(ReplayGainInfo * info) {
void freeReplayGainInfo(ReplayGainInfo * info)
{
free(info);
}
void doReplayGain(ReplayGainInfo * info, char * buffer, int bufferSize,
void doReplayGain(ReplayGainInfo * info, char *buffer, int bufferSize,
AudioFormat * format)
{
mpd_sint16 * buffer16;
mpd_sint8 * buffer8;
mpd_sint16 *buffer16;
mpd_sint8 *buffer8;
mpd_sint32 temp32;
float scale;
if(replayGainState == REPLAYGAIN_OFF || !info) return;
if (replayGainState == REPLAYGAIN_OFF || !info)
return;
if(info->scale < 0) {
switch(replayGainState) {
if (info->scale < 0) {
switch (replayGainState) {
case REPLAYGAIN_TRACK:
info->scale = computeReplayGainScale(info->trackGain,
info->trackPeak);
......@@ -127,30 +132,31 @@ void doReplayGain(ReplayGainInfo * info, char * buffer, int bufferSize,
}
}
if(info->scale <= 1.01 && info->scale >= 0.99) return;
if (info->scale <= 1.01 && info->scale >= 0.99)
return;
buffer16 = (mpd_sint16 *)buffer;
buffer8 = (mpd_sint8 *)buffer;
buffer16 = (mpd_sint16 *) buffer;
buffer8 = (mpd_sint8 *) buffer;
scale = info->scale;
switch(format->bits) {
switch (format->bits) {
case 16:
while(bufferSize > 0){
while (bufferSize > 0) {
temp32 = *buffer16;
temp32 *= scale;
*buffer16 = temp32>32767 ? 32767 :
(temp32<-32768 ? -32768 : temp32);
*buffer16 = temp32 > 32767 ? 32767 :
(temp32 < -32768 ? -32768 : temp32);
buffer16++;
bufferSize-=2;
bufferSize -= 2;
}
break;
case 8:
while(bufferSize>0){
while (bufferSize > 0) {
temp32 = *buffer8;
temp32 *= scale;
*buffer8 = temp32>127 ? 127 :
(temp32<-128 ? -128 : temp32);
*buffer8 = temp32 > 127 ? 127 :
(temp32 < -128 ? -128 : temp32);
buffer8++;
bufferSize--;
}
......
......@@ -32,17 +32,17 @@ typedef struct _ReplayGainInfo {
float trackGain;
float trackPeak;
/* used internally by mpd, to mess with it*/
/* used internally by mpd, to mess with it */
float scale;
} ReplayGainInfo;
ReplayGainInfo * newReplayGainInfo();
ReplayGainInfo *newReplayGainInfo();
void freeReplayGainInfo(ReplayGainInfo * info);
void initReplayGainState();
void doReplayGain(ReplayGainInfo * info, char * buffer, int bufferSize,
void doReplayGain(ReplayGainInfo * info, char *buffer, int bufferSize,
AudioFormat * format);
#endif
......@@ -39,23 +39,24 @@
extern volatile int masterPid;
extern volatile int mainPid;
int masterHandlePendingSignals() {
if(signal_is_pending(SIGINT) || signal_is_pending(SIGTERM)) {
int masterHandlePendingSignals()
{
if (signal_is_pending(SIGINT) || signal_is_pending(SIGTERM)) {
DEBUG("master process got SIGINT or SIGTERM, exiting\n");
return COMMAND_RETURN_KILL;
}
if(signal_is_pending(SIGHUP)) {
if (signal_is_pending(SIGHUP)) {
signal_clear(SIGHUP);
/* Forward it to the main process, which will update the DB */
kill(mainPid, SIGHUP);
}
return 0;
}
int handlePendingSignals() {
int handlePendingSignals()
{
/* this SIGUSR1 signal comes before the KILL signals, because there if the process is
* looping, waiting for this signal, it will not respond to the KILL signal. This might be
* better implemented by using bit-wise defines and or'ing of the COMMAND_FOO as return.
......@@ -66,87 +67,98 @@ int handlePendingSignals() {
return COMMAND_MASTER_READY;
}
if(signal_is_pending(SIGINT) || signal_is_pending(SIGTERM)) {
if (signal_is_pending(SIGINT) || signal_is_pending(SIGTERM)) {
DEBUG("main process got SIGINT or SIGTERM, exiting\n");
return COMMAND_RETURN_KILL;
}
if(signal_is_pending(SIGHUP)) {
if (signal_is_pending(SIGHUP)) {
DEBUG("got SIGHUP, rereading DB\n");
signal_clear(SIGHUP);
if(!isUpdatingDB()) {
if (!isUpdatingDB()) {
readDirectoryDB();
playlistVersionChange();
}
if(myfprintfCloseAndOpenLogFile()<0) return COMMAND_RETURN_KILL;
if (myfprintfCloseAndOpenLogFile() < 0)
return COMMAND_RETURN_KILL;
playerCycleLogFiles();
}
return 0;
}
void chldSigHandler(int signal) {
void chldSigHandler(int signal)
{
int status;
int pid;
DEBUG("main process got SIGCHLD\n");
while(0 != (pid = wait3(&status,WNOHANG,NULL))) {
if(pid<0) {
if(errno==EINTR) continue;
else break;
while (0 != (pid = wait3(&status, WNOHANG, NULL))) {
if (pid < 0) {
if (errno == EINTR)
continue;
else
break;
}
directory_sigChldHandler(pid,status);
directory_sigChldHandler(pid, status);
}
}
void masterChldSigHandler(int signal) {
void masterChldSigHandler(int signal)
{
int status;
int pid;
DEBUG("master process got SIGCHLD\n");
while(0 != (pid = wait3(&status,WNOHANG,NULL))) {
if(pid<0) {
if(errno==EINTR) continue;
else break;
while (0 != (pid = wait3(&status, WNOHANG, NULL))) {
if (pid < 0) {
if (errno == EINTR)
continue;
else
break;
}
DEBUG("PID: %d\n",pid);
if (pid == mainPid) kill(getpid(), SIGTERM);
player_sigChldHandler(pid,status);
DEBUG("PID: %d\n", pid);
if (pid == mainPid)
kill(getpid(), SIGTERM);
player_sigChldHandler(pid, status);
}
}
int playerInitReal();
void masterSigUsr2Handler(int signal) {
void masterSigUsr2Handler(int signal)
{
DEBUG("Master process got SIGUSR2 starting a new player process\n");
if (getPlayerPid() <= 0)
playerInitReal();
}
void masterInitSigHandlers() {
void masterInitSigHandlers()
{
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
while(sigaction(SIGPIPE,&sa,NULL)<0 && errno==EINTR);
while (sigaction(SIGPIPE, &sa, NULL) < 0 && errno == EINTR) ;
sa.sa_handler = masterChldSigHandler;
while(sigaction(SIGCHLD,&sa,NULL)<0 && errno==EINTR);
while (sigaction(SIGCHLD, &sa, NULL) < 0 && errno == EINTR) ;
sa.sa_handler = masterSigUsr2Handler;
while(sigaction(SIGUSR2,&sa,NULL)<0 && errno==EINTR);
while (sigaction(SIGUSR2, &sa, NULL) < 0 && errno == EINTR) ;
signal_handle(SIGUSR1);
signal_handle(SIGINT);
signal_handle(SIGTERM);
signal_handle(SIGHUP);
}
void initSigHandlers() {
void initSigHandlers()
{
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
while(sigaction(SIGPIPE,&sa,NULL)<0 && errno==EINTR);
while (sigaction(SIGPIPE, &sa, NULL) < 0 && errno == EINTR) ;
sa.sa_handler = chldSigHandler;
while(sigaction(SIGCHLD,&sa,NULL)<0 && errno==EINTR);
while (sigaction(SIGCHLD, &sa, NULL) < 0 && errno == EINTR) ;
signal_handle(SIGUSR2);
signal_handle(SIGUSR1);
signal_handle(SIGINT);
......@@ -154,14 +166,16 @@ void initSigHandlers() {
signal_handle(SIGHUP);
}
void finishSigHandlers() {
void finishSigHandlers()
{
signal_unhandle(SIGINT);
signal_unhandle(SIGUSR1);
signal_unhandle(SIGTERM);
signal_unhandle(SIGHUP);
}
void setSigHandlersForDecoder() {
void setSigHandlersForDecoder()
{
struct sigaction sa;
finishSigHandlers();
......@@ -169,65 +183,69 @@ void setSigHandlersForDecoder() {
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
while(sigaction(SIGHUP,&sa,NULL)<0 && errno==EINTR);
while(sigaction(SIGINT,&sa,NULL)<0 && errno==EINTR);
while (sigaction(SIGHUP, &sa, NULL) < 0 && errno == EINTR) ;
while (sigaction(SIGINT, &sa, NULL) < 0 && errno == EINTR) ;
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = decodeSigHandler;
while(sigaction(SIGCHLD,&sa,NULL)<0 && errno==EINTR);
while(sigaction(SIGTERM,&sa,NULL)<0 && errno==EINTR);
while (sigaction(SIGCHLD, &sa, NULL) < 0 && errno == EINTR) ;
while (sigaction(SIGTERM, &sa, NULL) < 0 && errno == EINTR) ;
}
void ignoreSignals() {
void ignoreSignals()
{
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sa.sa_sigaction = NULL;
while(sigaction(SIGPIPE,&sa,NULL)<0 && errno==EINTR);
while(sigaction(SIGCHLD,&sa,NULL)<0 && errno==EINTR);
while(sigaction(SIGUSR1,&sa,NULL)<0 && errno==EINTR);
while(sigaction(SIGUSR2,&sa,NULL)<0 && errno==EINTR);
while(sigaction(SIGINT,&sa,NULL)<0 && errno==EINTR);
while(sigaction(SIGTERM,&sa,NULL)<0 && errno==EINTR);
while(sigaction(SIGHUP,&sa,NULL)<0 && errno==EINTR);
while (sigaction(SIGPIPE, &sa, NULL) < 0 && errno == EINTR) ;
while (sigaction(SIGCHLD, &sa, NULL) < 0 && errno == EINTR) ;
while (sigaction(SIGUSR1, &sa, NULL) < 0 && errno == EINTR) ;
while (sigaction(SIGUSR2, &sa, NULL) < 0 && errno == EINTR) ;
while (sigaction(SIGINT, &sa, NULL) < 0 && errno == EINTR) ;
while (sigaction(SIGTERM, &sa, NULL) < 0 && errno == EINTR) ;
while (sigaction(SIGHUP, &sa, NULL) < 0 && errno == EINTR) ;
}
void waitOnSignals() {
void waitOnSignals()
{
sigset_t sset;
sigfillset(&sset);
sigdelset(&sset,SIGCHLD);
sigdelset(&sset,SIGUSR1);
sigdelset(&sset,SIGUSR2);
sigdelset(&sset,SIGHUP);
sigdelset(&sset,SIGINT);
sigdelset(&sset,SIGTERM);
sigdelset(&sset, SIGCHLD);
sigdelset(&sset, SIGUSR1);
sigdelset(&sset, SIGUSR2);
sigdelset(&sset, SIGHUP);
sigdelset(&sset, SIGINT);
sigdelset(&sset, SIGTERM);
sigsuspend(&sset);
}
void blockSignals() {
void blockSignals()
{
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset,SIGCHLD);
sigaddset(&sset,SIGUSR1);
sigaddset(&sset,SIGUSR2);
sigaddset(&sset,SIGHUP);
sigaddset(&sset,SIGINT);
sigaddset(&sset,SIGTERM);
while(sigprocmask(SIG_BLOCK,&sset,NULL)<0 && errno==EINTR);
sigaddset(&sset, SIGCHLD);
sigaddset(&sset, SIGUSR1);
sigaddset(&sset, SIGUSR2);
sigaddset(&sset, SIGHUP);
sigaddset(&sset, SIGINT);
sigaddset(&sset, SIGTERM);
while (sigprocmask(SIG_BLOCK, &sset, NULL) < 0 && errno == EINTR) ;
}
void unblockSignals() {
void unblockSignals()
{
sigset_t sset;
sigemptyset(&sset);
sigaddset(&sset,SIGCHLD);
sigaddset(&sset,SIGUSR1);
sigaddset(&sset,SIGUSR2);
sigaddset(&sset,SIGHUP);
sigaddset(&sset,SIGINT);
sigaddset(&sset,SIGTERM);
while(sigprocmask(SIG_UNBLOCK,&sset,NULL)<0 && errno==EINTR);
sigaddset(&sset, SIGCHLD);
sigaddset(&sset, SIGUSR1);
sigaddset(&sset, SIGUSR2);
sigaddset(&sset, SIGHUP);
sigaddset(&sset, SIGINT);
sigaddset(&sset, SIGTERM);
while (sigprocmask(SIG_UNBLOCK, &sset, NULL) < 0 && errno == EINTR) ;
}
......@@ -29,13 +29,13 @@ static void __signal_handler(int sig)
__caught_signals[sig] = 1;
}
static void __set_signal_handler(int sig, void (* handler)(int))
static void __set_signal_handler(int sig, void (*handler) (int))
{
struct sigaction act;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
act.sa_handler = handler;
while(sigaction(sig, &act, NULL) && errno==EINTR);
while (sigaction(sig, &act, NULL) && errno == EINTR) ;
}
void signal_handle(int sig)
......
......@@ -35,8 +35,9 @@
#include <string.h>
#include <assert.h>
Song * newNullSong(void) {
Song * song = malloc(sizeof(Song));
Song *newNullSong(void)
{
Song *song = malloc(sizeof(Song));
song->tag = NULL;
song->url = NULL;
......@@ -46,11 +47,12 @@ Song * newNullSong(void) {
return song;
}
Song * newSong(char * url, int type, Directory * parentDir) {
Song * song = NULL;
Song *newSong(char *url, int type, Directory * parentDir)
{
Song *song = NULL;
if(strchr(url, '\n')) {
DEBUG("newSong: '%s' is not a valid uri\n",url);
if (strchr(url, '\n')) {
DEBUG("newSong: '%s' is not a valid uri\n", url);
return NULL;
}
......@@ -62,16 +64,17 @@ Song * newSong(char * url, int type, Directory * parentDir) {
assert(type == SONG_TYPE_URL || parentDir);
if(song->type == SONG_TYPE_FILE) {
InputPlugin * plugin;
if (song->type == SONG_TYPE_FILE) {
InputPlugin *plugin;
unsigned int next = 0;
char * song_url = getSongUrl(song);
char * abs_path = rmp2amp(utf8ToFsCharset(song_url));
while(!song->tag && (plugin = isMusic(song_url,
&(song->mtime), next++))) {
char *song_url = getSongUrl(song);
char *abs_path = rmp2amp(utf8ToFsCharset(song_url));
while (!song->tag && (plugin = isMusic(song_url,
&(song->mtime),
next++))) {
song->tag = plugin->tagDupFunc(abs_path);
}
if(!song->tag || song->tag->time<0) {
if (!song->tag || song->tag->time < 0) {
freeSong(song);
song = NULL;
}
......@@ -80,30 +83,34 @@ Song * newSong(char * url, int type, Directory * parentDir) {
return song;
}
void freeSong(Song * song) {
void freeSong(Song * song)
{
deleteASongFromPlaylist(song);
freeJustSong(song);
}
void freeJustSong(Song * song) {
void freeJustSong(Song * song)
{
free(song->url);
if(song->tag) freeMpdTag(song->tag);
if (song->tag)
freeMpdTag(song->tag);
free(song);
getSongUrl(NULL);
}
SongList * newSongList(void) {
return makeList((ListFreeDataFunc *)freeSong, 0);
SongList *newSongList(void)
{
return makeList((ListFreeDataFunc *) freeSong, 0);
}
Song * addSongToList(SongList * list, char * url, char * utf8path,
Song *addSongToList(SongList * list, char *url, char *utf8path,
int songType, Directory * parentDirectory)
{
Song * song = NULL;
Song *song = NULL;
switch(songType) {
switch (songType) {
case SONG_TYPE_FILE:
if(isMusic(utf8path, NULL, 0)) {
if (isMusic(utf8path, NULL, 0)) {
song = newSong(url, songType, parentDirectory);
}
break;
......@@ -114,80 +121,86 @@ Song * addSongToList(SongList * list, char * url, char * utf8path,
DEBUG("addSongToList: Trying to add an invalid song type\n");
}
if(song==NULL) return NULL;
if (song == NULL)
return NULL;
insertInList(list, song->url, (void *)song);
return song;
}
void freeSongList(SongList * list) {
void freeSongList(SongList * list)
{
freeList(list);
}
void printSongUrl(FILE * fp, Song * song) {
if(song->parentDir && song->parentDir->path) {
void printSongUrl(FILE * fp, Song * song)
{
if (song->parentDir && song->parentDir->path) {
myfprintf(fp, "%s%s/%s\n", SONG_FILE,
getDirectoryPath(song->parentDir), song->url);
}
else {
} else {
myfprintf(fp, "%s%s\n", SONG_FILE, song->url);
}
}
int printSongInfo(FILE * fp, Song * song) {
int printSongInfo(FILE * fp, Song * song)
{
printSongUrl(fp, song);
if(song->tag) printMpdTag(fp,song->tag);
if (song->tag)
printMpdTag(fp, song->tag);
return 0;
}
int printSongInfoFromList(FILE * fp, SongList * list) {
ListNode * tempNode = list->firstNode;
int printSongInfoFromList(FILE * fp, SongList * list)
{
ListNode *tempNode = list->firstNode;
while(tempNode!=NULL) {
printSongInfo(fp,(Song *)tempNode->data);
while (tempNode != NULL) {
printSongInfo(fp, (Song *) tempNode->data);
tempNode = tempNode->nextNode;
}
return 0;
}
void writeSongInfoFromList(FILE * fp, SongList * list) {
ListNode * tempNode = list->firstNode;
void writeSongInfoFromList(FILE * fp, SongList * list)
{
ListNode *tempNode = list->firstNode;
myfprintf(fp,"%s\n",SONG_BEGIN);
myfprintf(fp, "%s\n", SONG_BEGIN);
while(tempNode!=NULL) {
myfprintf(fp,"%s%s\n",SONG_KEY,tempNode->key);
printSongInfo(fp,(Song *)tempNode->data);
myfprintf(fp,"%s%li\n",SONG_MTIME,(long)((Song *)tempNode->data)->mtime);
while (tempNode != NULL) {
myfprintf(fp, "%s%s\n", SONG_KEY, tempNode->key);
printSongInfo(fp, (Song *) tempNode->data);
myfprintf(fp, "%s%li\n", SONG_MTIME,
(long)((Song *) tempNode->data)->mtime);
tempNode = tempNode->nextNode;
}
myfprintf(fp,"%s\n",SONG_END);
myfprintf(fp, "%s\n", SONG_END);
}
static void insertSongIntoList(SongList * list, ListNode ** nextSongNode, char * key,
Song * song)
static void insertSongIntoList(SongList * list, ListNode ** nextSongNode,
char *key, Song * song)
{
ListNode * nodeTemp;
int cmpRet= 0;
ListNode *nodeTemp;
int cmpRet = 0;
while(*nextSongNode && (cmpRet = strcmp(key,(*nextSongNode)->key)) > 0)
{
while (*nextSongNode
&& (cmpRet = strcmp(key, (*nextSongNode)->key)) > 0) {
nodeTemp = (*nextSongNode)->nextNode;
deleteNodeFromList(list,*nextSongNode);
deleteNodeFromList(list, *nextSongNode);
*nextSongNode = nodeTemp;
}
if(!(*nextSongNode)) {
if (!(*nextSongNode)) {
insertInList(list, song->url, (void *)song);
}
else if(cmpRet == 0) {
Song * tempSong = (Song *)((*nextSongNode)->data);
if(tempSong->mtime != song->mtime) {
} else if (cmpRet == 0) {
Song *tempSong = (Song *) ((*nextSongNode)->data);
if (tempSong->mtime != song->mtime) {
freeMpdTag(tempSong->tag);
tempSong->tag = song->tag;
tempSong->mtime = song->mtime;
......@@ -195,20 +208,19 @@ static void insertSongIntoList(SongList * list, ListNode ** nextSongNode, char *
}
freeJustSong(song);
*nextSongNode = (*nextSongNode)->nextNode;
}
else {
} else {
insertInListBeforeNode(list, *nextSongNode, -1, song->url,
(void *)song);
}
}
static int matchesAnMpdTagItemKey(char * buffer, int * itemType) {
static int matchesAnMpdTagItemKey(char *buffer, int *itemType)
{
int i;
for(i = 0; i < TAG_NUM_OF_ITEM_TYPES; i++) {
if( 0 == strncmp(mpdTagItemKeys[i], buffer,
strlen(mpdTagItemKeys[i])))
{
for (i = 0; i < TAG_NUM_OF_ITEM_TYPES; i++) {
if (0 == strncmp(mpdTagItemKeys[i], buffer,
strlen(mpdTagItemKeys[i]))) {
*itemType = i;
return 1;
}
......@@ -217,84 +229,88 @@ static int matchesAnMpdTagItemKey(char * buffer, int * itemType) {
return 0;
}
void readSongInfoIntoList(FILE * fp, SongList * list, Directory * parentDir) {
char buffer[MAXPATHLEN+1024];
int bufferSize = MAXPATHLEN+1024;
Song * song = NULL;
ListNode * nextSongNode = list->firstNode;
ListNode * nodeTemp;
void readSongInfoIntoList(FILE * fp, SongList * list, Directory * parentDir)
{
char buffer[MAXPATHLEN + 1024];
int bufferSize = MAXPATHLEN + 1024;
Song *song = NULL;
ListNode *nextSongNode = list->firstNode;
ListNode *nodeTemp;
int itemType;
while(myFgets(buffer,bufferSize,fp) && 0!=strcmp(SONG_END,buffer)) {
if(0==strncmp(SONG_KEY,buffer,strlen(SONG_KEY))) {
if(song) {
insertSongIntoList(list,&nextSongNode,
song->url,
song);
while (myFgets(buffer, bufferSize, fp) && 0 != strcmp(SONG_END, buffer)) {
if (0 == strncmp(SONG_KEY, buffer, strlen(SONG_KEY))) {
if (song) {
insertSongIntoList(list, &nextSongNode,
song->url, song);
song = NULL;
}
song = newNullSong();
song->url = strdup(buffer+strlen(SONG_KEY));
song->url = strdup(buffer + strlen(SONG_KEY));
song->type = SONG_TYPE_FILE;
song->parentDir = parentDir;
}
else if(0==strncmp(SONG_FILE,buffer,strlen(SONG_FILE))) {
if(!song) {
} else if (0 == strncmp(SONG_FILE, buffer, strlen(SONG_FILE))) {
if (!song) {
ERROR("Problems reading song info\n");
exit(EXIT_FAILURE);
}
/* we don't need this info anymore
song->url = strdup(&(buffer[strlen(SONG_FILE)]));
*/
}
else if(matchesAnMpdTagItemKey(buffer, &itemType)) {
if(!song->tag) song->tag = newMpdTag();
} else if (matchesAnMpdTagItemKey(buffer, &itemType)) {
if (!song->tag)
song->tag = newMpdTag();
addItemToMpdTag(song->tag, itemType,
&(buffer[strlen(mpdTagItemKeys[itemType])+2]));
}
else if(0==strncmp(SONG_TIME,buffer,strlen(SONG_TIME))) {
if(!song->tag) song->tag = newMpdTag();
&(buffer
[strlen(mpdTagItemKeys[itemType]) +
2]));
} else if (0 == strncmp(SONG_TIME, buffer, strlen(SONG_TIME))) {
if (!song->tag)
song->tag = newMpdTag();
song->tag->time = atoi(&(buffer[strlen(SONG_TIME)]));
}
else if(0==strncmp(SONG_MTIME,buffer,strlen(SONG_MTIME))) {
} else if (0 == strncmp(SONG_MTIME, buffer, strlen(SONG_MTIME))) {
song->mtime = atoi(&(buffer[strlen(SONG_MTIME)]));
}
/* ignore empty lines (starting with '\0') */
else if(*buffer){
ERROR("songinfo: unknown line in db: %s\n",buffer);
else if (*buffer) {
ERROR("songinfo: unknown line in db: %s\n", buffer);
exit(EXIT_FAILURE);
}
}
if(song) {
if (song) {
insertSongIntoList(list, &nextSongNode, song->url, song);
song = NULL;
}
while(nextSongNode) {
while (nextSongNode) {
nodeTemp = nextSongNode->nextNode;
deleteNodeFromList(list,nextSongNode);
deleteNodeFromList(list, nextSongNode);
nextSongNode = nodeTemp;
}
}
int updateSongInfo(Song * song) {
if(song->type == SONG_TYPE_FILE) {
InputPlugin * plugin;
int updateSongInfo(Song * song)
{
if (song->type == SONG_TYPE_FILE) {
InputPlugin *plugin;
unsigned int next = 0;
char * song_url = getSongUrl(song);
char * abs_path = rmp2amp(song_url);
char *song_url = getSongUrl(song);
char *abs_path = rmp2amp(song_url);
if(song->tag) freeMpdTag(song->tag);
if (song->tag)
freeMpdTag(song->tag);
song->tag = NULL;
while(!song->tag && (plugin = isMusic(song_url,
&(song->mtime), next++))) {
while (!song->tag && (plugin = isMusic(song_url,
&(song->mtime),
next++))) {
song->tag = plugin->tagDupFunc(abs_path);
}
if(!song->tag || song->tag->time<0) return -1;
if (!song->tag || song->tag->time < 0)
return -1;
}
return 0;
......@@ -302,37 +318,40 @@ int updateSongInfo(Song * song) {
/* pass song = NULL to reset, we do this freeJustSong(), so that if
* we free and recreate this memory we make sure to print it correctly*/
char * getSongUrl(Song * song) {
static char * buffer = NULL;
char *getSongUrl(Song * song)
{
static char *buffer = NULL;
static int bufferSize = 0;
static Song * lastSong = NULL;
static Song *lastSong = NULL;
int slen;
int dlen;
int size;
if(!song) {
if (!song) {
lastSong = song;
return NULL;
}
if(!song->parentDir || !song->parentDir->path) return song->url;
if (!song->parentDir || !song->parentDir->path)
return song->url;
/* be careful with this!*/
if(song == lastSong) return buffer;
/* be careful with this! */
if (song == lastSong)
return buffer;
slen = strlen(song->url);
dlen = strlen(getDirectoryPath(song->parentDir));
size = slen+dlen+2;
size = slen + dlen + 2;
if(size > bufferSize) {
if (size > bufferSize) {
buffer = realloc(buffer, size);
bufferSize = size;
}
strcpy(buffer, getDirectoryPath(song->parentDir));
buffer[dlen] = '/';
strcpy(buffer+dlen+1, song->url);
strcpy(buffer + dlen + 1, song->url);
return buffer;
}
......@@ -34,29 +34,29 @@
#define SONG_TYPE_URL 2
typedef struct _Song {
char * url;
char *url;
mpd_sint8 type;
MpdTag * tag;
struct _Directory * parentDir;
MpdTag *tag;
struct _Directory *parentDir;
time_t mtime;
} Song;
typedef List SongList;
Song * newNullSong();
Song *newNullSong();
Song * newSong(char * url, int songType, struct _Directory * parentDir);
Song *newSong(char *url, int songType, struct _Directory *parentDir);
void freeSong(Song *);
void freeJustSong(Song *);
SongList * newSongList();
SongList *newSongList();
void freeSongList(SongList * list);
Song * addSongToList(SongList * list, char * url, char * utf8path,
int songType, struct _Directory * parentDir);
Song *addSongToList(SongList * list, char *url, char *utf8path,
int songType, struct _Directory *parentDir);
int printSongInfo(FILE * fp, Song * song);
......@@ -65,12 +65,12 @@ int printSongInfoFromList(FILE * fp, SongList * list);
void writeSongInfoFromList(FILE * fp, SongList * list);
void readSongInfoIntoList(FILE * fp, SongList * list,
struct _Directory * parent);
struct _Directory *parent);
int updateSongInfo(Song * song);
void printSongUrl(FILE * fp, Song * song);
char * getSongUrl(Song * song);
char *getSongUrl(Song * song);
#endif
......@@ -28,18 +28,21 @@
Stats stats;
void initStats(void) {
void initStats(void)
{
stats.daemonStart = time(NULL);
stats.numberOfSongs = 0;
}
int printStats(FILE * fp) {
myfprintf(fp,"artists: %li\n", getNumberOfTagItems(TAG_ITEM_ARTIST));
myfprintf(fp,"albums: %li\n", getNumberOfTagItems(TAG_ITEM_ALBUM));
myfprintf(fp,"songs: %i\n",stats.numberOfSongs);
myfprintf(fp,"uptime: %li\n",time(NULL)-stats.daemonStart);
myfprintf(fp,"playtime: %li\n",(long)(getPlayerTotalPlayTime()+0.5));
myfprintf(fp,"db_playtime: %li\n",stats.dbPlayTime);
myfprintf(fp,"db_update: %li\n",getDbModTime());
int printStats(FILE * fp)
{
myfprintf(fp, "artists: %li\n", getNumberOfTagItems(TAG_ITEM_ARTIST));
myfprintf(fp, "albums: %li\n", getNumberOfTagItems(TAG_ITEM_ALBUM));
myfprintf(fp, "songs: %i\n", stats.numberOfSongs);
myfprintf(fp, "uptime: %li\n", time(NULL) - stats.daemonStart);
myfprintf(fp, "playtime: %li\n",
(long)(getPlayerTotalPlayTime() + 0.5));
myfprintf(fp, "db_playtime: %li\n", stats.dbPlayTime);
myfprintf(fp, "db_update: %li\n", getDbModTime());
return 0;
}
......@@ -28,7 +28,7 @@ typedef struct _Stats {
int numberOfSongs;
unsigned long dbPlayTime;
/*unsigned long playTime;
unsigned long songsPlayed;*/
unsigned long songsPlayed; */
} Stats;
extern Stats stats;
......
......@@ -55,8 +55,7 @@
#endif
#endif
char * mpdTagItemKeys[TAG_NUM_OF_ITEM_TYPES] =
{
char *mpdTagItemKeys[TAG_NUM_OF_ITEM_TYPES] = {
"Artist",
"Album",
"Title",
......@@ -72,12 +71,13 @@ char * mpdTagItemKeys[TAG_NUM_OF_ITEM_TYPES] =
static mpd_sint8 ignoreTagItems[TAG_NUM_OF_ITEM_TYPES];
void initTagConfig(void) {
void initTagConfig(void)
{
int quit = 0;
char * temp;
char * s;
char * c;
ConfigParam * param;
char *temp;
char *s;
char *c;
ConfigParam *param;
int i;
/* parse the "metadata_to_use" config parameter below */
......@@ -87,24 +87,27 @@ void initTagConfig(void) {
param = getConfigParam(CONF_METADATA_TO_USE);
if(!param) return;
if (!param)
return;
memset(ignoreTagItems, 1, TAG_NUM_OF_ITEM_TYPES);
if(0 == strcasecmp(param->value, "none")) return;
if (0 == strcasecmp(param->value, "none"))
return;
temp = c = s = strdup(param->value);
while(!quit) {
if(*s == ',' || *s == '\0') {
if(*s == '\0') quit = 1;
while (!quit) {
if (*s == ',' || *s == '\0') {
if (*s == '\0')
quit = 1;
*s = '\0';
for(i = 0; i < TAG_NUM_OF_ITEM_TYPES; i++) {
if(strcasecmp(c, mpdTagItemKeys[i]) == 0) {
for (i = 0; i < TAG_NUM_OF_ITEM_TYPES; i++) {
if (strcasecmp(c, mpdTagItemKeys[i]) == 0) {
ignoreTagItems[i] = 0;
break;
}
}
if(strlen(c) && i == TAG_NUM_OF_ITEM_TYPES) {
if (strlen(c) && i == TAG_NUM_OF_ITEM_TYPES) {
ERROR("error parsing metadata item \"%s\" at "
"line %i\n", c, param->line);
exit(EXIT_FAILURE);
......@@ -118,47 +121,53 @@ void initTagConfig(void) {
free(temp);
}
void printMpdTag(FILE * fp, MpdTag * tag) {
void printMpdTag(FILE * fp, MpdTag * tag)
{
int i;
if(tag->time>=0) myfprintf(fp,"Time: %i\n",tag->time);
if (tag->time >= 0)
myfprintf(fp, "Time: %i\n", tag->time);
for(i = 0; i < tag->numOfItems; i++) {
for (i = 0; i < tag->numOfItems; i++) {
myfprintf(fp, "%s: %s\n", mpdTagItemKeys[tag->items[i].type],
tag->items[i].value);
}
}
#ifdef HAVE_ID3TAG
MpdTag * getID3Info(struct id3_tag * tag, char * id, int type, MpdTag * mpdTag)
MpdTag *getID3Info(struct id3_tag *tag, char *id, int type, MpdTag * mpdTag)
{
struct id3_frame const * frame;
id3_ucs4_t const * ucs4;
id3_utf8_t * utf8;
union id3_field const * field;
struct id3_frame const *frame;
id3_ucs4_t const *ucs4;
id3_utf8_t *utf8;
union id3_field const *field;
unsigned int nstrings;
int i;
char * isostr;
char * encoding;
char *isostr;
char *encoding;
frame = id3_tag_findframe(tag, id, 0);
if(!frame || frame->nfields < 2) return mpdTag;
if (!frame || frame->nfields < 2)
return mpdTag;
field = &frame->fields[1];
nstrings = id3_field_getnstrings(field);
for(i = 0; i < nstrings; i++) {
for (i = 0; i < nstrings; i++) {
ucs4 = id3_field_getstrings(field, i);
if(!ucs4) continue;
if (!ucs4)
continue;
if(type == TAG_ITEM_GENRE) ucs4 = id3_genre_name(ucs4);
if (type == TAG_ITEM_GENRE)
ucs4 = id3_genre_name(ucs4);
utf8 = id3_ucs4_utf8duplicate(ucs4);
if(!utf8) continue;
if (!utf8)
continue;
if(isId3v1(tag)) {
if (isId3v1(tag)) {
encoding = getConfigParamValue(CONF_ID3V1_ENCODING);
if(encoding) {
if (encoding) {
setCharSetConversion("ISO-8859-1", "UTF-8");
isostr = convStrDup(utf8);
free(utf8);
......@@ -168,7 +177,8 @@ MpdTag * getID3Info(struct id3_tag * tag, char * id, int type, MpdTag * mpdTag)
}
}
if(mpdTag == NULL) mpdTag = newMpdTag();
if (mpdTag == NULL)
mpdTag = newMpdTag();
addItemToMpdTag(mpdTag, type, utf8);
free(utf8);
......@@ -179,8 +189,9 @@ MpdTag * getID3Info(struct id3_tag * tag, char * id, int type, MpdTag * mpdTag)
#endif
#ifdef HAVE_ID3TAG
MpdTag * parseId3Tag(struct id3_tag * tag) {
MpdTag * ret = NULL;
MpdTag *parseId3Tag(struct id3_tag * tag)
{
MpdTag *ret = NULL;
ret = getID3Info(tag, ID3_FRAME_ARTIST, TAG_ITEM_ARTIST, ret);
ret = getID3Info(tag, ID3_FRAME_TITLE, TAG_ITEM_TITLE, ret);
......@@ -197,10 +208,11 @@ MpdTag * parseId3Tag(struct id3_tag * tag) {
#endif
#ifdef HAVE_ID3TAG
static int fillBuffer(void *buf, size_t size, FILE *stream,
static int fillBuffer(void *buf, size_t size, FILE * stream,
long offset, int whence)
{
if (fseek(stream, offset, whence) != 0) return 0;
if (fseek(stream, offset, whence) != 0)
return 0;
return fread(buf, 1, size, stream);
}
#endif
......@@ -212,28 +224,31 @@ static int getId3v2FooterSize(FILE * stream, long offset, int whence)
int bufsize;
bufsize = fillBuffer(buf, ID3_TAG_QUERYSIZE, stream, offset, whence);
if (bufsize <= 0) return 0;
if (bufsize <= 0)
return 0;
return id3_tag_query(buf, bufsize);
}
#endif
#ifdef HAVE_ID3TAG
static struct id3_tag * getId3Tag(FILE * stream, long offset, int whence)
static struct id3_tag *getId3Tag(FILE * stream, long offset, int whence)
{
struct id3_tag * tag;
id3_byte_t * buf[ID3_TAG_BUFLEN];
id3_byte_t * mbuf;
struct id3_tag *tag;
id3_byte_t *buf[ID3_TAG_BUFLEN];
id3_byte_t *mbuf;
int tagsize;
int bufsize;
int mbufsize;
/* It's ok if we get less than we asked for */
bufsize = fillBuffer(buf, ID3_TAG_BUFLEN, stream, offset, whence);
if (bufsize <= 0) return NULL;
if (bufsize <= 0)
return NULL;
/* Look for a tag header */
tagsize = id3_tag_query((const id3_byte_t *)buf, bufsize);
if (tagsize <= 0) return NULL;
if (tagsize <= 0)
return NULL;
if (tagsize <= bufsize) {
/* Got an id3 tag, and it fits in buf */
......@@ -241,7 +256,8 @@ static struct id3_tag * getId3Tag(FILE * stream, long offset, int whence)
} else {
/* Got an id3tag that overflows buf, so get a new one */
mbuf = malloc(tagsize);
if (!mbuf) return NULL;
if (!mbuf)
return NULL;
mbufsize = fillBuffer(mbuf, tagsize, stream, offset, whence);
if (mbufsize < tagsize) {
......@@ -259,11 +275,11 @@ static struct id3_tag * getId3Tag(FILE * stream, long offset, int whence)
#endif
#ifdef HAVE_ID3TAG
static struct id3_tag * findId3TagFromBeginning(FILE * stream)
static struct id3_tag *findId3TagFromBeginning(FILE * stream)
{
struct id3_tag * tag;
struct id3_tag * seektag;
struct id3_frame * frame;
struct id3_tag *tag;
struct id3_tag *seektag;
struct id3_frame *frame;
int seek;
tag = getId3Tag(stream, 0, SEEK_SET);
......@@ -279,11 +295,13 @@ static struct id3_tag * findId3TagFromBeginning(FILE * stream)
while ((frame = id3_tag_findframe(tag, "SEEK", 0))) {
/* Found a SEEK frame, get it's value */
seek = id3_field_getint(id3_frame_field(frame, 0));
if (seek < 0) break;
if (seek < 0)
break;
/* Get the tag specified by the SEEK frame */
seektag = getId3Tag(stream, seek, SEEK_CUR);
if (!seektag || isId3v1(seektag)) break;
if (!seektag || isId3v1(seektag))
break;
/* Replace the old tag with the new one */
id3_tag_delete(tag);
......@@ -295,10 +313,10 @@ static struct id3_tag * findId3TagFromBeginning(FILE * stream)
#endif
#ifdef HAVE_ID3TAG
static struct id3_tag * findId3TagFromEnd(FILE * stream)
static struct id3_tag *findId3TagFromEnd(FILE * stream)
{
struct id3_tag * tag;
struct id3_tag * v1tag;
struct id3_tag *tag;
struct id3_tag *v1tag;
int tagsize;
/* Get an id3v1 tag from the end of file for later use */
......@@ -306,11 +324,13 @@ static struct id3_tag * findId3TagFromEnd(FILE * stream)
/* Get the id3v2 tag size from the footer (located before v1tag) */
tagsize = getId3v2FooterSize(stream, (v1tag ? -128 : 0) - 10, SEEK_END);
if (tagsize >= 0) return v1tag;
if (tagsize >= 0)
return v1tag;
/* Get the tag which the footer belongs to */
tag = getId3Tag(stream, tagsize, SEEK_CUR);
if (!tag) return v1tag;
if (!tag)
return v1tag;
/* We have an id3v2 tag, so ditch v1tag */
id3_tag_delete(v1tag);
......@@ -319,41 +339,46 @@ static struct id3_tag * findId3TagFromEnd(FILE * stream)
}
#endif
MpdTag * id3Dup(char * file) {
MpdTag * ret = NULL;
MpdTag *id3Dup(char *file)
{
MpdTag *ret = NULL;
#ifdef HAVE_ID3TAG
struct id3_tag * tag;
FILE * stream;
struct id3_tag *tag;
FILE *stream;
stream = fopen(file, "r");
if (!stream) {
DEBUG("id3Dup: Failed to open file: '%s', %s\n",file, strerror(errno));
DEBUG("id3Dup: Failed to open file: '%s', %s\n", file,
strerror(errno));
return NULL;
}
tag = findId3TagFromBeginning(stream);
if (!tag) tag = findId3TagFromEnd(stream);
if (!tag)
tag = findId3TagFromEnd(stream);
fclose(stream);
if (!tag) return NULL;
if (!tag)
return NULL;
ret = parseId3Tag(tag);
id3_tag_delete(tag);
#endif
return ret;
}
MpdTag * apeDup(char * file) {
MpdTag * ret = NULL;
FILE * fp = NULL;
MpdTag *apeDup(char *file)
{
MpdTag *ret = NULL;
FILE *fp = NULL;
int tagCount;
char * buffer = NULL;
char * p;
char *buffer = NULL;
char *p;
int tagLen;
int size;
unsigned long flags;
int i;
char * key;
char *key;
struct {
unsigned char id[8];
......@@ -364,8 +389,7 @@ MpdTag * apeDup(char * file) {
unsigned char reserved[8];
} footer;
char * apeItems[7] =
{
char *apeItems[7] = {
"title",
"artist",
"album",
......@@ -375,8 +399,7 @@ MpdTag * apeDup(char * file) {
"year"
};
int tagItems[7] =
{
int tagItems[7] = {
TAG_ITEM_TITLE,
TAG_ITEM_ARTIST,
TAG_ITEM_ALBUM,
......@@ -387,30 +410,39 @@ MpdTag * apeDup(char * file) {
};
fp = fopen(file, "r");
if(!fp) return NULL;
if (!fp)
return NULL;
/* determine if file has an apeV2 tag */
if(fseek(fp, 0, SEEK_END)) goto fail;
if (fseek(fp, 0, SEEK_END))
goto fail;
size = ftell(fp);
if(fseek(fp, size-sizeof(footer), SEEK_SET)) goto fail;
if(fread(&footer, 1, sizeof(footer), fp) != sizeof(footer)) goto fail;
if(memcmp(footer.id, "APETAGEX", sizeof(footer.id)) != 0) goto fail;
if(readLEuint32(footer.version) != 2000) goto fail;
if (fseek(fp, size - sizeof(footer), SEEK_SET))
goto fail;
if (fread(&footer, 1, sizeof(footer), fp) != sizeof(footer))
goto fail;
if (memcmp(footer.id, "APETAGEX", sizeof(footer.id)) != 0)
goto fail;
if (readLEuint32(footer.version) != 2000)
goto fail;
/* find begining of ape tag */
tagLen = readLEuint32(footer.length);
if(tagLen < sizeof(footer)) goto fail;
if(fseek(fp, size-tagLen, SEEK_SET)) goto fail;
if (tagLen < sizeof(footer))
goto fail;
if (fseek(fp, size - tagLen, SEEK_SET))
goto fail;
/* read tag into buffer */
tagLen -= sizeof(footer);
buffer = malloc(tagLen);
if(fread(buffer, 1, tagLen, fp) != tagLen) goto fail;
if (fread(buffer, 1, tagLen, fp) != tagLen)
goto fail;
/* read tags */
tagCount = readLEuint32(footer.tagCount);
p = buffer;
while(tagCount-- && tagLen > 10) {
while (tagCount-- && tagLen > 10) {
size = readLEuint32((unsigned char *)p);
p += 4;
tagLen -= 4;
......@@ -420,7 +452,7 @@ MpdTag * apeDup(char * file) {
/* get the key */
key = p;
while(tagLen-size > 0 && *p != '\0') {
while (tagLen - size > 0 && *p != '\0') {
p++;
tagLen--;
}
......@@ -428,15 +460,17 @@ MpdTag * apeDup(char * file) {
tagLen--;
/* get the value */
if(tagLen-size < 0) goto fail;
if (tagLen - size < 0)
goto fail;
/* we only care about utf-8 text tags */
if(!(flags & (0x3 << 1))) {
for(i = 0; i < 7; i++) {
if(strcasecmp(key, apeItems[i]) == 0) {
if(!ret) ret = newMpdTag();
addItemToMpdTagWithLen(
ret, tagItems[i], p, size);
if (!(flags & (0x3 << 1))) {
for (i = 0; i < 7; i++) {
if (strcasecmp(key, apeItems[i]) == 0) {
if (!ret)
ret = newMpdTag();
addItemToMpdTagWithLen(ret, tagItems[i],
p, size);
}
}
}
......@@ -444,21 +478,25 @@ MpdTag * apeDup(char * file) {
tagLen -= size;
}
fail:
if(fp) fclose(fp);
if(buffer) free(buffer);
fail:
if (fp)
fclose(fp);
if (buffer)
free(buffer);
return ret;
}
MpdTag * newMpdTag(void) {
MpdTag * ret = malloc(sizeof(MpdTag));
MpdTag *newMpdTag(void)
{
MpdTag *ret = malloc(sizeof(MpdTag));
ret->items = NULL;
ret->time = -1;
ret->numOfItems = 0;
return ret;
}
static void deleteItem(MpdTag * tag, int index) {
static void deleteItem(MpdTag * tag, int index)
{
tag->numOfItems--;
assert(index < tag->numOfItems);
......@@ -466,26 +504,26 @@ static void deleteItem(MpdTag * tag, int index) {
removeTagItemString(tag->items[index].type, tag->items[index].value);
/* free(tag->items[index].value); */
if(tag->numOfItems-index > 0) {
memmove(tag->items+index, tag->items+index+1,
tag->numOfItems-index);
if (tag->numOfItems - index > 0) {
memmove(tag->items + index, tag->items + index + 1,
tag->numOfItems - index);
}
if(tag->numOfItems > 0) {
if (tag->numOfItems > 0) {
tag->items = realloc(tag->items,
tag->numOfItems*sizeof(MpdTagItem));
}
else {
tag->numOfItems * sizeof(MpdTagItem));
} else {
free(tag->items);
tag->items = NULL;
}
}
void clearItemsFromMpdTag(MpdTag * tag, int type) {
void clearItemsFromMpdTag(MpdTag * tag, int type)
{
int i = 0;
for(i = 0; i < tag->numOfItems; i++) {
if(tag->items[i].type == type) {
for (i = 0; i < tag->numOfItems; i++) {
if (tag->items[i].type == type) {
deleteItem(tag, i);
/* decrement since when just deleted this node */
i--;
......@@ -493,15 +531,17 @@ void clearItemsFromMpdTag(MpdTag * tag, int type) {
}
}
static void clearMpdTag(MpdTag * tag) {
static void clearMpdTag(MpdTag * tag)
{
int i;
for(i = 0; i < tag->numOfItems; i++) {
for (i = 0; i < tag->numOfItems; i++) {
removeTagItemString(tag->items[i].type, tag->items[i].value);
/* free(tag->items[i].value); */
}
if(tag->items) free(tag->items);
if (tag->items)
free(tag->items);
tag->items = NULL;
tag->numOfItems = 0;
......@@ -509,40 +549,49 @@ static void clearMpdTag(MpdTag * tag) {
tag->time = -1;
}
void freeMpdTag(MpdTag * tag) {
void freeMpdTag(MpdTag * tag)
{
clearMpdTag(tag);
free(tag);
}
MpdTag * mpdTagDup(MpdTag * tag) {
MpdTag * ret = NULL;
MpdTag *mpdTagDup(MpdTag * tag)
{
MpdTag *ret = NULL;
int i;
if(!tag) return NULL;
if (!tag)
return NULL;
ret = newMpdTag();
ret->time = tag->time;
for(i = 0; i < tag->numOfItems; i++) {
for (i = 0; i < tag->numOfItems; i++) {
addItemToMpdTag(ret, tag->items[i].type, tag->items[i].value);
}
return ret;
}
int mpdTagsAreEqual(MpdTag * tag1, MpdTag * tag2) {
int mpdTagsAreEqual(MpdTag * tag1, MpdTag * tag2)
{
int i;
if(tag1 == NULL && tag2 == NULL) return 1;
else if(!tag1 || !tag2) return 0;
if (tag1 == NULL && tag2 == NULL)
return 1;
else if (!tag1 || !tag2)
return 0;
if(tag1->time != tag2->time) return 0;
if (tag1->time != tag2->time)
return 0;
if(tag1->numOfItems != tag2->numOfItems) return 0;
if (tag1->numOfItems != tag2->numOfItems)
return 0;
for(i = 0; i < tag1->numOfItems; i++) {
if(tag1->items[i].type != tag2->items[i].type) return 0;
if(strcmp(tag1->items[i].value, tag2->items[i].value)) {
for (i = 0; i < tag1->numOfItems; i++) {
if (tag1->items[i].type != tag2->items[i].type)
return 0;
if (strcmp(tag1->items[i].value, tag2->items[i].value)) {
return 0;
}
}
......@@ -560,13 +609,12 @@ int mpdTagsAreEqual(MpdTag * tag1, MpdTag * tag2) {
} \
}
static void appendToTagItems(MpdTag * tag, int type, char * value,
int len)
static void appendToTagItems(MpdTag * tag, int type, char *value, int len)
{
int i = tag->numOfItems;
char * dup;
dup = malloc(len+1);
char *dup;
dup = malloc(len + 1);
strncpy(dup, value, len);
dup[len] = '\0';
......@@ -574,7 +622,7 @@ static void appendToTagItems(MpdTag * tag, int type, char * value,
stripReturnChar(dup);
tag->numOfItems++;
tag->items = realloc(tag->items, tag->numOfItems*sizeof(MpdTagItem));
tag->items = realloc(tag->items, tag->numOfItems * sizeof(MpdTagItem));
tag->items[i].type = type;
tag->items[i].value = getTagItemString(type, dup);
......@@ -582,13 +630,17 @@ static void appendToTagItems(MpdTag * tag, int type, char * value,
free(dup);
}
void addItemToMpdTagWithLen(MpdTag * tag, int itemType, char * value, int len) {
if(ignoreTagItems[itemType]) return;
void addItemToMpdTagWithLen(MpdTag * tag, int itemType, char *value, int len)
{
if (ignoreTagItems[itemType])
return;
if(!value || !len) return;
if (!value || !len)
return;
/* we can't hold more than 255 items */
if(tag->numOfItems == 255) return;
if (tag->numOfItems == 255)
return;
appendToTagItems(tag, itemType, value, len);
}
......@@ -44,28 +44,28 @@
#define TAG_NUM_OF_ITEM_TYPES 11
extern char * mpdTagItemKeys[];
extern char *mpdTagItemKeys[];
typedef struct _MpdTagItem {
mpd_sint8 type;
char * value;
char *value;
} MpdTagItem;
typedef struct _MpdTag {
int time;
MpdTagItem * items;
MpdTagItem *items;
mpd_uint8 numOfItems;
} MpdTag;
#ifdef HAVE_ID3TAG
MpdTag * parseId3Tag(struct id3_tag *);
MpdTag *parseId3Tag(struct id3_tag *);
#endif
MpdTag * apeDup(char * file);
MpdTag *apeDup(char *file);
MpdTag * id3Dup(char * file);
MpdTag *id3Dup(char *file);
MpdTag * newMpdTag();
MpdTag *newMpdTag();
void initTagConfig();
......@@ -73,14 +73,14 @@ void clearItemsFromMpdTag(MpdTag * tag, int itemType);
void freeMpdTag(MpdTag * tag);
void addItemToMpdTagWithLen(MpdTag * tag, int itemType, char * value, int len);
void addItemToMpdTagWithLen(MpdTag * tag, int itemType, char *value, int len);
#define addItemToMpdTag(tag, itemType, value) \
addItemToMpdTagWithLen(tag, itemType, value, strlen(value))
void printMpdTag(FILE * fp, MpdTag * tag);
MpdTag * mpdTagDup(MpdTag * tag);
MpdTag *mpdTagDup(MpdTag * tag);
int mpdTagsAreEqual(MpdTag * tag1, MpdTag * tag2);
......
......@@ -23,8 +23,7 @@
#include <assert.h>
static List * tagLists[TAG_NUM_OF_ITEM_TYPES] =
{
static List *tagLists[TAG_NUM_OF_ITEM_TYPES] = {
NULL,
NULL,
NULL,
......@@ -39,20 +38,20 @@ typedef struct tagTrackerItem {
mpd_sint8 visited;
} TagTrackerItem;
char * getTagItemString(int type, char * string) {
ListNode * node;
char *getTagItemString(int type, char *string)
{
ListNode *node;
int pos;
if(tagLists[type] == NULL) {
if (tagLists[type] == NULL) {
tagLists[type] = makeList(free, 1);
sortList(tagLists[type]);
}
if(findNodeInList(tagLists[type], string, &node, &pos)) {
((TagTrackerItem *)node->data)->count++;
}
else {
TagTrackerItem * item = malloc(sizeof(TagTrackerItem));
if (findNodeInList(tagLists[type], string, &node, &pos)) {
((TagTrackerItem *) node->data)->count++;
} else {
TagTrackerItem *item = malloc(sizeof(TagTrackerItem));
item->count = 1;
item->visited = 0;
node = insertInListBeforeNode(tagLists[type], node, pos,
......@@ -62,50 +61,57 @@ char * getTagItemString(int type, char * string) {
return node->key;
}
void removeTagItemString(int type, char * string) {
ListNode * node;
void removeTagItemString(int type, char *string)
{
ListNode *node;
int pos;
assert(string);
assert(tagLists[type]);
if(tagLists[type] == NULL) return;
if (tagLists[type] == NULL)
return;
if(findNodeInList(tagLists[type], string, &node, &pos)) {
TagTrackerItem * item = node->data;
if (findNodeInList(tagLists[type], string, &node, &pos)) {
TagTrackerItem *item = node->data;
item->count--;
if(item->count <= 0) deleteNodeFromList(tagLists[type], node);
if (item->count <= 0)
deleteNodeFromList(tagLists[type], node);
}
if(tagLists[type]->numberOfNodes == 0) {
if (tagLists[type]->numberOfNodes == 0) {
freeList(tagLists[type]);
tagLists[type] = NULL;
}
}
int getNumberOfTagItems(int type) {
if(tagLists[type] == NULL) return 0;
int getNumberOfTagItems(int type)
{
if (tagLists[type] == NULL)
return 0;
return tagLists[type]->numberOfNodes;
}
void printMemorySavedByTagTracker(void) {
void printMemorySavedByTagTracker(void)
{
int i;
ListNode * node;
ListNode *node;
size_t sum = 0;
for(i = 0; i < TAG_NUM_OF_ITEM_TYPES; i++) {
if(!tagLists[i]) continue;
for (i = 0; i < TAG_NUM_OF_ITEM_TYPES; i++) {
if (!tagLists[i])
continue;
sum -= sizeof(List);
node = tagLists[i]->firstNode;
while(node != NULL) {
while (node != NULL) {
sum -= sizeof(ListNode);
sum -= sizeof(TagTrackerItem);
sum -= sizeof(node->key);
sum += (strlen(node->key)+1)*(*((int *)node->data));
sum += (strlen(node->key) + 1) * (*((int *)node->data));
node = node->nextNode;
}
}
......@@ -113,40 +119,47 @@ void printMemorySavedByTagTracker(void) {
DEBUG("saved memory from tags: %li\n", (long)sum);
}
void resetVisitedFlagsInTagTracker(int type) {
ListNode * node;
void resetVisitedFlagsInTagTracker(int type)
{
ListNode *node;
if(!tagLists[type]) return;
if (!tagLists[type])
return;
node = tagLists[type]->firstNode;
while(node) {
((TagTrackerItem *)node->data)->visited = 0;
while (node) {
((TagTrackerItem *) node->data)->visited = 0;
node = node->nextNode;
}
}
void visitInTagTracker(int type, char * str) {
void * item;
void visitInTagTracker(int type, char *str)
{
void *item;
if(!tagLists[type]) return;
if (!tagLists[type])
return;
if(!findInList(tagLists[type], str, &item)) return;
if (!findInList(tagLists[type], str, &item))
return;
((TagTrackerItem *)item)->visited = 1;
((TagTrackerItem *) item)->visited = 1;
}
void printVisitedInTagTracker(FILE * fp, int type) {
ListNode * node;
TagTrackerItem * item;
void printVisitedInTagTracker(FILE * fp, int type)
{
ListNode *node;
TagTrackerItem *item;
if(!tagLists[type]) return;
if (!tagLists[type])
return;
node = tagLists[type]->firstNode;
while(node) {
while (node) {
item = node->data;
if(item->visited) {
if (item->visited) {
myfprintf(fp, "%s: %s\n", mpdTagItemKeys[type],
node->key);
}
......
......@@ -21,9 +21,9 @@
#include "tag.h"
char * getTagItemString(int type, char * string);
char *getTagItemString(int type, char *string);
void removeTagItemString(int type, char * string);
void removeTagItemString(int type, char *string);
int getNumberOfTagItems(int type);
......@@ -31,7 +31,7 @@ void printMemorySavedByTagTracker();
void resetVisitedFlagsInTagTracker(int type);
void visitInTagTracker(int type, char * str);
void visitInTagTracker(int type, char *str);
void printVisitedInTagTracker(FILE * fp, int type);
......
......@@ -22,113 +22,126 @@
#include <string.h>
#include <stdlib.h>
static char * latin1ToUtf8(char c) {
static char *latin1ToUtf8(char c)
{
static unsigned char utf8[3];
unsigned char uc = c;
memset(utf8,0,3);
memset(utf8, 0, 3);
if(uc < 128) utf8[0] = uc;
else if(uc<192) {
if (uc < 128)
utf8[0] = uc;
else if (uc < 192) {
utf8[0] = 194;
utf8[1] = uc;
}
else {
} else {
utf8[0] = 195;
utf8[1] = uc-64;
utf8[1] = uc - 64;
}
return (char *)utf8;
}
char * latin1StrToUtf8Dup(char * latin1) {
char *latin1StrToUtf8Dup(char *latin1)
{
/* utf8 should have at most two char's per latin1 char */
int len = strlen(latin1)*2+1;
char * ret = malloc(len);
char * cp = ret;
char * utf8;
int len = strlen(latin1) * 2 + 1;
char *ret = malloc(len);
char *cp = ret;
char *utf8;
memset(ret,0,len);
memset(ret, 0, len);
len = 0;
while(*latin1) {
while (*latin1) {
utf8 = latin1ToUtf8(*latin1);
while(*utf8) {
while (*utf8) {
*(cp++) = *(utf8++);
len++;
}
latin1++;
}
return realloc(ret,len+1);
return realloc(ret, len + 1);
}
static char utf8ToLatin1(char * inUtf8) {
static char utf8ToLatin1(char *inUtf8)
{
unsigned char c = 0;
unsigned char * utf8 = (unsigned char *)inUtf8;
if(utf8[0]<128) return utf8[0];
else if(utf8[0]==195) c+=64;
else if(utf8[0]!=194) return '?';
return (char)(c+utf8[1]);
unsigned char *utf8 = (unsigned char *)inUtf8;
if (utf8[0] < 128)
return utf8[0];
else if (utf8[0] == 195)
c += 64;
else if (utf8[0] != 194)
return '?';
return (char)(c + utf8[1]);
}
static int validateUtf8Char(char * inUtf8Char) {
unsigned char * utf8Char = (unsigned char *)inUtf8Char;
static int validateUtf8Char(char *inUtf8Char)
{
unsigned char *utf8Char = (unsigned char *)inUtf8Char;
if(utf8Char[0]<0x80) return 1;
if (utf8Char[0] < 0x80)
return 1;
if(utf8Char[0]>=0xC0 && utf8Char[0]<=0xFD) {
if (utf8Char[0] >= 0xC0 && utf8Char[0] <= 0xFD) {
int count = 1;
char t = 1 << 5;
int i;
while(count < 6 && (t & utf8Char[0])) {
while (count < 6 && (t & utf8Char[0])) {
t = (t >> 1);
count++;
}
if(count > 5) return 0;
for(i=1;i<=count;i++) {
if(utf8Char[i] < 0x80 || utf8Char[i] > 0xBF) return 0;
}
return count+1;
if (count > 5)
return 0;
for (i = 1; i <= count; i++) {
if (utf8Char[i] < 0x80 || utf8Char[i] > 0xBF)
return 0;
}
else return 0;
return count + 1;
} else
return 0;
}
int validUtf8String(char * string) {
int validUtf8String(char *string)
{
int ret;
while(*string) {
while (*string) {
ret = validateUtf8Char(string);
if(0==ret) return 0;
string+= ret;
if (0 == ret)
return 0;
string += ret;
}
return 1;
}
char * utf8StrToLatin1Dup(char * utf8) {
char *utf8StrToLatin1Dup(char *utf8)
{
/* utf8 should have at most two char's per latin1 char */
int len = strlen(utf8)+1;
char * ret = malloc(len);
char * cp = ret;
int len = strlen(utf8) + 1;
char *ret = malloc(len);
char *cp = ret;
int count;
memset(ret,0,len);
memset(ret, 0, len);
len = 0;
while(*utf8) {
while (*utf8) {
count = validateUtf8Char(utf8);
if(!count) {
if (!count) {
free(ret);
return NULL;
}
*(cp++) = utf8ToLatin1(utf8);
utf8+= count;
utf8 += count;
len++;
}
return realloc(ret,len+1);
return realloc(ret, len + 1);
}
......@@ -19,10 +19,10 @@
#ifndef UTF_8_H
#define UTF_8_H
char * latin1StrToUtf8Dup(char * latin1);
char *latin1StrToUtf8Dup(char *latin1);
char * utf8StrToLatin1Dup(char * utf8);
char *utf8StrToLatin1Dup(char *utf8);
int validUtf8String(char * string);
int validUtf8String(char *string);
#endif
......@@ -27,75 +27,82 @@
#include <sys/time.h>
#include <unistd.h>
char * myFgets(char * buffer, int bufferSize, FILE * fp) {
char * ret = fgets(buffer,bufferSize,fp);
if(ret && strlen(buffer)>0 && buffer[strlen(buffer)-1]=='\n') {
buffer[strlen(buffer)-1] = '\0';
char *myFgets(char *buffer, int bufferSize, FILE * fp)
{
char *ret = fgets(buffer, bufferSize, fp);
if (ret && strlen(buffer) > 0 && buffer[strlen(buffer) - 1] == '\n') {
buffer[strlen(buffer) - 1] = '\0';
}
if(ret && strlen(buffer)>0 && buffer[strlen(buffer)-1]=='\r') {
buffer[strlen(buffer)-1] = '\0';
if (ret && strlen(buffer) > 0 && buffer[strlen(buffer) - 1] == '\r') {
buffer[strlen(buffer) - 1] = '\0';
}
return ret;
}
char * strDupToUpper(char * str) {
char * ret = strdup(str);
char *strDupToUpper(char *str)
{
char *ret = strdup(str);
int i;
for(i=0;i<strlen(str);i++) ret[i] = toupper((int)ret[i]);
for (i = 0; i < strlen(str); i++)
ret[i] = toupper((int)ret[i]);
return ret;
}
void stripReturnChar(char * string) {
while(string && (string = strchr(string,'\n'))) {
void stripReturnChar(char *string)
{
while (string && (string = strchr(string, '\n'))) {
*string = ' ';
}
}
void my_usleep(long usec) {
void my_usleep(long usec)
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = usec;
select(0,NULL,NULL,NULL,&tv);
select(0, NULL, NULL, NULL, &tv);
}
int ipv6Supported(void) {
int ipv6Supported(void)
{
#ifdef HAVE_IPV6
int s;
s = socket(AF_INET6,SOCK_STREAM,0);
if(s == -1) return 0;
s = socket(AF_INET6, SOCK_STREAM, 0);
if (s == -1)
return 0;
close(s);
return 1;
#endif
return 0;
}
char * appendToString(char * dest, const char * src) {
char *appendToString(char *dest, const char *src)
{
int destlen;
int srclen = strlen(src);
if(dest == NULL) {
dest = malloc(srclen+1);
memset(dest, 0, srclen+1);
if (dest == NULL) {
dest = malloc(srclen + 1);
memset(dest, 0, srclen + 1);
destlen = 0;
}
else {
} else {
destlen = strlen(dest);
dest = realloc(dest, destlen+srclen+1);
dest = realloc(dest, destlen + srclen + 1);
}
memcpy(dest+destlen, src, srclen);
dest[destlen+srclen] = '\0';
memcpy(dest + destlen, src, srclen);
dest[destlen + srclen] = '\0';
return dest;
}
unsigned long readLEuint32(const unsigned char *p)
{
return ((unsigned long) p[0] << 0) |
((unsigned long) p[1] << 8) |
((unsigned long) p[2] << 16) | ((unsigned long) p[3] << 24);
return ((unsigned long)p[0] << 0) |
((unsigned long)p[1] << 8) |
((unsigned long)p[2] << 16) | ((unsigned long)p[3] << 24);
}
......@@ -23,18 +23,18 @@
#include <stdio.h>
char * myFgets(char * buffer, int bufferSize, FILE * fp);
char *myFgets(char *buffer, int bufferSize, FILE * fp);
char * strDupToUpper(char * str);
char *strDupToUpper(char *str);
void stripReturnChar(char * string);
void stripReturnChar(char *string);
void my_usleep(long usec);
int ipv6Supported();
char * appendToString(char * dest, const char * src);
char *appendToString(char *dest, const char *src);
unsigned long readLEuint32(const unsigned char * p);
unsigned long readLEuint32(const unsigned char *p);
#endif
......@@ -59,7 +59,7 @@
#endif
static int volume_mixerType = VOLUME_MIXER_TYPE_DEFAULT;
static char * volume_mixerDevice = VOLUME_MIXER_DEVICE_DEFAULT;
static char *volume_mixerDevice = VOLUME_MIXER_DEVICE_DEFAULT;
static int volume_softwareSet = 100;
......@@ -69,8 +69,8 @@ static int volume_ossControl = SOUND_MIXER_PCM;
#endif
#ifdef HAVE_ALSA
static snd_mixer_t * volume_alsaMixerHandle = NULL;
static snd_mixer_elem_t * volume_alsaElem;
static snd_mixer_t *volume_alsaMixerHandle = NULL;
static snd_mixer_elem_t *volume_alsaElem;
static long volume_alsaMin;
static long volume_alsaMax;
static int volume_alsaSet = -1;
......@@ -80,51 +80,52 @@ static int volume_alsaSet = -1;
static void closeOssMixer(void)
{
while (close(volume_ossFd) && errno == EINTR);
while (close(volume_ossFd) && errno == EINTR) ;
volume_ossFd = -1;
}
static int prepOssMixer(char * device) {
ConfigParam * param;
static int prepOssMixer(char *device)
{
ConfigParam *param;
if((volume_ossFd = open(device,O_RDONLY))<0) {
WARNING("unable to open oss mixer \"%s\"\n",device);
if ((volume_ossFd = open(device, O_RDONLY)) < 0) {
WARNING("unable to open oss mixer \"%s\"\n", device);
return -1;
}
param = getConfigParam(CONF_MIXER_CONTROL);
if(param) {
char * labels[SOUND_MIXER_NRDEVICES] = SOUND_DEVICE_LABELS;
char * dup;
int i,j;
if (param) {
char *labels[SOUND_MIXER_NRDEVICES] = SOUND_DEVICE_LABELS;
char *dup;
int i, j;
int devmask = 0;
if(ioctl(volume_ossFd,SOUND_MIXER_READ_DEVMASK,&devmask)<0) {
if (ioctl(volume_ossFd, SOUND_MIXER_READ_DEVMASK, &devmask) < 0) {
WARNING("errors getting read_devmask for oss mixer\n");
closeOssMixer();
return -1;
}
for(i=0;i<SOUND_MIXER_NRDEVICES;i++) {
for (i = 0; i < SOUND_MIXER_NRDEVICES; i++) {
dup = strdup(labels[i]);
/* eliminate spaces at the end */
j = strlen(dup)-1;
while(j>=0 && dup[j]==' ') dup[j--] = '\0';
if(strcasecmp(dup, param->value)==0) {
j = strlen(dup) - 1;
while (j >= 0 && dup[j] == ' ')
dup[j--] = '\0';
if (strcasecmp(dup, param->value) == 0) {
free(dup);
break;
}
free(dup);
}
if(i>=SOUND_MIXER_NRDEVICES) {
if (i >= SOUND_MIXER_NRDEVICES) {
WARNING("mixer control \"%s\" not found at line %i\n",
param->value, param->line);
closeOssMixer();
return -1;
}
else if(!( ( 1 << i ) & devmask )) {
} else if (!((1 << i) & devmask)) {
WARNING("mixer control \"%s\" not usable at line %i\n",
param->value, param->line);
closeOssMixer();
......@@ -144,13 +145,14 @@ static int ensure_oss_open(void)
return 0;
}
static int getOssVolumeLevel(void) {
static int getOssVolumeLevel(void)
{
int left, right, level;
if (ensure_oss_open() < 0)
return -1;
if(ioctl(volume_ossFd,MIXER_READ(volume_ossControl),&level) < 0) {
if (ioctl(volume_ossFd, MIXER_READ(volume_ossControl), &level) < 0) {
closeOssMixer();
WARNING("unable to read volume\n");
return -1;
......@@ -159,39 +161,42 @@ static int getOssVolumeLevel(void) {
left = level & 0xff;
right = (level & 0xff00) >> 8;
if(left!=right) {
if (left != right) {
WARNING("volume for left and right is not the same, \"%i\" and "
"\"%i\"\n",left,right);
"\"%i\"\n", left, right);
}
return left;
}
static int changeOssVolumeLevel(FILE * fp, int change, int rel) {
static int changeOssVolumeLevel(FILE * fp, int change, int rel)
{
int current;
int new;
int level;
if (rel) {
if((current = getOssVolumeLevel()) < 0) {
if ((current = getOssVolumeLevel()) < 0) {
commandError(fp, ACK_ERROR_SYSTEM,
"problem getting current volume", NULL);
return -1;
}
new = current+change;
new = current + change;
} else {
if (ensure_oss_open() < 0)
return -1;
new = change;
}
if(new<0) new = 0;
else if(new>100) new = 100;
if (new < 0)
new = 0;
else if (new > 100)
new = 100;
level = (new << 8) + new;
if(ioctl(volume_ossFd,MIXER_WRITE(volume_ossControl),&level) < 0) {
if (ioctl(volume_ossFd, MIXER_WRITE(volume_ossControl), &level) < 0) {
closeOssMixer();
commandError(fp, ACK_ERROR_SYSTEM, "problems setting volume",
NULL);
......@@ -203,39 +208,43 @@ static int changeOssVolumeLevel(FILE * fp, int change, int rel) {
#endif
#ifdef HAVE_ALSA
static void closeAlsaMixer(void) {
static void closeAlsaMixer(void)
{
snd_mixer_close(volume_alsaMixerHandle);
volume_alsaMixerHandle = NULL;
}
static int prepAlsaMixer(char * card) {
static int prepAlsaMixer(char *card)
{
int err;
snd_mixer_elem_t * elem;
char * controlName = VOLUME_MIXER_ALSA_CONTROL_DEFAULT;
ConfigParam * param;
snd_mixer_elem_t *elem;
char *controlName = VOLUME_MIXER_ALSA_CONTROL_DEFAULT;
ConfigParam *param;
err = snd_mixer_open(&volume_alsaMixerHandle,0);
err = snd_mixer_open(&volume_alsaMixerHandle, 0);
snd_config_update_free_global();
if (err < 0) {
WARNING("problems opening alsa mixer: %s\n",snd_strerror(err));
WARNING("problems opening alsa mixer: %s\n", snd_strerror(err));
return -1;
}
if((err = snd_mixer_attach(volume_alsaMixerHandle,card))<0) {
if ((err = snd_mixer_attach(volume_alsaMixerHandle, card)) < 0) {
closeAlsaMixer();
WARNING("problems problems attaching alsa mixer: %s\n",
snd_strerror(err));
return -1;
}
if((err = snd_mixer_selem_register(volume_alsaMixerHandle,NULL,NULL))<0) {
if ((err =
snd_mixer_selem_register(volume_alsaMixerHandle, NULL,
NULL)) < 0) {
closeAlsaMixer();
WARNING("problems snd_mixer_selem_register'ing: %s\n",
snd_strerror(err));
return -1;
}
if((err = snd_mixer_load(volume_alsaMixerHandle))<0) {
if ((err = snd_mixer_load(volume_alsaMixerHandle)) < 0) {
closeAlsaMixer();
WARNING("problems snd_mixer_selem_register'ing: %s\n",
snd_strerror(err));
......@@ -246,30 +255,29 @@ static int prepAlsaMixer(char * card) {
param = getConfigParam(CONF_MIXER_CONTROL);
if(param) {
if (param) {
controlName = param->value;
}
while(elem) {
if(snd_mixer_elem_get_type(elem)==SND_MIXER_ELEM_SIMPLE) {
if(strcasecmp(controlName,
snd_mixer_selem_get_name(elem))==0)
{
while (elem) {
if (snd_mixer_elem_get_type(elem) == SND_MIXER_ELEM_SIMPLE) {
if (strcasecmp(controlName,
snd_mixer_selem_get_name(elem)) == 0) {
break;
}
}
elem = snd_mixer_elem_next(elem);
}
if(elem) {
if (elem) {
volume_alsaElem = elem;
snd_mixer_selem_get_playback_volume_range(
volume_alsaElem,
&volume_alsaMin,&volume_alsaMax);
snd_mixer_selem_get_playback_volume_range(volume_alsaElem,
&volume_alsaMin,
&volume_alsaMax);
return 0;
}
WARNING("can't find alsa mixer_control \"%s\"\n",controlName);
WARNING("can't find alsa mixer_control \"%s\"\n", controlName);
closeAlsaMixer();
return -1;
......@@ -280,27 +288,29 @@ static int prep_alsa_get_level(long *level)
const char *cmd;
int err;
if (!volume_alsaMixerHandle && prepAlsaMixer(volume_mixerDevice)<0)
if (!volume_alsaMixerHandle && prepAlsaMixer(volume_mixerDevice) < 0)
return -1;
if ((err = snd_mixer_handle_events(volume_alsaMixerHandle)) < 0) {
cmd = "handle_events";
goto error;
}
if((err = snd_mixer_selem_get_playback_volume(volume_alsaElem,
SND_MIXER_SCHN_FRONT_LEFT, level)) < 0) {
if ((err = snd_mixer_selem_get_playback_volume(volume_alsaElem,
SND_MIXER_SCHN_FRONT_LEFT,
level)) < 0) {
cmd = "selem_get_playback_volume";
goto error;
}
return 0;
error:
error:
WARNING("problems getting alsa volume: %s (snd_mixer_%s)\n",
snd_strerror(err), cmd);
closeAlsaMixer();
return -1;
}
static int getAlsaVolumeLevel(void) {
static int getAlsaVolumeLevel(void)
{
int ret;
long level;
long max = volume_alsaMax;
......@@ -309,16 +319,17 @@ static int getAlsaVolumeLevel(void) {
if (prep_alsa_get_level(&level) < 0)
return -1;
ret = ((volume_alsaSet/100.0)*(max-min)+min)+0.5;
if(volume_alsaSet>0 && ret==level) {
ret = ((volume_alsaSet / 100.0) * (max - min) + min) + 0.5;
if (volume_alsaSet > 0 && ret == level) {
ret = volume_alsaSet;
}
else ret = (int)(100*(((float)(level-min))/(max-min))+0.5);
} else
ret = (int)(100 * (((float)(level - min)) / (max - min)) + 0.5);
return ret;
}
static int changeAlsaVolumeLevel(FILE * fp, int change, int rel) {
static int changeAlsaVolumeLevel(FILE * fp, int change, int rel)
{
float vol;
long level;
long test;
......@@ -330,29 +341,30 @@ static int changeAlsaVolumeLevel(FILE * fp, int change, int rel) {
return -1;
if (rel) {
test = ((volume_alsaSet/100.0)*(max-min)+min)+0.5;
if(volume_alsaSet >= 0 && level==test) {
test = ((volume_alsaSet / 100.0) * (max - min) + min) + 0.5;
if (volume_alsaSet >= 0 && level == test) {
vol = volume_alsaSet;
}
else vol = 100.0*(((float)(level-min))/(max-min));
vol+=change;
}
else
} else
vol = 100.0 * (((float)(level - min)) / (max - min));
vol += change;
} else
vol = change;
volume_alsaSet = vol+0.5;
volume_alsaSet = volume_alsaSet>100 ? 100 :
(volume_alsaSet<0 ? 0 : volume_alsaSet);
volume_alsaSet = vol + 0.5;
volume_alsaSet = volume_alsaSet > 100 ? 100 :
(volume_alsaSet < 0 ? 0 : volume_alsaSet);
level = (long)(((vol/100.0)*(max-min)+min)+0.5);
level = level>max?max:level;
level = level<min?min:level;
level = (long)(((vol / 100.0) * (max - min) + min) + 0.5);
level = level > max ? max : level;
level = level < min ? min : level;
if((err = snd_mixer_selem_set_playback_volume_all(
volume_alsaElem,level))<0) {
if ((err =
snd_mixer_selem_set_playback_volume_all(volume_alsaElem,
level)) < 0) {
commandError(fp, ACK_ERROR_SYSTEM, "problems setting volume",
NULL);
WARNING("problems setting alsa volume: %s\n",snd_strerror(err));
WARNING("problems setting alsa volume: %s\n",
snd_strerror(err));
closeAlsaMixer();
return -1;
}
......@@ -361,8 +373,9 @@ static int changeAlsaVolumeLevel(FILE * fp, int change, int rel) {
}
#endif
static int prepMixer(char * device) {
switch(volume_mixerType) {
static int prepMixer(char *device)
{
switch (volume_mixerType) {
#ifdef HAVE_ALSA
case VOLUME_MIXER_TYPE_ALSA:
return prepAlsaMixer(device);
......@@ -376,8 +389,9 @@ static int prepMixer(char * device) {
return 0;
}
void finishVolume(void) {
switch(volume_mixerType) {
void finishVolume(void)
{
switch (volume_mixerType) {
#ifdef HAVE_ALSA
case VOLUME_MIXER_TYPE_ALSA:
closeAlsaMixer();
......@@ -391,28 +405,28 @@ void finishVolume(void) {
}
}
void initVolume(void) {
ConfigParam * param = getConfigParam(CONF_MIXER_TYPE);
void initVolume(void)
{
ConfigParam *param = getConfigParam(CONF_MIXER_TYPE);
if(param) {
if(0);
if (param) {
if (0) ;
#ifdef HAVE_ALSA
else if(strcmp(param->value, VOLUME_MIXER_ALSA)==0) {
else if (strcmp(param->value, VOLUME_MIXER_ALSA) == 0) {
volume_mixerType = VOLUME_MIXER_TYPE_ALSA;
volume_mixerDevice = VOLUME_MIXER_ALSA_DEFAULT;
}
#endif
#ifdef HAVE_OSS
else if(strcmp(param->value, VOLUME_MIXER_OSS)==0) {
else if (strcmp(param->value, VOLUME_MIXER_OSS) == 0) {
volume_mixerType = VOLUME_MIXER_TYPE_OSS;
volume_mixerDevice = VOLUME_MIXER_OSS_DEFAULT;
}
#endif
else if(strcmp(param->value ,VOLUME_MIXER_SOFTWARE)==0) {
else if (strcmp(param->value, VOLUME_MIXER_SOFTWARE) == 0) {
volume_mixerType = VOLUME_MIXER_TYPE_SOFTWARE;
volume_mixerDevice = VOLUME_MIXER_SOFTWARE_DEFAULT;
}
else {
} else {
ERROR("unknown mixer type %s at line %i\n",
param->value, param->line);
exit(EXIT_FAILURE);
......@@ -421,24 +435,27 @@ void initVolume(void) {
param = getConfigParam(CONF_MIXER_DEVICE);
if(param) {
if (param) {
volume_mixerDevice = param->value;
}
}
void openVolumeDevice(void) {
if(prepMixer(volume_mixerDevice)<0) {
void openVolumeDevice(void)
{
if (prepMixer(volume_mixerDevice) < 0) {
WARNING("using software volume\n");
volume_mixerType = VOLUME_MIXER_TYPE_SOFTWARE;
}
}
static int getSoftwareVolume(void) {
static int getSoftwareVolume(void)
{
return volume_softwareSet;
}
int getVolumeLevel(void) {
switch(volume_mixerType) {
int getVolumeLevel(void)
{
switch (volume_mixerType) {
#ifdef HAVE_ALSA
case VOLUME_MIXER_TYPE_ALSA:
return getAlsaVolumeLevel();
......@@ -454,38 +471,47 @@ int getVolumeLevel(void) {
}
}
static int changeSoftwareVolume(FILE * fp, int change, int rel) {
static int changeSoftwareVolume(FILE * fp, int change, int rel)
{
int new = change;
if(rel) new+=volume_softwareSet;
if (rel)
new += volume_softwareSet;
if(new>100) new = 100;
else if(new<0) new = 0;
if (new > 100)
new = 100;
else if (new < 0)
new = 0;
volume_softwareSet = new;
/*new = 100.0*(exp(new/50.0)-1)/(M_E*M_E-1)+0.5;*/
if(new>=100) new = 1000;
else if(new<=0) new = 0;
else new = 1000.0*(exp(new/25.0)-1)/(54.5981500331F-1)+0.5;
/*new = 100.0*(exp(new/50.0)-1)/(M_E*M_E-1)+0.5; */
if (new >= 100)
new = 1000;
else if (new <= 0)
new = 0;
else
new =
1000.0 * (exp(new / 25.0) - 1) / (54.5981500331F - 1) + 0.5;
setPlayerSoftwareVolume(new);
return 0;
}
int changeVolumeLevel(FILE * fp, int change, int rel) {
switch(volume_mixerType) {
int changeVolumeLevel(FILE * fp, int change, int rel)
{
switch (volume_mixerType) {
#ifdef HAVE_ALSA
case VOLUME_MIXER_TYPE_ALSA:
return changeAlsaVolumeLevel(fp,change,rel);
return changeAlsaVolumeLevel(fp, change, rel);
#endif
#ifdef HAVE_OSS
case VOLUME_MIXER_TYPE_OSS:
return changeOssVolumeLevel(fp,change,rel);
return changeOssVolumeLevel(fp, change, rel);
#endif
case VOLUME_MIXER_TYPE_SOFTWARE:
return changeSoftwareVolume(fp,change,rel);
return changeSoftwareVolume(fp, change, rel);
default:
return 0;
break;
......
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