| 1 |
# EBML/Matroska parser |
| 2 |
# Copyright (C) 2010, 2015 Johannes Sasongko <[email protected]> |
| 3 |
# |
| 4 |
# This program is free software; you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation; either version 2, or (at your option) |
| 7 |
# any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program; if not, write to the Free Software |
| 16 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 17 |
# |
| 18 |
# |
| 19 |
# The developers of the Exaile media player hereby grant permission |
| 20 |
# for non-GPL compatible GStreamer and Exaile plugins to be used and |
| 21 |
# distributed together with GStreamer and Exaile. This permission is |
| 22 |
# above and beyond the permissions granted by the GPL license by which |
| 23 |
# Exaile is covered. If you modify this code, you may extend this |
| 24 |
# exception to your version of the code, but you are not obligated to |
| 25 |
# do so. If you do not wish to do so, delete this exception statement |
| 26 |
# from your version. |
| 27 |
|
| 28 |
|
| 29 |
# This code is heavily based on public domain code by "Omion" (from the |
| 30 |
# Hydrogenaudio forums), as obtained from Matroska's Subversion repository at |
| 31 |
# revision 858 (2004-10-03), under "/trunk/Perl.Parser/MatroskaParser.pm". |
| 32 |
|
| 33 |
|
| 34 |
import sys |
| 35 |
from struct import pack, unpack |
| 36 |
from warnings import warn |
| 37 |
|
| 38 |
SINT, UINT, FLOAT, STRING, UTF8, DATE, MASTER, BINARY = range(8) |
| 39 |
|
| 40 |
|
| 41 |
class EbmlException(Exception): |
| 42 |
pass |
| 43 |
|
| 44 |
|
| 45 |
class EbmlWarning(Warning): |
| 46 |
pass |
| 47 |
|
| 48 |
|
| 49 |
class BinaryData(bytes): |
| 50 |
def __repr__(self): |
| 51 |
return "<BinaryData>" |
| 52 |
|
| 53 |
|
| 54 |
def bchr(n): |
| 55 |
"""chr() that always returns bytes in Python 2 and 3""" |
| 56 |
return pack('B', n) |
| 57 |
|
| 58 |
|
| 59 |
class Ebml: |
| 60 |
"""EBML parser. |
| 61 |
|
| 62 |
Usage: Ebml(location, tags).parse() |
| 63 |
where `tags` is a dictionary of the form {id: (name, type)}. |
| 64 |
""" |
| 65 |
|
| 66 |
## Constructor and destructor |
| 67 |
|
| 68 |
def __init__(self, location, tags): |
| 69 |
self.tags = tags |
| 70 |
self.open(location) |
| 71 |
|
| 72 |
def __del__(self): |
| 73 |
self.close() |
| 74 |
|
| 75 |
## File access. |
| 76 |
## These can be overridden to provide network support. |
| 77 |
|
| 78 |
def open(self, location): |
| 79 |
"""Open a location and set self.size.""" |
| 80 |
self.file = f = open(location, 'rb') |
| 81 |
f = self.file |
| 82 |
f.seek(0, 2) |
| 83 |
self.size = f.tell() |
| 84 |
f.seek(0, 0) |
| 85 |
|
| 86 |
def seek(self, offset, mode): |
| 87 |
self.file.seek(offset, mode) |
| 88 |
|
| 89 |
def tell(self): |
| 90 |
return self.file.tell() |
| 91 |
|
| 92 |
def read(self, length): |
| 93 |
return self.file.read(length) |
| 94 |
|
| 95 |
def close(self): |
| 96 |
self.file.close() |
| 97 |
|
| 98 |
## Element reading |
| 99 |
|
| 100 |
def readID(self): |
| 101 |
b = self.read(1) |
| 102 |
b1 = ord(b) |
| 103 |
if b1 & 0b10000000: # 1 byte |
| 104 |
return b |
| 105 |
elif b1 & 0b01000000: # 2 bytes |
| 106 |
return unpack(">H", b + self.read(1))[0] |
| 107 |
elif b1 & 0b00100000: # 3 bytes |
| 108 |
return unpack(">L", b"\0" + b + self.read(2))[0] |
| 109 |
elif b1 & 0b00010000: # 4 bytes |
| 110 |
return unpack(">L", b + self.read(3))[0] |
| 111 |
else: |
| 112 |
raise EbmlException("invalid element ID (leading byte 0x%02X)" % b1) |
| 113 |
|
| 114 |
def readSize(self): |
| 115 |
b1 = ord(self.read(1)) |
| 116 |
if b1 & 0b10000000: # 1 byte |
| 117 |
return b1 & 0b01111111 |
| 118 |
elif b1 & 0b01000000: # 2 bytes |
| 119 |
return unpack(">H", bchr(b1 & 0b00111111) + self.read(1))[0] |
| 120 |
elif b1 & 0b00100000: # 3 bytes |
| 121 |
return unpack(">L", b"\0" + bchr(b1 & 0b00011111) + self.read(2))[0] |
| 122 |
elif b1 & 0b00010000: # 4 bytes |
| 123 |
return unpack(">L", bchr(b1 & 0b00001111) + self.read(3))[0] |
| 124 |
elif b1 & 0x00001000: # 5 bytes |
| 125 |
return unpack(">Q", b"\0\0\0" + bchr(b1 & 0b00000111) + self.read(4))[0] |
| 126 |
elif b1 & 0b00000100: # 6 bytes |
| 127 |
return unpack(">Q", b"\0\0" + bchr(b1 & 0b0000011) + self.read(5))[0] |
| 128 |
elif b1 & 0b00000010: # 7 bytes |
| 129 |
return unpack(">Q", b"\0" + bchr(b1 & 0b00000001) + self.read(6))[0] |
| 130 |
elif b1 & 0b00000001: # 8 bytes |
| 131 |
return unpack(">Q", b"\0" + self.read(7))[0] |
| 132 |
else: |
| 133 |
assert b1 == 0 |
| 134 |
raise EbmlException("undefined element size") |
| 135 |
|
| 136 |
def readInteger(self, length, signed): |
| 137 |
if length == 1: |
| 138 |
value = ord(self.read(1)) |
| 139 |
elif length == 2: |
| 140 |
value = unpack(">H", self.read(2))[0] |
| 141 |
elif length == 3: |
| 142 |
value = unpack(">L", b"\0" + self.read(3))[0] |
| 143 |
elif length == 4: |
| 144 |
value = unpack(">L", self.read(4))[0] |
| 145 |
elif length == 5: |
| 146 |
value = unpack(">Q", b"\0\0\0" + self.read(5))[0] |
| 147 |
elif length == 6: |
| 148 |
value = unpack(">Q", b"\0\0" + self.read(6))[0] |
| 149 |
elif length == 7: |
| 150 |
value = unpack(">Q", b"\0" + (self.read(7)))[0] |
| 151 |
elif length == 8: |
| 152 |
value = unpack(">Q", self.read(8))[0] |
| 153 |
else: |
| 154 |
raise EbmlException("don't know how to read %r-byte integer" % length) |
| 155 |
if signed: |
| 156 |
nbits = (8 - length) + 8 * (length - 1) |
| 157 |
if value >= (1 << (nbits - 1)): |
| 158 |
value -= 1 << nbits |
| 159 |
return value |
| 160 |
|
| 161 |
def readFloat(self, length): |
| 162 |
if length == 4: |
| 163 |
return unpack('>f', self.read(4))[0] |
| 164 |
elif length == 8: |
| 165 |
return unpack('>d', self.read(8))[0] |
| 166 |
else: |
| 167 |
raise EbmlException("don't know how to read %r-byte float" % length) |
| 168 |
|
| 169 |
## Parsing |
| 170 |
|
| 171 |
def parse(self, from_=0, to=None): |
| 172 |
"""Parses EBML from `from_` (inclusive) to `to` (exclusive). |
| 173 |
|
| 174 |
Note that not all streams support seeking backwards, so prepare to handle |
| 175 |
an exception if you try to parse from arbitrary position. |
| 176 |
""" |
| 177 |
if to is None: |
| 178 |
to = self.size |
| 179 |
self.seek(from_, 0) |
| 180 |
node = {} |
| 181 |
# Iterate over current node's children. |
| 182 |
while self.tell() < to: |
| 183 |
try: |
| 184 |
id = self.readID() |
| 185 |
except EbmlException as e: |
| 186 |
# Invalid EBML header. We can't reliably get any more data from |
| 187 |
# this level, so just return anything we have. |
| 188 |
warn(EbmlWarning(e)) |
| 189 |
return node |
| 190 |
size = self.readSize() |
| 191 |
if size == 0b01111111: |
| 192 |
warn(EbmlWarning("don't know how to handle unknown-sized element")) |
| 193 |
size = to - self.tell() |
| 194 |
try: |
| 195 |
key, type_ = self.tags[id] |
| 196 |
except KeyError: |
| 197 |
self.seek(size, 1) |
| 198 |
continue |
| 199 |
try: |
| 200 |
if type_ is SINT: |
| 201 |
value = self.readInteger(size, True) |
| 202 |
elif type_ is UINT: |
| 203 |
value = self.readInteger(size, False) |
| 204 |
elif type_ is FLOAT: |
| 205 |
value = self.readFloat(size) |
| 206 |
elif type_ is STRING: |
| 207 |
value = self.read(size).decode('ascii') |
| 208 |
elif type_ is UTF8: |
| 209 |
value = self.read(size).decode('utf-8') |
| 210 |
elif type_ is DATE: |
| 211 |
us = self.readInteger(size, True) / 1000.0 # ns to us |
| 212 |
from datetime import datetime, timedelta |
| 213 |
|
| 214 |
value = datetime(2001, 1, 1) + timedelta(microseconds=us) |
| 215 |
elif type_ is MASTER: |
| 216 |
tell = self.tell() |
| 217 |
value = self.parse(tell, tell + size) |
| 218 |
elif type_ is BINARY: |
| 219 |
value = BinaryData(self.read(size)) |
| 220 |
else: |
| 221 |
assert False, type_ |
| 222 |
except (EbmlException, UnicodeDecodeError) as e: |
| 223 |
warn(EbmlWarning(e)) |
| 224 |
else: |
| 225 |
try: |
| 226 |
parentval = node[key] |
| 227 |
except KeyError: |
| 228 |
parentval = node[key] = [] |
| 229 |
parentval.append(value) |
| 230 |
return node |
| 231 |
|
| 232 |
|
| 233 |
## GIO-specific code |
| 234 |
|
| 235 |
from gi.repository import Gio |
| 236 |
|
| 237 |
|
| 238 |
class GioEbml(Ebml): |
| 239 |
# NOTE: All seeks are faked using InputStream.skip because we need to use |
| 240 |
# BufferedInputStream but it does not implement Seekable. |
| 241 |
|
| 242 |
def open(self, location): |
| 243 |
f = Gio.File.new_for_commandline_arg(location) |
| 244 |
self.buffer = Gio.BufferedInputStream.new(f.read()) |
| 245 |
self._tell = 0 |
| 246 |
|
| 247 |
self.size = f.query_info( |
| 248 |
'standard::size', Gio.FileQueryInfoFlags.NONE, None |
| 249 |
).get_size() |
| 250 |
|
| 251 |
def seek(self, offset, mode): |
| 252 |
if mode == 0: |
| 253 |
skip = offset - self._tell |
| 254 |
elif mode == 1: |
| 255 |
skip = offset |
| 256 |
elif mode == 2: |
| 257 |
skip = self.size - self._tell + offset |
| 258 |
else: |
| 259 |
raise ValueError("invalid seek mode: %r" % mode) |
| 260 |
if skip < 0: |
| 261 |
raise NotImplementedError("seeking backwards not supported") |
| 262 |
self._tell += skip |
| 263 |
self.buffer.skip(skip) |
| 264 |
|
| 265 |
def tell(self): |
| 266 |
return self._tell |
| 267 |
|
| 268 |
def read(self, length): |
| 269 |
result = self.buffer.read_bytes(length).get_data() |
| 270 |
self._tell += len(result) |
| 271 |
return result |
| 272 |
|
| 273 |
def close(self): |
| 274 |
self.buffer.close() |
| 275 |
|
| 276 |
|
| 277 |
## Matroska-specific code |
| 278 |
|
| 279 |
# Interesting Matroska tags. |
| 280 |
# Tags not defined here are skipped while parsing. |
| 281 |
MatroskaTags = { |
| 282 |
# Segment |
| 283 |
0x18538067: ('Segment', MASTER), |
| 284 |
# Segment Information |
| 285 |
0x1549A966: ('Info', MASTER), |
| 286 |
0x7384: ('SegmentFilename', UTF8), |
| 287 |
0x2AD7B1: ('TimecodeScale', UINT), |
| 288 |
0x4489: ('Duration', FLOAT), |
| 289 |
0x4461: ('DateUTC', DATE), |
| 290 |
0x7BA9: ('Title', UTF8), |
| 291 |
0x4D80: ('MuxingApp', UTF8), |
| 292 |
0x5741: ('WritingApp', UTF8), |
| 293 |
# Track |
| 294 |
0x1654AE6B: ('Tracks', MASTER), |
| 295 |
0xAE: ('TrackEntry', MASTER), |
| 296 |
0xD7: ('TrackNumber', UINT), |
| 297 |
0x83: ('TrackType', UINT), |
| 298 |
0xB9: ('FlagEnabled', UINT), |
| 299 |
0x88: ('FlagDefault', UINT), |
| 300 |
0x23E383: ('DefaultDuration', UINT), |
| 301 |
0x536E: ('Name', UTF8), |
| 302 |
0x22B59C: ('Language', STRING), |
| 303 |
0x86: ('CodecID', STRING), |
| 304 |
0x258688: ('CodecName', UTF8), |
| 305 |
# Video |
| 306 |
0xE0: ('Video', MASTER), |
| 307 |
# Audio |
| 308 |
0xE1: ('Audio', MASTER), |
| 309 |
0xB5: ('SamplingFrequency', FLOAT), |
| 310 |
0x78B5: ('OutputSamplingFrequency', FLOAT), |
| 311 |
0x9F: ('Channels', UINT), |
| 312 |
0x6264: ('BitDepth', UINT), |
| 313 |
# Attachment |
| 314 |
0x1941A469: ('Attachments', MASTER), |
| 315 |
0x61A7: ('AttachedFile', MASTER), |
| 316 |
0x466E: ('FileName', UTF8), |
| 317 |
0x465C: ('FileData', BINARY), |
| 318 |
# Chapters |
| 319 |
0x1043A770: ('Chapters', MASTER), |
| 320 |
0x45B9: ('EditionEntry', MASTER), |
| 321 |
0x45BC: ('EditionUID', UINT), |
| 322 |
0x45BD: ('EditionFlagHidden', UINT), |
| 323 |
0x45DB: ('EditionFlagDefault', UINT), |
| 324 |
0x45DD: ('EditionFlagOrdered', UINT), |
| 325 |
0xB6: ('ChapterAtom', MASTER), |
| 326 |
0x73C4: ('ChapterUID', UINT), |
| 327 |
0x91: ('ChapterTimeStart', UINT), |
| 328 |
0x92: ('ChapterTimeEnd', UINT), |
| 329 |
0x98: ('ChapterFlagHidden', UINT), |
| 330 |
0x4598: ('ChapterFlagEnabled', UINT), |
| 331 |
0x63C3: ('ChapterPhysicalEquiv', UINT), |
| 332 |
0x8F: ('ChapterTrack', MASTER), |
| 333 |
0x89: ('ChapterTrackNumber', UINT), |
| 334 |
0x80: ('ChapterDisplay', MASTER), |
| 335 |
0x85: ('ChapString', UTF8), |
| 336 |
0x437C: ('ChapLanguage', STRING), |
| 337 |
0x437E: ('ChapCountry', STRING), |
| 338 |
# Tagging |
| 339 |
0x1254C367: ('Tags', MASTER), |
| 340 |
0x7373: ('Tag', MASTER), |
| 341 |
0x63C0: ('Targets', MASTER), |
| 342 |
0x68CA: ('TargetTypevalue', UINT), |
| 343 |
0x63CA: ('TargetType', STRING), |
| 344 |
0x63C5: ('TagTrackUID', UINT), |
| 345 |
0x63C9: ('TagEditionUID', UINT), |
| 346 |
0x63C4: ('TagChapterUID', UINT), |
| 347 |
0x67C8: ('SimpleTag', MASTER), |
| 348 |
0x45A3: ('TagName', UTF8), |
| 349 |
0x447A: ('TagLanguage', STRING), |
| 350 |
0x4484: ('TagDefault', UINT), |
| 351 |
0x4487: ('TagString', UTF8), |
| 352 |
0x4485: ('TagBinary', BINARY), |
| 353 |
} |
| 354 |
|
| 355 |
|
| 356 |
def parse(location): |
| 357 |
return GioEbml(location, MatroskaTags).parse() |
| 358 |
|
| 359 |
|
| 360 |
def dump(location): |
| 361 |
from pprint import pprint |
| 362 |
|
| 363 |
pprint(parse(location)) |
| 364 |
|
| 365 |
|
| 366 |
def dump_tags(location): |
| 367 |
from pprint import pprint |
| 368 |
|
| 369 |
mka = parse(location) |
| 370 |
segment = mka['Segment'][0] |
| 371 |
info = segment['Info'][0] |
| 372 |
try: |
| 373 |
timecodescale = info['TimecodeScale'][0] |
| 374 |
except KeyError: |
| 375 |
timecodescale = 1000000 |
| 376 |
length = info['Duration'][0] * timecodescale / 1e9 |
| 377 |
print("Length = %s seconds" % length) |
| 378 |
pprint(segment['Tags'][0]['Tag']) |
| 379 |
|
| 380 |
|
| 381 |
def gio_location(location): |
| 382 |
"""Convert location to GIO-compatible location. |
| 383 |
|
| 384 |
This works around broken behaviour in the Win32 GIO port (it converts paths |
| 385 |
into UTF-8 and requires them to be specified in UTF-8 as well). |
| 386 |
|
| 387 |
:type location: str |
| 388 |
:rtype: bytes |
| 389 |
""" |
| 390 |
if sys.platform == 'win32' and '://' not in location: |
| 391 |
if isinstance(location, bytes): |
| 392 |
# Decode the path according to the FS encoding to get the Unicode |
| 393 |
# representation first. If the path is in a different encoding, |
| 394 |
# this step will fail. |
| 395 |
location = location.decode(sys.getfilesystemencoding()) |
| 396 |
location = location.encode('utf-8') |
| 397 |
return location |
| 398 |
|
| 399 |
|
| 400 |
if __name__ == '__main__': |
| 401 |
location = gio_location(sys.argv[1]) |
| 402 |
dump_tags(location) |
| 403 |
|
| 404 |
|
| 405 |
# vi: et sts=4 sw=4 ts=4 |