beta.blog

Archive for August, 2024

Golang: Check if an MP4 file is streamable

by on Aug.01, 2024, under News

Determining if an MP4 file is streamable involves checking the arrangement of the file’s metadata, particularly the ‘moov atom’ (a key part of the file’s structure). In a streamable MP4 file, the ‘moov atom’ is placed at the beginning of the file, allowing playback to start before the file is fully downloaded. In a non-streamable file, the ‘moov atom’ is typically at the end, meaning the entire file must be downloaded before playback can begin.

In a HEX editor, this could look something like this:

Of course, we can also write a Go program to check this fact.

package main

import (
	"fmt"
	"os"
)

func isStreamableMP4(filePath string) (bool, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return false, err
	}
	defer file.Close()

	const bufferSize = 1024
	buffer := make([]byte, bufferSize)

	_, err = file.Read(buffer)
	if err != nil {
		return false, err
	}

	for i := 0; i < len(buffer)-4; i++ {
		if string(buffer[i:i+4]) == "moov" {
			return true, nil
		}
	}

	return false, nil
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: ./stremable <path_to_mp4_file>")
		return
	}

	filePath := os.Args[1]
	streamable, err := isStreamableMP4(filePath)
	if err != nil {
		fmt.Println("Error checking file:", err)
		return
	}
	if streamable {
		fmt.Println("The file is streamable.")
	} else {
		fmt.Println("The file is not streamable.")
	}
}
Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!