3 Generate C definitions for parsing Matroska files.
4 Can also be used to directly parse Matroska files and display their contents.
8 # This file is part of MPlayer.
10 # MPlayer is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # MPlayer is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License along
21 # with MPlayer; if not, write to the Free Software Foundation, Inc.,
22 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 'EBML, 1a45dfa3, sub', (
28 'EBMLVersion, 4286, uint',
29 'EBMLReadVersion, 42f7, uint',
30 'EBMLMaxIDLength, 42f2, uint',
31 'EBMLMaxSizeLength, 42f3, uint',
33 'DocTypeVersion, 4287, uint',
34 'DocTypeReadVersion, 4285, uint',
42 'Segment, 18538067, sub', (
44 'SeekHead*, 114d9b74, sub', (
46 'SeekID, 53ab, ebml_id',
47 'SeekPosition, 53ac, uint',
51 'Info*, 1549a966, sub', (
52 'SegmentUID, 73a4, binary',
53 'PrevUID, 3cb923, binary',
54 'NextUID, 3eb923, binary',
55 'TimecodeScale, 2ad7b1, uint',
56 'DateUTC, 4461, sint',
58 'MuxingApp, 4d80, str',
59 'WritingApp, 5741, str',
60 'Duration, 4489, float',
63 'Cluster*, 1f43b675, sub', (
65 'BlockGroup*, a0, sub', (
67 'BlockDuration, 9b, uint',
68 'ReferenceBlock*, fb, sint',
70 'SimpleBlock*, a3, binary',
73 'Tracks*, 1654ae6b, sub', (
74 'TrackEntry*, ae, sub', (
75 'TrackNumber, d7, uint',
76 'TrackUID, 73c5, uint',
77 'TrackType, 83, uint',
78 'FlagEnabled, b9, uint',
79 'FlagDefault, 88, uint',
80 'FlagForced, 55aa, uint',
81 'FlagLacing, 9c, uint',
82 'MinCache, 6de7, uint',
83 'DefaultDuration, 23e383, uint',
84 'TrackTimecodeScale, 23314f, float',
85 'MaxBlockAdditionID, 55ee, uint',
87 'Language, 22b59c, str',
89 'CodecPrivate, 63a2, binary',
90 'CodecDecodeAll, aa, uint',
92 'FlagInterlaced, 9a, uint',
93 'PixelWidth, b0, uint',
94 'PixelHeight, ba, uint',
95 'DisplayWidth, 54b0, uint',
96 'DisplayHeight, 54ba, uint',
97 'FrameRate, 2383e3, float',
100 'SamplingFrequency, b5, float',
101 'Channels, 9f, uint',
102 'BitDepth, 6264, uint',
104 'ContentEncodings, 6d80, sub', (
105 'ContentEncoding*, 6240, sub', (
106 'ContentEncodingOrder, 5031, uint',
107 'ContentEncodingScope, 5032, uint',
108 'ContentEncodingType, 5033, uint',
109 'ContentCompression, 5034, sub', (
110 'ContentCompAlgo, 4254, uint',
111 'ContentCompSettings, 4255, binary',
118 'Cues, 1c53bb6b, sub', (
119 'CuePoint*, bb, sub', (
121 'CueTrackPositions*, b7, sub', (
122 'CueTrack, f7, uint',
123 'CueClusterPosition, f1, uint',
128 'Attachments, 1941a469, sub', (
129 'AttachedFile*, 61a7, sub', (
130 'FileName, 466e, str',
131 'FileMimeType, 4660, str',
132 'FileData, 465c, binary',
133 'FileUID, 46ae, uint',
137 'Chapters, 1043a770, sub', (
138 'EditionEntry*, 45b9, sub', (
139 'EditionUID, 45bc, uint',
140 'EditionFlagHidden, 45bd, uint',
141 'EditionFlagDefault, 45db, uint',
142 'EditionFlagOrdered, 45dd, uint',
143 'ChapterAtom*, b6, sub', (
144 'ChapterUID, 73c4, uint',
145 'ChapterTimeStart, 91, uint',
146 'ChapterTimeEnd, 92, uint',
147 'ChapterFlagHidden, 98, uint',
148 'ChapterFlagEnabled, 4598, uint',
149 'ChapterSegmentUID, 6e67, binary',
150 'ChapterSegmentEditionUID, 6ebc, uint',
151 'ChapterDisplay*, 80, sub', (
152 'ChapString, 85, str',
153 'ChapLanguage*, 437c, str',
154 'ChapCountry*, 437e, str',
159 'Tags*, 1254c367, sub', (
161 'Targets, 63c0, sub', (
162 'TargetTypeValue, 68ca, uint',
163 'TargetTrackUID, 63c5, uint',
164 'TargetEditionUID, 63c9, uint',
165 'TargetChapterUID, 63c4, uint',
166 'TargetAttachmentUID, 63c6, uint',
168 'SimpleTag*, 67c8, sub', (
169 'TagName, 45a3, str',
170 'TagLanguage, 447a, str',
171 'TagString, 4487, str'
180 from math
import ldexp
183 return int(s
.encode('hex'), 16)
185 def camelcase_to_words(name
):
188 for i
in range(1, len(name
)):
189 if name
[i
].isupper() and (name
[i
-1].islower() or
190 name
[i
+1:i
+2].islower()):
191 parts
.append(name
[start
:i
])
193 parts
.append(name
[start
:])
194 return '_'.join(parts
).lower()
196 class MatroskaElement(object):
198 def __init__(self
, name
, elid
, valtype
, namespace
):
200 self
.definename
= '%s_ID_%s' % (namespace
, name
.upper())
201 self
.fieldname
= camelcase_to_words(name
)
202 self
.structname
= 'ebml_' + self
.fieldname
204 self
.valtype
= valtype
206 self
.ebmltype
= 'EBML_TYPE_SUBELEMENTS'
207 self
.valname
= 'struct %s' % self
.structname
209 self
.ebmltype
= 'EBML_TYPE_' + valtype
.upper()
211 self
.valname
= {'uint': 'uint64_t', 'str': 'struct bstr',
212 'binary': 'struct bstr', 'ebml_id': 'uint32_t',
213 'float': 'double', 'sint': 'int64_t',
216 raise SyntaxError('Unrecognized value type ' + valtype
)
217 self
.subelements
= ()
219 def add_subelements(self
, subelements
):
220 self
.subelements
= subelements
221 self
.subids
= set(x
[0].elid
for x
in subelements
)
225 def parse_elems(l
, namespace
):
228 if isinstance(el
, str):
229 name
, hexid
, eltype
= [x
.strip() for x
in el
.split(',')]
230 multiple
= name
.endswith('*')
231 name
= name
.strip('*')
232 new
= MatroskaElement(name
, hexid
, eltype
, namespace
)
233 elementd
[hexid
] = new
234 elementlist
.append(new
)
235 subelements
.append((new
, multiple
))
237 new
.add_subelements(parse_elems(el
, namespace
))
240 parse_elems(elements_ebml
, 'EBML')
241 parse_elems(elements_matroska
, 'MATROSKA')
243 def generate_C_header():
244 print('// Generated by TOOLS/matroska.py, do not edit manually')
247 for el
in elementlist
:
248 print('#define %-40s 0x%s' % (el
.definename
, el
.elid
))
252 for el
in reversed(elementlist
):
253 if not el
.subelements
:
256 print('struct %s {' % el
.structname
)
257 l
= max(len(subel
.valname
) for subel
, multiple
in el
.subelements
)+1
258 for subel
, multiple
in el
.subelements
:
259 print(' %-*s %s%s;' % (l
, subel
.valname
, (' ', '*')[multiple
],
262 for subel
, multiple
in el
.subelements
:
263 print(' int n_%s;' % (subel
.fieldname
))
266 for el
in elementlist
:
267 if not el
.subelements
:
269 print('extern const struct ebml_elem_desc %s_desc;' % el
.structname
)
272 print('#define MAX_EBML_SUBELEMENTS %d' % max(len(el
.subelements
)
273 for el
in elementlist
))
277 def generate_C_definitions():
278 print('// Generated by TOOLS/matroska.py, do not edit manually')
280 for el
in reversed(elementlist
):
283 print('#define N %s' % el
.fieldname
)
284 print('E_S("%s", %d)' % (el
.name
, len(el
.subelements
)))
285 for subel
, multiple
in el
.subelements
:
286 print('F(%s, %s, %d)' % (subel
.definename
, subel
.fieldname
,
291 print('E("%s", %s, %s)' % (el
.name
, el
.fieldname
, el
.ebmltype
))
305 while not ord(t
) & mask
:
317 while not ord(t
) & mask
:
320 t
= chr(ord(t
) & (mask
- 1))
322 return i
+1, byte2num(t
)
324 def read_str(s
, length
):
325 return read(s
, length
)
327 def read_uint(s
, length
):
331 def read_sint(s
, length
):
332 i
= read_uint(s
, length
)
333 mask
= 1 << (length
* 8 - 1)
338 def read_float(s
, length
):
342 f
= ldexp((i
& 0x7fffff) + (1 << 23), (i
>> 23 & 0xff) - 150)
346 f
= ldexp((i
& ((1 << 52) - 1)) + (1 << 52), (i
>> 52 & 0x7ff) - 1075)
353 def parse_one(s
, depth
, parent
, maxlen
):
354 elid
= read_id(s
).encode('hex')
355 elem
= elementd
.get(elid
)
356 if parent
is not None and elid
not in parent
.subids
and elid
not in ('ec', 'bf'):
357 print('Unexpected:', elid
)
359 raise NotImplementedError
360 size
, length
= read_vint(s
)
361 this_length
= len(elid
) / 2 + size
+ length
363 if elem
.valtype
!= 'skip':
364 print depth
, elid
, elem
.name
, 'size:', length
, 'value:',
365 if elem
.valtype
== 'sub':
366 print('subelements:')
368 length
-= parse_one(s
, depth
+ 1, elem
, length
)
371 elif elem
.valtype
== 'str':
372 print 'string', repr(read_str(s
, length
))
373 elif elem
.valtype
in ('binary', 'ebml_id'):
374 t
= read_str(s
, length
)
376 if elem
.valtype
== 'ebml_id':
377 idelem
= elementd
.get(t
.encode('hex'))
381 dec
= '(%s)' % idelem
.name
385 t
= '<skipped %d bytes>' % len(t
)
386 print 'binary', t
, dec
387 elif elem
.valtype
== 'uint':
388 print 'uint', read_uint(s
, length
)
389 elif elem
.valtype
== 'sint':
390 print 'sint', read_sint(s
, length
)
391 elif elem
.valtype
== 'float':
392 print 'float', read_float(s
, length
)
393 elif elem
.valtype
== 'skip':
396 raise NotImplementedError
398 print(depth
, 'Unknown element:', elid
, 'size:', length
)
402 def parse_toplevel(s
):
403 parse_one(s
, 0, None, 1 << 63)
405 if sys
.argv
[1] == '--generate-header':
407 elif sys
.argv
[1] == '--generate-definitions':
408 generate_C_definitions()
410 s
= open(sys
.argv
[1])