An MP4 (ISOBMFF) file is a stack of boxes, each tagged with a size and a name. Once you know what the three most important boxes hold, it becomes clear why the file behaves the way it does.
In Chapter 10 you learned that a container is an "envelope" separate from the codec (Containers and codecs). This chapter opens the envelope. MP4 follows the ISO Base Media File Format (ISOBMFF), whose basic unit is the box. The same concept in Apple's QuickTime is called an "atom," so depending on the document you will see both words.
A box starts with a size and a type (four characters), followed by its contents. Because the size is known, a parser can skip over any box it doesn't recognize and read the next one. A box can contain other boxes, so the whole file forms a tree. If the size field is 1, a separate 64-bit size follows (for boxes larger than 4 GB), and if it is 0, it means "to the end of the file."
Box names and roles are defined in ISO/IEC 14496-12 (ISOBMFF). The table above is condensed for beginners.
Inside mdat, frames are simply laid end to end, with nothing marking where one ends and the next begins. That information lives in the sample table (stbl) inside moov. For every sample it records the size, the position in the file, the playback time, and whether it is a keyframe. So a player can read just moov before playback starts and then seek to any point in time: it finds the nearest keyframe in the table and jumps to that position (GOP structure).
MP4 is built so that you need the index (moov) before you can read the data (mdat). That makes seeking fast and editing friendly, but it also makes *when* and *where* the index gets written a problem. This is the starting point for the next lesson (faststart) and for fMP4.
A regular MP4 usually has its moov completed when the recording ends. So if the power goes out or the program crashes mid-recording, mdat may hold data but there is no moov, and players can't open the file. For recordings where this risk matters, fMP4 or MKV is often used.
The basic unit of ISOBMFF. It starts with a size and a four-character type, and it can contain other boxes.
The metadata box holding track information and the sample location table. It acts as the index for playback and seeking.
The box that actually holds the compressed video and audio bytes.
A table inside moov listing each sample's size, position, time, and whether it is a keyframe.
In an MP4, where can you find out which byte of mdat frame number N starts at?