TweetFollow Us on Twitter

Dec 00 QTToolkit Volume Number: 16 (2000)
Issue Number: 12
Column Tag: QuickTime Toolkit

Timecode

By Tim Monroe

Using QuickTime's Timecode Media Handler

Introduction

It's often useful — especially when editing some video or audio media — to be able to assign a precise time stamp to a place in a stream of media data. In 1967, the Society of Motion Picture and Television Engineers (SMPTE) introduced a method for doing this, called timecoding. Timecoding is a way of putting time stamps (called timecodes) on recorded media such as film, video, sound, and the like.

QuickTime, of course, has its own methods of specifying times within a movie, using time bases, time values, and time scales. (See "Movie Controller Potpourri" in MacTech, February, 1999 for a preliminary discussion of these concepts.) But QuickTime also supports storing and displaying SMPTE timecodes. Figure 1 shows a frame of a QuickTime movie with a timecode value displayed below the video track.


Figure 1. A movie frame with timecode displayed.

Timecode is displayed using an eight-digit, 24-hour clock that looks like this: hh:mm:ss:ff. The digits represent (from left to right) hours, minutes, seconds, and frames. As you can see, the frame displayed in Figure 1 is exactly 14 seconds from the beginning of the movie (assuming that the movie began at timecode 00:00:00:00). The actual timecode values of a specific QuickTime movie can be synthesized by the computer or captured along with the source material.

In this article, we'll take a look at using timecodes in QuickTime movies. Timecodes are stored in timecode tracks, which are created and managed using the timecode media handler. The timecode media handler is extremely easy to work with; it provides a grand total of 11 functions (of which we'll use only 7 here) and requires us to work with only a handful of data structures. In fact, there is only one mildly difficult concept we'll need to understand: the notion of drop-frame timecode. We'll begin by investigating the standard timecode formats, and then we'll move on to seeing how to create and manage timecode tracks in QuickTime movies.

Our sample application this month is called QTTimeCode; its Test menu contains the timecode-specific commands. Figure 2 shows the Test menu for movies that do not contain a timecode track.


Figure 2. The Test menu of QTTimeCode.

Figure 3 shows the Test menu for movies that do contain a timecode track.


Figure 3. The Test menu of QTTimeCode.

Timecode Standards

As we've seen, timecode is expressed using an eight-digit clock, where the rightmost two digits represent a frame number. There are four standard frame rates used commercially around the world, so there are four standard timecode formats:

  • Most film produced in the United States uses a standard of 24 frames per second (fps).
  • Most film produced in Europe and Australia uses a standard of 25 fps, established by the European Broadcasting Union (EBU); 25 fps is also used for PAL or SECAM video and television.
  • The SMPTE standard for American black-and-white television uses 30 fps. This frame rate is also commonly used for audio and CD mastering.
  • American color television and systems based on it (such as NTSC video) use a standard of 29.97 fps. This rate is the result of certain technical decisions made when converting from black-and-white to color television.

The oddball here is the SMPTE standard for American color television and NTSC video, which uses a frame rate of 29.97. This is close enough to 30 that people typically consider American color TV to have a frame rate of 30 fps. But 29.97 isn't exactly 30, and the difference can add up. For instance, over a period of one hour, a 30 fps movie will display 108,000 frames, whereas a 29.97 fps movie will display 107,892 frames. This means that, if we use a 30 fps timecode to display the time of a 29.97 fps movie, the movie would be 108 frames (or about 3.6 seconds) longer than a movie that has exactly 30 fps. That is to say, by the time a 29.97 fps movie gets to 108,000 frames, 1 hour and 3.6 seconds has elapsed. For most purposes, an extra 3.6 seconds per hour is pretty insignificant. But on commercial TV, time is money. For example, ABC Broadcasting is expected to charge $2.2 million for a 30-second advertisement during the 2001 Super Bowl. In that case, 3.6 seconds is worth about $264,000. So it's sometimes important to get timecode values exactly right. To ensure that 30 fps timecodes displayed by a 29.97 fps movie exactly match the time on a wall clock, SMPTE defined drop-frame timecoding, according to which two frame numbers are dropped at the start of every minute, except for every minute that is evenly divisible by ten. (For example, the timecode value 11:31:59:29 is immediately followed by 11:32:00:02.) So, over the course of one hour, 108 frame numbers will be dropped, which is exactly what is needed to bring the 30 fps timecode display into synchronization with a wall clock. In spite of the name ("drop-frame timecode"), no video frames are dropped. Rather, frame numbers are dropped from the timecode display so that the timecode stays in synch with a wall clock. When drop-frame timecode is being used, it's conventional to use a comma (',') or a semicolon (';') to separate the seconds digits from the frames digits. Figure 4 shows a QuickTime movie that uses drop-frame timecode.


Figure 4. A movie frame with drop-frame timecode.

Keep in mind that in a timecode, the rightmost two digits represent a frame number, not (say) hundredths of a second. This is worth remarking, if only because there are occasions where QuickTime does use the rightmost digits to represent fractions of a second. For instance, in the previous QuickTime Toolkit article ("Word Is Out" in MacTech, November 2000), we saw that the text movie importer recognizes a number of text descriptors, one of which is a timestamp indicating the time at which the imported text sample is to begin. In this case, the rightmost digits represent a number of time scale units.

Timecode in QuickTime

QuickTime version 2.0 introduced the timecode media handler, which we can use to create timecode tracks in movies, hide and show those tracks, get and set information about timecode tracks, and so forth. The timecode media handler supports both drop-frame and non-drop-frame timecodes, as well as a simple counter (shown in Figure 5).


Figure 5. A movie frame with a counter.

A timecode track specifies timing information for one or more other tracks, which are typically video or sound tracks. To associate the timecode track with a target track, the target track contains a track reference to the timecode track. (See the "Word Is Out" article once again for a discussion of track references.)

All of the QuickTime functions for working with timecodes take an instance of the timecode media handler as a parameter. Our sample application QTTimeCode creates a single timecode track in a movie, so we can call GetMovieIndTrackType and GetMediaHandler to find a movie's timecode media handler, as shown in Listing 1.

Listing 1: Finding a movie's timecode media handler instance

QTTC_GetTimeCodeMediaHandler

MediaHandler QTTC_GetTimeCodeMediaHandler (Movie theMovie)
{
   Track               myTrack = NULL;
   Media               myMedia = NULL;
   MediaHandler      myHandler = NULL;
   
   // get the (first) timecode track in the specified movie
   myTrack = GetMovieIndTrackType(theMovie, 1, 
                  TimeCodeMediaType, movieTrackMediaType);
   if (myTrack != NULL) {
      // get the timecode track's media and media handler
      myMedia = GetTrackMedia(myTrack);
      if (myMedia != NULL)
         myHandler = GetMediaHandler(myMedia);
   }
   
   return(myHandler);
}

When the user selects the "Add Timecode Track..." command in the Test menu of our QTTimeCode application, QTTimeCode displays the dialog box shown in Figure 6 to elicit some settings from the user.


Figure 6. QTTimeCode's Timecode Options dialog box.

As you can see, QTTimeCode allows the user to specify the name of the media source (which might be the name of the tape from which the video was digitized). The user can also indicate whether the timecode should be displayed at all, and (if so) whether the timecode should be displayed below the video. QTTimeCode allows the user to specify the font in which the timecode is displayed and the starting time of the timecodes.

It's worth emphasizing that a timecode track in a QuickTime movie does not affect the actual timing of the movie playback. QuickTime's own timing facilities always determine the rate at which frames in a movie are displayed. If, for example, we play a movie back at twice its normal rate, the timecodes would also zip by at twice the speed of a wall clock.

Timecode Tracks

We add a timecode track to a movie in exactly the same way we've added other kinds of tracks. The main difference, of course, is that the media type of the new track will be TimeCodeMediaType. To know how to add a timecode track to an existing movie, we need to know only two things: (1) the format of the data in a timecode media sample; and (2) the structure of a sample description for a timecode media sample. Let's tackle these issues in reverse order. We'll also consider how to set the placement of the timecode track and configure some of the text options.

Creating a Timecode Sample Description

A timecode sample description is defined by the TimeCodeDescription data type, like this:

struct TimeCodeDescription {
   long                      descSize;
   long                      dataFormat;
   long                      resvd1;
   short                   resvd2;
   short                   dataRefIndex;
   long                      flags;
   TimeCodeDef          timeCodeDef;
   long                      srcRef[1];
};

The first five fields are common to all sample descriptions, and we need to fill in only the descSize and dataFormat fields:

TimeCodeDescriptionHandle      myDesc = NULL;
long                  mySize;

mySize = sizeof(TimeCodeDescription);
myDesc = (TimeCodeDescriptionHandle)NewHandleClear(mySize);
if (myDesc == NULL)
   goto bail;
      
(**myDesc).descSize = mySize;
(**myDesc).dataFormat = TimeCodeMediaType;

The flags field is reserved and should be set to 0. The timeCodeDef field is a timecode definition structure that contains information about the desired format of the timecode. A timecode definition structure is defined by the TimeCodeDef structure:

struct TimeCodeDef {
   long                      flags;
   TimeScale                fTimeScale;
   TimeValue                frameDuration;
   UInt8                      numFrames;
   UInt8                      padding;
};
typedef struct TimeCodeDef TimeCodeDef;

The flags field of the TimeCodeDef structure contains a set of flags that specify information about the format of the timecode. Currently, these flags are defined:

enum {
   tcDropFrame               = 1 << 0,
   tc24HourMax               = 1 << 1,
   tcNegTimesOK               = 1 << 2,
   tcCounter                  = 1 << 3
};

The tcDropFrame flag, of course, indicates whether the timecode is drop-frame or non-drop-frame timecode. The tc24HourMax flag indicates whether the hours digits return to 0 at 24 hours or keep advancing. The tcNegTimesOK flag indicates whether negative timecode values are allowed. Finally, the tcCounter flag indicates whether to display the simple counter instead of a SMPTE timecode.

The numFrames field of the TimeCodeDef structure indicates the number of frames in each second of media data in the target track. If the simple counter is being displayed, this field indicates the number of frames that make up each increment of the counter. The frameDuration field indicates the duration, in time units defined by the fTimeScale field, of each frame in the target media.

QTTimeCode keeps track of most of these settings by defining a set of global variables (which makes it easy to get information into and out of the Timecode Options dialog box). Using some of these globals, we set up the timecode definition structure as shown in Listing 2.

Listing 2: Setting up a timecode definition structure

QTTC_AddTimeCodeToMovie

// set the timecode format information flags
if (gUseTimeCode) {
   myFlags = 0L;
   if (gDropFrameVal)
      myFlags |= tcDropFrame;
   if (gIsNeg)
      myFlags |= tcNegTimesOK;
   if (g24Hour)
      myFlags |= tc24HourMax;
} else {
   myFlags = tcCounter;
}
   
myTCDef.flags = myFlags;
myTCDef.fTimeScale = gTimeScale;
myTCDef.frameDuration = gFrameDur;
myTCDef.numFrames = gNumFrames;

The last field in a timecode sample description is the srcRef field, which is defined as an array containing a single long integer. This field contains information about the source of the timecode values. As mentioned earlier, this is typically the name of the tape or other source of the media data from which the timecode values were originally captured. The interesting thing here is that the data in this field must be formatted in the same way as a piece of movie or track user data. As a result, we can create the source information using QuickTime's user data functions like NewUserData and AddUserDataText. But the source information is not stored in the same location as movie or track user data; instead, it's stored in the timecode sample description itself. The timecode media handler provides a function, TCSetSourceRef, that we can use to put the source information into the timecode sample description. Listing 3 shows how we set the source information for a timecode track. Notice that the user data item is of type TCSourceRefNameType.

Listing 3: Setting the source information

QTTC_AddTimeCodeToMovie

UserData         myUserData;
 
myErr = NewUserData(&myUserData);
if (myErr == noErr) {
   Handle                   myNameHandle = NULL;
         
   myErr = PtrToHand(&gSrcName[1], &myNameHandle, 
                                                   gSrcName[0]);
   if (myErr == noErr) {
   myErr = AddUserDataText(myUserData, myNameHandle,                        TCSourceRefNameType, 1, langEnglish);
      if (myErr == noErr)
         TCSetSourceRef(myHandler, myDesc, myUserData);
   }
         
   if (myNameHandle != NULL)
      DisposeHandle(myNameHandle);
            
   DisposeUserData(myUserData);
}

Why isn't the source information stored as part of the track's user data (in an atom of type 'udta')? Part of the reason is that there can be more than one timecode sample in a timecode track, and each sample may be associated with timecode information from a different source. So it makes sense to attach the source information to the timecode sample description. In any event, we really don't need to worry about where the source information is stored, since we shall always use the functions TCSetSourceRef and TCGetSourceRef to set and get that information. (For what it's worth, QTTimeCode will create only one timecode sample, which spans length of the entire target track.) TCSetSourceRef updates the descSize field of the timecode sample description, so we don't need to do this ourselves.

Creating a Timecode Media Sample

Now we need to see how to create a media sample for our timecode track. The sample description contains information about the format and source of the timecode. The start time and duration of the media sample indicate the start time and duration of the timecode display. All that remains is to specify the timecode value of the first frame of the target track segment. That is to say, when the timecode media handler encounters a timecode sample, it needs to know what the timecode value is at that moment. This is precisely what's contained in a timecode media sample.

A timecode media sample contains a long integer that specifies the timecode value of the first frame in the target track that is to have a timecode value associated with it. The timecode value is stored as a frame number, which is converted automatically to a timecode value by the timecode media handler. The timecode media handler provides functions for converting timecode values into frame values and vice versa. To see how this works, let's suppose that we want the first frame of a movie to have the timecode 08:23:11;00. Suppose further that the four parts of this timecode value are contained in the global variables gHours, gMinutes, gSeconds, and gFrames. Ultimately we want to call the function TCTimeCodeToFrameNumber to determine the frame number that we'll put into the media sample. We specify the timecode value to TCTimeCodeToFrameNumber by passing it a pointer to a time code record, defined like this:

union TimeCodeRecord {
   TimeCodeTime          t;
   TimeCodeCounter       c;
};
typedef union TimeCodeRecord    TimeCodeRecord;

This is a union that contains either a timecode time record or a timecode counter record:

struct TimeCodeTime {
   UInt8                      hours;
   UInt8                      minutes;
   UInt8                      seconds;
   UInt8                      frames;
};
typedef struct TimeCodeTime TimeCodeTime;

struct TimeCodeCounter {
   long                      counter;
};
typedef struct TimeCodeCounter    TimeCodeCounter;

Since we've got a timecode value that we want to convert into a frame number, we'll use the t variant, like this:

myTCRec.t.hours = (UInt8)gHours;
myTCRec.t.minutes = (UInt8)gMinutes;
myTCRec.t.seconds = (UInt8)gSeconds;
myTCRec.t.frames = (UInt8)gFrames;
if (gIsNeg)
   myTCRec.t.minutes |= tctNegFlag;

Notice that the minutes field of the time code time record should have the bit tctNegFlag (namely, 0x80) set if the timecode value is to be interpreted as a negative value. We're finally ready to create the timecode media sample data. Since AddMediaSample wants a handle to the media data, we need to allocate a relocatable block large enough to hold a long integer and then call TCTimeCodeToFrameNumber to convert the timecode stored in myTCRec into a frame number. Then we need to ensure that the frame number is stored in big-endian format, like this:

myFrameHandle = (long **)NewHandle(sizeof(long));
if (myFrameHandle == NULL)
   goto bail;
      
myErr = TCTimeCodeToFrameNumber(myHandler, 
            &(**myDesc).timeCodeDef, &myTCRec, *myFrameHandle);

**myFrameHandle = EndianS32_NtoB(**myFrameHandle);

Then we proceed as usual, calling BeginMediaEdits, AddMediaSample, EndMediaEdits, and InsertMediaIntoTrack.

Setting the Timecode Track Geometry

For simplicity, the QTTimeCode application uses the first video track in a movie as the target track (that is, the track that contains a track reference to the timecode track). We'll call GetTrackDimensions on the target track to get the desired width of the timecode track. For the initial height of the timecode track, we'll use a predefined constant. Ideally, however, the height of the timecode track should depend on the height of the timecode display, which depends of course on the font and point size of the characters in the timecode display. We can retrieve information about the timecode display by calling TCGetDisplayOptions, which returns information in a text options structure, defined by the TCTextOptions data type:

struct TCTextOptions {
   short                     txFont;
   short                     txFace;
   short                     txSize;
   short                     pad;
   RGBColor                  foreColor;
   RGBColor                  backColor;
};
typedef struct TCTextOptions    TCTextOptions;

The txFont field contains the font number of the timecode display font. When setting up a timecode track, we want to do two things with this font. First, we want to reset the txFont field to the font number of the font that the user selected in our application's Timecode Options dialog box (see Figure 6 again). Then we want to measure that font to determine the maximum height for our timecode track.

When the user closes the Timecode Options dialog box by clicking the OK button, QTTimeCode gets the index and name of the currently-selected font by executing these two lines of code:

gFontIndex = GetControlValue(myControl);
GetMenuItemText(myMenu, gFontIndex, gFontName);

Then, when creating a timecode track, QTTimeCode uses the font name stored in the gFontName global variable to find the appropriate font number:

TCGetDisplayOptions(myHandler, &myTextOptions);
GetFNum(gFontName, &myTextOptions.txFont);
TCSetDisplayOptions(myHandler, &myTextOptions);

Now we need to determine the maximum height of the timecode display. We can do this by getting a representative string containing a timecode and then measuring that string in the current font, style, and size:

// use the starting time to figure out the dimensions of track   
TCTimeCodeToString(myHandler,
                                       &myTCDef, &myTCRec, myString);
TextFont(myTextOptions.txFont);
TextFace(myTextOptions.txFace);
TextSize(myTextOptions.txSize);
GetFontInfo(&myFontInfo);
   
// calculate track width and height based on text   
myTCHeight = FixRatio(myFontInfo.ascent + 
                                 myFontInfo.descent + 2, 1);

You'll notice that we determine the height of the timecode track by adding the distance from the font baseline to the ascent line and the distance from the baseline to the descent line (plus a couple of pixels of extra space). In some fonts, the numerals have no descenders, so this calculation will tend to make the timecode look out of center vertically within the timecode track. Devising a better algorithm is left as an exercise for the reader. Now we've determined the proper height and width for the timecode track. At this point, we can reset the track dimensions:

SetTrackDimensions(myTrack, myWidth, myTCHeight);

Then, if the user has indicated that the timecode track should appear below the video track, we can reset the track matrix, like this:

GetTrackMatrix(myTrack, &myMatrix);
if (gDisplayBelowVideo)
   TranslateMatrix(&myMatrix, 0, myHeight);
SetTrackMatrix(myTrack, &myMatrix);

The timecode track is now positioned at the desired location with the appropriate width and height.

We can configure the track to be displayed by calling TCSetTimeCodeFlags with the tcdfShowTimeCode flag.

TCSetTimeCodeFlags(myHandler, 
   gDisplayTimeCode ? tcdfShowTimeCode : 0, tcdfShowTimeCode);

A timecode track must be enabled in order for it to be displayed, so we should call SetTrackEnabled before calling TCSetTimeCodeFlags.

Creating a Track Reference

The final thing we need to do, when creating a timecode track, is to create a track reference from the target track to the timecode track, like this:

myErr = AddTrackReference(myTypeTrack, myTrack, 
                                          TimeCodeMediaType, NULL);

Listing 4 shows our complete function for creating a timecode track in a movie.

Listing 4: Adding a timecode track to a QuickTime movie

QTTC_AddTimeCodeToMovie

OSErr QTTC_AddTimeCodeToMovie 
                              (Movie theMovie, OSType theType)
{
   Track                     myTypeTrack = NULL;
   Track                     myTrack = NULL;
   Media                     myMedia = NULL;
   MediaHandler         myHandler = NULL;
   TimeCodeDef            myTCDef;
   TimeCodeRecord      myTCRec;
   Str63                     myString;
   TimeValue               myDuration;
   MatrixRecord         myMatrix;
   Fixed                     myWidth;
   Fixed                     myHeight;
   Fixed                     myTCHeight;
   long                     myFlags = 0L;
   TCTextOptions         myTextOptions;
   FontInfo                  myFontInfo;
   TimeCodeDescriptionHandle      myDesc = NULL;
   long                     **myFrameHandle;
   OSErr                     myErr = noErr;
   
   // get the (first) track of the specified type; this track determines the width of the new timecode track
   myTypeTrack = GetMovieIndTrackType(theMovie, 1, 
                              theType, movieTrackMediaType);
   if (myTypeTrack == NULL) {
      myErr = trackNotInMovie;
      goto bail;
   }
   
   // get the dimensions of the target track
   GetTrackDimensions(myTypeTrack, &myWidth, &myHeight);
   
   // create the timecode track and media
   myTrack = NewMovieTrack(theMovie, myWidth, 
                              kTimeCodeTrackSize, kNoVolume);
   if (myTrack == NULL)
      goto bail;
      
   myMedia = NewTrackMedia(myTrack, TimeCodeMediaType, 
                              GetMovieTimeScale(theMovie), NULL, 0);
   if (myMedia == NULL)
      goto bail;
      
   myHandler = GetMediaHandler(myMedia);
   if (myHandler == NULL)
      goto bail;
   
   // fill in a timecode definition structure; this becomes part of the timecode description
   
   // set the timecode format information flags
   if (gUseTimeCode) {
      myFlags = 0L;
      if (gDropFrameVal)
         myFlags |= tcDropFrame;
      if (gIsNeg)
         myFlags |= tcNegTimesOK;
      if (g24Hour)
         myFlags |= tc24HourMax;
      
   } else {
      myFlags = tcCounter;
   }
   
   myTCDef.flags = myFlags;
   myTCDef.fTimeScale = gTimeScale;
   myTCDef.frameDuration = gFrameDur;
   myTCDef.numFrames = gNumFrames;

   // fill in a timecode record
   if (gUseTimeCode) {
      myTCRec.t.hours = (UInt8)gHours;
      myTCRec.t.minutes = (UInt8)gMinutes;
      myTCRec.t.seconds = (UInt8)gSeconds;
      myTCRec.t.frames = (UInt8)gFrames;
      if (gIsNeg)
         myTCRec.t.minutes |= tctNegFlag;
   } else {
      myTCRec.c.counter = gCounterVal;
   }

   // figure out the timecode track geometry
   
   // get display options to calculate box height
   TCGetDisplayOptions(myHandler, &myTextOptions);
   GetFNum(gFontName, &myTextOptions.txFont);
   TCSetDisplayOptions(myHandler, &myTextOptions);
   
   // use the starting time to figure out the dimensions of track   
   TCTimeCodeToString(myHandler, &myTCDef, &myTCRec, 
                                                   myString);
   TextFont(myTextOptions.txFont);
   TextFace(myTextOptions.txFace);
   TextSize(myTextOptions.txSize);
   GetFontInfo(&myFontInfo);
   
   // calculate track width and height based on text   
   myTCHeight = FixRatio(myFontInfo.ascent + 
                                    myFontInfo.descent + 2, 1);
   SetTrackDimensions(myTrack, myWidth, myTCHeight);

   GetTrackMatrix(myTrack, &myMatrix);
   if (gDisplayBelowVideo)
      TranslateMatrix(&myMatrix, 0, myHeight);
   
   SetTrackMatrix(myTrack, &myMatrix);   
   SetTrackEnabled(myTrack, gDisplayTimeCode ? true : false);
      
   TCSetTimeCodeFlags(myHandler, gDisplayTimeCode ? 
                        tcdfShowTimeCode : 0, tcdfShowTimeCode);
   
   // edit the track media
   myErr = BeginMediaEdits(myMedia);   
   if (myErr == noErr) {
      long            mySize;
      UserData         myUserData;
      
      // create and configure a new timecode description handle
      mySize = sizeof(TimeCodeDescription);
      myDesc = (TimeCodeDescriptionHandle) 
                                    NewHandleClear(mySize);
      if (myDesc == NULL)
         goto bail;
      
      (**myDesc).descSize = mySize;
      (**myDesc).dataFormat = TimeCodeMediaType;
      (**myDesc).timeCodeDef = myTCDef;
      
      // set the source identification information

      // the source identification information for a timecode track is stored
      // in a user data item of type TCSourceRefNameType
      myErr = NewUserData(&myUserData);
      if (myErr == noErr) {
         Handle                   myNameHandle = NULL;
         
         myErr = PtrToHand(&gSrcName[1], &myNameHandle, 
                                       gSrcName[0]);
         if (myErr == noErr) {
            myErr = AddUserDataText(myUserData, myNameHandle, 
                                 TCSourceRefNameType, 1, langEnglish);
            if (myErr == noErr)
               TCSetSourceRef(myHandler, myDesc, myUserData);
         }
         
         if (myNameHandle != NULL)
            DisposeHandle(myNameHandle);
            
         DisposeUserData(myUserData);
      }

      // add a sample to the timecode track
      myFrameHandle = (long **)NewHandle(sizeof(long));
      if (myFrameHandle == NULL)
         goto bail;
      
      myErr = TCTimeCodeToFrameNumber(myHandler, 
            &(**myDesc).timeCodeDef, &myTCRec, *myFrameHandle);

      // the data in the timecode track must be big-endian      
      **myFrameHandle = EndianS32_NtoB(**myFrameHandle);
      
      myDuration = GetMovieDuration(theMovie);
      // since we created the track with the same timescale as the movie,
      // we don't need to convert the duration
      
      myErr = AddMediaSample(myMedia, 
                              (Handle)myFrameHandle,
                              0,
                              GetHandleSize((Handle)myFrameHandle),
                              myDuration,
                              (SampleDescriptionHandle)myDesc, 
                              1, 0, 0);
      if (myErr != noErr)
         goto bail;   
   }
   
   myErr = EndMediaEdits(myMedia);   
   if (myErr != noErr)
      goto bail;
         
   myErr = InsertMediaIntoTrack(myTrack, 0, 0, 
                                 myDuration, fixed1);
   if (myErr != noErr)
      goto bail;
   
   // create a track reference from the target track to the timecode track
   myErr = AddTrackReference(myTypeTrack, myTrack, 
                                       TimeCodeMediaType, NULL);
   
bail:
   if (myDesc != NULL)
      DisposeHandle((Handle)myDesc);
      
   if (myFrameHandle != NULL)
      DisposeHandle((Handle)myFrameHandle);

   return(myErr);
}

Getting Information about a Timecode Track

The timecode media handler provides several functions that we can use to get and set information about a timecode track in a movie. For example, if we want to get the current timecode value for a movie, we can call the TCGetCurrentTimeCode function. Listing 5 defines the QTTC_ShowCurrentTimeCode function, which QTTimeCode uses to get the current timecode value and display it in a dialog box to the user.

Listing 5: Displaying the current timecode value

QTTC_ShowCurrentTimeCode

void QTTC_ShowCurrentTimeCode (Movie theMovie)
{
   MediaHandler         myHandler = NULL;
   HandlerError         myErr = noErr;
   TimeCodeDef         myTCDef;
   TimeCodeRecord      myTCRec;
   
   myHandler = QTTC_GetTimeCodeMediaHandler(theMovie);
   if (myHandler != NULL) {
   
      // get the timecode for the current movie time
   myErr = TCGetCurrentTimeCode(myHandler, NULL, &myTCDef, 
                                                &myTCRec, NULL);
      if (myErr == noErr) {
         Str255      myString;
         
         myErr = TCTimeCodeToString(myHandler, &myTCDef, 
                                                &myTCRec, myString);
         if (myErr == noErr)
            QTTC_ShowStringToUser(myString);
      }
   }
}]

As you can see, QTTC_ShowCurrentTimeCode first retrieves the instance of the timecode media handler and then calls TCGetCurrentTimeCode to get the current timecode value. Then it passes the timecode definition structure and timecode record filled in by TCGetCurrentTimeCode to the TCTimeCodeToString function, to convert the timecode value into a string. Finally, QTTC_ShowCurrentTimeCode calls the application function QTTC_ShowStringToUser to show the string to the user.

Similarly, we can display a timecode track's source information to the user by calling the QTTC_ShowTimeCodeSource function defined in Listing 6.

Listing 6: Displaying the timecode source information

QTTC_ShowTimeCodeSource

void QTTC_ShowTimeCodeSource (Movie theMovie)
{
   MediaHandler      myHandler = NULL;
   HandlerError      myErr = noErr;
   UserData            myUserData;
   
   myHandler = QTTC_GetTimeCodeMediaHandler(theMovie);
   if (myHandler != NULL) {
   
      // get the timecode source for the current movie time
      myErr = TCGetCurrentTimeCode(myHandler, NULL, NULL, 
                                             NULL, &myUserData);
      if (myErr == noErr) {
         Str255         myString = " [No source name!]";
         Handle       myNameHandle = NewHandleClear(0);
         
         GetUserDataText(myUserData, myNameHandle, 
                           TCSourceRefNameType, 1, langEnglish);
         if (GetHandleSize(myNameHandle) > 0) {
            BlockMove(*myNameHandle, &myString[1], 
                                 GetHandleSize(myNameHandle));
            myString[0] = GetHandleSize(myNameHandle);
         }
         
         if (myNameHandle != NULL)
            DisposeHandle(myNameHandle);
         
         QTTC_ShowStringToUser(myString);
         
         DisposeUserData(myUserData);
      }
   }
}

One thing to notice here is that the TCGetCurrentTimeCode function returns, through its last parameter, a user data list that contains the source information of a timecode track. (We didn't need the source information in Listing 5, so there we passed NULL for the last parameter.) Once we've successfully retrieved that information, we can use the Movie Toolbox user data function GetUserDataText to find the source information and then display it to the user.

Showing and Hiding a Timecode Track

As we've seen in earlier articles, we can show or hide a specific track in a movie by enabling and disabling that track using the Movie Toolbox function SetTrackEnabled. For example, we can toggle the visible state of a track with this line of code:

SetTrackEnabled(myTrack, !GetTrackEnabled(myTrack));

With a timecode track, we also want to keep the media handler informed of the visible state of the track by setting the timecode flags appropriately, like this:

TCGetTimeCodeFlags(myHandler, &myFlags);
myFlags ^= tcdfShowTimeCode;
TCSetTimeCodeFlags(myHandler, myFlags, tcdfShowTimeCode);

Here, we simply retrieve the current timecode flags, toggle the tcdfShowTimeCode bit, and then send the new set of flags back to the timecode media handler. The third parameter to the TCSetTimeCodeFlags function is a mask that indicates which bits in the myFlags parameter to consider. As you can see, we want the media handler to change only the tcdfShowTimeCode bit itself. Listing 7 shows the complete definition of the QTTC_ToggleTimeCodeDisplay function.

Listing 7: Toggling the visible state of a timecode track

QTTC_ToggleTimeCodeDisplay

void QTTC_ToggleTimeCodeDisplay (MovieController theMC)
{
   Movie               myMovie = MCGetMovie(theMC);
   Track               myTrack = NULL;
   MediaHandler      myHandler = NULL;
   long                  myFlags = 0L;
   
   // get the (first) timecode track in the specified movie
   myTrack = GetMovieIndTrackType(myMovie, 1, 
                        TimeCodeMediaType, movieTrackMediaType);
   if (myTrack != NULL) {
   
      // get the timecode track's media handler
      myHandler = QTTC_GetTimeCodeMediaHandler(myMovie);
      if (myHandler != NULL) {
      
         // toggle the show-timecode flag
         TCGetTimeCodeFlags(myHandler, &myFlags);
         myFlags ^= tcdfShowTimeCode;
         TCSetTimeCodeFlags(myHandler, myFlags,                                                             
         tcdfShowTimeCode);
         
         // toggle the track enabled state
      SetTrackEnabled(myTrack, !GetTrackEnabled(myTrack));
         
         // now tell the movie controller the movie has changed,
         // so that the movie rectangle gets updated correctly
         MCMovieChanged(theMC, myMovie);
      }
   }
}

Notice that we call MCMovieChanged to prompt the movie controller to reset its state based on the current properties of the associated movie. This causes the movie controller to recalculate the controller rectangle and redraw the movie.

Conclusion

As we've seen, it's quite easy to create and manipulate timecode tracks. These tracks take up very little space in a movie file, and they can be extremely useful in coordinating QuickTime movies with their external source material. While timecode display is principally useful to video or audio editors, the counter display can serve a variety of purposes.


Tim Monroe is happy to announce the birth of a baby lizard. Libra, the son or daughter of Sean and Avril, was born in early October. You can send reptile layette items to him at monroe@apple.com.

 
AAPL
$95.79
Apple Inc.
-2.36
MSFT
$43.28
Microsoft Corpora
-0.30
GOOG
$572.85
Google Inc.
-14.57

MacTech Search:
Community Search:

Software Updates via MacUpdate

Ember 1.8 - Versatile digital scrapbook....
Ember (formerly LittleSnapper) is your digital scrapbook of things that inspire you: websites, photos, apps or other things. Just drag in images that you want to keep, organize them into relevant... Read more
OmniPlan 2.3.6 - Robust project manageme...
With OmniPlan, you can create logical, manageable project plans with Gantt charts, schedules, summaries, milestones, and critical paths. Break down the tasks needed to make your project a success,... Read more
Command-C 1.1.1 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Knock 1.1.7 - Unlock your Mac by knockin...
Knock is a faster, safer way to sign in. You keep your iPhone with you all the time. Now you can use it as a password. You never have to open the app -- just knock on your phone twice, even when it's... Read more
Mellel 3.3.6 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
LibreOffice 4.3.0.4 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
Freeway Pro 7.0 - Drag-and-drop Web desi...
Freeway Pro lets you build websites with speed and precision... without writing a line of code! With it's user-oriented drag-and-drop interface, Freeway Pro helps you piece together the website of... Read more
Drive Genius 3.2.4 - Powerful system uti...
Drive Genius is an OS X utility designed to provide unsurpassed storage management. Featuring an easy-to-use interface, Drive Genius is packed with powerful tools such as a drive optimizer, a... Read more
Vitamin-R 2.15 - Personal productivity t...
Vitamin-R creates the optimal conditions for your brain to work at its best by structuring your work into short bursts of distraction-free, highly focused activity alternating with opportunities for... Read more
Toast Titanium 12.0 - The ultimate media...
Toast Titanium goes way beyond the very basic burning in the Mac OS and iLife software, and sets the standard for burning CDs, DVDs, and now Blu-ray discs on the Mac. Create superior sounding audio... Read more

Latest Forum Discussions

See All

Dawn of the Immortals Review
Dawn of the Immortals Review By Jennifer Allen on July 31st, 2014 Our Rating: :: RESPECTABLE EXPLORATIONUniversal App - Designed for iPhone and iPad Dawn of the Immortals might not re-invent the wheel, but it does tweak it a little... | Read more »
80 Days Review
80 Days Review By Jennifer Allen on July 31st, 2014 Our Rating: :: EPIC ADVENTUREUniversal App - Designed for iPhone and iPad A fantastic and fascinating re-envisioning of the classic novel by Jules Verne, 80 Days is a delightful... | Read more »
Battleheart Legacy Guide
The world of Battleheart Legacy is fun and deep; full of wizards, warriors, and witches. Here are some tips and tactics to help you get the most enjoyment out of this great game. | Read more »
Puzzle Roo Review
Puzzle Roo Review By Jennifer Allen on July 31st, 2014 Our Rating: :: PUZZLE-BASED TWISTUniversal App - Designed for iPhone and iPad A different take on the usual block dropping puzzle game, Puzzle Roo is quite pleasant.   | Read more »
Super Crossfire Re-Release Super Crossfi...
Super Crossfire Re-Release Super Crossfighter Coming Soon, Other Radiangames Titles Go 50% Off Posted by Ellis Spice on July 31st, 2014 [ | Read more »
Hexiled Review
Hexiled Review By Rob Thomas on July 31st, 2014 Our Rating: :: HEX SELLSUniversal App - Designed for iPhone and iPad In space, no one can hear you… spell? Hexiled is a neat concept for a word scramble puzzle, but it doesn’t go too... | Read more »
Summoners War: Sky Arena Passes 10 Milli...
Summoners War: Sky Arena Passes 10 Million Installs! Posted by Jessica Fisher on July 31st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Deep Loot Review
Deep Loot Review By Jennifer Allen on July 31st, 2014 Our Rating: :: DIVE DEEPUniversal App - Designed for iPhone and iPad Dive deep in this fun explore-em-up that’s a little grind heavy but ultimately quite entertaining.   | Read more »
Despicable Me: Minion Rush is One Year O...
Despicable Me: Minion Rush is One Year Old, Gets its Biggest Update Yet Posted by Jennifer Allen on July 31st, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Fish & Shark Review
Fish & Shark Review By Jordan Minor on July 31st, 2014 Our Rating: :: FLAPPY FISHUniversal App - Designed for iPhone and iPad Fish & Shark’s beauty is only scale deep.   | Read more »

Price Scanner via MacPrices.net

Save up to $130 on an iPad mini with Apple re...
The Apple Store has Certified Refurbished 2nd generation iPad minis with Retina Displays available for up to $130 off the cost of new models, starting at $339. Apple’s one-year warranty is included... Read more
iPad Cannibalization Threat “Overblown”
Seeking Alpha’s Kevin Greenhalgh observes that while many commentators think Apple’s forthcoming 5.5-inch panel iPhone 6 will cannibalize iPad sales, in his estimation, these concerns are being... Read more
Primate Labs Releases July 2014 MacBook Pro P...
Primate Labs’ John Poole has posted Geekbench 3 results for most of the new MacBook Pro models that Apple released on Tuesday. Poole observes that overall performance improvements for the new MacBook... Read more
Apple Re-Releases Bugfixed MacBook Air EFI Fi...
Apple has posted a bugfixed version EFI Firmware Update 2.9 a for MacBook Air (Mid 2011) models. The update addresses an issue where systems may take longer to wake from sleep than expected, and... Read more
Save $50 on the 2.5GHz Mac mini, plus free sh...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Save up to $140 on an iPad Air with Apple ref...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
$250 price drop on leftover 15-inch Retina Ma...
B&H Photo has dropped prices on 2013 15″ Retina MacBook Pros by $250 off original MSRP. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.3GHz Retina MacBook Pro: $2249, $250 off... Read more
More iPad Upgrade Musings – The ‘Book Mystiqu...
Much discussed recently, what with Apple reporting iPad sales shrinkage over two consecutive quarters, is that it had apparently been widely assumed that tablet users would follow a two-year hardware... Read more
13-inch 2.5GHz MacBook Pro on sale for $999,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $999.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $100 off MSRP. Price is... Read more
Save up to $300 on an iMac with Apple refurbi...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Sr. Product Leader, *Apple* Store Apps - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring Read more
Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.