1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
|
// Command mp4dump reads an MP4 file and prints its box structure.
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"strings"
"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() {
formatFlag := flag.String("format", "text", "output format: text (default), json")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [--format=text|json] <file.mp4>\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if flag.NArg() < 1 {
flag.Usage()
os.Exit(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()
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 {
buf := make([]byte, e.DataSize())
if err := sc.ReadBody(buf); err != nil {
fmt.Fprintf(os.Stderr, "error reading %s: %v\n", e.Type, err)
continue
}
r := mp4.NewReader(buf)
node.Children = buildTree(&r)
} else if e.Type == mp4.TypeFtyp {
buf := make([]byte, e.DataSize())
if err := sc.ReadBody(buf); err != nil {
fmt.Fprintf(os.Stderr, "error reading ftyp: %v\n", err)
continue
}
f := mp4.ReadFtyp(buf)
node.Info = make(map[string]any)
node.Info["brand"] = string(f.MajorBrand[:])
node.Info["version"] = f.MinorVersion
if len(f.Compatible) > 0 {
compat := make([]string, len(f.Compatible))
for i, c := range f.Compatible {
compat[i] = string(c[:])
}
node.Info["compatible"] = compat
}
} else if e.Type == mp4.TypeMdat {
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 buildTree(r *mp4.Reader) []BoxNode {
var nodes []BoxNode
for r.Next() {
boxType := r.Type()
node := BoxNode{
Type: string(boxType[:]),
Size: r.Size(),
}
if mp4.IsFullBox(r.Type()) {
v := r.Version()
f := r.Flags()
node.Version = &v
node.Flags = &f
}
// Collect box-specific info
node.Info = collectBoxInfo(r)
// Descend into containers
if mp4.IsContainerBox(r.Type()) {
r.Enter()
node.Children = buildTree(r)
r.Exit()
} else if r.Type() == mp4.TypeStsd {
// Handle stsd: entry count + sub-boxes
r.Enter()
r.Skip(4) // skip entry count
for r.Next() {
child := buildSampleEntryNode(r)
node.Children = append(node.Children, child)
}
r.Exit()
}
nodes = append(nodes, node)
}
return nodes
}
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())
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() {
childType := r.Type()
child := BoxNode{
Type: string(childType[:]),
Size: r.Size(),
}
if mp4.IsFullBox(r.Type()) {
ver := r.Version()
flg := r.Flags()
child.Version = &ver
child.Flags = &flg
}
if r.Type() == mp4.TypeAvcC {
codec := mp4.ReadAvcC(r.Data())
child.Info = map[string]any{"codec": codec}
}
node.Children = append(node.Children, child)
}
r.Exit()
case mp4.TypeMp4a:
a := mp4.ReadAudioSampleEntry(r.Data())
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() {
childType := r.Type()
child := BoxNode{
Type: string(childType[:]),
Size: r.Size(),
}
if mp4.IsFullBox(r.Type()) {
ver := r.Version()
flg := r.Flags()
child.Version = &ver
child.Flags = &flg
}
if r.Type() == mp4.TypeEsds {
codec := mp4.ReadEsdsCodec(r.Data())
child.Info = map[string]any{"codec": codec}
}
node.Children = append(node.Children, child)
}
r.Exit()
default:
if mp4.IsFullBox(r.Type()) {
ver := r.Version()
flg := r.Flags()
node.Version = &ver
node.Flags = &flg
}
dataLen := len(r.Data())
node.DataLength = &dataLen
}
return node
}
func collectBoxInfo(r *mp4.Reader) map[string]any {
info := make(map[string]any)
switch r.Type() {
case mp4.TypeFtyp:
f := mp4.ReadFtyp(r.Data())
info["brand"] = string(f.MajorBrand[:])
info["version"] = f.MinorVersion
if len(f.Compatible) > 0 {
compat := make([]string, len(f.Compatible))
for i, c := range f.Compatible {
compat[i] = string(c[:])
}
info["compatible"] = compat
}
case mp4.TypeMvhd:
ts, dur, ntid := r.ReadMvhd()
info["timescale"] = ts
info["duration"] = dur
info["nextTrackId"] = ntid
case mp4.TypeTkhd:
tid, dur, w, h := r.ReadTkhd()
info["trackId"] = tid
info["duration"] = dur
info["width"] = w >> 16
info["height"] = h >> 16
case mp4.TypeMdhd:
ts, dur, lang := r.ReadMdhd()
info["timescale"] = ts
info["duration"] = dur
info["language"] = lang
case mp4.TypeHdlr:
ht := r.ReadHdlr()
name := r.ReadHdlrName()
info["handlerType"] = string(ht[:])
info["name"] = name
case mp4.TypeStsd:
if len(r.Data()) >= 4 {
info["entries"] = r.EntryCount()
}
case mp4.TypeStsz:
it := mp4.NewStszIter(r.Data())
info["entries"] = it.Count()
case mp4.TypeStco, mp4.TypeStss:
it := mp4.NewUint32Iter(r.Data())
info["entries"] = it.Count()
case mp4.TypeCo64:
it := mp4.NewCo64Iter(r.Data())
info["entries"] = it.Count()
case mp4.TypeStts:
it := mp4.NewSttsIter(r.Data())
info["entries"] = it.Count()
case mp4.TypeCtts:
it := mp4.NewCttsIter(r.Data(), r.Version())
info["entries"] = it.Count()
case mp4.TypeStsc:
it := mp4.NewStscIter(r.Data())
info["entries"] = it.Count()
case mp4.TypeElst:
it := mp4.NewElstIter(r.Data(), r.Version())
info["entries"] = it.Count()
case mp4.TypeDref:
if len(r.Data()) >= 4 {
info["entries"] = r.EntryCount()
}
case mp4.TypeMehd:
dur := r.ReadMehd()
info["fragmentDuration"] = dur
case mp4.TypeTrex:
tid, _, _, _, _ := r.ReadTrex()
info["trackId"] = tid
case mp4.TypeMfhd:
seq := r.ReadMfhd()
info["sequence"] = seq
case mp4.TypeTfhd:
tid := r.ReadTfhd()
info["trackId"] = tid
case mp4.TypeTfdt:
bt := r.ReadTfdt()
info["baseMediaDecodeTime"] = bt
case mp4.TypeTrun:
it := mp4.NewTrunIter(r.Data(), r.Flags())
info["entries"] = it.Count()
if r.Flags()&mp4.TrunDataOffsetPresent != 0 {
info["dataOffset"] = it.DataOffset()
}
case mp4.TypeMdat:
info["dataLength"] = len(r.Data())
case mp4.TypeVmhd:
// graphicsMode and opcolor
case mp4.TypeSmhd:
// balance
default:
if !mp4.IsContainerBox(r.Type()) {
if len(r.Data()) > 0 {
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)
}
}
|