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
$111.78
Apple Inc.
-0.87
MSFT
$47.66
Microsoft Corpora
+0.14
GOOG
$516.35
Google Inc.
+5.25

MacTech Search:
Community Search:

Software Updates via MacUpdate

LibreOffice 4.3.5.2 - Free Open Source o...
LibreOffice is an office suite (word processor, spreadsheet, presentations, drawing tool) compatible with other major office suites. The Document Foundation is coordinating development and... Read more
CleanApp 5.0.0 Beta 5 - Application dein...
CleanApp is an application deinstaller and archiver.... Your hard drive gets fuller day by day, but do you know why? CleanApp 5 provides you with insights how to reclaim disk space. There are... Read more
Monolingual 1.6.2 - 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
NetShade 6.1 - Browse privately using an...
NetShade is an Internet security tool that conceals your IP address on the web. NetShade routes your Web connection through either a public anonymous proxy server, or one of NetShade's own dedicated... Read more
calibre 2.13 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Mellel 3.3.7 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
ScreenFlow 5.0.1 - Create screen recordi...
Save 10% with the exclusive MacUpdate coupon code: AFMacUpdate10 Buy now! ScreenFlow is powerful, easy-to-use screencasting software for the Mac. With ScreenFlow you can record the contents of your... Read more
Simon 4.0 - Monitor changes and crashes...
Simon monitors websites and alerts you of crashes and changes. Select pages to monitor, choose your alert options, and customize your settings. Simon does the rest. Keep a watchful eye on your... Read more
BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more

Latest Forum Discussions

See All

Make your own Tribez Figures (and More)...
Make your own Tribez Figures (and More) with Toyze Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
So Many Holiday iOS Sales Oh My Goodness...
The holiday season is in full-swing, which means a whole lot of iOS apps and games are going on sale. A bunch already have, in fact. Naturally this means we’re putting together a hand-picked list of the best discounts and sales we can find in order... | Read more »
It’s Bird vs. Bird in the New PvP Mode f...
It’s Bird vs. Bird in the New PvP Mode for Angry Birds Epic Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Telltale Games and Mojang Announce Minec...
Telltale Games and Mojang Announce Minecraft: Story Mode – A Telltale Games Series Posted by Jessica Fisher on December 19th, 2014 [ permalink ] | Read more »
WarChest and Splash Damage Annouce Their...
WarChest and Splash Damage Annouce Their New Game: Tempo Posted by Jessica Fisher on December 19th, 2014 [ permalink ] WarChest Ltd and Splash Damage Ltd are teaming up again to work | Read more »
BulkyPix Celebrates its 6th Anniversary...
BulkyPix Celebrates its 6th Anniversary with a Bunch of Free Games Posted by Jessica Fisher on December 19th, 2014 [ permalink ] BulkyPix has | Read more »
Indulge in Japanese cuisine in Cooking F...
Indulge in Japanese cuisine in Cooking Fever’s new sushi-themed update Posted by Simon Reed on December 19th, 2014 [ permalink ] Lithuanian developer Nordcurrent has yet again updated its restaurant simulat | Read more »
Badland Daydream Level Pack Arrives to C...
Badland Daydream Level Pack Arrives to Celebrate 20 Million Downloads Posted by Ellis Spice on December 19th, 2014 [ permalink ] | Read more »
Far Cry 4, Assassin’s Creed Unity, Desti...
Far Cry 4, Assassin’s Creed Unity, Destiny, and Beyond – AppSpy Takes a Look at AAA Companion Apps Posted by Rob Rich on December 19th, 2014 [ permalink ] These day | Read more »
A Bunch of Halfbrick Games Are Going Fre...
A Bunch of Halfbrick Games Are Going Free for the Holidays Posted by Ellis Spice on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »

Price Scanner via MacPrices.net

The Apple Store offering free next-day shippi...
The Apple Store is now offering free next-day shipping on all in stock items if ordered before 12/23/14 at 10:00am PT. Local store pickup is also available within an hour of ordering for any in stock... Read more
It’s 1992 Again At Sony Pictures, Except For...
Techcrunch’s John Biggs interviewed a Sony Pictures Entertainment (SPE) employee, who quite understandably wished to remain anonymous, regarding post-hack conditions in SPE’s L.A office, explaining “... Read more
Holiday sales this weekend: MacBook Pros for...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Holiday sales this weekend: MacBook Airs for...
B&H Photo has 2014 MacBook Airs on sale for up to $120 off MSRP, for a limited time, for the Thanksgiving/Christmas Holiday shopping season. Shipping is free, and B&H charges NY sales tax... Read more
Holiday sales this weekend: iMacs for up to $...
B&H Photo has 21″ and 27″ iMacs on sale for up to $200 off MSRP including free shipping plus NY sales tax only. B&H will also include a free copy of Parallels Desktop software: - 21″ 1.4GHz... Read more
Holiday sales this weekend: Mac minis availab...
B&H Photo has new 2014 Mac minis on sale for up to $80 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 1.4GHz Mac mini: $459 $40 off MSRP - 2.6GHz Mac mini: $629 $70 off MSRP... Read more
Holiday sales this weekend: Mac Pros for up t...
B&H Photo has Mac Pros on sale for up to $500 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: $2599, $400 off MSRP - 3.5GHz 6-core Mac Pro: $3499, $... Read more
Save up to $400 on MacBooks with Apple Certif...
The Apple Store has Apple Certified Refurbished 2014 MacBook Pros and MacBook Airs available for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Save up to $300 on Macs, $30 on iPads with Ap...
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
iOS and Android OS Targeted by Man-in-the-Mid...
Cloud services security provider Akamai Technologies, Inc. has released, through the company’s Prolexic Security Engineering & Research Team (PLXsert), a new cybersecurity threat advisory. The... Read more

Jobs Board

*Apple* Store Leader Program (US) - Apple, I...
…Summary Learn and grow as you explore the art of leadership at the Apple Store. You'll master our retail business inside and out through training, hands-on experience, 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
*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* 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* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.