Custom Data-Types in Max Part 4: Passing Object Pointers

How do you pass data between objects in Max?  If the data is a simple number or a symbol then the answer is easy.  What happens when you are trying to pass around audio vectors, dictionaries, images, or some other kind of object?  The implementation of Jamoma Multicore for Max deals with these issues head-on as it provides an illustration of how this problem can be tackled.

This is the fourth article in a series about working with custom data types in Max.  In the first two articles we laid the groundwork for the various methods by discussing how we wrap the data that we want to pass.  The third article demonstrated the use of Max’s symbol binding as means to pass custom data between objects.  This article will show an example of passing pointers directly between objects without using the symbol table.  In this series:

  1. Introduction
  2. Creating “nobox” classes
  3. Binding to symbols (e.g. table, buffer~, coll, etc.)
  4. Passing objects directly (e.g. Jamoma Audio Graph)
  5. Hash-based reference system (similar to Jitter)

A Peer Object System

Jamoma Audio Graph for Max is implemented as what might be called a Peer Object System.  What is meant is that for every object that a user creates and manipulates in a Max patcher, there is a matching object that exists in a parallel system. As detailed in Designing an Audio Graph, a Jamoma Audio Graph object has inlets and outlets and maintains connections to other objects to create a graph for processing audio through the objects.  The implementation of Jamoma Audio Graph for Max then has the task of creating and destroying these objects, sending them messages, and making the connections between them.  Once the objects are connected Jamoma Audio Graph will take care of itself.   The end result is that no audio processing actually happens in the Max objects for Jamoma Audio Graph — instead the Max objects are a thin façade that helps to set up the relationships between the objects as they exist in something akin to a parallel universe.

A Patcher

A Jamoma Multicore patcher in Max For context, let’s take a look at a Max patcher using Jamoma Audio Graph. In this patcher we have 4 Jamoma Audio Graph objects, identified by the ≈ symbol at the tail of the object name.  Each of these Max objects have a peer Audio Graph object internal to themselves.  Each Audio Graph object then contains a Jamoma DSP object that performs the actual signal processing. For example, the jcom.overdrive≈ object contains a pointer to a  Jamoma Audio Graph object that contains an instance of the Jamoma DSP overdrive class.  The attributes of the overdrive class, such as bypass, mute, and drive are then exposed as Max attributes so that they can be set in the patcher. Remember that each connection may carry N channels of audio.  The jcom.oscil≈ is, in this case, producing a stereo signal which is then propagated through the processing graph down to the jcom.dac≈ object.

Configuring the Graph

The exciting work doesn’t begin until the start message is sent to the jcom.dac≈ object.  As with all Jamoma Audio Graph externals, jcom.dac≈ Max external has a peer object.  In this case the peer object that it wraps is the multicore.output object.  This is the same multicore.output object that is shown in the Ruby examples in the Designing an Audio Graph article. When the start message is sent, the jcom.dac≈ object performs the following sequence:

  1. Send a multicore.reset message to all objects in the patcher.  This message sends a reset message to the peer objects underneath, which tells them to forget all of their previous connections.
  2. Send a multicore.setup message to all objects in the patcher.  This message tells the objects to try and connect to any object below it in the patcher.
  3. Tell the audio driver to start running.  When it is running it will periodically request blocks of samples from us, which in turn means that we will ask the other objects in the graph to process.

The processing happens completely within the Jamoma Multicore objects, thus not involving the Max objects at all.  It is the set up of the network of objects in the graph (steps 1 and 2) that involve our passing of custom data types in Max.

Diving into the code

For a full source listing of the jcom.dac≈ object, you can find the code in Jamoma Audio Graph source code repository.  We’ll abstract the important parts from that code below.  Let’s start with the method that is executed when the start message is sent:

TTErr DacStart(DacPtr self)
{
	MaxErr			err;
	ObjectPtr		patcher = NULL;
	long			vectorSize;
	long			result = 0;
	TTAudioGraphInitData	initData;

	self->multicoreObject->mUnitGenerator->getAttributeValue(TT("vectorSize"), vectorSize);

 	err = object_obex_lookup(self, gensym("#P"), &patcher);
 	object_method(patcher, gensym("iterate"), (method)DacIterateResetCallback, self, PI_DEEP, &result);
 	object_method(patcher, gensym("iterate"), (method)DacIterateSetupCallback, self, PI_DEEP, &result);

 	initData.vectorSize = vectorSize;
 	self->multicoreObject->init(initData);
 	return self->multicoreObject->mUnitGenerator->sendMessage(TT("start"));
}

As previously discussed, the last we thing we do is send a start message to our peer object, the multicore.output, so that the audio driver will start pulling audio vectors from us. Prior to that we iterate the Max patcher recursively (so the messages go to subpatchers too) to send the multicore.setup and multicore.reset messages.   To do this, we send the iterate message to the patcher and pass it a pointer to a method we define.  Those two methods are defined as follows.

void DacIterateResetCallback(DacPtr self, ObjectPtr obj)
{
	TTUInt32	vectorSize;
	method		multicoreResetMethod = zgetfn(obj, gensym("multicore.reset"));

	if (multicoreResetMethod) {
		self->multicoreObject->mUnitGenerator->getAttributeValue(TT("vectorSize"), vectorSize);
		multicoreResetMethod(obj, vectorSize);
	}
}

void DacIterateSetupCallback(DacPtr self, ObjectPtr obj)
{
	method multicoreSetupMethod = zgetfn(obj, gensym("multicore.setup"));

	if (multicoreSetupMethod)
		multicoreSetupMethod(obj);
}

These functions are called on every object in the patcher.  If we start with the last function, we can see that we first call zgetfn() on the object, obj, which is passed to us.  If that object possesses a multicore.setup method then we will receive a pointer to that method.  Otherwise we receive NULL.  If that method exists then we call it. The multicore.reset method works the same way.  The only difference is that the method takes an additional argument — the vector size at which the jcom.dac≈ is processing.

The Other End

At the other end of this calling sequence are the remaining objects in the patcher.  The full jcom.oscil≈ source code will show how this Max object is implemented.  In brief, we have two message bindings in the main function:

	class_addmethod(c, (method)OscilReset, "multicore.reset",	A_CANT, 0);
	class_addmethod(c, (method)OscilSetup, "multicore.setup",	A_CANT,	0);

These two methods respond to the those called by the jcom.dac≈ object.  They both have an A_CANT argument signature, which is how you define messages in Max that use function prototypes different than the standard  method prototypes.  These messages can’t be called directly by the user, and they are not listed in the object assistance, but we can send them from other parts of Max such as our jcom.dac≈ object.  The reset message (for forgetting about all previous connections) is simply passed on to the oscillator’s Multicore peer object:

TTErr OscilReset(OscilPtr self)
{
	return self->multicoreObject->reset();
}

The setup method, as we discussed, tells our object that we need to try and make a connection to any object below us in the patcher. To do this we wrap our peer Multicore object’s pointer up into a Max atom.  That, together with the outlet number (zero), are passed as arguments to the multicore.connect message which is sent out our outlet.

TTErr OscilSetup(OscilPtr self)
{
	Atom a[2];

	atom_setobj(a+0, ObjectPtr(self->multicoreObject));
	atom_setlong(a+1, 0);
	outlet_anything(self->multicoreOutlet, gensym("multicore.connect"), 2, a);
	return kTTErrNone;
}

One More Time…

That took care of the jcom.oscil≈ object.  Once it sends the multicore.connect message out its outlet, its work is done.  But what happens with that message when it is received?

In our example it is going to a jcom.overdrive≈ object.  The source code for jcom.overdrive≈ isn’t going to be very helpful though.  It uses a magic class-wrapper that wraps any Jamoma DSP object as a Multicore object using 1 line of code.  That’s really convenient for coding, but not for seeing how all of the parts communicate.  So for our discussion, we will look at the jcom.dcblocker≈ source code instead — beginning with the main() function.

	class_addmethod(c, (method)DCBlockerReset,	"multicore.reset",	A_CANT, 0);
	class_addmethod(c, (method)DCBlockerSetup,	"multicore.setup",	A_CANT, 0);
	class_addmethod(c, (method)DCBlockerConnect,	"multicore.connect",	A_OBJ, A_LONG, 0);

You should recognize the multicore.reset and multicore.setup messages.  Those are exactly the same as they were for our oscillator.  We now also have a multicore.connect message.  The oscillator was generating a signal but has no signal inputs, so it had no need for a multicore.connect message.  Any object that requires an input, however, will require this message binding.  How that method is implemented?

TTErr DCBlockerConnect(DCBlockerPtr self, TTMulticoreObjectPtr audioSourceObject, long sourceOutletNumber)
{
	return self->multicoreObject->connect(audioSourceObject, sourceOutletNumber);
}

We simply wrap a call to our peer object’s connect method, sending the audioSourceObject (which is the peer object that the jcom.oscil≈ object sent us), and the outlet number from which that object was sent.  If you compare this to the connect message from the Ruby example in Designing an Audio Graph, it may illuminate the process.

Some Final Details

The example code that we’ve seen from Jamoma Audio Graph demonstrates the passing of custom data (pointers to C++ objects) from one object to the next through the multicore.connect message. Because we are sending this custom data type, and not all inlets of all objects will understand this data type, it would be nice if we could protect users from hooking up the objects in a way that will not function.  For this task, Max makes it possible to give outlets type information.  When the type of an outlet is specified, a user will not be able to connect the patch cord to any inlet that doesn’t accept the specified message. To get this functionality, in DCBlockerNew(), we create our outlet like this:

	self->multicoreOutlet = outlet_new(self, "multicore.connect");

So instead of the customary NULL for the argument to outlet_new(), we specify that this outlet will be sending only multicore.connect messages.

Surfacing for Air

Jamoma Audio Graph provides a fairly intense example of passing custom data types in Max.  However, it presents not just the basics of how you would pass a pointer, but rather a context for why you might want to pass a custom type, and a real-world example to show what you can do.  I think that objective has been accomplished.

Designing an Audio Graph

In previous articles about the Jamoma Platform and the Jamoma DSP Library, there have been references to Jamoma Audio Graph (also previously known as Jamoma Multicore).  Up to this point, Jamoma Audio Graph has not been significantly documented or written about.  The authoritative information has been an Electrotap blog post showing the initial prototype in 2008.

At a workshop in Albi in 2009 we attempted to further expand Jamoma Audio Graph — and we failed.  The architecture was not able to handle N multichannel inputs and M multichannel outputs.  So we had to redesign a major portion of the inner-workings.  Get out your pipe wrench; it’s time to take a look at some plumbing…

What Is Jamoma Audio Graph ?

Let’s back up for moment to get the big picture.  The Jamoma Platform is essentially a layered architecture implementing various processes for interactive art, research, music, etc.  At the lowest level, the Jamoma Foundation delivers basic components for creating objects, passing values, storing values in lookup-tables, etc.  The Jamoma DSP library then extends the Foundation classes and provides a set of pre-built objects for audio signal processing.

Jamoma Audio Graph then gives us the ability to create Jamoma DSP objects and combine them into a graph.  In other words, we can connect the objects together like you might connect modules together on a Moog synthesizer.

A Moog Modular patch. Photo: Maschinenraum

A Moog Modular Patch. Photo: Maschinenraum

Unlike the Moog synthesizers of old, however, we can do a few new tricks.  Instead of sending a single channel of audio through a connection, we can send any number of channels through a connection.  While Jamoma Audio Graph does not currently implement any particular features for parellel processing on multiple cores/processors, the design of the system is ideal for such parallelization in the future.

The Audio Graph In Action

At the time of this writing, Jamoma Audio Graph has bridges to make it available in the Max and Ruby environments.  Most of the work is done on making it available to Pd as well (though if you are really interested in this then let us know so we can put you to work!).

In Ruby, you can code scripts that are executed in a sequence.  This provides a static interface to Jamoma Audio Graph even though all of the synthesis and processing is typically happening in real-time.  Alternatively, the irb environment allows you to type and execute commands interactively.  Jamoma Audio Graph, together with irb, then functions much like the ChucK environment for live coding performance.

Example

If you’ve been jonesin’ for an Atari/Amiga/Commodore fix then this might be your perfect example of Jamoma Audio Graph in Ruby:

# This is the standard require for the Jamoma Platform's Ruby bindings
require 'TTRuby'

# Create a couple of objects:
dac = TTAudio.new "multicore.output"
osc = TTAudio.new "wavetable"

# connect the oscillator to the dac
dac.connect_audio osc

# turn on the dac
dac.send "start"

# play a little tune...
osc.set "frequency", 220.0
sleep 1.0
osc.set "frequency", 440.0
sleep 1.0
osc.set "frequency", 330.0
sleep 0.5
osc.set "frequency", 220.0
sleep 2.0

# all done
dac.send "stop"

It’s a pretty cheesy example, but it should give you a quick taste.  If you want a flashback to kinds of music you could make with MS-DOS, be sure you set the oscillator to use a square waveform.

After creating a couple of objects, you connect two objects by passing the source object to the destination object using a connect message.  If you provide no further arguments, then the connection is made between the first outlet of the source object and first inlet of the destination object.  The inlets and outlets are numbered from zero, so the connect message in our example could also have been written as

dac.connect osc, 0, 0

The sleep commands are standard Ruby.  They tell Ruby to pause execution for the specified number of seconds.  Everything else is performed with the basic Jamoma Ruby bindings.  These provide the send method for sending messages and the set method for setting attribute values.

If you want to know the messages or attributes that an object possesses, you can use the messages? or attributes? methods.  This is particularly useful when coding on the fly in irb.  In the following example, I requested the list of attributes for the oscillator in the previous example:

>> osc.attributes?
=> ["gain", "mode", "size", "processInPlace", "maxNumChannels", "frequency", "mute", "interpolation", "sr", "bypass"]

How It Operates

If you create a visual data-flow diagram of the objects in a graph, like you would see in Max or PureData, then you would get a good sense of how audio starts at the top and works its way through various filters until it gets to the bottom.  The same is true for a Jamoma Audio Graph.  However, what is happening under the surface is exactly the opposite.

Pull I/O Model

Multicore Graph Flow

The flow of a Jamoma Audio Graph.

Jamoma Audio Graph is based on a “Pull” I/O Model.  Some other examples of audio graph solutions using a similar model include ChucK and Apple’s AUGraph.  In this model a destination, sink, or terminal node object sits at the bottom of any given graph — and this is the object driving the whole operation.  In Max, on the other hand, messages (e.g. a ‘bang’ from a metro) begins at the top of the graph and pushes down through the objects in the chain.

The image to the left visualizes the operation of the audio graph.  Let’s assume the the destination object is an interface to your computer’s DAC.  The DAC will request blocks of samples (vectors) every so often as it needs them.  To keep it simple, we’ll say that we are processing samples at a sample rate of 44.1KHz and a block size of 512 samples.  In this case, every 11 milliseconds the DAC will tell our destination object that it needs a block of samples and the process begins.

The process flows through the light blue lines.  The destination asks the limiter for a block of samples, which then asks the overdrive for a block of samples which then asks both the source and the multitap delay for samples, and then the multitap delays asks the source for a block of samples.  To summarize it: each object receives a request for a block of samples, and in response it needs to produce that block of sample values, possibly pulling blocks of samples from additional objects in the process.

One Object At A Time

To understand in finer detail what happens in each object, the graphic below zooms-in to view a single instance in the graphic above.  Here we can see that we have the actual unit generator, which is a Jamoma DSP object, and then a host of other objects that work to make the interface for the audio graph.

Anatomy of a Multicore Object

Jamoma Audio Graph class structure

The text in graphic explains each of the classes contained in a Jamoma Audio Graph object.  Implied in both of the figures, is the ability to handle “fanning” connections where many inlets are connected to an outlet, or an inlet is connected to many outlets.

In essence, the outlets are only buffers storing samples produced by the unit generator.  Each time a block is processed the unit generator is invoked only once.  Subsequent requests for the object’s samples then simply access the samples already stored in the outlet buffers.

As explained in the graphic, the inlets have more work to do, as they need to sum the signals that are connected.  And remember, each connection can have zero or more channels!

Benefits

The most obvious  benefit is the ability to easily handle multiple channels in a single connection.  So imagine that you create a Max patcher for mono operation.  It can then function in stereo or 8-channel or 32-channel without a single modification.

But there’s a lot more than that here.  The number of channels is dynamic and can change at any time.  One place this is valuable is in ambisonic encoding and decoding where the order of the encoding can dramatically alter the number of channels required for the encoded signal.  If you want to try changing the ambisonic order on-the-fly, which changes the number of channels passed, you can.

Likewise, the vectorsize can be altered dynamically on a per-signal basis.  The benefit here may not be immediately obvious, but for granular synthesis, spectral work, and analysis based on the wave length of an audio signal (e.g. the kinds of things in IRCAM’s Gabor) this can be a huge win.

Writing the objects is also very simple.  If you write a Jamoma DSP object, then all you have to do to make it available in Jamoma Audio Graph is…

Nothing!

That’s right.  In Ruby, for example, all Jamoma DSP classes are made available with no extra work.  If you want to make a Max external for a particular object then you can use a class wrapper (1 line of code) to create the Max external.

Interested in join the fun?  Come find us!

Writing DSP Objects

In my last article I talked about the structure of the Jamoma Platform.  That’s a bit abstract to be of much direct use.  A primer on how to write a DSP object seems to be in order.

So… let’s imagine we want to write a simple unit generator for audio processing.  One of the simplest filters we can write is a one-pole lowpass filter.  In pseudo code, it might look like this:

static float previous_output = 0.0;
static float feedback_coefficient = 0.5; // default is half way between 0 Hz and Nyquist

float processOneSample(float input)
{
    float output = (previous_output*feedback_coefficient) + ((1.0-feedback_coefficient)*input);
    previous_output = output;
    return output;
}

Simple, right?  Like most simple questions, the answer is only simple until you start asking more questions…  Let’s brainstorm a few practical questions about this simple filter:

  • How do we set the coefficient?
  • How do we efficiently process in blocks of samples instead of one sample at a time?
  • how do we handle multiple channels?
  • what if the number of channels changes on the fly?
  • is the audio processed in a different thread than the object is created and deleted on?  how do we handle thread safety?
  • do we want to have a “bypass” built-in so we can audition the effect?
  • How do we wrap this for a host environment like Max/MSP?
  • How do we wrap this as an AudioUnit plug-in?
  • What if we want to swap this unit generator out for another in real-time, without having to recompile any code?
  • How do we handle denormals and other similar gremlins that can cause performance headaches in realtime DSP code?

One more question: how do you get all of this without it sucking the life and love out of making cool DSP code? Funny you should ask, because that’s the very reason for the Jamoma DSP framework. Let’s look at an how we would write this object using Jamoma DSP.

Example Class: TTLowpassOnepole

First, the header file: TTLowpassOnepole.h:

#include "TTDSP.h"

class TTLowpassOnePole : TTAudioObject {
	TTCLASS_SETUP(TTLowpassOnePole)
	TTFloat64		mFrequency;	///< filter cutoff frequency
	TTFloat64		mCoefficient;	///< filter coefficients
	TTSampleVector		mFeedback;	///< previous output sample for each channel

	TTErr updateMaxNumChannels(const TTValue& oldMaxNumChannels);
	TTErr updateSr();
	TTErr clear();
	TTErr setfrequency(const TTValue& value);
	inline TTErr calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt channel);
	TTErr processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs);
};

The TTDSP.h header includes everything needed to create a subclass of TTAudioObject. We will see some of the magical joy of TTAudioObject shortly. In the class definition there is a macro called TTCLASS_SETUP. This creates prototypes for the constructor, destructor, and glue code for class registration, etc.

This class implementation thus follows as:

#include "TTLowpassOnePole.h"

#define thisTTClass		TTLowpassOnePole
#define thisTTClassName		"lowpass.1"
#define thisTTClassTags		"audio, processor, filter, lowpass"

TT_AUDIO_CONSTRUCTOR
{
	addAttributeWithSetter(Frequency,	kTypeFloat64);
	addAttributeProperty(Frequency, range, TTValue(2.0, sr*0.475));
	addAttributeProperty(Frequency, rangeChecking, TT("clip"));

	addMessageWithArgument(updateMaxNumChannels);
	addMessage(updateSr);
	addMessage(clear);

	// Set Defaults...
	setAttributeValue(TT("maxNumChannels"), arguments); // This attribute is inherited
	setAttributeValue(TT("frequency"), 1000.0);
	setProcessMethod(processAudio);
}

TTLowpassOnePole::~TTLowpassOnePole()
{
	; // Nothing special to do for this class
}

TTErr TTLowpassOnePole::updateMaxNumChannels(const TTValue& oldMaxNumChannels)
{
	mFeedback.resize(maxNumChannels);
	clear();
	return kTTErrNone;
}

TTErr TTLowpassOnePole::updateSr()
{
	TTValue	v(mFrequency);
	return setFrequency(v);
}

TTErr TTLowpassOnePole::clear()
{
	mFeedback.assign(maxNumChannels, 0.0);
	return kTTErrNone;
}

TTErr TTLowpassOnePole::setFrequency(const TTValue& newValue)
{
	TTFloat64	radians;

	mFrequency = newValue;
	radians = hertzToRadians(mFrequency);
	mCoefficient = TTClip(radians / kTTPi, 0.0, 1.0);
	return kTTErrNone;
}

inline TTErr TTLowpassOnePole::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt channel)
{
	y = mFeedback[channel] = TTAntiDenormal((x * mCoefficient) + (mFeedback[channel] * (1.0 - mCoefficient)));
	return kTTErrNone;
}

TTErr TTLowpassOnePole::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(calculateValue);
}

Breaking it Down

To understand what’s happening here, let’s start at the bottom and work our way back up toward the top.

processAudio

This method accepts an input and an output.  The input and output arguments are arrays of multichannel audio signals.  That is to say the each of the input and output can contain zero or more multichannel signals, and each of those signals may have zero or more channels.  The audio signal has a vector size which indicates how many samples are contained for each channel that is present.

In most cases an object is only functioning on one multichannel input signal and one multichannel output signal.  Also, in most cases, the number of input channels and output channels are the same (e.g. 2 inputs and 2 outputs).  Furthermore, it is quite common that each channel is processed in parallel, and can be considered independent of the other channels.

Given this set of somewhat common set of assumptions, we can avoid the work of handling all of this audio processing machinery and just call the TT_WRAP_CALCULATE_METHOD macro.  Calling that macro will invoke the named calculation method to be used for processing one sample on one channel of one signal.  The calculate method is inlined, so we do not give up the performance benefits of processing by vector.

calculateValue

As we had previously alluded, this method calculates one output value for one input value.  You can think of this method in the mathematical terms

y = f(x)

This method may be called directly or, as just discussed, called to crunch numbers for the vector-based audio processing method.

setFrequency

As we will see shortly, attributes can be set using a default setter method that works most of the time.  In this case we need to do some customized work when the “Frequency” attribute is set.  Namely, we need to calculate the feedback coefficient.  We want to do that here so that the coefficient isn’t calculated every time our audio processing method is called.

This is the first time we’ve seen the TTValue data type, but we’ll be seeing a lot more of it.  This is the standard way of passing values.  TTValue can contain zero or more of any common data type (ints, floats, pointers) or special types defined in the Jamoma Foundation (symbols, objects, strings, etc.).

clear

This method is quite simple: it resets all of the feedback samples for each audio channel to zero.  It can be invoked by a user if the filter ‘blows-up’.

updateSr

This method is slightly special.  Just as we have a “Frequency” attribute, we have an “sr” attribute, which is the sample-rate of the object.  The trick is that we inherit the “sr” attribute from TTAudioObject.

Some objects may ignore the sample rate, or will function properly when the sample rate changes by virtue of the face that the member variable changed values.  In our case we need to take further action because our coefficient needs to be re-calculated.  The “updateSr” method is a notification that we will receive from our base class when the base class’ “sr” attribute is modified.

updateMaxNumChannels

Just like the updateSr() method, this method is a notification sent to us by our base class.  In this case, the notification is sent when the base class has a change in its “maxNumChannels” attribute.

The “maxNumChannels” attribute is an indicator of the maximum number of channels the object should be prepared to process in the audio processing method.  As such, we use this notification to take care of memory allocation for anything in our instance that is related to the number of channels we process.

The Destructor

As the comment says, we don’t have anything special to take care of in this case.  We still define the destructor so that we can be explicit about what is happening regarding object life-cycle.

The Constructor

Obviously, to experienced C++ programmers anyway, the constructor is what gets called when a new instance of our class is created.  But what we do in this constructor is what makes everything else we’ve been through actually work.

First, we use a macro to define the function prototype.  We do this because it is the same every single time, and this ensures that we don’t screw up the initialization (or lack of initialization) of members or super-classes.

Next, we define attributes.  In our case we have only one attribute, and that attribute has a custom setter method (the setFrequency() method).  It is represented by the mFrequency member variable.  Attributes can be given properties.  In this case we limit the range of the values for our attribute to things that will actually work.

In addition to attributes, which have a state and are represented by data members, we have messages.  These are stateless methods that will be invoked any time our object receives the said message.  Messages might have no arguments, as in the case of the “sr” and “clear” messages.  If they do have arguments the arguments will passed as a TTValue reference, as in the case of the “updateMaxNumChannels” method.

Finally we set defaults.  This means default attribute values, but it also means the initial audio processing and value calculation methods.  These methods may be changed on the fly during operation, though in our case we only have one of each.

Gift Wrap

To summarize, we now have an object with the following features from our original list:

  • We set the coefficient using an attribute for cutoff frequency, which is automatically updated when the sample rate changes.
  • We efficiently process in blocks of samples (instead of one sample at a time) using the processAudio method.
  • processAudio also handles N channels of input and output transparently.
  • It is no problem if the number of channels changes on the fly, this is all handled properly.
  • The audio may be processed in a different thread than the one on which the object is created and deleted.  Thread safety for this circumstance is handled by the environment.
  • We did not discuss it, but we do have a “bypass” attribute that we inherited, among others, so we got this functionality for free.
  • We can swap any object inheriting from TTAudioObject for another in real-time.  The attributes and messages are called by dynamically bound symbols, so there are no linking problems or related concerns.
  • We did not discuss it but the calculateValue method handles denormals using a library function.

So now we just need to use the object.  TTAudioObject classes have been used directly and in combinations with each other to create Max/MSP objects, Pd objects, VST plug-ins, AudioUnit plug-ins, etc.  Some examples of these can be found in the Jamoma DSP Github repository.  Others include the Tap.Tools, sold by Electrotap.

The Magic Wand

One of the benefits of our dynamically-bound, message-passing TTAudioObjects is that we can use introspection on objects to find out about them at runtime.  That means we can load an object by name, ask what attributes it has and what types they are, and then create a new interface or adapter to the object.  One manifestation of this a class wrapper for Cycling ’74′s Max environment.

Given our TTAudioObject that implements a onepole lowpass filter, all that is required to make a full-blown Max/MSP object complete with Max attributes is this:

#include "TTClassWrapperMax.h"

int TTCLASSWRAPPERMAX_EXPORT main(void)
{
	TTDSPInit();
	return wrapTTClassAsMaxClass(TT("lowpass.1"), "jcom.onepole~", NULL);
}

The first symbol we pass is the symbol name of the TTAudioObject.  The second argument is the name of the Max class we generate.  It really is this easy.

At the time of this writing, no one that I’m aware of has written a similar class wrapper for PureData, SuperCollider, AudioUnits, etc.  but there is no reason that this kind of wrapper couldn’t work for any of those target environments.

It’s fun stuff!  As the Jamoma Foundation and DSP projects have evolved over the last six years the code for classes has become increasingly flexible and also increasingly clear.  It’s possible to really focus on the task in the code without having to worry about all of the glue and filler typically involved in writing audio code with C and C++ APIs.

Refactoring Jamoma

Over the last several months I haven’t been writing much in the way of prose.  Instead I have been working on the Jamoma 0.5 release, a consulting project built on top of the Jamoma DSP layer, and developing a graphics library to support a new version of Hipno.  Now, at the end of these projects we are doing much more than just dsp with the Jamoma “DSP” layer – in fact Jamoma underwent a major refactoring and restructuring.

The Jamoma Platform Revisited

Jamoma Layered TopologyIn my previous post about The Jamoma Platform, we introduced a graphic that looked like this first graphic.  The DSP Layer had a lot going on.  It was a runtime for a dynamically-bound object-oriented framework.  It was starting to grow graphics capabilities.  And Ruby language bindings.  None of this stuff has anything to do with audio or digital signal processing.

So it was time to break apart the monolithic beast to make the structure clearer, more focused, more flexible and to increase orthogonality and decoupling.

A New Pile

Jamoma's layered code architectureThe layers are now piled up on top of the Jamoma Foundation.  The Foundation is analogous to Cocoa’s Foundation classes.  It defines and implements the basic runtime architecture on which everything else relies.  It includes the base classes, message passing system, notifications, OS-specific glue, object instantiation, etc.

The DSP Layer, now, is actually focused on audio and signal processing.  It extends the Foundation’s classes to make it easy to create dynamically bound audio objects.  As before, there are example projects in Jamoma that compile into PureData externals and VST/AudioUnit plug-ins, but I’ve now taken the care to add them to the graphic.

The Multicore Audio Graph Layer is largely unchanged, as it was already separated from the DSP Layer.  With the new extensions, such as the Ruby language bindings, it becomes possible to create a graph of audio objects in real time using Ruby’s irb somewhat in the fashion that people use Ge Wang’s excellent Chuck environment.

Meanwhile, the new Graphics Engine creates both a platform-independent, and a host-independent, way to draw to the screen.  This means that GUI widgets can be created that will work both in Max/MSP and in other environments, such as AudioUnit plug-ins.  Internally the drawing is performed using the Cairo graphics library.  We extend the library to deal with other OS-related issues like fonts, mouse interaction, creating windows, etc.  We also make the Cairo API available through the Foundation’s message-passing system in addition to the old-fashioned static linking.  That means that we can perform drawing dynamically from environments such as Ruby.

Making it Happen

As an open source project, it is quite impressive how much a smallish group has been able to accomplish with limited resources and man-power.  While we may have missed on a few things, we have definitely gotten a lot of “bang for the buck”.  I mention this because we could use some help.  There are lots of areas where contributions are welcome.  We have a particular need for someone who is handy with C++ and oriented towards the Windows platform.  If you are interested, please make yourself known to us.  We don’t bite :-) .

Information can be found at the Jamoma website and over at our Github repository.

Custom Data-Types in Max Part 3: Binding to Symbols

When people design systems in Max that are composed of multiple objects that share data, they have a problem: how do you share the data between objects? The coll object, for example, can share its data among multiple coll objects with the same name.  The buffer~ object can also do this, and other objects like play~ and poke~ can also access this data.  These objects share their data by binding themselves to symbols.

This is the third article in a series about working with custom data types in Max.  In the first two articles we laid the groundwork for the various methods by discussing how we wrap the data that we want to pass.  The next several articles will be focusing on actually passing the custom data between objects in various ways.  In this series:

  1. Introduction
  2. Creating “nobox” classes
  3. Binding to symbols (e.g. table, buffer~, coll, etc.)
  4. Passing objects directly (e.g. Jamoma Multicore)
  5. Hash-based reference system (similar to Jitter)

The Symbol Table

Before we can talk about binding objects to symbols, we should review what a symbol is and how Max’s symbol table works. First, let’s consider the definition of a t_symbol from the Max API:

typedef struct _symbol {
    char      *s_name;
    t_object  *s_thing;
} t_symbol;

So the t_symbol has two members: a pointer to a standard C-string and a pointer to a Max object instance.  We never actually create, free, or otherwise manage t_symbols directly.  This is a function of the Max kernel.  What we do instead is call the gensym() function and Max will give us a pointer to a t_symbol that is resident in memory, like so:

t_symbol *s;

s = gensym("ribbit");

What is it that gensym() does exactly?  I’m glad you asked…  The gensym() function looks in a table maintained by Max to see if this symbol exists in that table.  If it does already exist, then it returns a pointer to that t_symbol.  If does not already exist then it creates it, adds it to the table, and then returns the pointer.  In essence, it is a hash table that maps C-strings to t_symbol struct instances.

As a side note, one of the really fantastic improvements introduced in Max 5 is dramatically faster performance from the gensym() function and the symbol table.  It’s not a sexy feature you will see on marketing materials, but it is one of the significant under-the-hood features that make Max 5 such a big upgrade.

As seasoned developers with the Max or Pd APIs will know, this makes it extremely fast to compare textual tidbits.  If you simply try to match strings with strcmp(), then each character of the two strings you are comparing will need to be evaluated to see if they match.  This is not a fast process, and Max is trying to do things in real time with a huge number of textual messages being passed between objects.  Using the symbol table, you can simply compare two t_symbol pointers for equality.  One equality check and you are done.

The symbol table is persistent throughout Max’s life cycle, so every symbol gensym()’d into existance will be present in the symbol table until Max is quit.  This has the benefit of knowing that you can cache t_symbol pointers for future comparisons without worrying about a pointer’s future validity.

There’s s_thing You Need to Know

So we have seen that Max maintains a table of t_symbols, and that we can get pointers to t_symbols in the table by calling the gensym() function.  Furthermore, we have seen that this is a handy and fast way to deal with strings that we will be re-using and comparing frequently.  That string is the s_name member of the t_symbol.  Great!

Now lets think about the problem we are trying to solve.  In the first part of this series we established that we want to have a custom data structure, which we called a ‘frog’.  In the second part of this series we implemented that custom data structure as a boxless class, which is to say it is Max object.  An now we need a way to access our object and share it between other objects.

You are probably looking at the s_thing member of the t_symbol and thinking, “I’ve got it!”  Well, maybe.  Let’s imagine that we simply charge ahead and start manipulating the s_thing member of our t_symbol.  If we did our code might look like this:

t_symbol *s;
t_object *o;

s = gensym("ribbit");
o = object_new_typed(_sym_nobox, gensym("frog"), 0, NULL);
s->s_thing = 0;

Now, in some other code in some other object, anywhere in Max, you could have code that looks like this:

t_symbol *s;
t_object *o;

s = gensym("ribbit");
o = s->s_thing;

// o is now a pointer to an instance of our frog
// which is created in another object

Looks good, right? That’s what we want. Except that we’ve made a lot of assumptions:

  1. We aren’t checking the s->s_thing before we assign it our frog object instance.  What if it already has a value?  Remember that the symbol table is global to all of Max.  If there is a buffer~, or a coll, or a table, or a detonate object, (etc.) bound to the name “ribbit” then we just broke something.
  2. In the second example, where we assign the s_thing to the o variable, we don’t check that the s_thing actually is anything.  It could be NULL.  It could be an object other than the frog object that we think it is.
  3. What happens if we assign the pointer to o in the second example and then the object is freed immediately afterwards in another thread before we actually start dereferencing our frog’s member data?  This thread-safety issue is not academic – events might be triggered by the scheduler in another thread or by the audio thread.

So clearly we need to do more.

Doing More

Some basic sanity checks are in order, so let’s see what the Max API has to offer us:

  1. First, we should check if the s_thing is NULL.  Most symbols in Max will probably have a NULL s_thing, because most symbols won’t have objects bound to them.
  2. If it is something, there is no guarantee that the pointer is pointing to a valid object.  You can use the NOGOOD macro defined in ext_mess.h to find out.  If you pass a pointer to NOGOOD then it will return true if the pointer is, um, no good.  Otherwise it returns false – in which case you are safe.
  3. If you want to be safe in the event that you have multiple objects accessing your object, then you may want to incoporate some sort of reference counting or locking of your object.  This will most likely involve adding a member to your struct which is zero when nothing is accessing your object (in our case the frog), and non-zero when something is accessing it.  You can use ATOMIC_INCREMENT and ATOMIC_DECREMENT (defined in ext_atomic.h) to modify that member in a thread safe manner.
  4. Finally, there is the “globalsymbol” approach is demonstrated in an article about safely accessing buffer~ data that appeared here a few weeks ago.

Alternative Approaches

There are some alternative approaches that don’t involve binding to symbols.  For example, you could have a class that instead implements a hash table that maps symbols to objects.  This would allow you to have named objects in a system that does not need to concern itself with conflicts in the global namespace.  This is common practice in the Jamoma Modular codebase.

The next article in this series will look at a very different approach where the custom data is passed through a chain of objects using inlets and outlets. Stay tuned…

Custom Data-Types in Max Part 2: Nobox Classes

In this series I am offering a few answers to the question “what’s the best way to have multiple max objects refering to a custom data structure?”  Another variation on that question is ”I want to define a class that will never become a full-blown external for instantiation in a Max patcher, but will be instantiated invisibly as a (possibly singleton) object that can serve some functions for other objects.”  In essence, the answer to both of these questions begins with the creation of ‘nobox’ objects.

This is the second of a multi-part series. Over the next several weeks I will be writing about several different approaches to passing custom data types in Max, and I’ll be using some real-world examples to demonstrate how and why these various strategies are effective.

  1. Introduction
  2. Creating “nobox” classes
  3. Binding to symbols (e.g. table, buffer~, coll, etc.)
  4. Passing objects directly (e.g. Jamoma Multicore)
  5. Hash-based reference system (similar to Jitter)

Boxless Objects

When people use Max they typically think about objects, created in a little ‘boxes’ in a patcher document.  These boxes are then connected with patch cords.

In the first part of this series I introduced a new data type called a ‘frog’.

The the frog class could be defined as a C++ object, a C struct, or some other way. We will define our custom ‘frog’ type as a Max class.  In Max there are two common ways to define a class.  The first is a “box” class, which is to say that it is an object that can be instantiated in a box that is in a patcher.  Most objects are box classes.

The second way is to create a “nobox” class.  A nobox is a class that cannot be created directly in a Max patcher. Instead this is a class that exists solely under-the-hood to be used by other classes, or by Max itself. We will create our ‘frog’ data type as a ‘nobox’ class.

One example of a nobox class that is defined internally to Max is the t_atomarray in the Max API.  Let’s consider it’s definition from ext_atomarray.h:

typedef struct _atomarray {
	t_object	ob;
	long		ac;
	t_atom		*av;
} t_atomarray;

The atomarray is simply an object that manages an array of atoms.  However it is a proper object. You can instantiate it by calling object_new() and you free it by calling object_free().  It has a the typical Max methods which can be invoked by sending messages to the object using the object_method(), object_method_typed(), and other similar functions.

If you poke around the Max SDK you will probably notice a number of these nobox classes.  They include t_linklist, t_hashtab, t_dictionary, t_symobject, etc.  Even The Max object, the one that you send cryptic messages to using message boxes that say things like “;max sortpatcherdictonsave 1″, is a nobox object.

Defining a Frog

If we define our frog as a nobox class, we may have a struct like this:

typedef struct _frog {
	t_object	ob;
	long		num_flies;
 	t_atom		*flies;
} t_frog;

This is basically the same thing as an atomarray, but we will make it ourselves from scratch.  And we can define some more whimsical names for its methods.

Just like any other class, we need to cache our class definition in a static or global toward the top of our file.  So we can simply do that like usual:

t_class *s_frog_class = NULL;

Then we can get to the class definition, which once again will look pretty familiar to anyone who has written a few objects using the Max 5 SDK.

int main(void)
{
	common_symbols_init();

	s_frog_class = class_new("frog",
				(method)frog_new,
				(method)frog_free,
				sizeof(t_frog),
				(method)NULL,
				A_GIMME,
				0L);

	class_addmethod(s_frog_class, (method)frog_getflies, 	"getflies", A_CANT, 0);
	class_addmethod(s_frog_class, (method)frog_appendfly, 	"appendfly", A_CANT, 0);
	class_addmethod(s_frog_class, (method)frog_getnumflies,	"getnumflies", 0);
	class_addmethod(s_frog_class, (method)frog_clear,	"clear", 0);

	class_register(_sym_nobox, s_frog_class);
	return 0;
}

Essentially:

  1. we define the class itself, which includes providing the instance create and destroy methods, the size of the object’s data, and what kind of arguments the creation method expects.
  2. we initialize commonsyms — this means we can refer to a whole slew of pre-defined symbols without having to make computationally expensive gensym() calls.  For example, we can use _sym_nobox instead of gensym(“nobox”).
  3. we add some message bindings so that we can call the methods using object_method() and friends.  One aspect of these messages is that we gave a couple of them A_CANT types.  This is uncommon for normal box classes, but quite common for nobox classes.  It essentially indicates that Max “can’t” typecheck the arguments.  This allows us to bind the message to a method with virtually any prototype we want.
  4. we register the class as a nobox object

Take special note of that last step.  Instead of registering the class in the “box” namespace, we register it in the “nobox” namespace.

We could also define attributes for our class, but for the sake of simplicity we are just using messages in this example.

The Froggy Lifecycle

When we go to use our frog class we will expect to be able to do the following:

t_object *myfroggy;
myfroggy = object_new_typed(_sym_nobox, gensym("frog"), 0, NULL);

// do a bunch of stuff
// snap up some flies
// sit around the pond and talk about how the mud was in the good ole days...

object_free(myfroggy);

Notice that once again we have to specify the correct namespace for the object, _sym_nobox, in our call to object_new_typed().  We used object_new_typed() because we defined the class to take arguments in the A_GIMME form.  If we use object_new() instead of object_new_typed() then the arguments passed to our instance creation routine would be pointing to bogus memory (and we definitely do not want that – unless you are a crash loving masochist).

Speaking of the object creation routine, it can be pretty simple:

t_object* frog_new(t_symbol *name, long argc, t_atom *argv)
{
    t_frog	*x;

    x = (t_frog*)object_alloc(s_frog_class);
    if(x){
		// in Max 5 our whole struct is zeroed by object_alloc()
		// ... so we don't need to do that manually

		// handle attribute arguments.
		// we don't have any attributes now, but we might add some later...
		attr_args_process(x, argc, argv);
	}
	return x;
}

In addition to the things noted in the method’s code, I’ll point out the obvious fact that we don’t need to worry about creating inlets or outlets — our object will never be visible in a box in a patcher, and thus never have patch cords connected to it.

Our free method is also quite simple.  We just call the clear method.

void frog_free(t_frog *x)
{
	frog_clear(x);
}

Sending Messages to a Frog

At the beginning of the previous section we created an instance of the frog object with object_new_typed().  We probably didn’t do this just to free the object again.  We want to send some messages to get our frog to do something – like collect flies.

Let’s define the four methods we specified above:

void frog_getflies(t_frog *x, long *numflies, t_atom **flies)
{
	if (numflies && flies) {
		numflies = x->num_flies;
		flies = x->flies;
	}
}

void frog_appendfly(t_frog *x, t_atom *newfly)
{
	if (x->num_flies == 0) {
		x->num_flies = 1;
		flies = (t_atom*)sysmem_newptr(x->num_flies * sizeof(t_atom));
	}
	else {
		x->num_flies++;
		flies = (t_atom*)sysmem_resizeptr(flies, x->num_flies * sizeof(t_atom));
	}
	x->flies[x->num_flies-1].a_type = newfly->a_type;
	sysmem_copyptr(newfly, x->flies+(x->num_flies-1), sizeof(t_atom));
}

long frog_getnumflies(t_frog *x)
{
	return x->num_flies;
}

void frog_clear(t_frog *x)
{
	if (x->num_flies && x->flies) {
		sysmem_freeptr(x->flies);
		x->flies = NULL;
		x->num_flies = 0;
	}
}

None of the messages are defined with argument types of A_GIMME, so we will use object_method() to send messages, and not object_method_typed() or its immediate descendants.  Usage of these methods might then look like this:

t_atom	mosquito;
t_atom	bee;
long	n;
long	ac = 0;
t_atom	*av = NULL;

atom_setsym(&mosquito, gensym("eeeeyeyeeyyeyyyyeeyyye"));
atom_setsym(&bee, gensym("bzzzzzzzz"));
// here we have the frog snap up the flies using one its A_CANT methods
object_method(myfroggy, gensym("appendfly"), &mosquito);
object_method(myfroggy, gensym("appendfly"), &bee);

// this call returns a value -- we have to cast it, but that's okay
n = (long)object_method(myfroggy, gensym("getnumflies"));
// another A_CANT method, passing two pointer args
object_method(myfroggy, gensym("getflies"), &ac, &av);

// we're all done and the froggy has a bowel movement
object_method(myfroggy, gensym("clear"));

Wrap Up

So we have a boxless class now.  It isn’t all that different from a regular class, but there are always people asking me about example code that shows how to do this sort of thing.  And this information lays the foundation for the upcoming articles in this series.

If you have any questions, please leave a comment!

Custom Data-Types in Max Part 1: Introduction

The Max API makes it easy to pass a handful of standard data types in Max: ints, floats, symbols, lists of the aforementioned.  But what happens when you want to pass a frog from one object to the next?  A frog is not a standard data type.  Instead it is something made up that we want to send hopping through our Max patch from one green object box to the next.

Where do we start?

Before we can pass the frog from one object to another, we first need to define the frog type.  What is it?  Is it an object (meaning a proper Max class with a t_object as it’s first member)?  Or is it a naked struct or C++ class?  Or something else entirely?  Are we passing the data by value, or by reference (meaning a pointer)?

That last question may be more difficult that it seems at first glance.  Answering the question may help to determine the answer to the other questions.  If we pass by value then we have a certain amount of simplicity, but for anything other than rudimentary types it quickly becomes a very computational expensive situation.  So the obvious answer here is to pass by pointer, right?  Not so fast…  Consider the following patcher topology:

simple-patcherIf we pass by value from the first number object, then we get the results that are shown.  If we simply pass a pointer to the value (pass by reference) without some sort of management in place then we will get very different results.  The result could be the following:

  1. The address of the data (2) is passed to the [+ 5] object.
  2. 5 is added to 2, the data now has a value of 7 and this new value is passed to the lower-right number box.
  3. The address of the data (which now has the value 7!) is now passed to the [+ 7] object.
  4. 7 is added to 7, the data now has a value of 14(!) and this new value is passed to the lower-left number box.

Indeed.  A subtle problem with real life consequences.  In our example the problem may seem trivial, but when you are operating on more complex structures (e.g. Jitter or FTM) then there needs to be a system in place that allows for the graph to bifurcate without downstream operations corrupting the output of other operations happening ‘in parallel’.

Series Overview

This introduction to the problem is the first of a multi-part series. Over the next several weeks I will be writing about several different approaches to passing custom data types in Max, and I’ll be using some real-world examples to demonstrate how and why these various strategies are effective.

  1. Introduction
  2. Creating “nobox” classes
  3. Binding to symbols (e.g. table, buffer~, coll, etc.)
  4. Passing objects directly (e.g. Jamoma Multicore)
  5. Hash-based reference system (similar to Jitter)

Accessing buffer~ Objects in Max5

One thing that has always been a bit tricky, and perhaps a bit under-documented, has been writing good code for accessing the contents of a buffer~ object in Max.  What has made the situation a bit more confusing is that the API has changed slowly over a number of versions of Max to make the system more robust and easier to use.  This is certainly true of Max 5, and the most recent version of the Max 5 Software Developer Kit makes these new facilities available.

I’ll be showing the favored way to access buffer~ objects for Max 5 in the context of a real object: tap.buffer.peak~ from Tap.Tools.  I’ll show how it should be done now, and in some places I’ll show how it was done in the past for reference.

Getting a Pointer

The first thing we need to do is get a pointer to the buffer~ bound to a given name.  If you know that there is a buffer~ object with the name “foo” then you could simply do this:

t_symbol* s = gensym("foo");
t_buffer* b = s->s_thing;

However, there are some problems here.  What if “foo” is the name of a table and not a buffer~?  What if there is a buffer~ named foo in the patcher, but when the patcher is loaded the buffer~ is instantiated after your object.  What if you execute the above code and then the user delete’s the buffer~ from their patch?  These are a few of the scenarios that happen regularly.

A new header in Max 5 includes a facility for eleganty handling these scenarios:

#include "ext_globalsymbol.h"

Having included that header, you can now implement a ‘set’ method for your buffer~-accessing object like so:

// Set Buffer Method
void peak_set(t_peak *x, t_symbol *s)
{
	if(s != x->sym){
		x->buf = (t_buffer*)globalsymbol_reference((t_object*)x, s->s_name, "buffer~");
		if(x->sym)
			globalsymbol_dereference((t_object*)x, x->sym->s_name, "buffer~");
		x->sym = s;
		x->changed = true;
	}
}

By calling globalsymbol_reference(), we will bind to the named buffer~ when it gets created or otherwise we will attach to an existing buffer.  And when I say attached, I mean it.  Internally this function calls object_attach() and our object, in this case tap.buffer.peak~, will receive notifications from the buffer~ object.  To respond to these notifications we need to setup a message binding:

class_addmethod(c, (method)peak_notify,		"notify",		A_CANT,	0);

And then we need to implement the notify method:

t_max_err peak_notify(t_peak *x, t_symbol *s, t_symbol *msg, void *sender, void *data)
{
	if (msg == ps_globalsymbol_binding)
		x->buf = (t_buffer*)x->sym->s_thing;
	else if (msg == ps_globalsymbol_unbinding)
		x->buf = NULL;
	else if (msg == ps_buffer_modified)
		x->changed = true;

	return MAX_ERR_NONE;
}

As you may have deduced, the notify method is called any time a buffer~ is bound to the symbol we specified, unbound from the symbol, or any time the contents of the buffer~ are modified.  For example, this is how the waveform~ object in MSP knows to update its display when the buffer~ contents change.

Accessing the Contents

Now that you have a pointer to a buffer~ object (the t_buffer*), you want to access the contents.  Having the pointer to the buffer~ is not enough, because if you simply start reading or writing to the buffer’s b_samples member you will not be guaranteed of thread-safety, meaning that all matter of subtle (and sometimes not so subtle) problems may ensue at the most inopportune moment.

In Max 4 you might have used code that looked like the following before and after you accessed a buffer~’s contents:

    saveinuse = b->b_inuse;
    b->b_inuse = true;

    // access buffer contents here

    b->b_inuse = saveinuse;
    object_method((t_object*)b, gensym("dirty"));

The problem is that the above code is not entirely up to the task.  There’s a new sheriff in town, and in Max 5 the above code will be rewritten as:

    ATOMIC_INCREMENT((int32_t*)&b->b_inuse);
    // access buffer contents here
    ATOMIC_DECREMENT((int32_t*)&b->b_inuse);
    object_method((t_object*)b, gensym("dirty"));

This is truly threadsafe. (Note that you only need to call the dirty method on the buffer to tell that it changed if you wrote to the buffer).

Here is the code from tap.buffer.peak~ that access the buffer~’s contents to find the hottest sample in the buffer:

{
	t_buffer	*b = x->buf;		// Our Buffer
	float		*tab;		        // Will point to our buffer's values
	long		i, chan;
	double		current_samp = 0.0;	// current sample value

	ATOMIC_INCREMENT((int32_t*)&b->b_inuse);
	if (!x->buf->b_valid) {
		ATOMIC_DECREMENT((int32_t*)&b->b_inuse);
		return;
	}

	// FIND PEAK VALUE
	tab = b->b_samples;			// point tab to our sample values
	for(chan=0; chan < b->b_nchans; chan++){
		for(i=0; i < b->b_frames; i++){
			if(fabs(tab[(chan * b->b_nchans) + i]) > current_samp){
				current_samp = fabs(tab[(chan * b->b_nchans) + i]);
				x->index = (chan * b->b_nchans) + i;
			}
		}
	}

	ATOMIC_DECREMENT((int32_t*)&b->b_inuse);
}

Reflections on ObjectiveMax

objective-max-screenshot

A couple of years ago I got on an Objective-C kick.  In the process I created ObjectiveMax, an open-source framework for writing Max externals using Objective-C.  The goal was to create the easiest way possible to write objects for Max/MSP with minimal amount of “decoration code”.

My feeling is that it has been under-used by the community as a whole.  Reflecting, I think I know (at least partially) why…

I had intended (and even started) writing all of Tap.Tools 3 using ObjectiveMax.  The problem was that getting it to work on Windows, and then keeping it working on Windows, was beyond onerous.  I eventually decided that my personal sanity could not be tied to the inner workings of the GNUStep project.  In the end only the tap.applescript object is using ObjectiveMax.

A lot of people writing Max objects think about cross-platform compatibility.  Objective-C, and thus ObjectiveMax, do not easily provide this.  So that’s the first problem.

The second problem is that ObjectiveMax was initially licensed in a fairly unfriendly manner.  It took a dual-licensing approach similar to the one used by JUCE: GNU GPL for open source people, and pay money for a closed-source license.  While not an impossible license, there is enough in there to annoy and offend everyone.

There is a third problem too, ultimately caused by the first two problems: lack of adoption or popularity begets a lack of adoption and popularity.  No one uses it because no one else is using it.

If it’s Broke, Fix it.

I’m convinced that for Mac users this is the easiest way possible to write objects for Max/MSP.  So how should these concerns be addressed?

First, I just changed the licensing of ObjectiveMax to a single new BSD license.  This license was first suggested to me for ObjectiveMax about a year ago by Niklas Saers.  The more I’ve thought about it, the more sense it makes.  This makes the framework free and open-source to everyone for virtually all purposes, including commercial purposes.

Second, I don’t plan on rushing in to making ObjectiveMax work on Windows.  But I’m more than happy to help anyone who does want to get it working.  I’ve been keeping an eye on the Cocotron project for a while now, and I’d be very pleased to see people join the ObjectiveMax GoogleCode project to work on using Cocotron to get a version working for Windows.

And the third problem?  Well, it would be futile to try and control the adoption of the framework.  It’s open-source, and if people think it is worthwhile then they will use it.  Hopefully people will join the project and contribute to it.  One thing that is true is that I have not promoted ObjectiveMax much, and I’ve never taught any seminars using it.  This type of activity would be almost certain to increase the project’s luster and adoption.

… and if You Can’t Beat ‘em …

As previously mentioned, I ended up giving up on using ObjectiveMax for Tap.Tools 3, but solely for the reason of cross-platform compatibility.  A lot of what I learned, and learned to love, about Objective-C made it into the C++ library that Tap.Tools 3 and Jamoma use.

The TTBlue project (a.k.a the Jamoma DSP Library) incorporates reflection, message passing, and other aspects of Objective-C but in a C++ context that functions on both the Mac and Windows.  This project is very active, and the resulting code with which you write objects is getting progressively cleaner.

Or, as a card from Brian Eno’s Oblique Strategies states “When faced with a choice, do both.”