Skip to content

Opening and playing an MP4 file

Dimitri Podborski edited this page Sep 17, 2020 · 1 revision

Opening a movie file and playing a single track is demonstrated in the following listing:

Opening a Movie and Playing a Track

#include "ISOMovies.h"

ISOErr playMyMovie( char *filename, u32 trackNumber )
{
  ISOErr err;
  u32 handlerType;
  ISOMovie moov;
  ISOTrack trak;
  ISOMedia media;
  ISOTrackReader reader;
  ISOHandle sampleH;
  ISOHandle decoderConfigH;

  err = ISOOpenMovieFile( &moov, filename, 
            MP4OpenMovieNormal );
  err = ISOGetMovieIndTrack( moov, trackNumber, &trak );
  err = ISOGetTrackMedia( trak, &media );
  err = ISOGetMediaHandlerDescription( 
            media, &handlerType, NULL );
  err = ISONewHandle( 0, &decoderConfigH );
  err = ISOCreateTrackReader( trak, &reader );
  err = MP4TrackReaderGetCurrentDecoderConfig( 
            reader, decoderConfigH );
  /* instantiate proper decoder for mediatype/decoderconfig
    (not shown)
  */
  err = ISONewHandle( 0, &sampleH );
  for (;;)
  { /* play every frame */
    u32 unitSize;
    s32 cts;
    s32 dts;
    u32 sampleFlags;
    err = MP4TrackReaderGetNextAccessUnit(
            reader, sampleH, &unitSize, &sampleFlags, &cts, &dts );
    if ( err )
    {
      if ( err == ISOEOF ) err = ISONoErr;
      break;
    }
    /* send AU to decoder (simulated) */
    fprintf( stderr,
      "send AU to decoder: \
       size = %d, cts = %d, dts = %d\n", 
      unitSize, cts, dts );
  }
  err = ISODisposeHandle(sampleH);
  err = ISODisposeHandle(decoderConfigH);
  err = ISODisposeTrackReader(reader );
  err = ISODisposeMovie( moov );
  return err;
}

Important things to note:

  • The listing demonstrates getting the handler type and decoder config for the specified track, but the example doesn’t do anything with them. You will need to instantiate the proper decoder for the stream type and initialize it using the decoder config data.
  • The example uses a ISOTrackReader to simplify reading access units from MP4 media. The AUs are read using MP4TrackReaderGetNextAccessUnit. This function serves as an iterator, beginning at the start of the media and returning an access unit for each call until end of file is reached.