From d2027c75d58b10d78dce012b519a2ebb533d4046 Mon Sep 17 00:00:00 2001 From: Onur Gündüz Date: Mon, 16 Feb 2026 19:17:56 +0100 Subject: Add JSON output support to mp4dump --- cmd/mp4dump/README.md | 8 +- cmd/mp4dump/main.go | 360 +++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 289 insertions(+), 79 deletions(-) (limited to 'cmd/mp4dump') diff --git a/cmd/mp4dump/README.md b/cmd/mp4dump/README.md index ce25882..704e34d 100644 --- a/cmd/mp4dump/README.md +++ b/cmd/mp4dump/README.md @@ -6,7 +6,7 @@ Pipe the output of `mp4dump` to [`indentree`](https://github.com/tetsuo/indentree) to visualize the box hierarchy: -``` +```sh mp4dump "big-buck-bunny-1080p-60fps-30sec.mp4" | indentree ``` @@ -66,3 +66,9 @@ Output: ├─ [hdlr] size=33 v=0 flags=0x000000 type=mdir name="" └─ [ilst] size=341 (333 bytes) ``` + +You can also output in JSON format: + +```sh +mp4dump --format=json "big-buck-bunny-1080p-60fps-30sec.mp4" +``` diff --git a/cmd/mp4dump/main.go b/cmd/mp4dump/main.go index ee7a577..095b2b8 100644 --- a/cmd/mp4dump/main.go +++ b/cmd/mp4dump/main.go @@ -2,6 +2,8 @@ package main import ( + "encoding/json" + "flag" "fmt" "os" "strings" @@ -9,23 +11,66 @@ import ( "github.com/tetsuo/mp4" ) +// Format specifies the output format. +type Format int + +const ( + FormatText Format = iota + FormatJSON +) + +// BoxNode is a box in the tree structure. +type BoxNode struct { + Type string `json:"type"` + Size uint64 `json:"size"` + Version *uint8 `json:"version,omitempty"` + Flags *uint32 `json:"flags,omitempty"` + Info map[string]any `json:"info,omitempty"` + DataLength *int `json:"dataLength,omitempty"` + Children []BoxNode `json:"children,omitempty"` +} + func main() { - if len(os.Args) < 2 { - fmt.Fprintf(os.Stderr, "usage: %s \n", os.Args[0]) + formatFlag := flag.String("format", "text", "output format: text (default), json") + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "usage: %s [--format=text|json] \n", os.Args[0]) + flag.PrintDefaults() + } + flag.Parse() + + if flag.NArg() < 1 { + flag.Usage() os.Exit(1) } - f, err := os.Open(os.Args[1]) + format := FormatText + switch strings.ToLower(*formatFlag) { + case "json": + format = FormatJSON + case "text": + format = FormatText + default: + fmt.Fprintf(os.Stderr, "unknown format: %s\n", *formatFlag) + os.Exit(1) + } + + f, err := os.Open(flag.Arg(0)) if err != nil { fmt.Fprintf(os.Stderr, "error opening file: %v\n", err) os.Exit(1) } defer f.Close() + // Build tree structure + var root []BoxNode + sc := mp4.NewScanner(f) for sc.Next() { e := sc.Entry() - fmt.Printf("[%s] size=%d\n", e.Type, e.Size) + node := BoxNode{ + Type: string(e.Type[:]), + Size: uint64(e.Size), + } // Only load metadata boxes into memory for deep parsing if e.Type == mp4.TypeMoov || e.Type == mp4.TypeMoof { @@ -35,7 +80,7 @@ func main() { continue } r := mp4.NewReader(buf) - walk(&r, 1) + node.Children = buildTree(&r) } else if e.Type == mp4.TypeFtyp { buf := make([]byte, e.DataSize()) if err := sc.ReadBody(buf); err != nil { @@ -43,217 +88,262 @@ func main() { continue } f := mp4.ReadFtyp(buf) - fmt.Printf(" brand=%s ver=%d", string(f.MajorBrand[:]), f.MinorVersion) + node.Info = make(map[string]any) + node.Info["brand"] = string(f.MajorBrand[:]) + node.Info["version"] = f.MinorVersion if len(f.Compatible) > 0 { - fmt.Printf(" compat=[") + compat := make([]string, len(f.Compatible)) for i, c := range f.Compatible { - if i > 0 { - fmt.Printf(",") - } - fmt.Printf("%s", string(c[:])) + compat[i] = string(c[:]) } - fmt.Printf("]") + node.Info["compatible"] = compat } - fmt.Println() } else if e.Type == mp4.TypeMdat { - fmt.Printf(" dataLen=%d\n", e.DataSize()) + dataLen := int(e.DataSize()) + node.DataLength = &dataLen } + + root = append(root, node) } if err := sc.Err(); err != nil { fmt.Fprintf(os.Stderr, "scan error: %v\n", err) os.Exit(1) } + + printTree(root, format) } -func walk(r *mp4.Reader, depth int) { - for r.Next() { - indent := strings.Repeat(" ", depth) +func buildTree(r *mp4.Reader) []BoxNode { + var nodes []BoxNode - fmt.Printf("%s[%s] size=%d", indent, r.Type(), r.Size()) + for r.Next() { + boxType := r.Type() + node := BoxNode{ + Type: string(boxType[:]), + Size: r.Size(), + } if mp4.IsFullBox(r.Type()) { - fmt.Printf(" v=%d flags=0x%06x", r.Version(), r.Flags()) + v := r.Version() + f := r.Flags() + node.Version = &v + node.Flags = &f } - printBoxInfo(r) - fmt.Println() + // Collect box-specific info + node.Info = collectBoxInfo(r) // Descend into containers if mp4.IsContainerBox(r.Type()) { r.Enter() - walk(r, depth+1) + node.Children = buildTree(r) r.Exit() - continue - } - - // Handle stsd: entry count + sub-boxes - if r.Type() == mp4.TypeStsd { + } else if r.Type() == mp4.TypeStsd { + // Handle stsd: entry count + sub-boxes r.Enter() r.Skip(4) // skip entry count for r.Next() { - printSampleEntry(r, depth+1) + child := buildSampleEntryNode(r) + node.Children = append(node.Children, child) } r.Exit() - continue } + + nodes = append(nodes, node) } + + return nodes } -func printSampleEntry(r *mp4.Reader, depth int) { - indent := strings.Repeat(" ", depth) +func buildSampleEntryNode(r *mp4.Reader) BoxNode { + boxType := r.Type() + node := BoxNode{ + Type: string(boxType[:]), + Size: r.Size(), + Info: make(map[string]any), + } switch r.Type() { case mp4.TypeAvc1: v := mp4.ReadVisualSampleEntry(r.Data()) - fmt.Printf("%s[%s] size=%d %dx%d compressor=%q\n", indent, r.Type(), r.Size(), v.Width, v.Height, v.CompressorName) + node.Info["width"] = v.Width + node.Info["height"] = v.Height + node.Info["compressor"] = v.CompressorName + // Enter to find avcC and other children r.Enter() r.Skip(v.ChildOffset) for r.Next() { - childIndent := strings.Repeat(" ", depth+1) + childType := r.Type() + child := BoxNode{ + Type: string(childType[:]), + Size: r.Size(), + } if mp4.IsFullBox(r.Type()) { - fmt.Printf("%s[%s] size=%d v=%d flags=0x%06x", childIndent, r.Type(), r.Size(), r.Version(), r.Flags()) - } else { - fmt.Printf("%s[%s] size=%d", childIndent, r.Type(), r.Size()) + ver := r.Version() + flg := r.Flags() + child.Version = &ver + child.Flags = &flg } if r.Type() == mp4.TypeAvcC { codec := mp4.ReadAvcC(r.Data()) - fmt.Printf(" codec=%s", codec) + child.Info = map[string]any{"codec": codec} } - fmt.Println() + node.Children = append(node.Children, child) } r.Exit() case mp4.TypeMp4a: a := mp4.ReadAudioSampleEntry(r.Data()) - fmt.Printf("%s[%s] size=%d ch=%d sampleSize=%d sampleRate=%d\n", indent, r.Type(), r.Size(), a.ChannelCount, a.SampleSize, a.SampleRate>>16) + node.Info["channelCount"] = a.ChannelCount + node.Info["sampleSize"] = a.SampleSize + node.Info["sampleRate"] = a.SampleRate >> 16 + // Enter to find esds and other children r.Enter() r.Skip(a.ChildOffset) for r.Next() { - childIndent := strings.Repeat(" ", depth+1) + childType := r.Type() + child := BoxNode{ + Type: string(childType[:]), + Size: r.Size(), + } if mp4.IsFullBox(r.Type()) { - fmt.Printf("%s[%s] size=%d v=%d flags=0x%06x", childIndent, r.Type(), r.Size(), r.Version(), r.Flags()) - } else { - fmt.Printf("%s[%s] size=%d", childIndent, r.Type(), r.Size()) + ver := r.Version() + flg := r.Flags() + child.Version = &ver + child.Flags = &flg } if r.Type() == mp4.TypeEsds { codec := mp4.ReadEsdsCodec(r.Data()) - fmt.Printf(" codec=%s", codec) + child.Info = map[string]any{"codec": codec} } - fmt.Println() + node.Children = append(node.Children, child) } r.Exit() default: - fmt.Printf("%s[%s] size=%d", indent, r.Type(), r.Size()) if mp4.IsFullBox(r.Type()) { - fmt.Printf(" v=%d flags=0x%06x", r.Version(), r.Flags()) + ver := r.Version() + flg := r.Flags() + node.Version = &ver + node.Flags = &flg } - fmt.Printf(" (raw %d bytes)\n", len(r.Data())) + dataLen := len(r.Data()) + node.DataLength = &dataLen } + + return node } -func printBoxInfo(r *mp4.Reader) { +func collectBoxInfo(r *mp4.Reader) map[string]any { + info := make(map[string]any) + switch r.Type() { case mp4.TypeFtyp: f := mp4.ReadFtyp(r.Data()) - fmt.Printf(" brand=%s ver=%d", string(f.MajorBrand[:]), f.MinorVersion) + info["brand"] = string(f.MajorBrand[:]) + info["version"] = f.MinorVersion if len(f.Compatible) > 0 { - fmt.Printf(" compat=[") + compat := make([]string, len(f.Compatible)) for i, c := range f.Compatible { - if i > 0 { - fmt.Printf(",") - } - fmt.Printf("%s", string(c[:])) + compat[i] = string(c[:]) } - fmt.Printf("]") + info["compatible"] = compat } case mp4.TypeMvhd: ts, dur, ntid := r.ReadMvhd() - fmt.Printf(" timescale=%d duration=%d nextTrackId=%d", ts, dur, ntid) + info["timescale"] = ts + info["duration"] = dur + info["nextTrackId"] = ntid case mp4.TypeTkhd: tid, dur, w, h := r.ReadTkhd() - fmt.Printf(" trackId=%d duration=%d size=%dx%d", tid, dur, w>>16, h>>16) + info["trackId"] = tid + info["duration"] = dur + info["width"] = w >> 16 + info["height"] = h >> 16 case mp4.TypeMdhd: ts, dur, lang := r.ReadMdhd() - fmt.Printf(" timescale=%d duration=%d lang=%d", ts, dur, lang) + info["timescale"] = ts + info["duration"] = dur + info["language"] = lang case mp4.TypeHdlr: ht := r.ReadHdlr() name := r.ReadHdlrName() - fmt.Printf(" type=%s name=%q", string(ht[:]), name) + info["handlerType"] = string(ht[:]) + info["name"] = name case mp4.TypeStsd: if len(r.Data()) >= 4 { - fmt.Printf(" entries=%d", r.EntryCount()) + info["entries"] = r.EntryCount() } case mp4.TypeStsz: it := mp4.NewStszIter(r.Data()) - fmt.Printf(" entries=%d", it.Count()) + info["entries"] = it.Count() case mp4.TypeStco, mp4.TypeStss: it := mp4.NewUint32Iter(r.Data()) - fmt.Printf(" entries=%d", it.Count()) + info["entries"] = it.Count() case mp4.TypeCo64: it := mp4.NewCo64Iter(r.Data()) - fmt.Printf(" entries=%d", it.Count()) + info["entries"] = it.Count() case mp4.TypeStts: it := mp4.NewSttsIter(r.Data()) - fmt.Printf(" entries=%d", it.Count()) + info["entries"] = it.Count() case mp4.TypeCtts: it := mp4.NewCttsIter(r.Data(), r.Version()) - fmt.Printf(" entries=%d", it.Count()) + info["entries"] = it.Count() case mp4.TypeStsc: it := mp4.NewStscIter(r.Data()) - fmt.Printf(" entries=%d", it.Count()) + info["entries"] = it.Count() case mp4.TypeElst: it := mp4.NewElstIter(r.Data(), r.Version()) - fmt.Printf(" entries=%d", it.Count()) + info["entries"] = it.Count() case mp4.TypeDref: if len(r.Data()) >= 4 { - fmt.Printf(" entries=%d", r.EntryCount()) + info["entries"] = r.EntryCount() } case mp4.TypeMehd: dur := r.ReadMehd() - fmt.Printf(" fragmentDuration=%d", dur) + info["fragmentDuration"] = dur case mp4.TypeTrex: tid, _, _, _, _ := r.ReadTrex() - fmt.Printf(" trackId=%d", tid) + info["trackId"] = tid case mp4.TypeMfhd: seq := r.ReadMfhd() - fmt.Printf(" seq=%d", seq) + info["sequence"] = seq case mp4.TypeTfhd: tid := r.ReadTfhd() - fmt.Printf(" trackId=%d", tid) + info["trackId"] = tid case mp4.TypeTfdt: bt := r.ReadTfdt() - fmt.Printf(" baseMediaDecodeTime=%d", bt) + info["baseMediaDecodeTime"] = bt case mp4.TypeTrun: it := mp4.NewTrunIter(r.Data(), r.Flags()) - fmt.Printf(" entries=%d", it.Count()) + info["entries"] = it.Count() if r.Flags()&mp4.TrunDataOffsetPresent != 0 { - fmt.Printf(" dataOffset=%d", it.DataOffset()) + info["dataOffset"] = it.DataOffset() } case mp4.TypeMdat: - fmt.Printf(" dataLen=%d", len(r.Data())) + info["dataLength"] = len(r.Data()) case mp4.TypeVmhd: // graphicsMode and opcolor @@ -262,8 +352,122 @@ func printBoxInfo(r *mp4.Reader) { default: if !mp4.IsContainerBox(r.Type()) { if len(r.Data()) > 0 { - fmt.Printf(" (%d bytes)", len(r.Data())) + info["dataLength"] = len(r.Data()) } } } + + return info +} + +// printTree prints the tree in the specified format +func printTree(nodes []BoxNode, format Format) { + switch format { + case FormatJSON: + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + if err := enc.Encode(nodes); err != nil { + fmt.Fprintf(os.Stderr, "error encoding JSON: %v\n", err) + } + case FormatText: + for _, node := range nodes { + printNodeText(node, 0) + } + } +} + +// printNodeText prints a single node in text format +func printNodeText(node BoxNode, depth int) { + indent := strings.Repeat(" ", depth) + + fmt.Printf("%s[%s] size=%d", indent, node.Type, node.Size) + + if node.Version != nil { + fmt.Printf(" v=%d", *node.Version) + } + if node.Flags != nil { + fmt.Printf(" flags=0x%06x", *node.Flags) + } + + // Print info fields + if len(node.Info) > 0 { + for key, val := range node.Info { + switch key { + case "brand": + fmt.Printf(" brand=%v", val) + case "version": + fmt.Printf(" ver=%v", val) + case "compatible": + if compat, ok := val.([]string); ok { + fmt.Printf(" compat=[%s]", strings.Join(compat, ",")) + } + case "timescale": + fmt.Printf(" timescale=%v", val) + case "duration": + fmt.Printf(" duration=%v", val) + case "nextTrackId": + fmt.Printf(" nextTrackId=%v", val) + case "trackId": + fmt.Printf(" trackId=%v", val) + case "width": + if depth > 0 && node.Type == "avc1" { + // Special handling for sample entries + continue + } + fmt.Printf(" width=%v", val) + case "height": + if depth > 0 && node.Type == "avc1" { + continue + } + fmt.Printf(" height=%v", val) + case "language": + fmt.Printf(" lang=%v", val) + case "handlerType": + fmt.Printf(" type=%v", val) + case "name": + fmt.Printf(" name=%q", val) + case "entries": + fmt.Printf(" entries=%v", val) + case "fragmentDuration": + fmt.Printf(" fragmentDuration=%v", val) + case "sequence": + fmt.Printf(" seq=%v", val) + case "baseMediaDecodeTime": + fmt.Printf(" baseMediaDecodeTime=%v", val) + case "dataOffset": + fmt.Printf(" dataOffset=%v", val) + case "channelCount": + fmt.Printf(" ch=%v", val) + case "sampleSize": + fmt.Printf(" sampleSize=%v", val) + case "sampleRate": + fmt.Printf(" sampleRate=%v", val) + case "compressor": + fmt.Printf(" compressor=%q", val) + case "codec": + fmt.Printf(" codec=%v", val) + case "dataLength": + // Skip, will be handled by DataLength field + } + } + // Special formatting for avc1 and mp4a + if node.Type == "avc1" { + if w, haveW := node.Info["width"]; haveW { + if h, haveH := node.Info["height"]; haveH { + fmt.Printf(" %vx%v", w, h) + } + } + } + } + + if node.DataLength != nil { + fmt.Printf(" dataLen=%d", *node.DataLength) + } + + fmt.Println() + + // Print children + for _, child := range node.Children { + printNodeText(child, depth+1) + } } -- cgit v1.3.1