spelling fixes
[mplayer/glamo.git] / TOOLS / matroska.py
bloba9e897fea495c326f9d6f8549ca9d3cc6346be4d
1 #!/usr/bin/python
2 """
3 Generate C definitions for parsing Matroska files.
4 Can also be used to directly parse Matroska files and display their contents.
5 """
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.
26 elements_ebml = (
27 'EBML, 1a45dfa3, sub', (
28 'EBMLVersion, 4286, uint',
29 'EBMLReadVersion, 42f7, uint',
30 'EBMLMaxIDLength, 42f2, uint',
31 'EBMLMaxSizeLength, 42f3, uint',
32 'DocType, 4282, str',
33 'DocTypeVersion, 4287, uint',
34 'DocTypeReadVersion, 4285, uint',
37 'CRC32, bf, binary',
38 'Void, ec, binary',
41 elements_matroska = (
42 'Segment, 18538067, sub', (
44 'SeekHead*, 114d9b74, sub', (
45 'Seek*, 4dbb, 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',
57 'Title, 7ba9, str',
58 'MuxingApp, 4d80, str',
59 'WritingApp, 5741, str',
60 'Duration, 4489, float',
63 'Cluster*, 1f43b675, sub', (
64 'Timecode, e7, uint',
65 'BlockGroup*, a0, sub', (
66 'Block, a1, binary',
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',
86 'Name, 536e, str',
87 'Language, 22b59c, str',
88 'CodecID, 86, str',
89 'CodecPrivate, 63a2, binary',
90 'CodecDecodeAll, aa, uint',
91 'Video, e0, sub', (
92 'FlagInterlaced, 9a, uint',
93 'PixelWidth, b0, uint',
94 'PixelHeight, ba, uint',
95 'DisplayWidth, 54b0, uint',
96 'DisplayHeight, 54ba, uint',
97 'FrameRate, 2383e3, float',
99 'Audio, e1, sub', (
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', (
120 'CueTime, b3, uint',
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', (
160 'Tag*, 7373, 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'
179 import sys
180 from math import ldexp
182 def byte2num(s):
183 return int(s.encode('hex'), 16)
185 def camelcase_to_words(name):
186 parts = []
187 start = 0
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])
192 start = i
193 parts.append(name[start:])
194 return '_'.join(parts).lower()
196 class MatroskaElement(object):
198 def __init__(self, name, elid, valtype, namespace):
199 self.name = name
200 self.definename = '%s_ID_%s' % (namespace, name.upper())
201 self.fieldname = camelcase_to_words(name)
202 self.structname = 'ebml_' + self.fieldname
203 self.elid = elid
204 self.valtype = valtype
205 if valtype == 'sub':
206 self.ebmltype = 'EBML_TYPE_SUBELEMENTS'
207 self.valname = 'struct %s' % self.structname
208 else:
209 self.ebmltype = 'EBML_TYPE_' + valtype.upper()
210 try:
211 self.valname = {'uint': 'uint64_t', 'str': 'struct bstr',
212 'binary': 'struct bstr', 'ebml_id': 'uint32_t',
213 'float': 'double', 'sint': 'int64_t',
214 }[valtype]
215 except KeyError:
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)
223 elementd = {}
224 elementlist = []
225 def parse_elems(l, namespace):
226 subelements = []
227 for el in l:
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))
236 else:
237 new.add_subelements(parse_elems(el, namespace))
238 return subelements
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')
245 print
247 for el in elementlist:
248 print('#define %-40s 0x%s' % (el.definename, el.elid))
250 print
252 for el in reversed(elementlist):
253 if not el.subelements:
254 continue
255 print
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],
260 subel.fieldname))
261 print
262 for subel, multiple in el.subelements:
263 print(' int n_%s;' % (subel.fieldname))
264 print('};')
266 for el in elementlist:
267 if not el.subelements:
268 continue
269 print('extern const struct ebml_elem_desc %s_desc;' % el.structname)
271 print
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')
279 print
280 for el in reversed(elementlist):
281 print
282 if el.subelements:
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,
287 multiple))
288 print('}};')
289 print('#undef N')
290 else:
291 print('E("%s", %s, %s)' % (el.name, el.fieldname, el.ebmltype))
293 def read(s, length):
294 t = s.read(length)
295 if len(t) != length:
296 raise IOError
297 return t
299 def read_id(s):
300 t = read(s, 1)
301 i = 0
302 mask = 128
303 if ord(t) == 0:
304 raise SyntaxError
305 while not ord(t) & mask:
306 i += 1
307 mask >>= 1
308 t += read(s, i)
309 return t
311 def read_vint(s):
312 t = read(s, 1)
313 i = 0
314 mask = 128
315 if ord(t) == 0:
316 raise SyntaxError
317 while not ord(t) & mask:
318 i += 1
319 mask >>= 1
320 t = chr(ord(t) & (mask - 1))
321 t += read(s, i)
322 return i+1, byte2num(t)
324 def read_str(s, length):
325 return read(s, length)
327 def read_uint(s, length):
328 t = read(s, length)
329 return byte2num(t)
331 def read_sint(s, length):
332 i = read_uint(s, length)
333 mask = 1 << (length * 8 - 1)
334 if i & mask:
335 i -= 2 * mask
336 return i
338 def read_float(s, length):
339 t = read(s, length)
340 i = byte2num(t)
341 if length == 4:
342 f = ldexp((i & 0x7fffff) + (1 << 23), (i >> 23 & 0xff) - 150)
343 if i & (1 << 31):
344 f = -f
345 elif length == 8:
346 f = ldexp((i & ((1 << 52) - 1)) + (1 << 52), (i >> 52 & 0x7ff) - 1075)
347 if i & (1 << 63):
348 f = -f
349 else:
350 raise SyntaxError
351 return f
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)
358 if 1:
359 raise NotImplementedError
360 size, length = read_vint(s)
361 this_length = len(elid) / 2 + size + length
362 if elem is not None:
363 if elem.valtype != 'skip':
364 print depth, elid, elem.name, 'size:', length, 'value:',
365 if elem.valtype == 'sub':
366 print('subelements:')
367 while length > 0:
368 length -= parse_one(s, depth + 1, elem, length)
369 if length < 0:
370 raise SyntaxError
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)
375 dec = ''
376 if elem.valtype == 'ebml_id':
377 idelem = elementd.get(t.encode('hex'))
378 if idelem is None:
379 dec = '(UNKNOWN)'
380 else:
381 dec = '(%s)' % idelem.name
382 if len(t) < 20:
383 t = t.encode('hex')
384 else:
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':
394 read(s, length)
395 else:
396 raise NotImplementedError
397 else:
398 print(depth, 'Unknown element:', elid, 'size:', length)
399 read(s, length)
400 return this_length
402 def parse_toplevel(s):
403 parse_one(s, 0, None, 1 << 63)
405 if sys.argv[1] == '--generate-header':
406 generate_C_header()
407 elif sys.argv[1] == '--generate-definitions':
408 generate_C_definitions()
409 else:
410 s = open(sys.argv[1])
411 while 1:
412 parse_toplevel(s)