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
$117.60
Apple Inc.
-1.03
MSFT
$47.47
Microsoft Corpora
-0.12
GOOG
$541.08
Google Inc.
+1.81

MacTech Search:
Community Search:

Software Updates via MacUpdate

MacUpdate Desktop 6.0.3 - Discover and i...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
SteerMouse 4.2.2 - Powerful third-party...
SteerMouse is an advanced driver for USB and Bluetooth mice. It also supports Apple Mighty Mouse very well. SteerMouse can assign various functions to buttons that Apple's software does not allow,... Read more
iMazing 1.1 - Complete iOS device manage...
iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and from... Read more
PopChar X 7.0 - Floating window shows av...
PopChar X helps you get the most out of your font collection. With its crystal-clear interface, PopChar X provides a frustration-free way to access any font's special characters. Expanded... Read more
Carbon Copy Cloner 4.0.3 - Easy-to-use b...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
ForeverSave 2.1.3 - Universal auto-save...
ForeverSave auto-saves all documents you're working on while simultaneously doing backup versioning in the background. Lost data can be quickly restored at any time. Losing data, caused by... Read more
Voila 3.8.1 - Capture, annotate, organiz...
Voila is a screen-capture, recording, and annotation tool that is a full-featured replacement for Mac's screen-capture and screen-recording capabilities. It has a large and robust set of editing,... Read more
SyncTwoFolders 2.0.6 - Syncs two user-sp...
SyncTwoFolders simply synchronizes two folders. It supports synchronization across mounted network drives and it is a possibility to run a simulation showing in a log what will be done. Please visit... Read more
Duplicate Annihilator 5.1.1 - Find and d...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more
HandBrake 0.10.0 - Versatile video encod...
HandBrake is a tool for converting video from nearly any format to a selection of modern, widely supported codecs. Supported Sources: VIDEO_TS folder, DVD image or real DVD (unencrypted -- CSS is... Read more

Latest Forum Discussions

See All

Tilt to Live Bundle Set to Arrive This T...
Tilt to Live Bundle Set to Arrive This Thanksgiving Posted by Ellis Spice on November 25th, 2014 [ permalink ] One Man Left has unveiled an upcoming Tilt to Live bundle, allowing players to get the series for a di | Read more »
BattleLore: Command (Entertainment)
BattleLore: Command 1.0 Device: iOS Universal Category: Entertainment Price: $9.99, Version: 1.0 (iTunes) Description: ***NOTE: Compatible with iPad 2/iPad mini, iPod touch 5 and up and iPhone 4S and up – WILL NOT RUN ON EARLIER... | Read more »
Weather Or Not Review
Weather Or Not Review By Jennifer Allen on November 25th, 2014 Our Rating: :: STYLISH WEATHER REPORTINGiPhone App - Designed for the iPhone, compatible with the iPad Check the weather quickly and conveniently with Weather or Not... | Read more »
The All-New Football Manager Handheld 20...
The All-New Football Manager Handheld 2015 is Available Now Posted by Jessica Fisher on November 25th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Six iOS Games to Get You Ready for Thank...
Image Source: Friends Wiki At this point in the month, you or at least a few people you know are probably getting ready to scramble around (or are already scrambling around) for Thanksgiving Dinner. It’s a hectic day of precise oven utilization, but... | Read more »
Call of Duty: Heroes: Tips, Tricks, and...
Hello Heroes: What’d we think of Call of Duty‘s take on Clash of Clans? Check out our Call of Duty: Heroes review to find out! Just downloaded Call of Duty: Heroes and need some handy tips and tricks on how to get ahead of the rest? As we often do,... | Read more »
Call of Duty: Heroes Review
Call of Duty: Heroes Review By Jennifer Allen on November 25th, 2014 Our Rating: :: CLASH OF FRANCHISESUniversal App - Designed for iPhone and iPad Mix Clash of Clans with Call of Duty, and this is what you get.   | Read more »
Slider Review
Slider Review By Jordan Minor on November 25th, 2014 Our Rating: :: SLIDE TO PLAYUniversal App - Designed for iPhone and iPad Slider has all the excitement of unlocking your phone screen.   | Read more »
oh my giraffe (Games)
oh my giraffe 1.0.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.0 (iTunes) Description: Eat fruits while being chased by lions. Cut the vines to send fruit plummeting onto the lions. Don't worry, your flexible... | Read more »
One of 2000’s Most Loves Adventure Games...
One of 2000’s Most Loves Adventure Games, The Longest Journey, has Come to iOS Posted by Jessica Fisher on November 25th, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Early Black Friday MacBook Pro sale: 15-inch...
 Best Buy has posted early Black Friday prices on 15″ Retina MacBook Pros, with models on sale for $300 off MSRP on their online store for a limited time. Choose free local store pickup (if available... Read more
A9 Chips Already?
It’s barely more than a couple of months since Apple got the first A8 systems-on-chip into consumer hands, but rumor and news focus is already turning to the next-generation A9 SoC. Apple Daily... Read more
NewerTech Announces NuGuard KXs Impact X-Orbi...
NewerTech has announced updates to its family of Impact X-Orbing Screen Armor bringing military grade, triple layer protection to Apple’s new iPhone 6 and 6 Plus. Like all models in the NuGuard KXs... Read more
13-inch 1.4GHz MacBook Air on sale for $889,...
 B&H Photo has the 13″ 1.4GHz/128GB MacBook Air on sale for $889 including free shipping plus NY tax only. Their price is $110 off MSRP. B&H will also include free copies of Parallels Desktop... Read more
Save up to $300 on Macs and iPads with your A...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
Apple refurbished Mac Pros available for up t...
The Apple Store is offering Apple Certified Refurbished Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more
Jumptuit Launches One-Tap Windows 8.1 iTunes...
Jumptuit has launched Windows 8.1 support for One-Tap iTunes Sync. with which Windows 8.1 users can now easily sync their iTunes libraries with Microsoft OneDrive. Jumptuit provides easy access from... Read more
Apple restocks refurbished 13-inch 2014 Retin...
The Apple Store has restocked Apple Certified Refurbished 2014 13″ 2.6GHz Retina MacBook Pros for up to $230 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
CEA Study Finds More People Recycling Electro...
A new study by the Consumer Electronics Association (CEA) finds that electronics recycling receives the continued and growing support of consumers. According to the CEA,s Recycling and Reuse Study,... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale today for $1749. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of Parallels Desktop... 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
*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* 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* Solutions Consultant (ASC)- Retail S...
**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
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.