MpegImagePlugin.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # MPEG file handling
  6. #
  7. # History:
  8. # 95-09-09 fl Created
  9. #
  10. # Copyright (c) Secret Labs AB 1997.
  11. # Copyright (c) Fredrik Lundh 1995.
  12. #
  13. # See the README file for information on usage and redistribution.
  14. #
  15. from . import Image, ImageFile
  16. from ._binary import i8
  17. #
  18. # Bitstream parser
  19. class BitStream:
  20. def __init__(self, fp):
  21. self.fp = fp
  22. self.bits = 0
  23. self.bitbuffer = 0
  24. def next(self):
  25. return i8(self.fp.read(1))
  26. def peek(self, bits):
  27. while self.bits < bits:
  28. c = self.next()
  29. if c < 0:
  30. self.bits = 0
  31. continue
  32. self.bitbuffer = (self.bitbuffer << 8) + c
  33. self.bits += 8
  34. return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1
  35. def skip(self, bits):
  36. while self.bits < bits:
  37. self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1))
  38. self.bits += 8
  39. self.bits = self.bits - bits
  40. def read(self, bits):
  41. v = self.peek(bits)
  42. self.bits = self.bits - bits
  43. return v
  44. ##
  45. # Image plugin for MPEG streams. This plugin can identify a stream,
  46. # but it cannot read it.
  47. class MpegImageFile(ImageFile.ImageFile):
  48. format = "MPEG"
  49. format_description = "MPEG"
  50. def _open(self):
  51. s = BitStream(self.fp)
  52. if s.read(32) != 0x1B3:
  53. raise SyntaxError("not an MPEG file")
  54. self.mode = "RGB"
  55. self._size = s.read(12), s.read(12)
  56. # --------------------------------------------------------------------
  57. # Registry stuff
  58. Image.register_open(MpegImageFile.format, MpegImageFile)
  59. Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"])
  60. Image.register_mime(MpegImageFile.format, "video/mpeg")