TweetFollow Us on Twitter

A Bug's Life

Volume Number: 18 (2002)
Issue Number: 8
Column Tag: QuickTime Toolkit

A Bug's Life

Retrieving Errors in QuickTime Applications

by Tim Monroe


Termites happen. So do errors in QuickTime-savvy applications -- often for reasons other than mere sloppy programming. Network connections can fail in the middle of downloading a movie file or other data. System resources (memory, disk space, and so forth) can get depleted while an application runs. Components necessary for the playback of some media data might not be available on a particular machine. In short, lots of unpredictable occurrences can lead to the failure of QuickTime functions. How you deal with those failures is up to you. You might throw an exception, which (hopefully) is caught by an exception handler. Or you might just return an error code to your caller and expect it to handle the error gracefully. This is all part of the theory and practice of error handling, which is often the subject of heated debates among programmers. But before you even begin to handle an error, you first need to discover that it occurred in the first place. That's the subject of this article: how to determine that a QuickTime function has failed to do what you wanted it to do.

At first glance, this might seem like a fairly trivial topic. After all, many QuickTime functions return a result code that indicates the success or failure of the operation. But in fact things are not always that simple. For starters, not all QuickTime functions return a result code directly to the caller. Many of them, particularly Movie Toolbox calls, return a result code only indirectly, and we need to do a little work to retrieve that result code. We'll begin this article by looking at how to do that. Also, it's easy to misinterpret some of these result codes, so we'll investigate some of the pitfalls lurking here. Toward the end of the article, we'll take a look at a bug in our sample applications that I inadvertently added a few months ago.

Error-Reporting Functions

A large number of QuickTime functions return a result code directly to the caller as their function result. For instance, the EnterMovies function is declared essentially like this:

OSErr EnterMovies (void);

If a call to EnterMovies fails, QuickTime tells us so by returning a non-zero result code. The main reason that EnterMovies can fail is insufficient memory available for QuickTime to do the necessary initialization, so the result code is very likely to be memFullErr. No matter what the error here, however, our sample applications all quit pretty much immediately after they get one, first informing the user of the error. Listing 1 shows a portion of our application start-up code on the Macintosh.

Listing 1: Initializing the Movie Toolbox (Macintosh)

myErr = EnterMovies();
if (myErr != noErr) {
   QTFrame_ShowWarning("\pCould not initialize QuickTime. 
            Exiting.", myErr);

And Listing 2 shows the corresponding code in our Windows applications.

Listing 2: Initializing the Movie Toolbox (Windows)

myErr = EnterMovies();
if (myErr != noErr) {
   MessageBox(NULL, "Could not initialize QuickTime. 
            Exiting.", gAppName, MB_OK | MB_APPLMODAL);

But a significant number of QuickTime functions do not return an error code as their function result. A good example is StartMovie, which is declared like this:

void StartMovie (Movie theMovie);

As you can see, StartMovie returns no function result at all. Some other functions do return function results but they are not of type OSErr. An example here is GetMovieActive, which returns a result of type Boolean:

Boolean GetMovieActive (Movie theMovie);

To handle cases like these, QuickTime provides a set of error-reporting functions. Let's see how these work.

Getting the Current Error

We can use the Movie Toolbox function GetMoviesError to retrieve the current error value (or current error), which is the result code of the most recently executed QuickTime function. GetMoviesError is declared like this:

OSErr GetMoviesError (void);

We can use GetMoviesError to get the result code for those functions that do not return one as their function result. (GetMoviesError also returns the result code for functions that do return an OSErr, but it's pretty much redundant in those cases.) Here's a typical use of GetMoviesError:

myTrack = NewMovieTrack(myMovie, myWidth, myHeight, 0);
myErr = GetMoviesError();
if (myErr != noErr)
   goto bail;

We could just as easily have checked to see whether myTrack is equal to NULL after the call to NewMovieTrack, but calling GetMoviesError gives us a result code that we can return to our caller, if so desired.

It's worth noting that GetMoviesError (and GetMoviesStickyError, which we'll consider in a moment) are global to an application and are not thread-specific. This means that an error that occurs in one thread can be reported to another thread. (Just something to keep in mind if you are writing multi-threaded applications.)

Getting the Sticky Error

QuickTime also maintains an error value called the sticky error value (or sticky error), which is the first non-zero result code of a Movie Toolbox function that was generated since the last time the sticky error was cleared. We retrieve the sticky error value by calling GetMoviesStickyError and we clear the sticky error by calling ClearMoviesStickyError. Here are the function prototypes:

OSErr GetMoviesStickyError (void);
void ClearMoviesStickyError (void);

When our application first starts up, the sticky error is 0. If all our Movie Toolbox function calls succeed, the sticky error remains set to 0. But as soon as any Movie Toolbox function encounters an error, the appropriate error value is copied into the sticky error value. We can call GetMoviesStickyError at any time to retrieve the sticky error value. This value does not change, even if subsequent Movie Toolbox calls fail, until we explicitly reset it to 0 by calling ClearMoviesStickyError.

The sticky error value is useful when we want to execute a series of Movie Toolbox functions but don't particularly want to check for errors after each Movie Toolbox call. Listing 3 shows a situation in which GetMoviesStickyError might be used. The function VRObject_ImportVideoTrack copies a video track from one movie (the source) into a second movie (the destination).

Listing 3: Importing a video track from one movie into another

OSErr VRObject_ImportVideoTrack (Movie theSrcMovie, 
            Movie theDstMovie, Track *theImageTrack)
   Track         mySrcTrack = NULL;
   Media         mySrcMedia = NULL;
   Track         myDstTrack = NULL;
   Media         myDstMedia = NULL;
   Fixed         myWidth, myHeight;
   OSType         myType;
   OSErr         myErr = noErr;
   // get the first video track in the source movie
   mySrcTrack = GetMovieIndTrackType(theSrcMovie, 1, 
            VideoMediaType, movieTrackMediaType);
   if (mySrcTrack == NULL)
   // get the track's media and dimensions
   mySrcMedia = GetTrackMedia(mySrcTrack);
   GetTrackDimensions(mySrcTrack, &myWidth, &myHeight);
   // create a destination track
   myDstTrack = NewMovieTrack(theDstMovie, myWidth, myHeight, 
   // create a destination media
   GetMediaHandlerDescription(mySrcMedia, &myType, 0, 0);
   myDstMedia = NewTrackMedia(myDstTrack, myType, 
            GetMediaTimeScale(mySrcMedia), 0, 0);
   // copy the entire track
   InsertTrackSegment(mySrcTrack, myDstTrack, 0, 
            GetTrackDuration(mySrcTrack), 0);
   CopyTrackSettings(mySrcTrack, myDstTrack);
   SetTrackLayer(myDstTrack, GetTrackLayer(mySrcTrack));
   // an object video track should always be enabled
   SetTrackEnabled(myDstTrack, true);
   if (theImageTrack != NULL)
      *theImageTrack = myDstTrack;

As you can see, we call ClearMoviesStickyError at the beginning of this function and then return to our caller the value returned by GetMoviesStickyError. The idea here is that our caller will care only about the first error we encounter while executing this function, which will of course be the sticky error (since we cleared the sticky error at the beginning).

Another case where we may want to access the sticky error is when we know or suspect that a QuickTime function will report an error, but we don't really care about that error. Listing 4 defines a function, QTUtils_GetFrameCount, which returns the number of frames in a specified track. We use GetTrackNextInterestingTime to step through the track's samples.

Listing 4: Counting the frames in a track

long QTUtils_GetFrameCount (Track theTrack)
   long                  myCount = -1;
   short               myFlags;
   TimeValue         myTime = 0;
   OSErr               myErr = noErr;
   if (theTrack == NULL)
      goto bail;
   myErr = GetMoviesStickyError();
   // we want to begin with the first frame (sample) in the track
   myFlags = nextTimeMediaSample + nextTimeEdgeOK;
   while (myTime >= 0) {
      // look for the next frame in the track; when there are no more frames,
      // myTime is set to -1, so we'll exit the while loop
      GetTrackNextInterestingTime(theTrack, myFlags, myTime, 
            fixed1, &myTime, NULL);
      // after the first interesting time, don't include the time we're currently at
      myFlags = nextTimeStep;
   if (myErr == noErr)

GetTrackNextInterestingTime returns, in the sixth parameter, the first time value it finds that satisfies the search criteria specified in the flags parameter. When it cannot find a time value that satisfies those criteria, it sets that parameter to -1. For all we know, it's possible that GetTrackNextInterestingTime also sets an error value; if so, we want to clear that value by calling ClearMoviesStickyError (but only if the sticky error on entry to our function was noErr).

Error Notification Functions

QuickTime provides the SetMoviesErrorProc function, which we can use to install an error notification function (or, more briefly, error function). An error notification function is called whenever QuickTime encounters a non-zero result code during the execution of a Movie Toolbox function. SetMoviesErrorProc is declared like this:

void SetMoviesErrorProc (MoviesErrorUPP errProc, 
            long refcon);

The first parameter is a universal procedure pointer to our custom error notification function; the second parameter is a 4-byte reference constant that is passed to our error function when it is called. The error notification function is declared like this:

void MyMoviesErrorProc (OSErr theErr, long theRefcon);

The first parameter is the non-zero result code that was just encountered, and the second parameter is the reference constant we specified when we called SetMoviesErrorProc.

An error notification function is useful during application development or debugging, as they provide a single location where all errors are reported. This keeps us from having to put breakpoints all through our code as we track down problems.

Mysterious Errors

While we're on the topic of retrieving errors in QuickTime-savvy applications, it's worth discussing an issue that trips people up occasionally. This is the issue of mysterious QuickTime errors like -32766, which can occur when we execute some code like this:

OSErr      myErr = GraphicsExportSetDepth(myComponent, 32);

When this code is executed, then for certain graphics exporters, myErr is set to -32766. If we look in the file MacErrors.h, we won't find any such error. What's going on?

The explanation is surprisingly straightforward: GraphicsExportSetDepth and many other QuickTime functions that work with components return a function result of type ComponentResult, which is declared like this:

typedef long            ComponentResult;

On the other hand, the OSErr data type is declared like this:

typedef SInt16         OSErr;

When we try to fit a ComponentResult into an OSErr, we get only the low-order 16 bits, interpreted as a signed value. When the ComponentResult is noErr, this truncation is unproblematic. But several component errors use the full 32 bits of the long word, in which case the truncation will give us the mysterious errors described above. In particular, if a component does not support a particular action, then it will return the value badComponentSelector, which is defined as 0x80008002. Truncating 0x80008002 to a 16-bit signed quantity gives us -32766. That's what's happening with the call to GraphicsExportSetDepth we just considered: the particular component specified by the myComponent parameter does not support setting the export bit depth, in which case it returns badComponentSelector.

The lesson here is simple: pay attention to the data type of a function's return value and make sure you have enough space to hold that value. More specifically: don't use a variable of type OSErr to hold the return value of a component-related function whose return value is of type ComponentResult. But don't feel bad if you slip up occasionally. This mix-up is in fact so common that the file MacErrors.h contains some helpful comments:

/* ComponentError codes*/
enum {
   badComponentInstance   = (long)0x80008001,   /* when cast to an OSErr this is -32767*/
   badComponentSelector   = (long)0x80008002   /* when cast to an OSErr this is -32766*/

A Framework Bug

Let's close this article by squashing a particularly nasty bug that I introduced into our sample applications a few months back, when we updated our Macintosh code to use Carbon events instead of "classic" events. (See "Event Horizon" in MacTech, May 2002.) Recall that we added a Carbon event loop timer to each open movie window, so that we can periodically task the movie controller (by calling MCIsPlayerEvent or MCIdle). Unfortunately, our existing application can crash -- at least on Mac OS 9 -- if we do something so simple as open a movie window and then later close it. That's not good.

Fixing the Bug

The problematic code turns out to be in the Macintosh version of the QTFrame_CreateMovieWindow function, shown in Listing 5. Here we create a new window and window object. Then we attach standard and custom Carbon event handlers to the window. Finally, we call InstallEventLoopTimer to attach a timer to the window.

Listing 5: Creating a movie window

WindowReference QTFrame_CreateMovieWindow (void)
   WindowReference      myWindow = NULL;
   // create a new window to display the movie in
   myWindow = NewCWindow(NULL, &gWindowRect, gWindowTitle, 
            false, noGrowDocProc, (WindowPtr)-1L, true, 0);
   // create a new window object associated with the new window
   EventTypeSpec      myEventSpec[] = { 
      {kEventClassKeyboard, kEventRawKeyDown},
      {kEventClassKeyboard, kEventRawKeyRepeat},
      {kEventClassKeyboard, kEventRawKeyUp},
      {kEventClassWindow, kEventWindowUpdate},
      {kEventClassWindow, kEventWindowDrawContent},
      {kEventClassWindow, kEventWindowActivated},
      {kEventClassWindow, kEventWindowDeactivated},
      {kEventClassWindow, kEventWindowHandleContentClick},
      {kEventClassWindow, kEventWindowClose}
   // install Carbon event handlers for this window
   if (gWinEventHandlerUPP != NULL)
            gWinEventHandlerUPP, GetEventTypeCount(myEventSpec), 
            QTFrame_GetWindowObjectFromWindow(myWindow), NULL);
   if (gWinTimerHandlerUPP != NULL)
      InstallEventLoopTimer(GetMainEventLoop(), 0, 
                     gWinTimerHandlerUPP, myWindowObject, 

It turns out that InstallEventLoopTimer can move memory, which might invalidate its last parameter, &(**myWindowObject).fTimerRef. If the window object indeed moves, then InstallEventLoopTimer will write the timer reference into the previous location of the window object. That's bad enough, but it gets worse when you realize that the window object, in its new memory location, now won't contain the timer reference returned by InstallEventLoopTimer. Rather, (**myWindowObject).fTimerRef will still be NULL. The event loop timer indeed gets installed, but we don't have a reference to it.

This in itself isn't a problem until we try to remove the event loop timer when the window is closed. Here's the code we use to do that:

if ((**myWindowObject).fTimerRef != NULL)

Since (**myWindowObject).fTimerRef is indeed NULL, RemoveEventLoopTimer isn't called and the timer continues firing even after the movie window has disappeared. Listing 6 shows our event loop timer callback function.

Listing 6: Handling event loop timer callbacks

PASCAL_RTN void QTFrame_CarbonEventWindowTimer
            (EventLoopTimerRef theTimer, void *theRefCon)
#pragma unused(theTimer)
   WindowObject   myWindowObject = (WindowObject)theRefCon;
   // just pretend a null event has been received....
   if ((myWindowObject != NULL) && 
                        ((**myWindowObject).fController != NULL))
      if (!gMenuIsTracking || gRunningUnderX)

If the window object has been disposed of, then reading any of its fields (in this case, fController) will likely result in a segmentation fault or other error.

This is a classic case of using a dangling pointer, the address of a block of memory whose contents have moved. You can get the full details on this type of problem in the book Inside Macintosh: Memory (which I am presently chagrined to admit I myself wrote a decade ago). There are several solutions to this type of problem. A standard solution is to lock the window object before calling InstallEventLoopTimer and then unlock it afterwards:

if (gWinTimerHandlerUPP != NULL)
   InstallEventLoopTimer(GetMainEventLoop(), 0, 
                     gWinTimerHandlerUPP, myWindowObject, 

Or, even more simply, we can just use a temporary variable to hold the timer reference:

EventLoopTimerRef         myTimerRef;
if (gWinTimerHandlerUPP != NULL)
   InstallEventLoopTimer(GetMainEventLoop(), 0, 
                     gWinTimerHandlerUPP, myWindowObject, 
(**myWindowObject).fTimerRef = myTimerRef;

Adding Some More Protections

Let's take this opportunity to tinker with the Carbon event loop timer callback function QTFrame_CarbonEventWindowTimer (Listing 6, above). First of all, we should add a check at the top of the function to make sure we got a non-NULL window object:

if (myWindowObject == NULL)

And we should make sure that we are passed the same timer reference we are storing in the window object:

if ((**myWindowObject).fTimerRef != theTimer)

More importantly, I want to change the call to MCIdle into a call to MCIsPlayerEvent. We can achieve this end by building a null event and passing it to our framework function QTFrame_HandleEvent, as shown in Listing 7.

Listing 7: Handling event loop timer callbacks (revised)

PASCAL_RTN void QTFrame_CarbonEventWindowTimer
            (EventLoopTimerRef theTimer, void *theRefCon)
   WindowObject   myWindowObject = (WindowObject)theRefCon;
   if (myWindowObject == NULL)
   // sanity check: make sure it's our timer
   if ((**myWindowObject).fTimerRef != theTimer)
   // just issue a null event to our event-handling routine....
   if (!gMenuIsTracking || gRunningUnderX) {
      EventRecord   myEvent;
      myEvent.what = nullEvent;
      myEvent.message = 0;
      myEvent.modifiers = 0;
      myEvent.when = EventTimeToTicks(GetCurrentEventTime());

I prefer this revised approach to tasking our movie controllers because it routes null events through our existing event-handling routine QTFrame_HandleEvent. This in turn will make it easier to modify our code to handle movies that need to be tasked but which don't yet have a movie controller attached to them. In the next article, we'll see how this can happen.


Of the four new QuickTime functions we've encountered in this article (GetMoviesError, GetMoviesStickyError, ClearMoviesStickyError, and SetMoviesErrorProc), we're most likely to want to use GetMoviesError in our daily programming, as it provides our only means of retrieving the result codes for a large number of QuickTime functions. I generally find the sticky error less useful, but there are times we might want to take a look at it. The error procedure is, to my knowledge, largely unused. I can, however, imagine that a clever programmer could find some useful applications for it, so it's good to at least know it exists.

Tim Monroe in a member of the QuickTime engineering team. You can contact him at The views expressed here are not necessarily shared by his employer.


Community Search:
MacTech Search:

Software Updates via MacUpdate

Warhammer 40,000: Freeblade guide - How...
Warhammer 40,000: Freebladejust launched in the App Store and it lets you live your childhood dream of blowing up and slashing a bunch of enemies as a massive, hulking Space Marine. It's not easy being a Space Marine though - and particularly if... | Read more »
Gopogo guide - How to bounce like the be...
Nitrome just launched a new game and, as to be expected, it's a lot of addictive fun. It's called Gopogo, and it challenges you to hoparound a bunch of platforms, avoiding enemies and picking up shiny stuff. It's not easy though - just like the... | Read more »
Sago Mini Superhero (Education)
Sago Mini Superhero 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: KAPOW! Jack the rabbit bursts into the sky as the Sago Mini Superhero! Fly with Jack as he lifts impossible weights,... | Read more »
Star Wars: Galaxy of Heroes guide - How...
Star Wars: Galaxy of Heroes is all about collecting heroes, powering them up, and using them together to defeat your foes. It's pretty straightforward stuff for the most part, but increasing your characters' stats can be a bit confusing because it... | Read more »
The best cooking apps (just in time for...
It’s that time of year again, where you’ll be gathering around the dinner table with your family and a huge feast in front of you. [Read more] | Read more »
Square Rave guide - How to grab those te...
Square Rave is an awesome little music-oriented puzzle game that smacks of games like Lumines, but with its own unique sense of gameplay. To help wrap your head around the game, keep the following tips and tricks in mind. [Read more] | Read more »
Snowboard Party 2 (Games)
Snowboard Party 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Crowned the best snowboarding game available on the market, Snowboard Party is back to fulfill all your adrenaline needs in... | Read more »
One Button Travel (Games)
One Button Travel 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: “To cut a long story short, If you like interactive fiction, just go buy this one.” - “Oozes the polish that... | Read more »
Light Apprentice Volume 1 (Games)
Light Apprentice Volume 1 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Light Apprentice Volume 1 includes Chapters 1 to 4, all gathered in a new exclusive game. When life in the world of... | Read more »
The best games like Animal Crossing on m...
Animal Crossing amiibo Festival is out right now for the Wii U, reminding us of just how much fun that world can be. Or at least to go back and check in on our villages once in a while. [Read more] | Read more »

Price Scanner via

iMobie Releases its Ace iOS Cleaner PhoneClea...
iMobie Inc. has announced the new update of PhoneClean 4, its iOS cleaner designed to reclaim wasted space on iPhone/iPad for use and keep the device fast. Alongside, iMobie hosts a 3-day giveaway of... Read more
U.S. Cellular Offering iPad Pro
U.S. Cellular today announced that it is offering the new iPad Pro with Wi-Fi + Cellular, featuring a 12.9-inch Retina display with 5.6 million pixels — the most ever in an iOS device. U.S. Cellular... Read more
Newegg Canada Unveils Black Friday Deals for...
Newegg Canada is offering more than 1,000 deep discounts to Canadian customers this Black Friday, available now through Cyber Monday, with new deals posted throughout the week. “Black Friday is... Read more
Black Friday: Macs on sale for up to $500 off...
BLACK FRIDAY B&H Photo has all new Macs on sale for up to $500 off MSRP as part of their early Black Friday sale including free shipping plus NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $... Read more
Black Friday: Up to $125 off iPad Air 2s at B...
BLACK FRIDAY Walmart has the 16GB iPad Air 2 WiFi on sale for $100 off MSRP on their online store. Choose free shipping or free local store pickup (if available): - 16GB iPad Air 2 WiFi: $399, save $... Read more
Black Friday: iPad mini 4s on sale for $100 o...
BLACK FRIDAY Best Buy has iPad mini 4s on sale for $100 off MSRP on their online store for Black Friday. Choose free shipping or free local store pickup (if available): - 16GB iPad mini 4 WiFi: $299.... Read more
Black Friday: Apple Watch for up to $100 off...
BLACK FRIDAY Apple resellers are offering discounts and bundles with the purchase of an Apple Watch this Black Friday. Below is a roundup of the deals being offered by authorized Watch resellers:... Read more
Black Friday: Target offers 6th Generation iP...
BLACK FRIDAY Save $40 to $60 on a 6th generation iPod touch at Target with free shipping or free local store pickup (if available). Sale prices for online orders only, in-store prices may vary: -... Read more
Black Friday: Walmart and Target offer iPod n...
BLACK FRIDAY Walmart has the 16GB iPod nano (various colors) on sale for $119.20 on their online store for a limited time. That’s $30 off MSRP. Choose free shipping or free local store pickup (if... Read more
Black Friday deals on the Apple Watch and App...
Apple resellers are offering discounts and bundles with the purchase of an Apple Watch this Black Friday weekend. Below is a roundup of the deals being offered by authorized Watch resellers: Apple... Read more

Jobs Board

Storefront Operations Coordinator, *Apple* -...
# Storefront Operations Coordinator, Apple -Latin America Job Number: 43587750 Miami, Florida, United States Posted: Oct. 16, 2015 Weekly Hours: 40.00 **Job Summary** The Read more
*Apple* Enterprise / Government Professional...
# Apple Enterprise / Gove ment Professional Services Engineer Job Number: 42292976 Reston, Virginia, United States Posted: Aug. 18, 2015 Weekly Hours: 40.00 **Job Read more
iOS Wallet & *Apple* Pay Engineer - App...
# iOS Wallet & Apple Pay Engineer Job Number: 40586801 Santa Clara Valley, Califo ia, United States Posted: Nov. 16, 2015 Weekly Hours: 40.00 **Job Summary** The iOS Read more
Software Engineer, *Apple* Watch - Clock Fa...
# Software Engineer, Apple Watch - Clock Face Team Job Number: 44368761 Santa Clara Valley, Califo ia, United States Posted: Nov. 14, 2015 Weekly Hours: 40.00 **Job Read more
Administrative Assistant, *Apple* Online St...
# Administrative Assistant, Apple Online Store Job Number: 43992352 Santa Clara Valley, Califo ia, United States Posted: Nov. 9, 2015 Weekly Hours: 40.00 **Job Summary** Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.