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.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.