MpegImagePlugin.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. msg = "not an MPEG file"
  54. raise SyntaxError(msg)
  55. self._mode = "RGB"
  56. self._size = s.read(12), s.read(12)
  57. # --------------------------------------------------------------------
  58. # Registry stuff
  59. Image.register_open(MpegImageFile.format, MpegImageFile)
  60. Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"])
  61. Image.register_mime(MpegImageFile.format, "video/mpeg")