<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>benbritten.com &#187; iPhone</title>
	<atom:link href="http://benbritten.com/category/blog/iphone/feed/" rel="self" type="application/rss+xml" />
	<link>http://benbritten.com</link>
	<description>Software should be simple.</description>
	<lastBuildDate>Wed, 09 May 2012 12:37:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Compression settings for iPhone video</title>
		<link>http://benbritten.com/2010/07/13/compression-settings-for-iphone-video/</link>
		<comments>http://benbritten.com/2010/07/13/compression-settings-for-iphone-video/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 05:08:00 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://benbritten.com/?p=1053</guid>
		<description><![CDATA[So. If you read this blog at all you may already know that I am the sole developer for the Gamebook Adventure series of iOS apps. If you havent checked them out and enjoy some choose-your-own-adventure style fantasy games, then &#8230; <a href="http://benbritten.com/2010/07/13/compression-settings-for-iphone-video/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>So.  If you read this blog at all you may already know that I am the sole developer for the <a href="http://www.tinmangames.com.au/?page_id=203">Gamebook Adventure</a> series of iOS apps.</p>
<p>If you havent checked them out and enjoy some choose-your-own-adventure style fantasy games, then definitely do so. However, that is not what this post is about.  For the books, we have an intro bumper video that plays the first time you open the app.  Our first book: <a href="http://www.tinmangames.com.au/?page_id=210">Assassin in Orlandes</a> had a landscape oriented menu screen and so we made the video a normal landscape type video. However, the book reading bit was portrait orientation.  In our in-house testing we didnt go back and forth between the two orientations all that often, but (as is often the case) the users used the app differently and were constantly going back and forth and so the orientation switch was a bit annoying.<br />
For the second book: <a href="http://www.tinmangames.com.au/?page_id=45">The Siege of the Necromancer</a>, we switched to a fully portrait oriented app, with the exception of the intro video (it was already made when we decided to change the orientation, and being a poor indie studio we didnt have the cash to re-do the animations in a vertical aspect.  However, most people watch the bumper once or twice then never see it again, so that is OK. )</p>
<p>Now with book three, <a href="http://www.tinmangames.com.au/?p=689">Slaves of Rema</a>, we are finally moving to a fully portrait oriented video.  This poses some interesting problems.</p>
<p>Since I am the developer and we are indies, I am also the video codec guy, and often the video editor as well.  The animations are outsourced and the other GFX are done in house, but it falls to me to put it all together and get it ready for the iPhone.<br />
<a href="http://benbritten.com/wp-content/uploads/2010/07/phoneOrientations.png"><img src="http://benbritten.com/wp-content/uploads/2010/07/phoneOrientations-300x216.png" alt="" title="phoneOrientations" width="300" height="216" class="aligncenter size-medium wp-image-1054" /></a></p>
<p>What is the problem you ask?  Well, on the iPhone you can only play video in landscape and you can really only play landscape formatted videos.  On the iPad you can play videos in portrait, but they get all scrunched down.  If you want full screen vertical oriented videos then you really need to make your videos sideways.<br />
<a href="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.30.47-PM.png"><img src="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.30.47-PM-300x277.png" alt="" title="Screen shot 2010-07-13 at 2.30.47 PM" width="300" height="277" class="aligncenter size-medium wp-image-1055" /></a></p>
<p>This can be a bit of a pain to do.  One way to do it is to take all of you grafics and rotate them before inserting them into final cut or similar. This means that you also need to tell the guy doing the animations that you need them to be done sideways and all of that.  This is a fine way to go about it, but it can make working on the video a pain in the ass.  Who wants to work on a sideways video?  </p>
<p>Instead you can make the video upright and rotate it after you have done all the editing.  I find this to be the best for our workflow.  That way all the graphics guys and animation guys are all working with the right orientation in mind and everything looks good.  The hard bit is editing a video that is 320 x 480.  Final cut, which I love, is total shite at doing anything that is not meant for TV or HD resolutions.  What I use is a combination of <a href="http://www.telestream.net/screen-flow/overview.htm">Screenflow</a> and <a href="http://www.apple.com/quicktime/extending/">Quicktime pro</a>.  </p>
<p>wait what?</p>
<p>Screenflow is a screencasting program, why would you use it for editing? Well, mostly because I already use it for screencasting, so I have it laying around.  And it does a fine job of doing basic editing. Most importantly it allows you to export in any crazy-ass aspect ratio you want, and the export options are excellent.  This allows me to edit the video in the aspect it will be seen at, ie portrait.</p>
<p><a href="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.39.08-PM.png"><img src="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.39.08-PM-300x274.png" alt="" title="Screen shot 2010-07-13 at 2.39.08 PM" width="300" height="274" class="aligncenter size-medium wp-image-1056" /></a></p>
<p>So, what I do is edit my video in Screenflow, (in the case of the new books these videos are at 640 x 960, so I can do high rez versions for the iPhone4 and the iPad, but it all works the same for 320 x 480, just be sure your final export size is the size you are shooting for)</p>
<p>I export the video at full rez and lossless from Screenflow (make sure that your rez is 320 x 480 or 640 x 960).<br />
<a href="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.42.47-PM.png"><img src="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.42.47-PM-300x232.png" alt="" title="Screen shot 2010-07-13 at 2.42.47 PM" width="300" height="232" class="aligncenter size-medium wp-image-1058" /></a></p>
<p>next thing is to open it in Quicktime Pro.  (note, the quicktime that comes with your mac these days is not qt pro, it is just qt player.  QT pro is $30 ish and is an indispensable tool to have in your arsenal if you do any amount of video work.  (if you have final cut or FCX, you should already have QT pro).</p>
<p>Once in QT Pro, go to window->show movie properties.  Select the video track, and look at the Visual Settings tab. </p>
<p>All you need to do here is hit one of the rotate buttons.  I generally thing that rotating left (the rightmost button) is the way to go.  That way the home button on the phone will be facing downward when the phone is is standard portrait orientation and the video is playing.    </p>
<p>At this point your video should look like the one above that is tipped sideways. </p>
<p>Now for the fun part, the compression.  </p>
<p>This may take a little while, and if you have a slow machine it may take a long while.  The idea here is that you will probably need to try a half dozen different settings before you get one that looks good and is the size you want.</p>
<p>First off, see if the built-in settings work OK for your video:<br />
<a href="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.49.21-PM.png"><img src="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.49.21-PM-300x273.png" alt="" title="Screen shot 2010-07-13 at 2.49.21 PM" width="300" height="273" class="aligncenter size-medium wp-image-1059" /></a></p>
<p>Choose File->Export.  Then select the Movie to iPhone setting and save it off. This will generate an .m4v file. </p>
<p>Once it is done compressing, open it back up and watch it.  If your video still looks fine then you are done.  This seems to wrok well for about 90% of the videos I run through it.<br />
However I find that the default &#8216;iPhone&#8217; settings sometimes produce terrible video artifacting for certain types of video so I have to do it the hard way. (also, if you are trying to really squeeze every last meg out of your app packages, then the you can get similar quality with half (or less) the size by tweaking the settings yourself.</p>
<p>In this case you need to change the export options and select &#8216;Movie to MPEG-4&#8242;</p>
<p>Have a look at all the fields on the MPEG-4 options.<br />
<a href="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.58.28-PM.png"><img src="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.58.28-PM-300x285.png" alt="" title="Screen shot 2010-07-13 at 2.58.28 PM" width="300" height="285" class="aligncenter size-medium wp-image-1062" /></a></p>
<p>Make sure that the video size is set to what you want, make sure the video format is set to H.264.  After that the most important thing on this screen is the Data Rate. but before we get to that, hit the &#8216;Video Options&#8217; button, and select baseline.  </p>
<p>NOTE: if you dont do this, the video will simply not play on your device, not at all.<br />
<a href="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.58.33-PM.png"><img src="http://benbritten.com/wp-content/uploads/2010/07/Screen-shot-2010-07-13-at-2.58.33-PM-300x165.png" alt="" title="Screen shot 2010-07-13 at 2.58.33 PM" width="300" height="165" class="aligncenter size-medium wp-image-1063" /></a></p>
<p>Ok, back the the main MPEG-4 screen and the data rate.  This is where you will want to change the value and make a few different videos until you are happy with the quality and the size.  I generally start at 1200 or 1500 kbits/sec (this usually produces a fairly nice quality video, but it is generally pretty beefy in terms of size.) then I go down by 250 until the quality degrades to a point where I would never use it.  From there you should have a handful fo videos fo different qualities/sizes to choose from.  You can tweak the data rate down as accurate as you want.  If the video quality is almost good enough, then just bump up the data rate by 25 or 50 and see what you get.</p>
<p>cheers!<br />
-Ben</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2010/07/13/compression-settings-for-iphone-video/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DIY iPad stand for developing</title>
		<link>http://benbritten.com/2010/05/30/diy-ipad-stand-for-developing/</link>
		<comments>http://benbritten.com/2010/05/30/diy-ipad-stand-for-developing/#comments</comments>
		<pubDate>Sun, 30 May 2010 00:57:38 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[meta]]></category>

		<guid isPermaLink="false">http://benbritten.com/?p=1034</guid>
		<description><![CDATA[The iPad finally arrived in Australia this week. Some of us uber-geeks have had them for awhile now. (i got mine by calling my mom in the states and having her send one out for me, thanks mom!!) Anyhow, it &#8230; <a href="http://benbritten.com/2010/05/30/diy-ipad-stand-for-developing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The iPad finally arrived in Australia this week.  Some of us uber-geeks have had them for awhile now.  (i got mine by calling my mom in the states and having her send one out for me, thanks mom!!)</p>
<p>Anyhow, it seems like everyone is showing off their clever and not-so-clever custom stands and cases for the iPad, so to day I figure I would throw mine in the ring :-) (plus it is sunday, and I don&#8217;t want to work right now)   </p>
<p>When I first got the iPad, I had it propped up like how most of the stands work (ie like a picture frame sitting on your desk) However, this put it out past my mouse pad, and was a stretch to reach it.  Since I mainly use the iPad to <a href="http://www.tinmangames.com.au/?page_id=203">develop</a> <a href="http://escfactory.com/terracoreadventures/">games</a>, this solution was not ideal. (After about two hours of going back and forth between Unity, XCode and stretching to tap on the iPad, my shoulders were fooked)</p>
<p>Instead I needed something to get it closer to me.  This meant getting it up above my mouse pad.  This works well since the mousing area takes up a not insignificant amount of desk space, but not very much height.  So I went scrounging in my big piles of junk. looking for a good solution.</p>
<p>Here is what I came up with:</p>
<p><a href="http://benbritten.com/wp-content/uploads/2010/05/IMG_0175.png"><img src="http://benbritten.com/wp-content/uploads/2010/05/IMG_0175-225x300.png" alt="" title="IMG_0175" width="225" height="300" class="alignleft size-medium wp-image-1037" /></a></p>
<p>This stand didn&#8217;t cost me a single cent.  However, if you don&#8217;t have esoteric camera support gear lying about the house, then it might be a wee bit more expensive. (like, prohibitively so :-)</p>
<p>You will need:<br />
<a href="http://benbritten.com/wp-content/uploads/2010/05/a_magic_arm_2.jpg"><img src="http://benbritten.com/wp-content/uploads/2010/05/a_magic_arm_2-150x150.jpg" alt="" title="a_magic_arm_2" width="150" height="150" class="alignleft size-thumbnail wp-image-1035" /></a></p>
<p>1 x Magic arm (<a href="http://www.manfrotto.com/Jahia/site/manfrotto/lang/en/pid/2726">Manfrotto makes them</a>)</p>
<p><a href="http://benbritten.com/wp-content/uploads/2010/05/a_super-clamp.jpg"><img src="http://benbritten.com/wp-content/uploads/2010/05/a_super-clamp-150x150.jpg" alt="" title="a_super-clamp" width="150" height="150" class="alignleft size-thumbnail wp-image-1036" /></a><br />
1 x Super Clamp (<a href="http://www.manfrotto.com/Jahia/site/manfrotto/pid/2718">also by Manfrotto</a>, altho there are plenty of other similar clamps that work just dandy)</p>
<p>You will also need some way to attach the magic arm to your desk (or in this case the shelf that is just above my desk.  )<br />
<a href="http://benbritten.com/wp-content/uploads/2010/05/IMG_0179.png"><img src="http://benbritten.com/wp-content/uploads/2010/05/IMG_0179-225x300.png" alt="" title="IMG_0179" width="225" height="300" class="alignleft size-medium wp-image-1038" /></a><br />
I have chosen the tried and true method of: find a clamp in the shed, and clamp the bastard to the shelf.  However, if you are starting from scratch there are actually many better ways of doing this (for instance, maybe get two super clamps, and just use that.  It would definitely look less terrible, but again, this was just what I had around the house)</p>
<p>The last thing you need is some spare bits of wood.  I used a bit of 1&#215;2 and some plywood.  </p>
<p>The design is very simple, just a single cross piece screwed to the plywood (with a nice groove cut out where the charging cable fits) and a few bits on the back to give me some clamping options.  </p>
<p><a href="http://benbritten.com/wp-content/uploads/2010/05/IMG_0176.png"><img src="http://benbritten.com/wp-content/uploads/2010/05/IMG_0176-225x300.png" alt="" title="IMG_0176" width="225" height="300" class="alignleft size-medium wp-image-1040" /></a><br />
(note I am lifting the iPad so you can see the groove, it doesnt sit up like that)</p>
<p><a href="http://benbritten.com/wp-content/uploads/2010/05/IMG_0181.png"><img src="http://benbritten.com/wp-content/uploads/2010/05/IMG_0181-225x300.png" alt="" title="IMG_0181" width="225" height="300" class="alignleft size-medium wp-image-1039" /></a><br />
(I find the top one give me lots more &#8216;reach&#8217; with the arm, but is a bit wobbly.  The center clamp point is more stable)</p>
<p>The stand works well in both portrait and landscape mode:<br />
<a href="http://benbritten.com/wp-content/uploads/2010/05/IMG_0177.png"><img src="http://benbritten.com/wp-content/uploads/2010/05/IMG_0177-225x300.png" alt="" title="IMG_0177" width="225" height="300" class="alignleft size-medium wp-image-1043" /></a><br />
<a href="http://benbritten.com/wp-content/uploads/2010/05/IMG_0180.png"><img src="http://benbritten.com/wp-content/uploads/2010/05/IMG_0180-300x225.png" alt="" title="IMG_0180" width="300" height="225" class="alignleft size-medium wp-image-1044" /></a></p>
<p>As you can see, it hovers right over the mouseing area.  This means I can go from typing/mousing to iPad testing by just lifting my hand.  Much more ergonomic!  This is a perfect solution to keep the iPad in a useful position for coding and testing. At some point I might go out and spend the extra cash for a better mounting solution (either a mounting plate, or another super clamp)</p>
<p>Cheers!<br />
-Ben</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2010/05/30/diy-ipad-stand-for-developing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Streaming in OpenAL</title>
		<link>http://benbritten.com/2010/05/04/streaming-in-openal/</link>
		<comments>http://benbritten.com/2010/05/04/streaming-in-openal/#comments</comments>
		<pubDate>Tue, 04 May 2010 02:16:19 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[openAL]]></category>

		<guid isPermaLink="false">http://benbritten.com/?p=994</guid>
		<description><![CDATA[I have posted a few posts on OpenAL that have been very popular: a basic intro to OpenAL on the iPhone A rant about OpenAL and sample code how to properly handle interruptions in openAL on the iPhone how to &#8230; <a href="http://benbritten.com/2010/05/04/streaming-in-openal/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have posted a few posts on OpenAL that have been very popular:</p>
<ul>
<li> <a href="http://benbritten.com/2008/11/06/openal-sound-on-the-iphone/">a basic intro to OpenAL on the iPhone</a>
<li><a href="http://benbritten.com/2009/01/24/more-openal-tidbits-for-iphone/"> A rant about OpenAL and sample code</a>
<li><a href="http://benbritten.com/2009/02/02/restarting-openal-after-application-interruption-on-the-iphone/">how to properly handle interruptions in openAL on the iPhone</a>
<li><a href="http://benbritten.com/2009/05/02/lots-and-lots-of-sounds-in-openal/">how to play lots of sounds all at once in OpenAL</a>
</ul>
<p>One thing that people keep asking me is how to playback gigantic files in OpenAL.  Things like songs or audio books.  (This post has been slowly growing over the past few months and I am finally going to put the final bits in and post it!)</p>
<p>The answer to this problem (in case you didn&#8217;t read the title of the post) is streaming.  </p>
<p>First off, lets define what I really mean when I say streaming.  In all of the above code samples, the sound buffers were fully resident in memory.  This works great for smaller sounds like button click sounds and swords clanging sounds for games and whatnot.  However, for big files like full quality songs and really anything over about a dozen seconds long, putting it all into memory (especially on the iPhone) becomes a bit of a problem.</p>
<p>To solve this we read the data off of the disk in chunks, filling small buffers one at a time and then playing them back one after the other.  All the while, in the background we are removing the old buffers and replacing them with new buffers so that we only ever have a few seconds of sound in memory at one time.</p>
<p>Here is a crappy diagram that I spent way too much time on, and it is still crappy:</p>
<p><a href="http://benbritten.com/wp-content/uploads/2010/05/streamingHighLevel2.png"><img src="http://benbritten.com/wp-content/uploads/2010/05/streamingHighLevel2.png" alt="" title="streamingHighLevel" width="600" height="455" class="aligncenter size-full wp-image-999" /></a></p>
<p>OK, at the top we have the &#8216;standard&#8217; way to do thing (the way described in all those posts linked above).  Basically:</p>
<ul>
<li> Step1: Load the sound data from a file into an OpenAL Buffer
<li> Step2: Connect the OpenAL Buffer to an OpenAL source with something like: alSourcei(sourceID, AL_BUFFER, bufferID);
<li> step 3: Start source playing with with alSourcePlay(sourceID);
</ul>
<p>Pretty simple.  </p>
<p>Streaming is a bit more complicated, but still pretty simple (in concept). The first three steps are really very similar to the &#8216;standard&#8217; way above.</p>
<ul>
<li> Step A: Load in a few chunks of the big file into all the waiting OpenAL buffers.
<li> Step B: Queue up all the newly filled buffers into a single OpenAL source via alSourceQueueBuffers(sourceID, 1, &#038;bufferID);
<li> Step C: Start the source playing with alSourcePlay(sourceID); This will begin to consume the queued up buffers.
<li> Step D: In a background thread, check to see if there are any used buffers, and if so then load the next chunk of the sound file into the used buffer
<li> Step E: Queue up this newly filled buffer to the source with alSourceQueueBuffers(sourceID, 1, &#038;bufferID);  As long as there are still bufferes queued up, the source will continue to play them
</ul>
<p>So there it is, five easy steps.  Lets look at them one at a time:</p>
<p><strong> Step A: Load in a few chunks of the big file into all the waiting OpenAL buffers.</strong></p>
<p>Ok first thing we need to do is to prepare a place for all this state data to live.  This will be kinda like preloading the streaming file, execept that we dont load any sound into memory just yet, we are just going to get ready to do that.</p>
<pre lang="objc">
// this queues up the specified file for streaming
-(NSMutableDictionary*)initializeStreamFromFile:(NSString*)fileName format:(ALenum)format freq:(ALsizei)freq
{
	// first, open the file
	AudioFileID fileID = [self _openAudioFile:fileName];

	// find out how big the actual audio data is
	UInt32 fileSize = [self _audioFileSize:fileID];
</pre>
<p>First thing, we open the file.  This doesnt load it into memory, it just gives us a handle to some data that we need.  Specifically the file size.  We will need this to calculate the number of buffers we need to play the whole file.</p>
<pre lang="objc">

	UInt32 bufferSize = OPENAL_STREAMING_BUFFER_SIZE;
	UInt32 bufferIndex = 0;

	// ok, now we build a data record for this streaming file
	// before, with straight sounds this is just a soundID
	// but with the streaming sound, we need more info
	NSMutableDictionary * record = [NSMutableDictionary dictionary];
	[record setObject:fileName forKey:@"fileName"];
	[record setObject:[NSNumber numberWithUnsignedInteger:fileSize] forKey:@"fileSize"];
	[record setObject:[NSNumber numberWithUnsignedInteger:bufferSize] forKey:@"bufferSize"];
	[record setObject:[NSNumber numberWithUnsignedInteger:bufferIndex] forKey:@"bufferIndex"];
	[record setObject:[NSNumber numberWithInteger:format] forKey:@"format"];
	[record setObject:[NSNumber numberWithInteger:freq] forKey:@"freq"];
	[record setObject:[NSNumber numberWithBool:NO] forKey:@"isPlaying"];
</pre>
<p>Next we are going to make a streaming sound record.  This dictionary will hold all of the state for this stream.  </p>
<p>The OPENAL_STREAMING_BUFFER_SIZE is how many bytes of data we want in each buffer chunk.  I have had good luck with 48000, this is about a second at high quality so I have plenty of time to grab the next chunk.  </p>
<p>The bufferIndex is the current buffer that is full.  For now that is zero of course.</p>
<p>Format and Freq we will use when we eventually setup our source. and isPlaying will let us know if we need to be refilling the buffers or not.</p>
<pre lang="objc">

	// this will hold our buffer IDs
	NSMutableArray * bufferList = [NSMutableArray array];
	int i;
	for (i = 0; i < 3; i++) {
		NSUInteger bufferID;
		// grab a buffer ID from openAL
		alGenBuffers(1, &#038;bufferID);

		[bufferList addObject:[NSNumber numberWithUnsignedInteger:bufferID]];
	}	

	[record setObject:bufferList forKey:@"bufferList"];
</pre>
<p>This is where the actual buffer references will live.  In theory you can get away with just two buffers.  One to play and one to fill while the other is playing.  However If you get any stitch in your background thread, or do any heavy lifting on the processor that delays that refill, then you will get some nasty skipping.  Instead I tend to use three buffers.  This takes up more memory, but affords me a bit more robust playback.</p>
<pre lang="objc">
	// close the file
	AudioFileClose(fileID);

	return record;
}
</pre>
<p>Finally close our audio file and return the record. Take that record returned from the above method and store it into a big NSMutableDictionary called soundLibrary with some key, like the name of the sound. (or in whatever data structure you want, that is how I do it, and that is how the sample code works)</p>
<p>We are still in Step A (well, pre step A even). We haven't loaded any buffers, but we are ready when that time comes.</p>
<p>Once you are ready to play your sound, we move to:</p>
<p><strong>Steps A, B and C in one fell swoop<br />
</strong></p>
<p>OK, lets define a play streaming sound method that does A, B and C for us. (and kick off Step D)</p>
<p>We would call this method when we want to actually begin playing the streaming sound, the key is whatever key you used to store the record into the sound library.</p>
<p>This method returns the sourceID so that the calling object can use it to stop the sound.</p>
<pre lang="objc">
- (NSUInteger)playStream:(NSString*)soundKey gain:(ALfloat)gain pitch:(ALfloat)pitch loops:(BOOL)loops
{
	// if we are not active, then dont do anything
	if (!active) return 0;

	ALenum err = alGetError(); // clear error code
</pre>
<p>Just some housekeeping.  I have a big boolean called 'active' that shuts off all sounds. Makes it nice and easy.  Second we clear out the OpenAL errors so that anything in there will be a result of what we do in this method.</p>
<pre lang="objc">
	// generally the 'play sound method' whoudl be called for all sounds
	// however if someone did call this one in error, it is nice to be able to handle it
	if ([[soundLibrary objectForKey:soundKey] isKindOfClass:[NSNumber class]]) {
		return [self playSound:soundKey gain:1.0 pitch:1.0 loops:loops];
	}
</pre>
<p>If you followed along on the other tutorials you would know that previously I had simply stored the NSNumber value for the buffer in the soundLibrary.  This is a way to handle that if the streaming method gets called with the wrong key (ie a non-streaming sound) It just punts to the standard playSound method.  Similarly in my playsound method I check to see if the record is an NSDictionary, and if so then it calls this method.  That way  you can just use the playSounds method with either streaming sounds or regular sounds and it all works dandy.</p>
<pre lang="objc">

	// get our keyed sound record
	NSMutableDictionary * record = [soundLibrary objectForKey:soundKey];

	// first off, check to see if this sound is already playing
	if ([[record objectForKey:@"isPlaying"] boolValue]) return 0;
</pre>
<p>Ok, we grab the record and start to go through the state.  If the sound is already playing then we get out early.  </p>
<pre lang="objc">

	// first, find the buffer we want to play
	NSArray * bufferList = [record objectForKey:@"bufferList"];

	// now find an available source
	NSUInteger sourceID = [self nextAvailableSource];
	alSourcei(sourceID, AL_BUFFER, 0);

	// reset the buffer index to 0
	[record setObject:[NSNumber numberWithUnsignedInteger:0] forKey:@"bufferIndex"];
</pre>
<p>Now we are going to move into Step A proper.  Grab the buffer list, and get an available source.  the Method nextAvailableSource simply goes through a big list of premade sources and finds one that is not being used currrently.  I think I went over that in the 'lots of sounds' tutorial linked above.</p>
<p>Then we reset the bufferindex to 0.  This is basically setting the playhead to the beginning of the sound. next, we fill the buffers</p>
<pre lang="objc">
	// queue up the first 3 buffers on the source
	for (NSNumber * bufferNumber in bufferList) {
		NSUInteger bufferID = [bufferNumber unsignedIntegerValue];
		[self loadNextStreamingBufferForSound:soundKey intoBuffer:bufferID];
		alSourceQueueBuffers(sourceID, 1, &#038;bufferID);
		err = alGetError();
		if (err != 0) [self _error:err note:@"Error alSourceQueueBuffers!"];
	}
</pre>
<p>Ok, this is pretty simple looking but there is the one magic method: loadNextStreamingBufferForSound: intoBuffer: I will get to this in a minute, but basically it grabs a chunk of the audio file based on the bufferIndex and loads it into the buffer.  then it increments the bufferIndex so that the next time I call this method I will get the next chunk.<br />
We load a chunk into every buffer in the buffer list (which in our case will be three buffers)<br />
And here is the important part: (this would be the Step B part of the diagram)</p>
<pre lang="objc">
alSourceQueueBuffers(sourceID, 1, &#038;bufferID);
</pre>
<p>This is the magic OpenAL function call that makes this source a streaming source instead of a single buffer source. Basically it will continue to play as long as there are buffers queued up.</p>
<pre lang="objc">
	// set the pitch and gain of the source
	alSourcef(sourceID, AL_PITCH, pitch);
	err = alGetError();
	if (err != 0) [self _error:err note:@"Error AL_PITCH!"];
	alSourcef(sourceID, AL_GAIN, gain);
	err = alGetError();
	if (err != 0) [self _error:err note:@"Error AL_GAIN!"];
	// streams should not be looping
	// we will handle that in the buffer refill code
	alSourcei(sourceID, AL_LOOPING, AL_FALSE);
	err = alGetError();
	if (err != 0) [self _error:err note:@"Error AL_LOOPING!"];
</pre>
<p>With our buffers loaded and queued on the source, we just need to set up the source with all the properties that were passed in.  This is exactly like you would do it for a single buffer sound.</p>
<pre lang="objc">
	// everything is queued, start the buffer playing
	alSourcePlay(sourceID);
	// check to see if there are any errors
	err = alGetError();
	if (err != 0) {
		[self _error:err note:@"Error Playing Stream!"];
		return 0;
	}
</pre>
<p>Ok, finally we move to Step C: and we start the source playing.  From this point on, we are on the clock to keep the buffers filled up.  </p>
<pre lang="objc">
	// set up some state
	[record setObject:[NSNumber numberWithBool:YES] forKey:@"isPlaying"];
	[record setObject:[NSNumber numberWithBool:loops] forKey:@"loops"];
	[record setObject:[NSNumber numberWithUnsignedInteger:sourceID] forKey:@"sourceID"];

	// kick off the refill methods
	[NSThread detachNewThreadSelector:@selector(rotateBufferThread:) toTarget:self withObject:soundKey];
	return sourceID;
}
</pre>
<p>This last bit sets up the state we need to keep the buffers full, and kicks off a new thread to run in the background to keep our buffers full.</p>
<p>OK, before we move onto Step D lets have a look at our buffer loader method</p>
<p><strong>loadNextStreamingBufferForSound: intoBuffer:</strong></p>
<p>This is roughly equivalent to the method that you would use to load an entire file into a buffer for standard sound playback, only we are only going to be grabbing a small bit of the file.  Luckily for us this is a pretty common thing you would want to do, so mostly all we have to worry about is keeping the state set properly.</p>
<pre lang="objc">
// this takes the stream record, figures out where we are in the file
// and loads the next chunk into the specified buffer
-(BOOL)loadNextStreamingBufferForSound:(NSString*)key intoBuffer:(NSUInteger)bufferID
{
	// check some escape conditions
	if ([soundLibrary objectForKey:key] == nil) return NO;
	if (![[soundLibrary objectForKey:key] isKindOfClass:[NSDictionary class]]) return NO;
</pre>
<p>First off just some simple checks to make sure I am not trying to load a non-existent sound file, or a non-streaming file.</p>
<pre lang="objc">
	// get the record
	NSMutableDictionary * record = [soundLibrary objectForKey:key];

	// open the file
	AudioFileID fileID = [self _openAudioFile:[record objectForKey:@"fileName"]];

	// now we need to calculate where we are in the file
	UInt32 fileSize = [[record objectForKey:@"fileSize"] unsignedIntegerValue];
	UInt32 bufferSize = [[record objectForKey:@"bufferSize"] unsignedIntegerValue];
	UInt32 bufferIndex = [[record objectForKey:@"bufferIndex"] unsignedIntegerValue];;
</pre>
<p>Grab the record that has all of our state information, and set up all of our variables.</p>
<pre lang="objc">

	// how many chunks does the file have total?
	NSInteger totalChunks = fileSize/bufferSize;

	// are we past the end? if so get out
	if (bufferIndex > totalChunks) return NO;

	// this is where we need to start reading from the file
	NSUInteger startOffset = bufferIndex * bufferSize;

	// are we in the last chunk? it might not be the same size as all the others
	if (bufferIndex == totalChunks) {
		NSInteger leftOverBytes = fileSize - (bufferSize * totalChunks);
		bufferSize = leftOverBytes;
	}
</pre>
<p>Here we are just using our state info to figure out where in the file to look and how big of a chunk to take.  If we are at the last chunk, then it may not be a full sized chunk, so we have to take that into account and change our data size. </p>
<pre lang="objc">
	// this is where the audio data will live for the moment
	unsigned char * outData = malloc(bufferSize);

	// this where we actually get the bytes from the file and put them
	// into the data buffer
	UInt32 bytesToRead = bufferSize;
	OSStatus result = noErr;
	result = AudioFileReadBytes(fileID, false, startOffset, &#038;bytesToRead, outData);
	if (result != 0) NSLog(@"cannot load stream: %@",[record objectForKey:@"fileName"]);

	// if we are past the end, and no bytes were read, then no need to Q a buffer
        // this should not happen if the math above is correct, but to be sae we will add it
	if (bytesToRead == 0) {
            free(outData);
            return NO; // no more file!
        }
</pre>
<p>Ok, here we do the actual meat of the method.  We alloc some memory, and then use the AudioFileReadBytes() function to grab our desired slice of data from the big file. This loads our chunk of sound data into the outData memory.  At this point we will proceed exactly like we would with a single-buffer sound.</p>
<pre lang="objc">

	ALsizei freq = [[record objectForKey:@"freq"] intValue];
	ALenum format = [[record objectForKey:@"format"] intValue];

	// jam the audio data into the supplied buffer
	alBufferData(bufferID,format,outData,bytesToRead,freq);
</pre>
<p>Load out sound into our OpenAL buffer. easy.</p>
<pre lang="objc">
	// clean up the buffer
	if (outData)
	{
		free(outData);
		outData = NULL;
	}

	AudioFileClose(fileID);
</pre>
<p>Do some cleanup.</p>
<pre lang="objc">
	// increment the index so that next time we get the next chunk
	bufferIndex ++;
	// are we looping? if so then flip back to 0
	if ((bufferIndex > totalChunks) &#038;&#038; ([[record objectForKey:@"loops"] boolValue])) {
		bufferIndex = 0;
	}
	[record setObject:[NSNumber numberWithUnsignedInteger:bufferIndex] forKey:@"bufferIndex"];
	return YES;
}
</pre>
<p>Finally we increment the bufferIndex so that the net time we call this method we get the next chunk of data in the sequence. If we are looping we reset the index to 0 at the end.</p>
<p>So, that is steps A, B, C, and the beginning of D.</p>
<p>Lets look more closely at our background thread now.</p>
<p><strong>Step D (and E): The background thread to refill our buffers</strong></p>
<p>OK, you may recall, like ten pages ago, that we kicked off a thread to refill the buffers in the background.  Lets look at that:</p>
<pre lang="objc">
-(void)rotateBufferThread:(NSString*)soundKey
{
	NSAutoreleasePool * apool = [[NSAutoreleasePool alloc] init];
	BOOL stillPlaying = YES;
	while (stillPlaying) {
		stillPlaying = [self rotateBufferForStreamingSound:soundKey];
		if (interrupted) 	{
			// slow down our thread during interruptions
			[NSThread sleepForTimeInterval:kBufferRefreshDelay * 3];
		} else {
			// normal thread delay
			[NSThread sleepForTimeInterval:kBufferRefreshDelay];
		}
	}
	[apool release];
}
</pre>
<p>This is a pretty simple method.  Remember we are in a new thread, so we need to set up our own pool.  Once we are no longer playing, then the thread ends. We make one call basically to rotateBufferForStreamingSound:.  Finally if we are interrupted then we dont need to be refilling but our thread will still run (until we are terminated if that happens). To be good citizens we will decrease the amount of time we are checking the thread.  </p>
<p>Otherwise we just come back in kBufferRefreshDelay seconds.  Setting this number can be a bit tricky.  If you set it too close to the actual time it takes to play your individual buffers (as you would think) then if it lags at all then you will fall behind and never be able to catch up.  You want it to be more than once during every chunk, incase you need to load more than one chunk because of a slow thread.  However, run it too often and you are wasting cycles.  I have mine set to 0.25 seconds based on the 48000 byte buffer.  I dont even remember why i came to these numbers and they might be terrible. but they do work.  Feel free to tune them to your heart's desire.</p>
<p>Next up, the actual buffer rotator:</p>
<pre lang="objc">
// this checks to see if there is a buffer that has been used up.
// if it finds one then it loads the next bit of the sound into that buffer
// and puts it into the back of the queue
-(BOOL)rotateBufferForStreamingSound:(NSString*)soundKey
{
	// make sure we arent trying to stream a normal sound
	if (![[soundLibrary objectForKey:soundKey] isKindOfClass:[NSDictionary class]]) return NO;
	if (interrupted) return YES; // we are still 'playing' but we arent loading new buffers

	// get the keyed record
	NSMutableDictionary * record = [soundLibrary objectForKey:soundKey];
	NSUInteger sourceID = [[record objectForKey:@"sourceID"] unsignedIntegerValue];	
</pre>
<p>First some defensive programming,  if we are getting called with the wrong key then get out, if we are interrupted then we are not loading any new buffers, so get out (but return YES because we want to keep the thread alive)<br />
Then we grab our ubiquitous record and start to fill in some variables.</p>
<pre lang="objc">
	// check to see if we are stopped
	NSInteger sourceState;
	alGetSourcei(sourceID, AL_SOURCE_STATE, &#038;sourceState);
	if (sourceState != AL_PLAYING) {
		[record setObject:[NSNumber numberWithBool:NO] forKey:@"isPlaying"];
		return NO; // we are stopped, do not load any more buffers
	}
</pre>
<p>First up: check to see if this source that we are meant to be loading buffers into is stopped.  If it is, then we dont need to load any new buffers, and we want to return NO so that the thread finishes as well.</p>
<pre lang="objc">

	// get the processed buffer count
	NSInteger buffersProcessed = 0;
	alGetSourcei(sourceID, AL_BUFFERS_PROCESSED, &#038;buffersProcessed);

	// check to see if we have a buffer to deQ
	if (buffersProcessed > 0) {
		// great! deQ a buffer and re-fill it
		NSUInteger bufferID;
		// remove the buffer form the source
		alSourceUnqueueBuffers(sourceID, 1, &#038;bufferID);
		// fill the buffer up and reQ!
		// if we cant fill it up then we are finished
		// in which case we dont need to re-Q
		// return NO if we dont have mroe buffers to Q
		if (![self loadNextStreamingBufferForSound:soundKey intoBuffer:bufferID]) return NO;
		// Q the loaded buffer
		alSourceQueueBuffers(sourceID, 1, &#038;bufferID);
	}
</pre>
<p>Next up, the big event: we see how many buffers the source has processed since our last check.  For every buffer that has been processed we should fill in a new one and queue it up.<br />
Before we can queue up a new buffer, we need to dequeue the old one.  We do this with a call to alSourceUnqueueBuffers().  This fills in our bufferID variable, we can use this buffer now for whatever we want.  In this case we want to fill it up with the next chunk of sound data and then put it at the end of the queue.</p>
<p>We call our loadNextStreamingBufferForSound:intoBuffer: method and if it returns NO, then we are all done and we can get out.<br />
If it returns YES then we can queue up the newly filled buffer.</p>
<pre lang="objc">
	return YES;
}
</pre>
<p>Finally, if we have made it this far then it was a successful buffer load and we return a YES to keep our loop going.</p>
<p>That is about it.  The way this is all built, once you cann alSourceStop() on your streaming sound ID, everything sorta cleans itself up.  The buffers stop rotating, and the thread stops.  You still have buffers in memory tho, so if you want to clean those up too, be sure to add that code.</p>
<p><strong>To Sum Up</strong></p>
<p>OK, so there are the five-ish steps to streaming sound glory with OpenAL.  </p>
<p>Obviously I have left out all the other code you need to get this running, have a look at the articles linked at the top, they have most of the rest of it.  </p>
<p>Also I should mention that all of this code comes from an earlier, simpler version of what I generally use as my 'sound engine' nowadays. (basically I have been working on finishing this tutorial for awhile now and my working code has evolved since then :-)<br />
This is not to say the sample code here is necessarily inferior, in fact my current code does almost exactly the same things, only there is a bit more optimised state handling and some other things that make it faster/easier, but not as easy to explain in an already very long post.  So feel free to take this code and make it better in your own way :-)  (for instance, instead of using dictionaries for state, I now have some proper sound classes that hold all that state for me etc..)</p>
<p>Also, i should say that if this code crashes your machine, or bricks your phone or makes your cat lose all it's hair, it is not my fault, you have been warned.</p>
<p>Cheers!<br />
-B</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2010/05/04/streaming-in-openal/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>GameBook Teaser trailer!</title>
		<link>http://benbritten.com/2009/12/23/gamebook-teaser-trailer/</link>
		<comments>http://benbritten.com/2009/12/23/gamebook-teaser-trailer/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:08:05 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://benbritten.com/?p=942</guid>
		<description><![CDATA[Tin Man and I just finished making the teaser trailer for the upcoming Gamebook Adventure release: An Assassin in Orlandes. It is pretty cool, check it out: Assassin in Orlandes is nearly finished, we are planning for an early January &#8230; <a href="http://benbritten.com/2009/12/23/gamebook-teaser-trailer/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Tin Man and I just finished making the teaser trailer for the upcoming Gamebook Adventure release: An Assassin in Orlandes.  It is pretty cool, check it out:</p>
<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/akpOtcBCrFg&#038;hl=en_US&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/akpOtcBCrFg&#038;hl=en_US&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>
<p>Assassin in Orlandes is nearly finished, we are planning for an early January submission to the App Store, so look for it in mid to late January!</p>
<p>Cheers!<br />
-B</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2009/12/23/gamebook-teaser-trailer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mole at GCAP: Very well received!</title>
		<link>http://benbritten.com/2009/12/09/mole-at-gcap-very-well-received/</link>
		<comments>http://benbritten.com/2009/12/09/mole-at-gcap-very-well-received/#comments</comments>
		<pubDate>Wed, 09 Dec 2009 05:24:53 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://benbritten.com/?p=939</guid>
		<description><![CDATA[(Note: this is cross posted from Escape Factory) Chris and I just got back from the Global Connect Asia Pacific game dev conference here in Melbourne. We entered Mole into the GDAA Independent Games Awards 2009 and got selected as &#8230; <a href="http://benbritten.com/2009/12/09/mole-at-gcap-very-well-received/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>(Note: this is cross posted from <a href="http://escfactory.com/2009/12/mole-at-gcap-total-success/">Escape Factory</a>)</p>
<p><a href="http://designerwatts.com">Chris </a>and I just got back from the <a href="http://www.gameconnectap.com/">Global Connect Asia Pacific</a> game dev conference here in Melbourne.  We entered <a href="http://escfactory.com/mole">Mole</a> into the GDAA Independent Games Awards 2009 and got selected as one of the finalists.  </p>
<p>As a GDAA finalist we were invited to put up a table and show off our game at the conference.  Chris whipped up a few posters and I grabbed a couple of the stray laptops that I have laying around and we hit the expo.<br />
<a href="http://escfactory.com/mole"><br />
<img src="http://escfactory.com/wp-content/uploads/2009/12/Mole_Icon_125x125.png" alt="Mole_Icon_125x125" title="Mole_Icon_125x125" width="125" height="125" class="aligncenter size-full wp-image-318" /><br />
</a><br />
GCAP is not a gamer expo, it is a game developer expo, so all the people there are somehow involved in the creation of games.  Over the two day expo, we spoke to a zillion talented and creative people and they all played Mole, and let us know what they think.</p>
<p>The response was overwhelmingly positive.  We had people coming back two and three times to just sit and play Mole during the downtimes.  We had people who just sat down to have a quick look end up staying for 30 minutes trying to dig deeper and deeper.  </p>
<p>Best of all however was the ability to watch people play the game.  We spent a huge amount of time before the conference making sure that the core game play was solid and that the game was fun, and we were richly rewarded for that effort.  However, watching people play the game highlighted the areas of the user interface that were lacking.  It made apparent the places where we need to change the words on the menus or add new buttons.  For instance, when you go to the upgrade shop from the end-of-dig scorecard, it is not at all obvious how to get back.  Similarly, when people play it for the very first time, they run out of air and get back to the surface and don&#8217;t realize that they need to hit the &#8216;finish digging&#8217; button to end the dig so they can start a new one.  We even found a few gameplay bugs that we will iron out.</p>
<p>We are currently going through and tweaking all these little bits and pieces to try to hone the user experience before we release it to the app store.  But we want people to play the game so I have put up the GCAP version online so that anyone can play it for free. </p>
<p>If you are into it: head over to the <a href="http://escfactory.com/mole"><b>Mole page</b></a> and hit the &#8216;play now&#8217; link.  You will need the Unity3d player, and you can get it from the game page.</p>
<p><a href="http://escfactory.com/mole"><img src="http://escfactory.com/wp-content/uploads/2009/12/Mole_Icon_512x512-150x150.png" alt="Mole_Icon_512x512" title="Mole_Icon_512x512" width="150" height="150" class="aligncenter size-thumbnail wp-image-319" /></a></p>
<p>We are planning on keeping the online version free to use, and we will be updating it alongside the iPhone version, so if you come back and notice some new tweaks here and there, that is why.</p>
<p>We love to hear what you have to say about the game, so send me an email, or leave a comment here!</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2009/12/09/mole-at-gcap-very-well-received/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My thoughts on Unity Free</title>
		<link>http://benbritten.com/2009/10/29/my-thoughts-on-unity-free/</link>
		<comments>http://benbritten.com/2009/10/29/my-thoughts-on-unity-free/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 00:51:40 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://benbritten.com/?p=921</guid>
		<description><![CDATA[Just recently, like, very recently (maybe a few hours ago) Unity released their base-level product, Unity Indie for free. This is pretty huge news for the game development community. It is, as they say (and forgive the pun) a Game &#8230; <a href="http://benbritten.com/2009/10/29/my-thoughts-on-unity-free/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Just recently, like, very recently (maybe a few hours ago) Unity released their base-level product, Unity Indie for <a href="http://unity3d.com/#freeunity">free.</a></p>
<p>This is pretty huge news for the game development community. It is, as they say (and forgive the pun) a Game Changer.</p>
<p>If you don&#8217;t already know, Unity is a very powerful tool for rapidly building games. (it is billed as a 3d game engine, but it also works quite well for <a href="http://escfactory.com/2009/10/mole-coming-soon-for-iphone-play-it-now-on-the-web/">2d games</a>) One of the many features of Unity is the ability to take the game project you have built, and with the click of the mouse, build a version for the mac, a version for the pc and a version that runs in a web browser.  This is excellent for distributing your game but it has other side benefits as well.  I collaborate with people all over the world, and we use the in browser games to share our ideas quickly and easily, not to mention it is much easier to get your testers to test out your prototypes if all they have to do is open a browser window.  </p>
<p>Before now, the indie version was not very expensive, less than $200 or so, but now that it is free, I think we will see a flood of new and interesting games come out in the coming months.  </p>
<p>What does this mean for indie game development?</p>
<p>Well, the obvious thing is that we will see a ton more web based titles, probably lots of crap, but there will always be a few gems in there.  </p>
<p>I think that Flash development will start to see a big challenge from the Unity guys.  I know a ton of flash guys who have been eyeing unity for awhile now and this will most likely push them over the edge.  dont get me wrong, flash is a great tool, and it is great for making games, but it is not a game-building-tool.  Unity is designed from the ground up to make games. Here is a good post to read if you a flash dev who is on the fence: <a href="http://diamondtearz.org/2009/01/14/10-reasons-for-flash-developers-to-learn-unity-3d/">http://diamondtearz.org/2009/01/14/10-reasons-for-flash-developers-to-learn-unity-3d/</a></p>
<p>The even bigger news for me as an iPhone developer is that I think many many more people will start to use unity to build games for the iPhone.  </p>
<p>Now, Unity iPhone Basic (the cheapest iPhone license) is still about $400.  And some of the zero budget indie developers might have to think twice about that kind of money (it is totally worth it, trust me) But now you can download the Unity Free and prototype your game, or release a web version or just get to know unity and then be ready to port it over to the iPhone version.  We are doing that right now with &#8216;Mole&#8217; and I will be blogging about what it takes to move a prototype level game from the desktop version of unity into a working iPhone version.</p>
<p>I will also be interested to see how this effects the other iPhone game-focused APIs like cocoas2d.  Cocoas2d and the like are still free (so still $400 cheaper than using unity to develop your game) and if you are building a 2d game it makes a lot of sense to start with cocoas2d, but I can tell you from my personal experience that building a 2d game with unity is very easy and if your time is worth anything to you then the $400 investment to upgrade to iPhone Basic is well worth the money.  Also, I cant stress this enough, you can now prototype your game in Unity for free.  Even if you then decide to use cocoas2d to build the deployment version (a few reasons you might want to do this, more on that in a second) you can still do a rapid prototype with Unity to figure out all your gameplay mechanics and decide if the game is fun or not.</p>
<p>So, Unity is great, but what are the downsides?</p>
<p>Well, in terms of desktop or web development, there aren&#8217;t any real downsides.  Go get a copy and start making games. </p>
<p>In terms of iPhone development there are a few caveats.  </p>
<p>First off, as i have mentioned, it is not free. But $400 is very cheap for what you get.</p>
<p>The biggest issue with using Unity Basic (and to some extent this applies to the pro version as well) to develop iPhone games is that your app size will not be under 10M (which is the size limit for apps to be able to be downloaded over the cell network).  For the most part this is not a big deal, most games with any amount of depth tend to be bigger than 10M no matter the development tools used.  </p>
<p>However, the casual games that you are trying to sell for $0.99 and you want to be an impulse buy, and so you want them to be less than 10M, these are nigh impossible to make with Unity.  Why is that? Well, the unity engine is very capable, comes with all sorts of great things like built in physics, scripting, shaders, and lots of other goodies, but all that comes at the cost of size.  If you spring for iPhone Advanced then you can strip out parts of the engine you are not using, and possibly get under the 10M mark, but this is a very hard thing to do.</p>
<p>My advice: even if you are looking to build small casual games for the iPhone, I would still suggest you get the now free Unity and prototype with it. Then once your game is working fall back on one of the other frameworks like cocoas2d to build it.  However, if you have even an inkling that your game will exceed the 10M limit, then just get the iPhone version.</p>
<p>Cheers!<br />
-B</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2009/10/29/my-thoughts-on-unity-free/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>UIWebview overlay for Unity3d on the iPhone</title>
		<link>http://benbritten.com/2009/09/24/uiwebview-overlay-for-unity3d-on-the-iphone/</link>
		<comments>http://benbritten.com/2009/09/24/uiwebview-overlay-for-unity3d-on-the-iphone/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 02:15:07 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://benbritten.com/?p=905</guid>
		<description><![CDATA[I just wrote a big post about how to open up a UIWebView overtop of the unity game engine. This is a good way to add Playhaven integration to your app, as we are doing with Snowferno. Anyway, I posted &#8230; <a href="http://benbritten.com/2009/09/24/uiwebview-overlay-for-unity3d-on-the-iphone/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I just wrote a big post about how to open up a UIWebView overtop of the unity game engine.  This is a good way to add Playhaven integration to your app, as we are doing with Snowferno.  Anyway, I posted it on the Snowferno development blog:</p>
<p><a href="http://www.snowferno.com/2009/09/23/playhaven-unity-and-snowferno/">http://www.snowferno.com/2009/09/23/playhaven-unity-and-snowferno/</a></p>
<p>Check it out if that sounds like something you might want to do.</p>
<p>Cheers!<br />
-B</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2009/09/24/uiwebview-overlay-for-unity3d-on-the-iphone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>alBufferDataStatic: why you should avoid it</title>
		<link>http://benbritten.com/2009/09/20/albufferdatastatic-why-you-should-avoid-it/</link>
		<comments>http://benbritten.com/2009/09/20/albufferdatastatic-why-you-should-avoid-it/#comments</comments>
		<pubDate>Sun, 20 Sep 2009 01:11:24 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[openAL]]></category>

		<guid isPermaLink="false">http://benbritten.com/?p=898</guid>
		<description><![CDATA[OK, So, I just got an email from Ken, a dude who surfed across this OpenAL stuff on my blog, had some troubles, and asked me for help. He is having trouble unloading buffers and then re-using them again without &#8230; <a href="http://benbritten.com/2009/09/20/albufferdatastatic-why-you-should-avoid-it/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>OK, So, I just got an email from Ken, a dude who surfed across this OpenAL stuff on my blog, had some troubles, and asked me for help.  He is having trouble unloading buffers and then re-using them again without getting some esoteric OpenAL errors.  </p>
<p>So I went through the snippets he sent me very quickly and threw out some advice.  Ken came back with a few more questions and I went over the code again and noticed this:</p>
<pre lang="obj-c">
          // use the static buffer data API
          alBufferDataStaticProc(buffer, format, data, size, freq);
</pre>
<p>Ah-HA!  I said, that is probably your problem right there!  alBufferDataStatic should be avoided unless you <strong>need</strong> it.  When do you know if you will need it?  Here is a rule of thumb: If you dont know the answer to that question then you dont need it.</p>
<p>(I don&#8217;t want to seem to be picking on Ken, this problem is so common that I decided I needed to do a post about it (similar to my rant about never using the sample code from Apple in a shipping app))</p>
<p>OK, so why do I think you should avoid it? I am sure you have heard that if you want the best performance then you should be using alBufferDataStatic() right?!  No.</p>
<p>Well, what is alBufferDataStatic() anyway?  alBufferDataStatic puts the onus of memory management for all your buffer data onto your code.  </p>
<p>Let me repeat that:  When using alBufferDataStatic() <strong>YOU</strong> are responsible for all the memory management.</p>
<p>That is it.  That is your big performance boost.  </p>
<p>Wait! Really? that is all it does?</p>
<p>Yes. </p>
<p>The iPhone&#8217;s shared memory space and the way it handles memory and the way your app gets jettisoned if you use too much is a very unique situation.  A situation that requires that you often have to really closely handle your memory.  So!  That means that if you are trying to squeeze every single last byte of memory out of the iPhone so that your fully immersive 3d first-person-shooter can keep a consistent 30FPS then you will probably want to spend a few weeks tweaking your sound code so that you have very close control of your memory at all times.  </p>
<p>For the other %99.9999 percent of apps that might want to use OpenAL (even if you are using lots of sounds) you are just adding extra headaches to your code by using alBufferDataStatic(). Here is another rule of thumb:  If you are not employing a developer whose sole job is to handle the sound code in your app, then you don&#8217;t need alBufferDataStatic().</p>
<p>Have a quick read of the <a href="http://developer.apple.com/iphone/library/technotes/tn2008/tn2199.html">technote</a> that mentions alBufferDataStatic().</p>
<p>What does this really mean?</p>
<p>It means this:  when you use alBufferData() you load your sound data into a local buffer (one that you have to malloc) then when you call alBufferData(), OpenAL copies all those bytes into it&#8217;s own buffer that it deals with.  Then you free your local storage and OpenAL now owns that buffer.  The downside: for a brief moment, you have 2 copies of your sound in memory.  The upside: very very easy memory management.  </p>
<p>If you are getting jettisoned right here, during this buffer copy, then you may need alBufferDataStatic(). But more likely you have done a crap job of handling your memory elsewhere.  (also it is good to note that if you are loading big sounds into memory you are doing it wrong anyway, those big sounds should be streamed).  </p>
<p>Ok, you are absolutely, positively sure that you need to manage your own sound memory?  Maybe you should be using alBufferDataStatic(), but first: here is yet another rule of thumb: if you are reading this blog post to see if you need to use it; you don&#8217;t.  go to your code right now and take it out.  Just take it out.  </p>
<p>Obviously I am being a bit hyperbolic in an attempt to make a point.  I dont know about your code, but here is a small list of the most common bugs I find in my code:</p>
<ul>
<li> Forgot to release an object properly and it leaks and eventually my app is jettisoned</li>
<li> Accidentally released an autoreleased object, causing a crash</li>
<li> Accidentally released an object owned by some other object, causing it to crash much much later</li>
<li>malloced some space and forgot to free it, causing a leak and eventual jettison</li>
<li>freed some malloced space and then tried to use it, causing my app to go batshit crazy</li>
</ul>
<p>The list goes on.  But can you see a common thread?  Memory.  Why would I want to add yet more memory management responsibilities when I dont need it? Why do developers always insist on making their own lives so much more difficult than they have to?</p>
<p>Here are a few platitudes:</p>
<ul>
<li>Less code == Less bugs.  More code == More bugs.  Therefore Less Code is always better.</li>
<li>Do not add any code you dont need right now.  (this is very common, you think to yourself: Hmm I am already here in this object, and I could see that I might need a method that does X in the future so I will just write it now so I dont have to write it then.  Wrong.  In that &#8216;future&#8217; when you do need it, it will need to do Y, not X and you will have to re-write it.  Or, more likely you will never need a method that does X, and you just wasted a bunch of time and added more code</li>
<li>Do not prematurely optimize.  Get the code working first.  Then go back and identify the places you need to smooth out.  If you try to optimize as you go then you will end up spending all your time making that one method totally awesome (only to realize later that method only gets called once every few seconds, so really it could be the least efficient bit of code ever and nobody would ever notice.)
</li>
</ul>
<p>So, by using alBufferDataStatic() you are breaking all three of my lovely platitudes.  </p>
<p>Dont do it.  </p>
<p>You are only causing yourself grief and making your code buggy and shitty.  Use alBufferData(). It works.  It is easy.  The highly experienced engineers who work on OpenAL have made sure that there are no memory issues with alBufferData(). If you decide to port your code,  alBufferData() will still work!  alBufferData() makes your breath smell minty! alBufferData() will totally pull chicks.</p>
<p>I have put OpenAL code into about 6 apps now.  A few games and a few utilities.  And one &#8216;sound board&#8217; style app that played 32 sounds simultaneously (which was the max at the time, probably still is) and was able to handle gigantic sounds files (via streaming) without ever using alBufferDataStatic().  Was this some herculean task of super-awesome mad coding skillzzzz? </p>
<p>No. Just the opposite actually.  I keep all my code as absolutely bare-minimum simple as I can.  </p>
<p>Keep your code simple, don&#8217;t use stuff you don&#8217;t need. </p>
<p>Cheers!<br />
-B</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2009/09/20/albufferdatastatic-why-you-should-avoid-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Snowferno 1.0 submitted!</title>
		<link>http://benbritten.com/2009/07/25/snowferno-1-0-submitted/</link>
		<comments>http://benbritten.com/2009/07/25/snowferno-1-0-submitted/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 22:16:35 +0000</pubDate>
		<dc:creator>balord</dc:creator>
				<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://benbritten.com/blog/?p=755</guid>
		<description><![CDATA[SO, it was a long LONG road, but along with Mike and Brent at FatlabMusic, we finally submitted our first game offering to the approval gods at apple. and now we wait. .. ..waiting&#8230; still waiting&#8230; However! good news this &#8230; <a href="http://benbritten.com/2009/07/25/snowferno-1-0-submitted/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>SO, it was a long LONG road, but along with Mike and Brent at FatlabMusic, we finally submitted our <a href="http://www.snowferno.com/2009/07/23/v1-0-0-submitted-its-all-up-to-apple/">first game offering</a> to the approval gods at apple.  </p>
<p>and now we wait.</p>
<p>..</p>
<p>..waiting&#8230;</p>
<p>still waiting&#8230;</p>
<p>However!  good news this morning!  We got our first game site review!</p>
<p><a href="http://nodpad.com/2009/07/24/exclusive-hands-on-with-snowferno/">http://nodpad.com/2009/07/24/exclusive-hands-on-with-snowferno/</a></p>
<p>Here is a choice quote: (that will most likely become our pullquote from this review:</p>
<blockquote><p>I found that the earlier levels were quite easy, but once the game progressed, it became sheer challenge and sheer awesomeness.</p></blockquote>
<p>Thanks Daniel and nodpad.com!</p>
<p>cheers!<br />
-B</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2009/07/25/snowferno-1-0-submitted/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Snowferno is soooo close</title>
		<link>http://benbritten.com/2009/07/23/snowferno-is-soooo-close/</link>
		<comments>http://benbritten.com/2009/07/23/snowferno-is-soooo-close/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 22:39:52 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://benbritten.com/blog/?p=754</guid>
		<description><![CDATA[We just releases rc2 to the beta testers (after a bit of a debacle with rc1) and if no red flags go up in the next 24 &#8211; 48 hours we are going to submit to the app store! We &#8230; <a href="http://benbritten.com/2009/07/23/snowferno-is-soooo-close/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>We just releases rc2 to the beta testers (after a bit of a debacle with rc1) and if no red flags go up in the next 24 &#8211; 48 hours we are going to submit to the app store!  We are all very excited, mostly because it is our first game that is &#8216;ours&#8217; and we also have some great ideas for new games that we want to move on to!</p>
<p><a href="http://www.snowferno.com/2009/07/22/rc1-crasher-rc2-now-released-to-testers/">http://www.snowferno.com/2009/07/22/rc1-crasher-rc2-now-released-to-testers/</a></p>
<p>woo!</p>
]]></content:encoded>
			<wfw:commentRss>http://benbritten.com/2009/07/23/snowferno-is-soooo-close/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

