view examples/basic_libpd/render.cpp @ 340:69d86429a1cf prerelease

More on libpd support for threads
author Giulio Moro <giuliomoro@yahoo.it>
date Mon, 06 Jun 2016 02:37:30 +0100
parents 1802f99cd77f
children 7af9c5be3434
line wrap: on
line source
/*
 * render.cpp
 *
 *  Created on: Oct 24, 2014
 *      Author: parallels
 */

#include <Bela.h>
#include <cmath>
#include <Utilities.h>
#include <I2c_Codec.h>
#include <PRU.h>
#include <stdio.h>
#include "z_libpd.h"
#include "z_queued.h"
#include <UdpServer.h>
#include <Midi.h>


// setup() is called once before the audio rendering starts.
// Use it to perform any initialisation and allocation which is dependent
// on the period size or sample rate.
//
// userData holds an opaque pointer to a data structure that was passed
// in from the call to initAudio().
//
// Return true on success; returning false halts the program.
unsigned int gLibpdBlockSize;  //make sure this matches the one used to compile libpd

unsigned int gChannelsInUse = 10;
int gBufLength;

float* gInBuf;
float* gOutBuf;

void pdnoteon(int ch, int pitch, int vel) {
  printf("noteon: %d %d %d\n", ch, pitch, vel);
}

void Bela_printHook(const char *recv){
	rt_printf("%s", recv);
}

UdpServer udpServer;

void libpdReadFilesLoop(){
    while(!gShouldStop){
    	// check for modified sockets/file descriptors
    	// (libpd would normally do this every block WITHIN the audio thread)
    	// not sure if this is thread-safe at the moment
    	libpd_sys_microsleep(0);
        usleep(1000);
    }
}

#define PARSE_MIDI
AuxiliaryTask libpdReadFilesTask;
AuxiliaryTask libpdProcessMessageQueueTask;
AuxiliaryTask libpdProcessMidiQueueTask;
Midi midi;

bool setup(BelaContext *context, void *userData)
{
	midi.readFrom(0);
	midi.writeTo(0);
#ifdef PARSE_MIDI
	midi.enableParser(true);
#else
	midi.enableParser(false);
#endif /* PARSE_MIDI */
	gChannelsInUse = min((int)(context->analogChannels+context->audioChannels), (int)gChannelsInUse);
	udpServer.bindToPort(1234);

	gLibpdBlockSize = libpd_blocksize();
	// check that we are not running with a blocksize smaller than gLibPdBlockSize
	// it would still work, but the load would be executed unevenly between calls to render
	if(context->audioFrames < gLibpdBlockSize){
		fprintf(stderr, "Error: minimum block size must be %d\n", gLibpdBlockSize);
		return false;
	}
	// init pd
	libpd_set_queued_printhook(Bela_printHook); // set this before calling libpd_init
	libpd_set_queued_noteonhook(pdnoteon);
	//TODO: add hooks for other midi events and generate MIDI output appropriately
	libpd_queued_init();
	//TODO: ideally, we would analyse the ASCII of the patch file and find the in/outs to use
	libpd_init_audio(gChannelsInUse, gChannelsInUse, context->audioSampleRate);

	libpd_start_message(1); // one entry in list
	libpd_add_float(1.0f);
	libpd_finish_message("pd", "dsp");

	gBufLength = max(gLibpdBlockSize, context->audioFrames);
	unsigned int bufferSize = sizeof(float)*gChannelsInUse*gBufLength;
	gInBuf = (float*)malloc(bufferSize);
	gOutBuf = (float*)malloc(bufferSize);
	// no need to memset to zero

	char file[] = "_main.pd";
	char folder[] = "./";
	// open patch       [; pd open file folder(
	libpd_openfile(file, folder);
    
	libpdReadFilesTask = Bela_createAuxiliaryTask(libpdReadFilesLoop, 60, "libpdReadFiles");
	Bela_scheduleAuxiliaryTask(libpdReadFilesTask);

	// Higher priority for the midi queue and lower priority for the message queue. Adjust to taste
	libpdProcessMidiQueueTask = Bela_createAuxiliaryTask(libpd_queued_receive_midi_messages, 80, "libpdProcessMidiQueue");
	libpdProcessMessageQueueTask = Bela_createAuxiliaryTask(libpd_queued_receive_pd_messages, 70, "libpdProcessMessageQueue");
	return true;
}

// render() is called regularly at the highest priority by the audio engine.
// Input and output are given from the audio hardware and the other
// ADCs and DACs (if available). If only audio is available, numMatrixFrames
// will be 0.
BelaContext *c;
void render(BelaContext *context, void *userData)
{
	int num;
#ifdef PARSE_MIDI
	while((num = midi.getParser()->numAvailableMessages()) > 0){
		static MidiChannelMessage message;
		message = midi.getParser()->getNextChannelMessage();
//		message.prettyPrint(); // use this to print beautified message (channel, data bytes)
		switch(message.getType()){
			case kmmNoteOn:
			{
				int noteNumber = message.getDataByte(0);
				int velocity = message.getDataByte(1);
				int channel = message.getChannel();
				libpd_noteon(channel, noteNumber, velocity);
				break;
			}
			case kmmNoteOff:
			{
				/* PureData does not seem to handle noteoff messages as per the MIDI specs,
				 * so that the noteoff velocity is ignored. Here we convert them to noteon
				 * with a velocity of 0.
				 */
				int noteNumber = message.getDataByte(0);
//				int velocity = message.getDataByte(1); // would be ignored by Pd
				int channel = message.getChannel();
				libpd_noteon(channel, noteNumber, 0);
				break;
			}
			case kmmControlChange:
			{
				int channel = message.getChannel();
				int controller = message.getDataByte(0);
				int value = message.getDataByte(1);
				libpd_controlchange(channel, controller, value);
				break;
			}
			case kmmProgramChange:
			{
				int channel = message.getChannel();
				int program = message.getDataByte(0);
				libpd_programchange(channel, program);
				break;
			}
			case kmmPolyphonicKeyPressure:
			{
				int channel = message.getChannel();
				int pitch = message.getDataByte(0);
				int value = message.getDataByte(1);
				libpd_polyaftertouch(channel, pitch, value);
				break;
			}
			case kmmChannelPressure:
			{
				int channel = message.getChannel();
				int value = message.getDataByte(0);
				libpd_aftertouch(channel, value);
				break;
			}
			case kmmPitchBend:
			{
				int channel = message.getChannel();
				int value =  (message.getDataByte(1) << 7)| message.getDataByte(0);
				libpd_pitchbend(channel, value);
				break;
			}
			case kmmNone:
			case kmmAny:
				break;
		}
	}
#else
	int input;
	while((input = midi.getInput()) >= 0){
		libpd_midibyte(0, input);
	}
#endif /* PARSE_MIDI */

	static unsigned int inW = 0;
	static unsigned int outR = 0;
/*
 *	NOTE: if you are only using audio (or only analogs) and you are using interleaved buffers
 *	 and the blocksize of Bela is the same as gLibPdBlockSize, then you probably
 *	 do not need the for loops before and after libpd_process_float, so you can save quite some
 *	 memory operations.
 */
	static unsigned int analogChannelsInUse = min(context->analogChannels, gChannelsInUse - context->audioChannels);
	// rt_printf("channelsInUse: %d, analogChannels in Use: %d\n", gChannelsInUse, analogChannelsInUse);
	for(unsigned int n = 0; n < context->audioFrames; ++n){ //pd buffers are interleaved
		for(unsigned int ch = 0; ch < context->audioChannels; ++ch){ //first two channels are audio
			gInBuf[inW++] = audioRead(context, n, ch);
		}
		// then analogs
		// this loop resamples by ZOH, as needed, using m
		if(context->analogChannels == 8 ){ //hold the value for two frames
			for(unsigned int analogCh = 0; analogCh < analogChannelsInUse; ++analogCh){
				gInBuf[inW++] = analogRead(context, n/2, analogCh); // n/2 wil be the same for n and n+1 when n is even
			}
		} else if(context->analogChannels == 4){ //write every frame
			for(unsigned int analogCh = 0; analogCh < analogChannelsInUse; ++analogCh){
				gInBuf[inW++] = analogRead(context, n, analogCh);
			}
		} else if(context->analogChannels == 2){ //drop every other frame
			for(unsigned int analogCh = 0; analogCh < analogChannelsInUse; ++analogCh){
				gInBuf[inW++] = analogRead(context, n*2, analogCh);
			}
		}
		if(inW == gBufLength * gChannelsInUse){
			inW = 0;
		}
	}
	// rt_printf("inW %d\n", inW);
	if(inW == 0){ //if the buffer is full, process it
		static int numberOfPdBlocksToProcess = gBufLength/gLibpdBlockSize;
		// TODO: see if we can rewrite libpd_process_float so that it takes a buffer
		// of interleaved channels of arbitrary length rather than a series of
		// stacked buffers of size gLibPdBlockSize as it currently does.
		libpd_process_float(numberOfPdBlocksToProcess, gInBuf, gOutBuf);
		outR = 0; // reset the read pointer. NOTE: hopefully this is needed only the first time
	}

	for(unsigned int n = 0; n < context->audioFrames; n++){ //pd buffers are interleaved
		for(unsigned int ch = 0; ch < context->audioChannels; ++ch){
			audioWrite(context, n, ch, gOutBuf[outR++]);
		}
		//and analogs
		if(context->analogChannels == 8){
			for(unsigned int analogCh = 0; analogCh < analogChannelsInUse; ++analogCh){
				float analogOut = gOutBuf[outR++];				
				if((n&1) == 0){//write every two frames
					analogWrite(context, n/2, analogCh, analogOut);
				} else {
					// discard this sample
				}
			}
		} else if(context->analogChannels == 4){ //write every frame
			for(unsigned int analogCh = 0; analogCh < analogChannelsInUse; ++analogCh){
				float analogOut = gOutBuf[outR++];
				analogWrite(context, n, analogCh, analogOut);
			}
		} else if(context->analogChannels == 2){ //write twice every frame
			for(unsigned int analogCh = 0; analogCh < analogChannelsInUse; ++analogCh){
				float analogOut = gOutBuf[outR++];
				analogWrite(context, 2*n, analogCh, analogOut);
				analogWrite(context, 2*n + 1, analogCh, analogOut);
			}
		}
		if(outR == gBufLength * gChannelsInUse){
			outR = 0;
		}
	}
	// rt_printf("outR %d, analogChannelsInUse %d, channelsInUse %d\n", 
	// 	outR , analogChannelsInUse, gChannelsInUse);
	Bela_scheduleAuxiliaryTask(libpdProcessMidiQueueTask);
	Bela_scheduleAuxiliaryTask(libpdProcessMessageQueueTask);
}

// cleanup() is called once at the end, after the audio has stopped.
// Release any resources that were allocated in setup().

void cleanup(BelaContext *context, void *userData)
{
	libpd_queued_release();
	free(gInBuf);
	free(gOutBuf);
}