Archive for the ‘programming’ Category

JambaLaya approaching final candidate

Wednesday, March 19th, 2008

I’ve been working on it like crazy, stomping bugs and adding polish. It is pretty close to RC. Still need to add registration and complete the website infrastructure to automate dispensing of serials. I’m sure it will be huge because I just added the killer must-have feature.

Behold – Murph and the MagicTones Mode!

murphaboutbox.png

JambaLaya covered in “Thick Red Shag!” No other Audio Units host has that! Take that MainStage!

Addressing HAL Devices with Apple’s Core Audio in JambaLaya

Sunday, March 16th, 2008

I play guitar and keyboards in a rock band for fun. I’m basically a guitarist, but I have this knack for programming things, like computers and, as it turns out, synthesizers. Thus, I always end up doing some keyboard work in any band I play with. I have a lot of classic hardware synthesizers from the 80’s. But these days a lot of software emulations for hardware have come out and I use these as much as possible.

Occasionally, however, there is no replacement for an external synthesizer. It would be great if JambaLaya could present and allow routing to the hardware instruments in the same way as it does software instruments. While I’m at it, I might as well add support for audio routing. Currently JambaLaya just uses the default audio device and plays to its default outputs.

An AudioUnit MusicDevice takes in MIDI control information and outputs audio signals. A hardware synth does the same, but to get its audio, I have to map it to an audio input in my audio interface and then sort of pretend that the audio is generated from the device. The idea being a hardware synth is a midi endpoint, channel, and audio input set. While I’m at it, I might as well provide HAL support and allow any kind of audio routing the user wants. My live audio interface is a MOTU UltraLite. It has 12 audio inputs and 14 audio outputs. It also acts as my MIDI interface. The goal is to make a hardware synthesizer look and act just like an AudioUnit MusicDevice.

AUGraph Channels vs Busses

AUGraph connections connect BUSSES. A buss can contain many channels. How many is determined by setting the AudioStreamBasicDescription on the kAudioUnitProperty_StreamFormat for the buss. Each node in an AUGraph has a number of input and output busses. For some AudioUnits, the number of busses are fixed. Most MusicDevices just have one output buss. Others, like the MatrixMixer can be configured with any number of busses.

Connecting Busses

To connect busses, you make node connections using

AUGraphConnectNodeInput(graph, sourceNode,sourceBussNumber, destinationNode,destinationBussNumber)

Before you can do this though, you have to configure the busses on both sides by setting kAudioUnitProperty_StreamFormat using an AudioStreamBasicDescription on both sides to make sure the signal formats and number of channels is compatible. If you don’t do this, things don’t work the way you expect. This is especially true when connecting a mixer because the number of channels in the stream format determines the number of channels in mixer. The total number of input channels in the mixer is the sum of the number of channels of each of its input busses. Same for the outputs. This is why configuring stream formats is so important. Furthermore, you cannot change the stream format after making the connection – you’ll get an error. So, always configure both stream formats prior to connecting nodes.

Mapping Audio IO in HAL Devices

HAL devices present their IO channels all in one buss. All the audio inputs (in jacks) are presented on a single output buss for the device. All of the audio outputs are presented on a single input buss. Confused? THE TERMINOLOGY OF INPUT vs OUTPUT in a HAL DEVICE is VERY CONFUSING. This took me many days of experimentation to figure out and is the primary motivator for writing this article.

To begin with, all HAL devices are referred to as Output Devices, regardless of whether they do input, output, or both. In the case of the MOTU UltraLite, one device does both jobs, but you could use different devices for input and output. HAL devices are not at all configurable with respect to what audio appears where – so to do any kind of routing, you want to stick a matrix mixer in front of it, then work with that to do signal routing. Thus, your application will most likely have a matrix mixer representing the audio inputs, and a matrix mixer representing the audio outputs.

AudioIO2

Creating the Output Device

First you need to add a node to your AUGraph to represent your HAL device.

AUGraph graph;
OSStatus status=NewAUGraph(&graph);

// Description for HAL Output Device
ComponentDescription halAudioOutputDescription={
kAudioUnitType_Output,
kAudioUnitSubType_HALOutput,
kAudioUnitManufacturer_Apple};

// Create a node to represent the IO device
AUNode outputDeviceNode;
status=AUGraphNewNode(graph, &halAudioOuputDescription, 0, 0, &outputDeviceNode);

// get the component instance so we can initialize the device -
// nothing works until the device is initialized
ComponentInstance instance = 0;
status=AUGraphGetNodeInfo(graph, outputDeviceNode, 0, 0, 0, &instance);

// initialize the device
status=AudioUnitInitialize(instance);

//Get the identifiers of the default audio input and output devices

AudioDeviceID outputDeviceID;
AudioDeviceID inputDeviceID;
UInt32 size=sizeof(AudioDeviceID);

status=AudioHardwareGetProperty ( kAudioHardwarePropertyDefaultOutputDevice, &size, &outputDeviceID );
status=AudioHardwareGetProperty ( kAudioHardwarePropertyDefaultInputDevice, &size, &inputDeviceID );

//Now you must enable the device for audio output.

UInt32 value = 1;
status=AudioUnitSetProperty(instance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &value, sizeof(value));

If we are using the same device for input, enable it for input too. IMPORTANT! The hardware’s OUTPUT channels appear on BUSS 0. But the INPUT channels are on BUSS 1! Why? What’s the significance? I DON’T KNOW! But keep this in mind as it will come back to bite you when connecting the input mixer.

if(inputDeviceID == outputDeviceID)
{
inputDeviceNode=outputDeviceNode;
status=AudioUnitSetProperty(instance, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &value, sizeof(value));
}
else // signal an error - you can only have one output device in the graph

// Set the AudioDeviceID on the HAL device to map it to the right piece of hardware
status=AudioUnitSetProperty(instance, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &outputDeviceID, sizeof(outputDeviceID));

Creating the Output Mixer

If you were just interested in mapping hardware inputs to outputs, you could get by with a single matrix mixer and set matrix channel volumes to route audio. But it seems more natural to connect nodes to make connections – especially when mixing in Audio Unit Music Devices (virtual instruments). So I create a mixer for each interface, then connect various busses between them like a patch bay. You create the mixer pretty much the same way as the HAL device.

// Description for the matrix mixer
ComponentDescription matrixMixerDescription={kAudioUnitType_Mixer, kAudioUnitSubType_MatrixMixer,kAudioUnitManufacturer_Apple};

// Create a node to represent the mixer
AUNode outputMixerNode;
status=AUGraphNewNode(graph, &matrixMixerDescription, 0, 0, &outputMixerNode);

// get the component instance so we can initialize the device - nothing works until the device is initialized
ComponentInstance instance = 0;
status=AUGraphGetNodeInfo(graph, outputMixerNode, 0, 0, 0, &instance);

// initialize the mixer
status=AudioUnitInitialize(instance);

The output device node’s audio is fed into INPUT BUSS 0 which has one channel in it for each OUTPUT jack on the device. So you only need a single OUTPUT BUSS on the mixer, which you will connect to the INPUT BUSS 0 of the OUTPUT DEVICE. Refer to the picture if you’re getting confused.

UInt32 busCount = 1;
status=AudioUnitSetProperty(instance, kAudioUnitProperty_BusCount, kAudioUnitScope_Output, 0, &busCount, sizeof(busCount));

Prior to connecting the nodes, you want to make sure the number of channels and sample rates match. THIS IS CONFUSING! The stream description for the INPUT bus of the OUTPUT device for the device’s OUTPUTS is gotten by asking for the stream format for the OUTPUT device’s OUTPUT stream format for BUSS 0. Read that a couple times. Because you have to copy that stream description to the INPUT BUSS 0 of the output device and the OUTPUT BUSS 0 of the output device prior to connecting the busses. Here we go.

// get the node instance for the output device
status=AUGraphGetNodeInfo(graph, outputDeviceNode, 0, 0, 0, &instance);

// get the OUTPUT stream description for the OUTPUT device to set on the DEVICE's INPUT BUS 0 and MIXER's OUTPUT BUS 0
AudioStreamBasicDescription streamDescription;
UInt32 size=sizeof(AudioStreamBasicDescription);
status=AudioUnitGetProperty(instance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &streamDescription, &size);

// set the format on the INPUT BUS 0 of the OUTPUT DEVICE
status=AudioUnitSetProperty(instance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &streamDescription, sizeof(streamDescription));

// get the node instance for the output mixer
status=AUGraphGetNodeInfo(graph, outputMixerNode, 0, 0, 0, &instance);

// set the format on the OUTPUT BUS 0 of the MIXER
status=AudioUnitSetProperty(instance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &streamDescription, sizeof(streamDescription));

// connect the busses - OUTPUT BUS 0 of the MIXER to INPUT BUS 0 of the OUTPUT Device - hard to keep straight I think
status=AUGraphConnectNodeInput(graph, outputMixerNode,0,outputDeviceNode,0);

Now you can configure the input side of this mixer anyway you like. For instance, you could create a bunch of stereo pairs and then attach Audio Unit Music Device’s to them. Or some stereo pairs and a few mono inputs. Think of it as one side of your patch bay.

Creating the Input Mixer

This code is very similar – only for reasons that I don’t understand, all of the action on the INPUT side of an OUTPUT device occurs on OUTPUT BUSS 1. First we create the mixer as before.

// Create a node to represent the mixer
AUNode inputMixerNode;
status=AUGraphNewNode(graph, &matrixMixerDescription, 0, 0, &inputMixerNode);

// get the component instance so we can initialize the device - nothing works until the device is initialized
ComponentInstance instance=0;
status=AUGraphGetNodeInfo(graph, inputMixerNode, 0, 0, 0, &instance);

// initialize the mixer
status=AudioUnitInitialize(instance);

The output device used for INPUT has an OUTPUT BUSS 1 buss with one channel in it for each INPUT jack on the device. So you only need a single INPUT BUSS on the mixer, which you will connect to the OUTPUT BUSS 1 of the output device used for input. Refer to the picture if you’re getting confused.

UInt32 busCount = 1;
status=AudioUnitSetProperty(instance, kAudioUnitProperty_BusCount, kAudioUnitScope_Input, 0, &busCount, sizeof(busCount));

Now we need to setup the stream formats for the OUTPUT BUSS 1 of the DEVICE and INPUT BUSS 0 of the MIXER. You get the correct stream format for the OUTPUT BUSS by getting it from the DEVICE INPUT BUSS 1. THIS IS VERY CONFUSING!

// get the INPUT stream description for the OUTPUT device used for INPUT to set on the DEVICE's OUTPUT BUSS 1 and MIXER's INPUT BUSS 0
// REMEMBER that the INPUT description is found on ELEMENT 1

// get the device instance
status=AUGraphGetNodeInfo(graph, inputDeviceNode, 0, 0, 0, &instance);

AudioStreamBasicDescription streamDescription;
UInt32 size=sizeof(AudioStreamBasicDescription);
status=AudioUnitGetProperty(instance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &streamDescription, &size);

// set the format on the OUTPUT BUS 1 of the DEVICE used for INPUT
status=AudioUnitSetProperty(instance, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &streamDescription, sizeof(streamDescription));

// get the node instance for the input mixer
status=AUGraphGetNodeInfo(graph, inputMixerNode, 0, 0, 0, &instance);

// set the format on the INPUT BUS 0 of the MIXER
status=AudioUnitSetProperty(instance,kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,0,&streamDescription,sizeof(streamDescription));

// connect the busses - OUTPUT BUS 1 of the DEVICE to INPUT BUS 0 of the MIXER - THINK HARD!
status=AUGraphConnectNodeInput(graph,inputDeviceNode,1,inputMixerNode,0);

Now you can configure the outputs of the input mixer into any combination of busses and channels you like. To make a connection, just connect an output buss from the input mixer to an input buss on the output mixer.

Hopefully this will help someone else because it took me days to figure this out as CoreAudio’s documentation is really sketchy.

Looking for work again

Monday, March 3rd, 2008

I’ve been doing a lot of PHP lately – shopping cart integration, web service clients, lots of ecommerce stuff. But I’m coming to the end of these projects and am looking for new challenges. Got a project or position that I can do remotely? Drop me a line.

PHP Shopping Carts

Sunday, January 13th, 2008

I’ve been doing some e-commerce integration for various clients – all of whom are using PHP. The integration has been using SOAP calls to billing service and shopping cart service providers.

Now I’m looking into free open source implementations. I’ve found osCommerce, zen cart, CRE Loaded, and Ubercart.

I guess I’ll start downloading and experimenting next week.

Unhappy New Year

Saturday, January 12th, 2008

Welcome to 2008 – so far I’m not enjoying it.

Last week every steady stream of income I have evaporated. So I am actively seeking work. Either contract/remote, or possibly would consider joining an innovative startup with a great idea. I’m not too interested in conventional employment with a big company. People wondering about my skillz can check out my Linked In profile.

Lately I’ve been doing a lot of PHP, AJAX, and SOAP stuff, Smalltalk web programming with Seaside, and Mac application programming with CoreAudio (JambaLaya).

MIDI Performance Software

Friday, January 11th, 2008

jambalaya1.png

Last spring and summer, I decided to stop dragging a bunch of hardware synthesizers back and forth to band practice and start using a laptop as an all-in-one solution. This is more or less possible thanks to the availability of a variety of virtual instruments in Audio Units format that rival (and in some cases faithfully reproduce) the hardware synths of olde.

Seems simple. I need a MIDI controller keyboard – I chose an 88 key model and figured I’d map various instruments to different ranges of keys. So I started looking for an Audio Units host oriented towards live performance.

I came up empty. Nearly all of them are oriented towards sequencing and multi-track recording. They could kind of do what I wanted, but the user interface wasn’t oriented towards what I needed. There was one product – an independent program called RAX – that seemed right – only its author had just withdrawn it from the market. I managed to get an evaluation license from the developer but I disqualified it because it had a problem handling sustain pedal events and its future was uncertain.

So I set out to build my own and I’ve succeeded. It works well enough, is pretty bare bones, but allows the user to do complex splits and layers very quickly. I call it JambaLaya and I use it all the time. It isn’t quite production quality and there are missing feature I’d like to add. But it is a great feeling to control your own destiny and not have to worry about a critical piece of software disappearing from the market.

Now I’m trying to decide what to do with it. I could polish it up and offer it for sale, but since I wrote it two things have happened. RAX was acquired by a new publisher who is once again selling and supporting it and Apple has released a Logic 8 update with a program called Mainstage that is also oriented towards live performance. In both cases, I prefer the way the JambaLaya works, the UI is much more feature dense and it works the way I expect (little wonder, since I wrote it). I think in the short term, the best thing is to start a community website for it and give it away. So I think that’s the plan unless somebody has a better idea. I just need more time to configure the Drupal site and get that going.

I’m a Google Summer of Code Mentor!

Wednesday, March 21st, 2007

Are you a student? Want to make some cash? Want to do it with Smalltalk? Sign up for one of my Google Summer of Code projects.

Seaside update complete!

Tuesday, February 6th, 2007

That was easier than I thought – thanks to a nearly complete port done by my predecessor. However, I have finally thrown in the towel and upgraded the entire application to a 3.8 Squeak image. 3.8 brings a lot of baggage I don’t need – like character encodings and true type font rendering.

However, enough tools such as squeakmap and glorp have become dependent on the newer apis that integrating new code was getting to be too hard. So I started with a clean 3.8 image and started loading Monticello packages and eventually ended up with a completely new build. Then I upgraded the Seaside version.

With a new build and upgraded infrastructure, I then successfully loaded Magritte into the image. So now I have been working through the tutorials.

More on that later.

Database Transplant Successful

Wednesday, January 31st, 2007

OmniBase is dead.

I killed it.

The replacement with GLORP has been successful. Rate of error discovery has stabilized and, after about 3 weeks of production experience and many small fixes, is now below OmniBase’s on its best day.

A few things I’ve learned along the way:

1) Put limits on all search queries. All of them. Too many times in the last couple weeks the system became unresponsive for a couple minutes as it fetched every blessed row in the database. If you’re getting that much stuff, you’re not gonna find it. I’ve limited all searches to 20 rows.

2) Use plain old objects wherever possible. OODBs have a history of being rotten at schema migration. So all objects used dictionaries for ivar storage. This makes it easy to add or remove ivars without getting messed up in the OODB as the object’s ‘format’ is always the same. However, all that hashing and fetching, and searching, isn’t free. I didn’t realize how expensive it was until I ripped it out and replaced them with vanilla ivars. Zooooom!

Because the mapping is from the objects to the RDBMS through GLORP on an attribute level rather than relying on blitting a whole object as a chunk, the format of the objects is decoupled from the database representation. Changes in the object’s binary format has no bearing on the database representation.

3) When generating accessors – add lazy initialization where nil is not an acceptable value.

4) Keep it meta. The meta model is the most important thing we have. With a good meta model all else can be rapidly replaced. Consequently, I think the next step in evolution – conversion of the meta model to use Magritte and then replacement of the UI to use Magritte as well, will radically improve agility.

Meanwhile, to prepare, I’m updating the version of Seaside that the application is built on. This is turning out to be harder than I thought as Seaside has moved on quite a bit and many classes in my old version have been simply replaced in the newer one.

The really great thing about using meta facilities like glorp and magritte, is that the application continues to shrink until it is mostly just the meta model.

Less code, less bugs.

Records and Objects

Tuesday, January 2nd, 2007

I’ve been slow in posting this because I’ve been trying to make a deadline and there hasn’t been time to do anything else. But at the moment, the data migration scripts are running and I’m just babysitting a pair of computers watching for problems, tweaking the code, and restarting the migration.

And it is taking forever. The old OmniBase db is about 880M, a fair amount of it is garbage. A hot backup script written by OmniBase’s author takes over 2 hours to run. It doesn’t reinflate the objects either. This is just not scaling. At any given time, I figure this application hosts perhaps 20 users tops. On those days, it crawls.

The users have been wanting extracts for generating annual reports for the last 4 months. I have written numerous scripts to try to generate this for them. They always fail. Often, after a few hundred reads, OmniBase will get itself into a state with some hanging locks and will need to be killed. A script that tries to touch every object in the database takes well over 30 hours to run. Why? I’m not sure. Also, users are asking for reports that involve complex traversals that take too long. Not enough entry points into the data. There has to be a better way.

Enter PostgreSQL. The best and most free database of the free solutions. Postgres rocks. It just works. The tools are nice. The data type selection is extensive. It is easy to extend with additional scripting languages. The most magical (to me) utility is pg_dump. This little gem can back up an entire fully populated postgres database with equivalent data, hot while the app is running, in about 10 seconds. The resulting file is around 140M. I’m sold.

Except that, because of the ‘magic’ nature of OODBs, this application is written (mostly) as if all objects are just in memory – so converting to a SQL oriented format just wasn’t going to be feasible.

So I adopted GLORP and set out to emulate the existing database api. This has been successsful. Wildly so.
Glorp uses a meta model – actually two of them – one for the databse, one for the objects, plus a mapping model in between. The whole bundle is contained in a class called DescriptorSystem. DescriptorSystem is abstract and uses the Template Method Pattern to help you build out the models. You subclass DescriptorSystem and then override methods like allClassNames, allTableNames and so forth. The initialize method will call these and then start iterating over them calling methods with names derived from items in the list. So if you have a class Login mapped to a Table LOGIN, you need to add ‘Login’ to the list returned by allClassNames, ‘LOGIN’ to the list returned by allTableNames, and methods called classModelForLogin that creates and returns the appropriate class model describing Login, and tableForLOGIN that returns an initialized DatabaseTable.

Inside of the classModelForLogin, you create a GlorpClassModel, give it a name, and then you describe attributes by calling methods like

newAttributeNamed: aSymbol collection: collectionClass of: aClass

for single values and toOne relationships or

newAttributeNamed: aSymbol collection: collectionClass of: aClass, Field, Relationship

for toMany relationships. Notice that this adds the typing information for attributes that is typically missing in Smalltalk.
The other model represents the underlying database and includes objects like DatabaseTable, DatabaseColumn, ForeignKeyConstraint, DatabaseSequence, DatabaseIndex and such. Stuff all relational databases have. You describe your database procedurally, same as you did with the class model, only you implement tableForLOGIN and say things like:
system tableNamed: aString
addColumnNamed: aString type: aDatabaseType
addForeignKeyConstraint: (ForeignKeyConstraint sourceField: srcField targetField: toField)

You have to be totally explicit here, if you need a foreign key field, you have to define it. If you need a link table, you need to define it. You have to specify the field for the primary key – which means the object has to have a field for the primary key. Glorp doesn’t figure any of that stuff out for you.

Finally, you specify the mapping from the class model to the table model. You do this by creating Descriptors (one for each class) and Mappings. Mappings can represent either data fields, or relationships. There are several kinds. For instance, a many to many mapping will involve specifying the primary keys of each table, the link table, and the mappings from primary keys to link table fields. Most of this can be derived from the class model’s relationship and foreign key constraints. But you still have to specify it.

At this point, you are probably thinking – I have 100 classes in my model That’s 300 methods I have to write! And it is all mostly boilerplate! I couldn’t agree more. All you really need is an appropriate metamodel.

In a previous life, I wrote WebObjects applications. WebObjects has an ORM called the Enterprise Objects Framework or EOF. It was light years ahead of its time. Now, its about average as Apple has neglected WebObjects terribly and nobody I know uses it anymore. EOF came with a great program called EOModeler and stored the model in text files in PList format. I have code that reads and writes PLists in every language I know – they are insanely useful.

The EOModel was the first file format that described all of the meta information required by a typical ORM library. So I did the easy thing – leveraged EOModel files to build DescriptorSystems. (I was not alone in realizing this). I subclassed DescriptorSystem and created EODescriptorSystem which reads an EOModel file and builds a DescriptorSystem from it. (I also wrote my own EOModeler application in Java Swing, both as an experiment, and out of frustration because Apple was neglecting WebObjects to an extent that the tools were falling apart. It works well enough but the experience of writing it put me off Java for good).

This experience teaches me that any reasonably expressive meta model can be leveraged to build a descriptor system.  In my current porting project, the original developers ended up creating their own ad hoc meta model with explicit modeling of attributes, relationships, and types.  I leveraged this to automatically generate a descriptor system from the classes themselves (all domain classes have a common root), and was able to infer link tables, foreign keys, and so forth from the meta model.  So from the model I get the schema and the descriptor system.
Of course, translating to relational format required a few subtle changes to the object model, so I also added code to construct the table model directly from PostgreSQL and, by comparing it with the schema generated from the classes, can figure out alter scripts to automate schema migration.  This is working great and building out new domain objects has become really easy.  I would say with Seaside and this infrastructure, I have surpassed Rails for ease of development.

But I think I can do better and have begun to investigate Magritte. Stay tuned.