Creating Flat Packages in OSX

I was recently involved with a daemon-style Java project that needed a simple installer solution for OSX. We didn’t require a huge amount of sophistication from the installer. So we opted for flat packages. Flat packages are simple, self-contained files that are easy to pass around.

Prior to Leopard (10.5), packages weren’t flat at all. They were bundles, which are just folders that OSX treats in a special way. Bundles contain a variety of files. Package bundles, for example, contain files used as part of the install process such as a bill of materials, the application payload, and a collection of localized resources among other things. Previously, if you wanted to distribute one of these packages, you’d have to put the package inside a DMG or tar it up.

Another interesting thing happened during the evolution of OSX packages. PackageMaker, a wart in the eyes of many developers and source control systems, was officially deprecated and dropped in Xcode 4.6 (and there was much rejoicing :-)). Developers were left with three terminal-based utilities that could be used to build packages – pkgbuild, productbuild, and pkgutil.

For more information on the evolution of OSX packages, I highly recommend reading this MacTech article which goes into the subject in some depth.

pkgbuild

pkgbuild is a tool for creating a very basic, bare-bones component package. The resulting package will contain the payload for a single component. It also supports preinstall/postinstall scripts. And that’s about it.

productbuild

productbuild is a tool for creating a “product archive”, which is kind of like a super-package. I like to think of it as a package of packages. But it’s really so much more. You can customize the UI, as well as explicitly declare installation prerequisites such as the minimum required RAM, OS version, etc. Even JavaScript is supported for some things. If you create apps for the Mac App store, this is the tool you’ll be using to build your packages.

pkgutil

pkgutil is kind of like a Swiss Army knife for packages. With pkgutil, you can rip a package apart and then put it back together again. It doesn’t matter if it’s a product archive or a component package. If it’s a pkg file, pkgutil can work with it. It also provides a number of options for examining package contents and performing tasks like package verification and repair.

I’m going to give a quick overview on how I use these three utilities to build the flat package for our product. This approach can be adapted for your own needs.

Simple Component Packages

If you want to create a very simple package for a single component application, the easiest tool for the job is pkgutil. A complete list of options for pkgutil can be found on the man page. But here are the ones that are important.

--root – This option specifies the location of the source content you want packaged up. This can be a path containing anything. Our own application is Java-based and is nothing more than a folder of JAR files. We simply point --root to the folder containing all of our JAR artifacts.

--component – You can use this option as an alternative to --root. With --component, you’re being a bit more specific by giving pkgbuild the path to a component bundle. This might be an app bundle, a browser plugin bundle, etc. Why would you use this option instead of --root? If pkgbuild knows it’s working with a bundle, it can infer some of the other configuration options it needs, such as package identifier and install location.

--identifier – The identifier is a unique string that identifies your component. The normal convention for the identifier resembles something like a backwards domain. You start with a TLD, then follow that with a company name or developer name, and then follow that with a product name. So an identifier for Roadie Assist (not an iOS or OSX app, but could be someday) might look like “com.shanekirk.roadieassist” (this is indeed the package name on the Google Play store). There’s certainly flexibility in how you name your package IDs. They just need to be unique. But don’t deviate too much from the convention. It’ll only cause confusion.

--version – This is a monotonically increasing number. The idea is that every time you release a new version of the component, you need to increase this value. Otherwise, the upgrade process may fail. If this value isn’t set, pkgutil defaults with a value to 0. (Tip: If your build system keeps track of build numbers, consider using that as your package version. If the whole thing is automated with scripts, you’ll probably never have to think too much about this value again.)

--install-location – This is where you want to place the component on the target system. For instance, if you’ve built an application bundle, you’ll probably want to place it in /Applications on the target machine.

--scripts – Packages support a number of scripts that are invoked during the install process. If you have a script called preinstall, this will be invoked before the component is installed. If you have a script called postinstall, it will be invoked after the component is installed. The --scripts option specifies where you’re storing these scripts. The scripts can be in any language so long as the files are marked executable and have the appropriate shebang indicating the path to the interpreter. If either of the scripts return a number other than 0, Installer assumes a failure occurred and the installation halts.

A typical invocation of pkgbuild might look like so…

pkgbuild --root ./stagedfiles --scripts ./scripts --identifier com.example.myapp --version 1 --install-location /Applications mypackage.pkg

For many folks, this may be all that’s needed. From within Finder, you can double click the resulting package and component can be installed without having to do much else. If you would like to customize the UI a bit, allow for a more “componentized” installation, or distribute your application through the Mac App store, you’ll need to use productbuild.

Product Archives with productbuild

Much of what you can do with pkgbuild you can also do with productbuild. But don’t be fooled. Product archives and component packages aren’t quite the same thing. Synthesizing a distribution from a product archive (package created with productbuild), for example, will fail, but doing the same thing with a component package (package created with pkgbuild) works just fine (have no idea what I just said? Don’t worry. You will soon.) With productbuild, you can also customize quite a bit of what the end user sees. If you peruse the man page for productbuild, you’ll find that many of the command-line options you used with pkgbuild are there for productbuild as well. But you’ll also see a few other things mentioned like plugins, distribution files, resource folders, etc.

Regardless of how you created your package, you’ll probably want to update the UI or perform more sophisticated prerequisites checking. To do this you’ll need to create a distribution file.

A distribution file is just an XML file. It’s used to configure both look and feel, as well as behavior, of the package installer. The idea is that you create this file and then use productbuild to create a new package from the old one and the new distribution file. Confused yet? Let’s work through an example.

productbuild example

Let’s assume we have a package called mypackage.pkg kicking around (if you’re reading closely, you’ll notice this is the same package I use as an example above while discussing pkgbuild.). Our goal is to change the title and background image shown to the user. So we need to create a distribution file and modify it to suit our needs. Fortunately for us, productbuild is able to synthesize a skeleton distribution file for us.

productbuild --synthesize --package ./mypackage.pkg distribution.xml

Note that this only works against component packages created with pkgbuild. If you try to do this against a pkg created by productbuild, it’ll result in an error. The resulting XML will look something like the following.

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<installer-gui-script minSpecVersion="1">
    <pkg-ref id="com.example.myapp"/>
    <options customize="never" require-scripts="false"/>
    <choices-outline>
        <line choice="default">
            <line choice="com.example.myapp"/>
        </line>
    </choices-outline>
    <choice id="default"/>
    <choice id="com.example.myapp" visible="false">
        <pkg-ref id="com.example.myapp"/>
    </choice>
    <pkg-ref id="com.example.myapp" version="1" onConclusion="none">mypackage.pkg</pkg-ref>
</installer-gui-script>

So far, so good. Let’s first change our package title. We want the title to be “My Example Application”. Open the distribution XML with your favorite text editor. Within the installer-gui-script element, create a new child element called “title” and set the element’s character data appropriately. It should look something like this.

<title>My Example Application</title>

Now let’s create a new background image for our installer. The recommended size for the background image is 620×418. The background image I’ll be using for this is example is a simple PNG as shown below.

Create a new folder for your installer resources and place the image in there. We’ll call it the file background.png.

Now, let’s add the PNG reference to the distribution.xml. Open the XML file and within the root installer-gui-script element, create a new element called background. Add two attributes, one called “file” that simply names the file and one called “mime-type” that describes the image type. For example, your background element might look like so.

<background file="background.png" mime-type="image/png" />

Save your changes. Now we just need to create a new package with our modified distribution file. Using productbuild the command might look like so.

productbuild --distribution distribution.xml --resources ./myimages --package-path ./mypackage.pkg myimprovedpackage.pkg

This command produces a new package called myimprovedpackage.pkg that has the new modified background image. If you double click on it with Finder, you should see your new background image, but it should also install the new package just as it did the old one.

For a complete list of everything you can do to a distribution.xml, check out the distribution xml schema reference. You’ll find that there’s a lot of flexibility in what you can do to your packages. There are some things I always do, such as customize the welcome, license, readme pages, run JavaScript as part of the startup validation, and limit install locations to the root volume. But I’ll save discussion of those types of things for a future blog post.

Injecting Files Into Flat Packages

At some point in your journey with flat packages, you’ll find that you can’t get something into the package file that you really think should be there. This might be an extra script or even an Installer plugin (a topic that deserves its own blog entry). Both pkgbuild and productbuild promise to copy content out of the scripts or resources folders, but sometimes they just don’t. So we need to get these files into our package. That’s where pkgutil comes in.

pkgutil allows you to expand a package to a folder structure like so.

pkgutil --expand myimprovedpackage.pkg expandedcontent

This creates a folder called expandedcontent that contains the expanded content of the package. If you explore the folder structure, most of what you see will only make sense if you’re familiar with the structure of the original package bundles. I strongly advise you to read up on the history of the package format I mentioned in the beginning to be effective at shuffling stuff around within these folders.

Once you’ve got things where they need to be, then you can flatten everything again like so.

pkgutil --flatten expandedcontent myimprovedpackage.pkg

Conclusion

And that’s it. I realize I glossed over a lot of interesting stuff with regards to the distribution XML file. Experiment with it. I hope to write a followup to expand on some of these topics in closer detail. If you have questions, post them!

Parasailing in the Dominican Republic

Leora and I just got back from our honeymoon in the Dominican Republic. It was an amazing time. If you’ve never been down there, I highly recommend you go. The people are friendly, the weather is magnificent, and, best of all, it’s not all that expensive.

On one of our days at the resort, we decided to venture out for a little parasailing excursion. Leora took some video as I climbed up in the air. It was quite the experience. I really wish I had taken a GoPro with me, because the view was something to behold. But, alas…

Anyway, here’s the video. Enjoy!



Building a Home Media Server with Raspbmc: Part Four

If you’ve been following along with the last few blog entries, you should have a pretty good idea of how to build a Raspbmc device for cheap (What’s Raspbmc? Click here to start at the beginning.) Maybe you’ve already built one. And maybe it’s already achieved family-member status. 🙂 If so, congratulations!

In this last installment, I’m going to talk about enhancing your Raspbmc experience. I’ll also discuss some of the issues I had along with their solutions.

The topics presented below are in no particular order. It’s really more of a collection of Raspbmc recipes. So feel free to scan down the list until something catches your eye. And if you have a tip that doesn’t appear here, please leave a comment!

Fickle HDMI – When I first began using Raspbmc, the HDMI connection was a real pain. I’d finish watching one of my favorite movies, turn the TV off, and then return later to watch something else. Once I turned the TV back on, Raspbmc was nowhere to be seen. My only recourse was rebooting the Pi by unplugging it and plugging it back in. Not only was this inconvenient, but also extremely clumsy. Not shutting down Raspbmc properly before yanking the power can damage the filesystem.

If you experience this problem, the solution is to modify the /boot/config.txt file. Simply SSH into Raspbmc (User: pi, Password: raspberry) and edit /boot/config.txt using your favorite text editor. Add the following two lines at the end of the file.

hdmi_force_hotplug=1
hdmi_drive=2

Then save and reboot.

Setting hdmi_force_hotplug to 1 forces Raspbmc to use HDMI even if the TV or monitor isn’t detected. The other setting, hdmi_drive, controls the mode that HDMI runs in. Setting it to 1 forces Raspbmc to use DVI mode, which is merely HDMI without sound. This is NOT what we want. Setting it to 2 forces Raspbmc to use normal HDMI mode, which includes sound. This IS what we want.

Hulu/Netflix/Amazon Playback – One of the things that attracted me to Raspbmc was the ability to stream content from providers like Hulu. I had read about the Free Cable add-on from the Bluecop repo before starting the project. Free Cable is an XBMC add-on that allows you to stream content from both paid services (e.g., Hulu, Netflix, Amazon, etc.) and networks that make their content available online for free (CBS, Fox, etc.). So I tried it. And my experience with Free Cable was less than spectacular. Not only was it incredibly slow. But for many media sources, such as CBS, HGTV, etc., it simply didn’t work.

The solution for my woes wasn’t a Raspbmc add-on, but a desktop application called PlayOn. PlayOn is an application that acts as a middleman for streamable content. You install it on a PC and then supply it with credentials for whatever streaming services you use. It accesses content on behalf of Raspbmc and then restreams it. It’s fast. It’s simple. And it works.

At the time of this writing, PlayOn costs between $8.99 and $59.99 depending on your needs and budget. At the low end, they offer subscription model. At the high end, you can purchase a lifetime license.

A word of caution. To use PlayOn with Raspbmc, you MUST ALSO purchase the MPEG-2 license from RaspberryPi.com. Otherwise, Raspbmc won’t be able to decode PlayOn’s video stream. I didn’t realize this at first and all I got from PlayOn was audio.

When you purchase the MPEG-2 license, I suggest SSHing in to Raspbmc and adding it to the /boot/config.txt file using your favorite text editor. Just open up the /boot/config.txt file and paste the lines they instruct you to copy from the email you receive. Then reboot. Alternatively, you can enter the keys using the Raspbmc Settings program. But if you do, you’ll probably lose any custom settings you’ve added to the config.txt file, including the HDMI settings I mentioned above.

To use PlayOn with Raspbmc, you’ll need to add a uPnP video location. Start PlayOn from your PC, hop over to your Raspbmc device, and then navigate to Videos->Files->Add Videos. Click the Browse button and then select uPnP Devices. The PC running PlayOn should show up in the list. If it does, select it. If it doesn’t, check that your PC’s firewall isn’t blocking uPnP traffic. Once you’ve added the PlayOn source, you can use it by navigating to Videos->Files->PlayOn. I haven’t figured out a way to put PlayOn on the main Raspbmc menu. So if someone knows, please tell me how in a comment below.

Subtitles – The first time I curled up on the couch and started watching an English speaking movie with subtitles, I just about lost my mind. I couldn’t figure out how to shut them off. If you look around in the system settings you’ll find there isn’t a single subtitles on/off setting anywhere.

The trick to fixing this starts with playing a single video that contains subtitles. Press the “OK” button on your remote to pop up the On Screen Display. Then press the right button until the little speaker icon is selected. Press OK again. This will pop up the audio settings for the current video. If you scan down the list of options, you’ll find one called “Disable Subtitles”. Turn it off. And then at the bottom of the menu there will be another option called “Set as default for all videos”. That is the secret sauce. Select that and subtitles will be disabled globally. For videos that you need subtitled, you can navigate back to this menu to turn them back on for that single video.

Remote Updating/Cleaning – We store the bulk of our media on a FreeNAS box in a part of the house that’s about as far away from the TV as you can get. The computer I usually use to maintain our collection is just as far away. A common chore for me was having to fire up Raspbmc’s web based remote control to clean and update Raspbmc’s video library.

Raspbmc actually features a pretty slick JSON-RPC API. It’s what enables applications like Yatse to work as a remote control. Since it’s web based, you can also use it to do tasks like library cleaning and updating through your browser. I created bookmarks in my browser to make these sorts of tasks quick to do.

If you’re curious as to what services are available, here’s a link to the docs for Version 6 of the API. My favorite calls, and the ones I have bookmarked in my browser, are as follows. To use them for yourself, you’ll need to change the IP address to point to your own Raspbmc device.

This will update your video library.

http://pi:raspberry@192.168.0.7/jsonrpc?request={"jsonrpc":"2.0","method":"VideoLibrary.Scan"}

This will clean dead content from your video library.

http://pi:raspberry@192.168.0.7/jsonrpc?request={"jsonrpc":"2.0","method":"VideoLibrary.Clean"}

This will update your audio library.

http://pi:raspberry@192.168.0.7/jsonrpc?request={"jsonrpc":"2.0","method":"AudioLibrary.Scan"}

This will clean dead content from your audio library.

http://pi:raspberry@192.168.0.7/jsonrpc?request={"jsonrpc":"2.0","method":"AudioLibrary.Clean"}

File Management – When you select a folder as a media source, Raspbmc gives you the option of selecting that folder’s media type (TV or Movie). So you’ve probably already figured out that it’s best to have separate folders for your movie and TV content. What you might not have figured out is how your files should be named.

Raspbmc is extremely smart when it comes to file names. If you have a file named “Night.Of.The.Living.Dead.720p.mkv”, for example, it’ll be able to parse out the name and find it in the Movie Database. On the other hand, if you name the file “NOTLD.mkv”, Raspbmc will have no idea what the file is and you’ll probably not see the title show up in your movie library. So make sure you’re smart with your naming. If Raspbmc doesn’t add a title to the library, chances are it couldn’t parse the name or it couldn’t find it online. This also includes titles with accented characters. For instance, Raspbmc won’t be able to find “Les.Miserables.mkv”, but it will find “Les Misérables.mkv”.

I prefer to keep separate folders for each movie or TV show. For TV shows, you can also create subfolders, one for each season. For instance, underneath your TV folder, you might have a folder for “The Office (UK)”. And inside that folder you might have two folders, “Season 1” and “Season 2”, each of which contain the files for their respective season. If you follow this scheme, make sure you turn on the setting for “separate folders for content” when you add your content source in Raspbmc

Another cool thing about having your content in separate folders is that you can control the artwork that Raspbmc displays for a given title. You just need to deposit one or more of the following files in the same folder as your content.

fanart.jpg Background image. See the movie database or TV database for examples.
poster.jpg The poster that’s displayed for a given title. See the movie database or TV database for examples.
banner.jpg Banner image. I’ve only see this used in 3rd party remote control applications, like Yatse. See the TV database for examples.
thumbnail.jpg The thumbnail used for a given title. This is usually automatically extracted by Raspbmc and can take some time. Supplying it can save Raspbmc a bit of trouble.

Audio – I mentioned this in part 3, but it bears repeating one more time. Don’t use the mini-jack for your audio. You’ll just be subjecting your ears to bad stuff. Turn the audio-over-HDMI setting on and configure it appropriately for your home theater.

Remote Controls – If you haven’t ditched the mouse to control Raspbmc, you should. If you’re an Android user, check out Yatse. It’s a great remote control app you can use on whatever WiFi enabled Android device you have. I used this for a long time on my Kindle Fire before I got annoyed with the amount of time it took to establish a WiFi connection. I then dropped a whopping $14 on a SANOXY remote and never looked back.

Video Podcasts – One of my favorite things to watch on the Pi are video podcasts, such as those from Leo Laporte’s TWiT network. I really wanted to be able to automatically download shows as they were made available. And fortunately, the TWiT network features an RSS feed for video.

For TWiT’s “All About Android”, I wrote a bash script that looks like the following. Keep in mind that this is script runs as a cron job on an older FreeNAS box. Depending on what machine you use, you may have better regex facilities available to you. If you choose to use this script, you’ll need to adapt it to your environment and podcast source.

#!/bin/bash
 
cd "/mnt/Public/Media/"
wget http://feeds.twit.tv/aaa_video_hd -O feed.xml
 
# The version of grep that comes with FreeNAS doesn't support the -P option and Perl
# isn't installed. So we make do with what we've got.
LINKS=(`cat feed.xml | tr '\n' ' ' | grep -ho "<link>[^<]*" | grep -ho "http:.*.mp4" `)
LATESTLINK=${LINKS[0]}
 
FILENAME=`echo $LATESTLINK | grep -ho "[^/]*$"`
 
# We need to mangle the filename a bit to play nice with Raspbmc.
VERSION=(`echo $FILENAME | grep -ho "[^a0_]*_" | grep -ho "^.*[^_]"`)
FILENAME="All.About.Android.S01E${VERSION[0]}.mp4";
FILENAME="./TV Shows/All About Android/$FILENAME"
 
echo "Latest Link: $LATESTLINK"
echo "Destination File: $FILENAME"
 
if [ -f "$FILENAME" ]; then
    echo "File exists. Nothing to do.";
    rm feed.xml
    exit 1;
fi
 
rm feed.xml
echo "wget $LATESTLINK -O \"$FILENAME\"";
wget $LATESTLINK -O "$FILENAME"
 
# Telling Raspbmc to update itself.
wget "http://pi:raspberry@192.168.0.7/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22VideoLibrary.Scan%22}" -O /dev/null

Reclaim SD Card – Perhaps you’ve decided to replace or upgrade your SD card. Or maybe you’ve had enough of Raspbmc and you’re moving on to something else like Openelec. In either case, you’ll want to reclaim and reformat that old SD card to something your PC can use again.

To do this you’ll need the tool that started us down this road way back in the beginning – the Simple UI installer.

Fire up the installer and you’ll be presented with this familiar window.

Simply select the SD card and click the “Restore device for formatting” button. It does its work pretty quickly. Once it’s finished, you’ll still need to format it.

The SD card should now show up in Windows Explorer. From there, you can right click on the card and select Format.

Conclusion

Those are all of the Raspbmc tricks up my sleeve. If you have any tips of your own, please leave them in a comment below. Good luck!