#include "MessageSoundfiler.h"
#include "MessageTable.h"
#include "PdGraph.h"
#include <sndfile.h>
message::Object *MessageSoundfiler::new_object(pd::Message *init_message, PdGraph *graph) {
return new MessageSoundfiler(init_message, graph);
}
MessageSoundfiler::MessageSoundfiler(pd::Message *init_message, PdGraph *graph) : message::Object(1, 1, graph) {
}
MessageSoundfiler::~MessageSoundfiler() {
}
void MessageSoundfiler::process_message(int inlet_index, pd::Message *message)
{
if (message->is_symbol_str(0, "read"))
{
int currentElementIndex;
bool shouldResizeTable = false;
char *tabName;
char *soundfilePath;
MessageTable *table;
for (currentElementIndex = 1;
currentElementIndex < message->get_num_elements();
++currentElementIndex)
{
if (message->is_symbol_str(currentElementIndex, "-resize"))
shouldResizeTable = true;
else
break;
}
if (message->get_num_elements() - currentElementIndex - 2 < 0)
{
graph->print_err("[soundfiler]: parameters are incorrect");
return;
}
soundfilePath = message->get_symbol(currentElementIndex++);
tabName = message->get_symbol(currentElementIndex++);
if ((table = graph->get_table(tabName)) == NULL)
{
graph->print_err("[soundfiler]: table '%s' cannot be found", tabName);
return;
}
SF_INFO sfInfo;
char *fullPath = graph->resolveFullPath(soundfilePath);
if (fullPath == NULL)
{
graph->print_err("[soundfiler]: file '%s' cannot be found.", soundfilePath);
return;
}
SNDFILE *sndFile = sf_open(fullPath, SFM_READ, &sfInfo);
if (sndFile == NULL)
{
graph->print_err("[soundfiler]: file %s cannot be opened.", fullPath);
free(fullPath);
return; }
delete fullPath;
int samplesPerChannel = static_cast<int>(sfInfo.frames);
int bufferLength = samplesPerChannel * sfInfo.channels;
float *buffer = (float *) malloc(bufferLength * sizeof(float));
sf_read_float(sndFile, buffer, bufferLength); sf_close(sndFile);
if (sfInfo.channels > 0) {
int tableLength = samplesPerChannel;
float *tableBuffer = shouldResizeTable ? table->resizeBuffer(samplesPerChannel) :
table->getBuffer(&tableLength);
if (tableLength > samplesPerChannel)
{
tableLength = samplesPerChannel;
}
for (int i = 0, j = 0; i < bufferLength; i+=sfInfo.channels, j++)
{
tableBuffer[j] = buffer[i];
}
if (sfInfo.channels > 1 &&
(tabName = message->get_symbol(currentElementIndex++)) != NULL &&
(table = graph->get_table(tabName)) != NULL)
{
tableLength = samplesPerChannel;
tableBuffer = shouldResizeTable ? table->resizeBuffer(samplesPerChannel) :
table->getBuffer(&tableLength);
if (tableLength > samplesPerChannel)
{
tableLength = samplesPerChannel;
}
for (int i = 1, j = 0; i < bufferLength; i+=sfInfo.channels, j++)
tableBuffer[j] = buffer[i];
}
}
delete buffer;
pd::Message *outgoing_message = PD_MESSAGE_ON_STACK(1);
outgoing_message->from_timestamp_and_float(message->get_timestamp(), samplesPerChannel);
send_message(0, outgoing_message);
}
else if (message->is_symbol_str(0, "write"))
{
graph->print_err("[soundfiler]: The 'write' command is not supported yet.");
}
}