- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse_mp4_headers.py
More file actions
Latest commit
87 lines (76 loc) · 2.43 KB
/
Copy pathparse_mp4_headers.py
File metadata and controls
87 lines (76 loc) · 2.43 KB
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
importargparse
importstruct
fromtypingimportList, Dict, Tuple, Any
defread_atom(data:bytes, pos:int) ->Tuple[int, str, int, bytes]:
size, atom_type=struct.unpack(">I4s", data[pos:pos+8])
header_len=8
ifsize==1:
size=struct.unpack(">Q", data[pos+8:pos+16])[0]
header_len=16
atom_type=atom_type.decode()
payload=data[pos+header_len: pos+size] ifsize!=0elseb""
returnsize, atom_type, header_len, payload
defparse_atoms(data:bytes, start:int=0, end:int|None=None, depth:int=0) ->List[Dict[str, Any]]:
"""
recursive parse `data` from start to end.
return list of dict:
{
"type": str,
"size": int, # full size including header
"offset": int, # relative to the beginning of whole file
"header_len": int,
"children": list[dict], # sub-atom
"payload": bytes, # payload(contain sub-atom)
}
"""
ifendisNone:
end=len(data)
atoms: List[Dict[str, Any]] = []
pos=start
whilepos<end:
try:
size, tp, hlen, payload=read_atom(data, pos)
exceptExceptionase:
print(e)
print("There is break atom in the file, stop parse.")
break
ifsize==0:
size=end-pos# 到文件尾
atom: Dict[str, Any] = {
"type": tp,
"size": size,
"offset": pos,
"header_len": hlen,
"payload": payload,
"children": []
}
# if the atom has children, parse sub-atom recurrently.
iftpin {"moov", "trak", "mdia", "mdhd", "minf", "stbl", "edts", "udta",
"edts", "udta", "meta", "free", "skip", "mvex"}:
atom["children"] =parse_atoms(payload, 0, len(payload), depth+1)
atoms.append(atom)
pos+=size
returnatoms
deffind_atoms(atoms:List[Dict[str, Any]], tp:str) ->List[Dict[str, Any]]:
res: List[Dict[str, Any]] = []
forainatoms:
ifa["type"] ==tp:
res.append(a)
ifa["children"]:
res+=find_atoms(a["children"], tp)
returnres
defshow_atoms(atoms, depth:int=0):
columns= ["type", "size", "offset", "header_len"]
foratominatoms:
info=f"{atom["type"]} offset:{atom["offset"]} size:{atom["size"]}"
print(("| "* (depth-1) +"|___"ifdepthelse"") +info)
ifatom["children"]:
show_atoms(atom["children"], depth+1)
if__name__=="__main__":
parser=argparse.ArgumentParser(description="Parse and show atoms of a mp4 file.")
parser.add_argument("File", type=str, help="Path of mp4 file.")
args=parser.parse_args()
withopen(args.File, "rb") asf:
bs=f.read()
atoms=parse_atoms(bs)
show_atoms(atoms)