Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can you help me? I can't get the duration of a fragmented video #389

Open
ruohuaii opened this issue Nov 19, 2024 · 1 comment
Open

Can you help me? I can't get the duration of a fragmented video #389

ruohuaii opened this issue Nov 19, 2024 · 1 comment

Comments

@ruohuaii
Copy link

package main

import (
"fmt"
"os"

"github.com/Eyevinn/mp4ff/mp4"

)

func main() {
filename := "aa.mp4"
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
d, err := mp4.DecodeFile(f)
if err != nil {
panic(err)
}

if !d.IsFragmented() {
	mvhd := d.Moov.Mvhd
	duration := mvhd.Duration
	timeScale := mvhd.Timescale
	fmt.Println("duration:", duration/uint64(timeScale))
	return
}

traks := d.Moov.Traks
timescale := uint32(0)
for _, trak := range traks {
	if trak.Mdia.Hdlr.HandlerType == "vide" {
		timescale = trak.Mdia.Mdhd.Timescale
	}
}
if timescale == 0 {
	return
}

var duration uint32
segments := d.Segments
for _, segment := range segments {
	fragments := segment.Fragments
	for _, fragment := range fragments {
		trafs := fragment.Moof.Trafs
		for _, traf := range trafs {
			defaultDur := traf.Tfhd.DefaultSampleDuration
			sampleCount := traf.Trun.SampleCount()
			samples := traf.Trun.Samples
			for _, sample := range samples {
				if sample.Dur > 0 {
					duration += sample.Dur
				} else {
					duration += defaultDur
				}
			}
			if len(traf.Trun.Samples) == 0 && defaultDur > 0 {
				duration += defaultDur * sampleCount
			}
		}
	}
}

fmt.Println(duration / timescale)

}

@tobbee
Copy link
Collaborator

tobbee commented Nov 20, 2024

@ruohuaii Thanks for using mp4ff.

If you get a duration of zero, it may be because the defaultSampleDuration is set in the trex box in the init segment, and that the other durations are not set.

You may also find an mehd box inside the mvex box in the init segment which provides the total duration of the track.

If you have the defaultDuration properly set from trex and tfhd, you can call the function

TrunBox.Duration(defaultSampleDuration uint32) uint64

to get the total duration of all samples in that box.

I hope this helps?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants