Skip to content

Instantly share code, notes, and snippets.

@alastairmccormack
Created March 4, 2014 21:26
Show Gist options
  • Save alastairmccormack/9356075 to your computer and use it in GitHub Desktop.
Save alastairmccormack/9356075 to your computer and use it in GitHub Desktop.
MPEG 2 Transport Stream + MP2 Video DAR Aspect Detector
# An Display aspect ratio (DAR) detector for MPEG 2 Transport Streams with MP2 Video
import array
import logging
import sys
class NullHandler(logging.Handler):
def emit(self, record):
pass
h = NullHandler()
logger = logging.getLogger("mpeg2video")
logger.addHandler(h)
aspect_ratio_dict = [ False, "1:1", "4:3", "16:9", "2.21:1" ]
class mpeg2video(object):
file = None
def __init__(self, file_name):
self.file = open(file_name, "rb")
def get_aspect_ratio(self):
block_size = 1048576
file_header = array.array('B')
try:
file_header.fromfile(self.file, block_size)
except EOFError:
logger.debug("Could not read full block_size")
pass
for i in xrange(0,len(file_header)):
if (file_header[i] == 0 and
file_header[i+1] == 0 and
file_header[i+2] == 0x01 and
file_header[i+3] == 0xB3):
logger.debug("Found start code at %s", hex(i))
start_data = i + 4
aspect_frame_rate_byte = file_header[start_data+3]
logger.debug("aspect_frame_rate_byte: %s", hex(aspect_frame_rate_byte))
aspect_ratio_id = aspect_frame_rate_byte >> 4
aspect_ratio = aspect_ratio_dict[aspect_ratio_id]
return aspect_ratio
logger.warning("No start code or aspect key found")
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
m2v = mpeg2video(sys.argv[1])
print m2v.get_aspect_ratio()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment