abema / go-mp4

Go library for reading and writing MP4 file
https://dev.to/sunfishshogi/go-mp4-golang-library-and-cli-tool-for-mp4-52o1
MIT License
464 stars 30 forks source link

Incremental/arbitrary parsing #120

Closed onthegit closed 2 years ago

onthegit commented 2 years ago

Hello, thanks for the library. Can the library do Incremental/arbitrary parsing? E.g given bytes from MP4 file to try to parse the moov? And once moov is parsed based on the sample offset to be able to parse that sample (chunk)?

sunfish-shogi commented 2 years ago

@onthegit Thank you for having interest in our library.

If you want to walk box tree structure manually, you can use ReadBoxStructure. You can decide behaviors (parse box payload/expand child boxes/do nothing) by handler.

_, err := ReadBoxStructure(r, handler) 

And go-mp4 has some wrapper functions of above.

ExtractBox finds boxes which are specified type. For example, you can list tracks (trak boxes) as following.

traks, err := ExtractBox(file, nil, mp4.BoxPath{BoxTypeMoov(), BoxTypeTrak()})

ExtractBoxWithPayload finds boxes and parses those payload.

boxes, err := ExtractBoxWithPayload(file, trak, mp4.BoxPath{BoxTypeMdia(), BoxTypeMinf(), BoxTypeStbl(), BoxTypeStco()})
if err != nil {
  // error 
}
if len(boxes) == 0 { 
  // stco box not found
}
stco := boxes[0].Payload.(*Stco)
for _, offset := range stco.ChunkOffset {
  _, err := r.Seek(int64(offset), io.SeekStart)
  // ...
}

For your reference, following implementation reads NAL units and finds key frames, using information of stco box and stts box.

https://github.com/abema/go-mp4/blob/v0.7.2/probe.go#L184-L202 https://github.com/abema/go-mp4/blob/v0.7.2/probe.go#L311-L319 https://github.com/abema/go-mp4/blob/v0.7.2/probe.go#L325-L331 https://github.com/abema/go-mp4/blob/v0.7.2/probe.go#L576-L616

Note that go-mp4 has no encoding/decoding implementation for codecs.

onthegit commented 2 years ago

@sunfish-shogi thanks for your reply.