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
$524.94
Apple Inc.
+5.93
MSFT
$40.01
Microsoft Corpora
-0.39
GOOG
$536.10
Google Inc.
-20.44

MacTech Search:
Community Search:

Software Updates via MacUpdate

VMware Fusion 6.0.3 - Run Windows apps a...
VMware Fusion allows you to create a Virtual Machine on your Mac and run Windows (including Windows 8.1) and Windows software on your Mac. Run your favorite Windows applications alongside Mac... Read more
Tweetbot 1.5.1 - Popular iOS twitter cli...
Tweetbot is a full-featured OS X Twitter client with a lot of personality. Whether it's the meticulously-crafted interface, sounds and animation, or features like multiple timelines and column views... Read more
Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty 1.1.1.180...
Download the patch by launching the Starcraft II game and downloading it through the Battle.net connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more

Latest Forum Discussions

See All

Have a Special Dead Trigger 2 Easter Bas...
Have a Special Dead Trigger 2 Easter Basket Full of Goodies, Courtesy of Madfinger Games Posted by Rob Rich on April 18th, 2014 [ permalink ] Dead Trigger 2 | Read more »
Almost All of Playdek’s Library is on Sa...
Almost All of Playdek’s Library is on Sale Right Now, and You Should Check it Out Posted by Rob Rich on April 18th, 2014 [ permalink ] Playdek has released quite a few great iOS ports of board and card games over the years, and now most of them... | Read more »
Zynga Launches Brand New Farmville Exper...
Zynga Launches Brand New Farmville Experience with Farmville 2: Country Escape Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
David. Review
David. Review By Cata Modorcea on April 18th, 2014 Our Rating: :: MINIMALISTIC IN A DIFFERENT WAYUniversal App - Designed for iPhone and iPad David is a minimalistic game wrapped inside of a soothing atmosphere in which the hero... | Read more »
Eyefi Unveils New Eyefi Cloud Service Th...
Eyefi Unveils New Eyefi Cloud Service That Allows Users to Share Media Across Personal Devices Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
Tales from the Dragon Mountain: The Lair...
Tales from the Dragon Mountain: The Lair Review By Jennifer Allen on April 18th, 2014 Our Rating: :: STEADY ADVENTURINGiPad Only App - Designed for the iPad Treading a safe path, Tales from the Dragon Mountain: The Lair is a... | Read more »
Yahoo Updates Flickr App with Advanced E...
Yahoo Updates Flickr App with Advanced Editing Features and More Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
My Incredible Body - A Kid's App to...
My Incredible Body - A Kid's App to Learn about the Human Body 1.1.00 Device: iOS Universal Category: Education Price: $2.99, Version: 1.1.00 (iTunes) Description: Wouldn’t it be cool to look inside yourself and see what was going on... | Read more »
Trials Frontier Review
Trials Frontier Review By Carter Dotson on April 18th, 2014 Our Rating: :: A ROUGH LANDINGUniversal App - Designed for iPhone and iPad Trials Frontier finally brings the famed stunt racing franchise to mobile, but how much does its... | Read more »
Evernote Business Notebook by Moleskin I...
Evernote Business Notebook by Moleskin Introduced – Support Available in Evernote for iOS Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Free HopTo 2.2 Helps Enhance Your Productivit...
The HopTo app helps you do more on your iPad by providing more and easier adaccess to files and documents. Version 2.2 adds Egnyte and HopTo’s Mac OSX File Connector. If you already have the hopTo... Read more
National Distracted Driving Awareness Month:...
As the country recognizes National Distracted Driving Awareness Month, Sprint is reminding wireless consumers to focus on driving while behind the wheel, to not text or email while driving, and to... Read more
13-inch 2.4GHz Retina MacBook Pro available f...
Abt has the 13″ 2.4GHz 128GB Retina MacBook Pro available for $1229 including free shipping. Their price is $70 off MSRP. Read more
iMacs on sale for up to $160 off MSRP this we...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
iPad Airs on sale this weekend for up to $100...
Best Buy has WiFi iPad Airs on sale for $50 off MSRP and WiFi + Cellular iPad Airs on sale for $100 off MSRP on their online store for a limited time, with prices now starting at $449. Choose free... Read more
Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Hyundai Brings Apple CarPlay To The 2015 Sona...
Hyundai Motor America has announced it will bring Apple CarPlay functionality to the 2015 Sonata. CarPlay is pitched as a smarter, safer and easier way to use iPhone in the car and gives iPhone users... Read more
Updated iPads Coming Sooner Than We Had Thoug...
MacRumors, cites KGI securities analyst Ming Chi Kuo, well-respected as an Apple product prognisticator, saying that Apple will introduce an upgraded iPad Air and iPad mini in 2014/Q3, meaning the... Read more
Toshiba Unveils New High And Low End Laptop M...
Toshiba has announced new laptop models covering both the high-end and low-end of the notebook computer spectrum. Toshiba 4K Ultra HD Laptop Toshiba’s new Satellite P55t features one of the world’s... Read more
Save up to $270 with Apple refurbished 13-inc...
The Apple Store has Apple Certified Refurbished October 2013 13″ Retina MacBook Pros available starting at $1099, with models up to $270 off MSRP. Apple’s one-year warranty is standard, and shipping... Read more

Jobs Board

*Apple* Automotive Parts Department position...
Apple Automotive is one of the fastest growing dealer…and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive, we 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
*Apple* Retail - Manager - Holyoke - Apple I...
Job Summary Keeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you’re a master of them all. In the store’s fast-paced, Read more
*Apple* Retail - Manager - Apple (United Sta...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic 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.