Skip to main content

extract_track_samples

Function extract_track_samples 

Source
pub fn extract_track_samples<R: Read + Seek>(
    trak_box: &Box,
    reader: &mut R,
) -> Result<Option<TrackSamples>>
Expand description

Extracts sample information from a single track box (trak) in an MP4 file.

This function processes a specific track box from an already-parsed MP4 file structure and extracts all sample-related information from its sample table boxes (stbl). It’s a lower-level function typically used internally by track_samples_from_reader().

The function navigates through the MP4 box hierarchy (trak → mdia → minf → stbl) to locate and parse the various sample table boxes (stts, stsc, stsz, stco, etc.) that contain the sample metadata.

§Parameters

  • trak_box - A reference to a parsed track box (trak) from an MP4 file. This box should contain the complete track structure including media information and sample tables.
  • reader - A mutable reference to the file reader, used for seeking to specific byte offsets when calculating sample file positions.

§Returns

Returns:

  • Ok(Some(TrackSamples)) - Successfully extracted sample information from the track
  • Ok(None) - Track box is valid but contains no usable sample information
  • Err(anyhow::Error) - Failed to parse the track due to structural issues

The returned TrackSamples contains:

  • Track metadata (ID, media handler type, timescale, duration)
  • Complete sample information (timing, sizes, sync points, file offsets)

§Errors

This function may return an error in the following cases:

  • Missing required child boxes (mdia, minf, stbl)
  • Corrupted or invalid sample table data
  • Inconsistent sample counts between different sample tables
  • I/O errors when calculating file offsets
  • Memory allocation failures for tracks with many samples

§Example

use mp4box::get_boxes;
use mp4box::samples::extract_track_samples;
use std::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut file = File::open("video.mp4")?;
    let file_size = file.metadata()?.len();
    let boxes = get_boxes(&mut file, file_size, true)?;

    // Find moov box and extract samples from each track
    for moov_box in boxes.iter().filter(|b| b.typ == "moov") {
        if let Some(children) = &moov_box.children {
            for trak_box in children.iter().filter(|b| b.typ == "trak") {
                if let Some(samples) = extract_track_samples(trak_box, &mut file)? {
                    println!("Found track with {} samples", samples.sample_count);
                }
            }
        }
    }
    Ok(())
}