Compile Speex For iPhone

Speex is an audio codec specially designed for voice audio. I’m sorry, a codec is a software component used for encoding and decoding something. Oops, I’m terribly sorry! An iPhone is kinda like a phone but it has no wires, y’see… and the letter i is prefixed to it because… Hi, I’m Cliff. You’re probably here because you already know what an iPhone is. Maybe you’ve seen one of the commercials. Maybe your cousin’s best friend’s uncle’s nephew’s best friend’s cousin has one. (In case you missed it, that was a really really verbose way of saying “your cousin”!) Maybe you’ve been around the block once or twice and happen to know about both codecs and Speex. (Maybe it was dem fools throwin’ bones by the liquor store that taught you about Speex. Don’t laugh, cause you’d be surprised by what you learn on the streets these days.) Whatever the case, I’m going to explain how I got a clean compile on the Speex library using XCode. Hold tight because the remainder of this post is designed to be informative… that is all jokes and nonsense to the side.

  1. Download the Speex C source bundle
  2. Unpack it
  3. you might wanna try building it from the cmd line. Run “./configure;make” from the folder where you unpacked it.
  4. Create a new project in XCode. This can be an iPhone or an OSX project but for consistency’s sake (and because it’s what I put in the title) let’s use an iPhone project.
  5. Create an actual folder, not an XCode group, under the root of your new project and call it “CSource”. This is where we’ll put the Speex source code.
  6. Drag/drop the folder into your XCode project or create a group that points to that folder.
  7. Double click your project icon in the left hand tree in XCode to edit the project settings.
  8. Goto the build tab and type “header” in the search field to filter your choices to the things that deal with headers. (Yes I just blatantly included a “goto” in a modern day technical writeup.)
  9. Look for the “Header Search paths” build setting. It should fall under the search paths category somewhere toward the middle of the screen. If you don’t see it finish typing the term “header search paths” in the search bar above. It does an incremental search as you type.
  10. Double click the Header Search Paths build setting to bring up the edit dialog then double click in the value field and set the value to “$(SRCROOT)/CSource”
  11. Open the folder that you unpacked Speex to in Finder and drag the “libspeex” folder directly into the CSource grouping you created in XCode. Choose yes to copy the files.
  12. Back in Finder, navigate to the include folder under the Speex unpack directory. Drag the “speex” folder out of here and next to the libspeex folder you added to your project in XCode. Choose yes to copy the files.
  13. Back in Finder, drag the “config.h” file out of the root of the speex unpacked folder and into your XCode project.
  14. Back in XCode, hit Cmd+Shift+D and type “arch.h” to find and open the arch.h file we’ve imported into our project.
  15. Add a “#include” to include “config.h” at the top.
  16. Remove the “echo_diagnostic.m” file under libspeex from the project as it will just cause complications.
  17. Hit compile and wait for the errors to roll in!

If you followed the above steps correctly then you should only see a few errors relating to duplicate symbols. If you get thousands of errors then it’s likely related to missing header files. You probably have to make sure you imported the speex folder with all the headers and double check your header search path to make sure that it points to the directory containing the imported “speex” folder. You might find a bunch of errors if you don’t remove the “echo_diagnostic.m” file from compilation. The last order of busniess would be to import the ogg container source.I downloaded libogg-1.1.4 which appears to work with speex-1.2rc1. Including the “ogg.h”, “os_types.h”, “bitwise.c”, and “framing.c” files allows me to compile code included from the “speexen.c” and “speexdec.c” examples.

Free Voice Guidance Navigation on the iPhone

Yesterday we became the first to offer free voice guided turn by turn navigation on the iPhone. Not Google, not Apple, not even AT&T but MapQuest! I know a lot of people will be all like, “Google’s free on Android!”, or “Verizon does this!” and “Garmin does that!” but let me tell you. There has been a monumental change within the walls of AOL. Things are moving in MapQuest. Free turn by turn is only the first step. And because you got a nut like me working on the project you can believe there’s a lot more coming. I don’t typically post a lot of specifics about AOL or MapQuest here but yesterday was highly important. We’re going to establish ground in the market of mobile. And we’re going to do so while you’re sleeping. …While you’re obsessing over whatever Motorola puts out. …While you’re tinkering with your Google Maps mashup. We’re going to release something that will have you saying “wha?? Why didn’t Tom-Tom think of that? Where was Google when they thunk that up?” If you don’t know, then you’ll know!

Leopard/Snow Leopard and iPhone Simulator Audio drama

You’re demoing an iPhone game that you’ve run successfully for months now. You’re standing in front of your superiors but you aren’t concerned because you have unit test coverage that spans the seven seas. You managed to find and stomp out even the littlest, most insignificant bugs that only a developer will notice. You’re on your way to becoming a superstar as soon as your demo completes, wowing everyone in and near proximity to the room. You have remote viewers watching as well over a conference call to Los Angeles via WebEx. You launch your app in the Simulator and for no reason what so ever the room is silent! The updated sound track that was supposed to accompany your splash screen is not playing! Even worse, the title screen explosion sound is completely absent. Double check your audio cable, your volume controls, the system preferences. Everything is set to full blast. Playing a test clip in iTunes confirms. You get audio out of every orifice except when the simulator runs! What gives? Hi I’m Cliff. I’m going to explain why you have egg on your face.

Fold your Macbook Pro up and call the demo. You can explain later why everyone in the room wasted their lunch hour to watch you fumble nervously with network cords and make awkward hand gestures in an attempt to draw lines in the air tracing the sound that wasn’t there. Back at your desk yet? Don’t waste time linking different audio frameworks for your sim build. Don’t waste time debating AVAudio vs. Audio Queues. Instead, pay attention to the color of your shirt and the amount of creamer you add to your cup of joe. Your hair should be brushed from back to front and not to the side or you won’t pull this off at all. Also, any notes or paperwork should be stacked to the right side of your laptop when you launch the simulator. What I’m getting at is the impact of your environment on the iPhone simulator. There may be nothing wrong in your code or your make file. The problem exists with you’re environment.

Twice it has happened to me where I thought I had accidentally allowed a bug to slip through causing audio glitches. In both occasions I found a different external factor causing my iPhone simulator audio to fail. The first time I had been using a Bluetooth headset paired to my Mac to watch Ali on DVD. That caused Simulator audio to not play at all. Un-pairing the device remedied the situation. Now, just recently, I learned that leaving the iShowU screen recorder idle in the background can cause an echo effect on the simulator’s audio. Bottom line, if you have iPhone simulator audio issues that just weren’t there yesterday… double check the movie you rented from Blockbuster the night before because it could be the culprit.

Downgrade your iPhone DFU mode

My iPhone crapped out on me this weekend. I went to use it and the screen wouldn’t show at all. I loaded iTunes which was able to recognize it and offer to restore it to factory. Word of advice, iTunes is very sneaky! I didn’t realize that the factory restore it offered came with a complimentary upgrade to OS 3.1.2! It became apparent after I went to use the device and swiped right revealing the new spotlight search. Crap! I needed to keep it on 2.2 because I need to verify 2.2 compatibility. No worries, I’l just down grade when I get to the office. I then realized that I couldn’t build and run on device using XCode. I was getting “No Provisioned device connected” errors. I got concerned thinking I had to go through the whole re-provisioning my device hassle. Then I realized the “use for development” button in XCode. One thing lead to another then I finally realized all of the ugly truths about iPhone development.

1. OS 3.1.2 only accepts builds from XCode with iPhone SDK 3.1.2.
2. The iPhone SDK 3.1.2 only installs on OSX 10.6 (Snow Leopard)
3. Apple no longer offers any iPhone OS earlier than 3.1.2 on its website.
4. If you are lucky enough to find a lingering copy of iPhone OS 3.0 or earlier, you cannot roll back from 3.1.2 (…easily) due to baseband errors.
5. DFU mode is not easy to do or understand.
6. You will likely spend the good part of a couple of days trying to recover from an unintentional upgrade as your first 5-7 rollbacks will leave you with misc errors.

The simple answer is that you cannot downgrade the OS without using DFU mode. DFU stands for Device Firmware Upgrade and is a secret mode that Apple doesn’t want you to know about. You have to use something similar to the old Nintendo Contra cheat (you remember up, up, down, down, left, right, left, right, b, a…) to enable it. I’ve tried it a couple of times so far and realized that you probably should have a completely installed OS before trying it. My second attempt (after a fresh iTunes restore) left me with an error and I’m hoping the third time is a charm. Here goes nothing…

AssertRunsInAnotherThread ?

I’ve updated my example below after realizing I left out some important pieces…

How do you assert that something runs in a different thread? Or more generically, how do you assert that something runs asynchronously? I need to do this in ObjC but also in Java. The scenario is as follows. I have a WhatzItz object instance stored in myWhatzItz. I tell myWhatzItz to doDisThing. I need to specify that myWhatzItz will doDisThing asynchronously. Experience tells the story that multi-threaded unit tests are dumb, complicated and wrong. So asking myWhatzItz to doDisThing then waiting or polling for completion of doDisThing is not what we want to do here. (It may be what you want to do but it’s not what I want. Since we’re on the same team and since I’m doing the writing you have to want what I want not what you want. I want you to want my wants… forget your wants… your wants are dumb anyhow!)

So how do we design myWhatzItz to doDisThing and doDisThing right? I’m going to suggest an interface… err prototcol. That is an abstraction for what we want to design. In unit testing we stay focused on one thing. All distractions are tossed behind abstractions. So after asking myWhatzItz to doDisThing I need to assert that it uses asynchronous behavior. That brings us a step back. I have to design a dependency on asynchronous behavior first. Right now you’re probably wondering how asynchronous behavior works. Right now I’m ’bout to slap you like Bruce Lee slapped that boy in Enter the Dragon. (Or was that Return of the Dragon? Maybe it was the game of death? Bonus points to the 1st person that gets the movie correct with a link to the clip on YouTube!) “Don’t focus on the finger or you’ll miss the beauty in the sky above!”, says Bruce. We don’t care about how asynchronous behavior works, as its irrelevant to our design. We only care that our work is done asynchronously! So we’ll code this test in ObjectiveC:

@protocol MyAsynchronousBehavior
-(void) performAsynchronously:(SEL) aSelctor onTarget:(id)aTarget withObject:(id)anObject;

@interface MyWhatzItzTest : SenTestCase <MyAsynchronousBehavior>
  MyWhatzItz *myWhatzItz;
  SEL selectorPerformed;
  id targetForSelector;
  id parameterForSelector;
  int performAsynchronouslyInvocationCount;

@implementation MyWhatzItzTest

-(void) setUp
   myWhatzItz = [[MyWhatzItz alloc] init];
   //The test uses the self-shunt pattern to listen for MyAsynchronousBehavior interaction.
   id theAsynchronousBehavior = self;
   myWhatzItz.asynchronousBehavior = theAsynchronousBehavior;

-(void) testMyWhatzItzWillAsynchronouslyDoDisThingWhenAskedToDoDatThing
  STAssertEquals(performAsynchronouslyInvocationCount, 0, @"Assuming that we haven't been asked to performAsynchronously");
  [myWhatzItz doDatThing];
  STAssertEquals(performAsynchronouslyInvocationCount, 1, @"We SHOULD HAVE been asked to performAsynchronously");
  STAssertEquals(selectorPerformed, @selector(doDisThing:), @"Should have asked to doDisThing using asynchronous behavior.");
  STAssertEquals(targetForSelector, myWhatzItz, @"Should use myWhatzItz for asynchronous execution.");
#pragma mark MyAsynchronousBehavior protocol methods
-(void) performAsynchronously:(SEL) aSelctor onTarget:(id)aTarget withObject:(id)anObject
  performAsynchronouslyInvocationCount++; selectorPerformed = aSelctor; targetForSelector = aTarget; parameterForSelector = anObject;

Supplying the asynchronous behavior becomes a construction/intialization concern, which could be extracted into a wiring framework like Interface Builder (or if you do Java, Springframework). The nice thing is that we can alternate our asynchronous behavior without touching the rest of the project. We can do something quick/dirty like detachThread… and later get more elegant with RunLoops. Today’s tip comes to you (me) completely by accident. I’ve been trying to test drive things in Java and ObjC for several years now and I’ve never got this part quite right. Feel free to share your opinions/experiences with threads and tests.

The above example demonstrates a few important unit testing concepts. first it uses the self-shunt pattern to allow the test to become a mock and listen for interactions between the tested object and its collaborator(s). Second, it demonstrates the importance of using tests to carve out the pieces that should NOT be under test. In this situation it’s multi-tasking, however in other scenarios it could be anything from a DBMS to a network call. I could have illustrated an example where I spin up a Thread pool of some sort from within the test started work, paused the main thread and waited for a response. That’s what I’ve done in the past and it becomes extremely complicated and brittle. In stead, I use the elegance of abstraction to make the test 100% predictable, 200% more simplistic, and 300% more maintainable. Where do I get those statistics? The short answer is they’re sequential. (The long story begins yesterday when my 5yr old spontaneously decided to count from 1 to infinity in the middle of our shopping trip. You see, she only recently learned her numbers up to 100 and after getting to 199 we all realized the child’s computational limits as she continued with one hundred one hundred then followed up with one hundred one hundred one, one hundred one hundred two…)

How not to link a framework in iPhone dev

With much help from Erik, the owner of OCMock, I discovered how much of a loon I can be. Let me set the stage with a story, like I typically do on this site. You’re writing unit tests for a spankin’ new iPhone project that’s gonna shake the world if it ever releases. You’ve got backing support of everybody from MGM Studios to Barack Obama helping you to make your release date. You are an advocate of all things Agile, TDD, and behavior driven. You absolutely cannot fail! You now need to do something clever in your unit tests. Something Apple doesn’t provide facilities for. You find a framework that does it. Maybe you’re bringing in OCMock or maybe you’re just trying to link Hamcrest. Hi, I’m Cliff. You’re here because your framework won’t load in your unit tests. I’m here to tell you how not to link against it.


Many, many years ago (like 1), I tried to link against OCMock. The only way to make it work was to drop it into the magic place called “/Library/Frameworks/”. It worked. It worked well. It worked so well that I decided to become the OCMock super hero. I wrote a blog about it. (Like to hear it? Here it go!) I wrote an OCMock setup thing with Automator/AppleScript for other developers that weren’t as John Blazed as I was so that they too could enjoy the beauty that was OCMock. (Just had a flashback to the little stored procedure runner tool I wrote when I was being the VB6-toRPGIV super hero many more years ago.) Here’s where a super hero becomes a super zero.

I neglected the principles of software development. Anything that goes in a System folder is visible to everything. Putting files, tools, trinkets there is always error prone, remedies for disaster. Why? Because it’s fire and forget… A one time setup that you never need to worry about. The “forget” part of the “fire and forget” is what bites. The one time step that you always need to think about when troubleshooting but never do. Like I said, a year passes and I haven’t done much with OCMock except for occasions. Now I wanna upgrade to the latest version. I’ve since learned a better way to link projects to frameworks but my machine still “remembers” the old way. My new process, from memory, goes something like:

  • Find a framework
  • Drag/drop it into your project
  • Do something in the build configs, like setting a framework search path
  • I think that’s it, right? Yeah. Compile and run and I see the green button. I’m good!

Everything works as expected. I’m pretty sure I’m picking up the right version because I just double clicked the little framework icon and triple checked the path pointing to the newly downloaded folder. I could go the extra mile and look for the notes I wrote last year and make sure there’s no other gotcha’s but things are working. Why bother?

There’s two critical problems here. the first is that I never removed the frameworks from the magic “fire and forget” place. Just don’t put things here and you’ll never have to remember to delete them when you upgrade or when they break other things. The second problem is that I didn’t remember my new method for linking because my machine still remembered the old way making me feel like I was all good. The better way to link frameworks in iPhone dev is to put a “copy files” build phase into your target, set the destination path to “products directory” and drag/drop your frameworks into this phase. One caution is that while you can run on the Mac using the Simulator you still can’t load frameworks on the device. So I conclude this long winded article that could have been summarized in 2-3 sentences by saying, if you wanna suck at programming overload your system folders with development frameworks and libraries. Not only will you immediately solve the problem at hand and meet your immediate deadline but you’ll break the next twelve identical problems in the future and miss all of those deadlines. Good luck making up weeks of productivity lost chasing a problem that only exists on your machine. Good luck making up several more weeks of lost productivity while you reinstall your OS and lose several other important files/temporary projects trying to fix the problem that only happens on your machine.

Mock It To Me!

I’m playing with OCMock on a random iPhone project and having nothing but pain. Naturally my only outlet is to you, dear reader. Thanx for stopping by and thank you all for the comments you’ve been leaving. Not everyone realizes how important it is not only to comment with well formed answers but to reply with well thought out questions and problems. We all suck our knowledge from the same cloud of computers nowadays. I don’t know about you but I constantly find myself trapped behind a convoluted compiler or runtime error and an unanswered question on some forum. No matter how good Stackoverflow is getting these days it still does not have AI and cannot answer all of your questions in twenty minutes or less. That leaves many adventures and problematic programming paths without a “happy ever after”. Hi, I’m Cliff. My job is to continually post cryptic compiler messages and explanations on this site for all to follow. One day my Ode to an EmptyStackException will be the saving grace of a project on the brink of a deadline. (I’ll gladly share my PayPal to those interested in tipping should any of my topics be informative enough to land such a multi-million dollar deal.) I digress.

Today, as I was saying earlier, I wrestle OCMock for iPhone development. When I setup an iPhone project I drag/drop the OCMock.Framework folder in, attach it to my UnitTests target, and double check the framework search paths build property for my test target. I then use a slightly modified version of the OCMockObjectTests to validate all of the features are available. On my latest project I got anal. There was a particular feature (ordered method invocations) that wasn’t in the release I downloaded last year. I updated my version of OCMock then instead of modifying its test suite I copied it into my project. Certain things wouldn’t compile for one reason or another so I hacked around a bit. I got down to a snippet that was attempting to return a “BOOL” from a mock and began seeing these errors:

expected specifier-qualifier-list before 'typeof'

I remember these errors from a while ago when I ran across an article describing a similar solution. I hacked the code around a bit going as far as to download OCMock's source and run the tests from within. The funny thing is that these tests pass without issue, possibly because they're running in OS X world. When run in iPhone world things seem to be slightly different. Here's what I see in particular.

This works:

BOOL variable;
[NSValue value:&variable withObjCType:@encode(BOOL)]

This doesn't work:

BOOL variable;
[NSValue value:&variable withObjCType:@encode(typeof(variable))]

There are a few other subtle issues that I can't get into because I hacked around so much I lost my place. I'm now facing a "Bus error" when I run through the remaining tests. I you know what I don't, then type one of those comment things. You'll not only improve my life, but you'll enrich the lives of hundreds of Googling souls facing similar trouble.

CoverStory on IPhone projects

I really, really, really don’t care about test coverage when I develop because it’s one of those things you get for free when you follow the right practices. I always thought projects like Clover and Cobertura were a waste of time. However I recently started dreaming up an interesting use case for these kind of tools. Help me, if you will, get CoverStory (a test coverage tool for ObjC) up and running so I can prove myself wrong. I’ve followed the [sparse] documentation and steps on the CoverStory home site. There’s a section on including an alternate, fat libgcov.a file that confused me. Not knowing what path to what file or where to set the path I stumbled on a way of satisfying the “no such file for -lgcov” error by dragging/dropping the fat libgcov.a file into my project. Now when I build I get the .gcno files but no .gcna files and Coverstory won’t report coverage. CoverStorySettings

iPhone Boot Camp

Platoon… Attention! Forward… March! About… Face! Platoon… Halt! Parade Rest!… At ease…

Many moons ago I attended boot camp and that’s kinda the jest of it. Sure there were some rifles fired here and some push ups done there. I believe there was even a drill sergeant or two but the above was the general format. Hi, I’m Cliff. You’re probably here because you’re wondering how to fix that EmptyStackException in your XML transform. Or maybe you’re trying to run Blackberry compilers on your MacPro and you keep getting verification errors. Or maybe you just Googled my name and landed here by chance. Whatever the catalyst the net result will be pure edutainment. (Yes edutainment is a “Can’t See Nothing But the Source” exclusive! Remember where you heard it first!) If you are not completely edutained then you’ll probably feel edu-pain.

Back to Boot Camp. That’s where I was privileged to be this past week. Not the original left-right-left boot camp, but a different kind. This boot camp was lead by none other than Aaron Hillegass. He wasn’t as loud as my former Drill sergeant’s Morris, Decker, and Perez (BTW, they would just love to hear me address them without their demanded “Drill Sergeant” prefix), but he did give a lot of quality info on all things Mac and iPhone development related. Tag teaming with Jaun Pablo, Aaron gave a five day hands on shop which involved responding to touch events, in depth networking, iPhone multi-media and more. The second half of the course was all about software development for the Mac desktop. We learned how to build installers, how to auto upgrade via app-casts, how to build quick look and spotlight plugins, and how to overlay Quartz graphics on an Open GL context. Then there was my favorite topic, unit testing. I found out that Apple released support for iPhone unit testing behind my back with their 2.2 SDK release. I’d love to write more about the topic but I have a lot of catching up to do. Shotz out to Aaron and Juan Pablo! Drop a line on whatever and we’ll speak on it.

iPhony Frameworks

So I’m writin’ all kinds of Objective-C code, right? And I’m finally in my element because I got Google Tools For Mac doin’ the SenTest thing, right? I even figured out how to include modules using project relative paths. That’s when my trouble started. Y’see, I thought frameworks were no different than modules. Of course they’re different or else they wouldn’t be called frameworks! Still, I blurred the line between the two. So then I’m writing all these gnarly tests using OCMock. Remember OCMock? I complained on the forums about adding it to an iPhone project. then I finally found a hack to get it to run in my iPhone tests. Then the whole module thing started to make me feel warm and fuzzy inside so I thought I had a better approach. At any rate, I tried the same approach with Hamcrest, a tool advertised on the OCMock home page. I couldn’t get it to work. Finally, it dawned on me! You can’t add frameworks to iPhone projects! [Honestly it didn’t dawn on me, I had to be told then re-told by someone who knows waaay more about iPhone stuff than me.]

The point is that Frameworks in XCode iPhone projects don’t work like modules. With a module, you can just drag/drop the module file into your project, set its dependencies in your target, build and then you’re off and running. Frameworks are different. Frameworks have to exist (to the best of my knowledge and until someone who knows stuff tells me some new stuff) under /Library/Frameworks in order for SenTest test cases to use them. Frameworks can not be used at all during run time in an iPhone project. I don’t even think they’ll run in the Simulator which means no debugging unit test code, which means you better write some very fine grained unit tests which turns out to be necessary anyhow. That’s the point. You can’t run Framework code in an iPhone project but you can run it in a GTMSenTestCase as part of the build (not build/go process). If anybody knows better speak up now or I’ll forever hold out the peace sign.