cpython/Lib/plat-mac/videoreader.py

297 lines
10 KiB
Python
Raw Normal View History

# Video file reader, using QuickTime
#
# This module was quickly ripped out of another software package, so there is a good
# chance that it does not work as-is and it needs some hacking.
#
# Jack Jansen, August 2000
#
from warnings import warnpy3k
warnpy3k("In 3.x, the videoreader module is removed.", stacklevel=2)
import sys
from Carbon import Qt
from Carbon import QuickTime
from Carbon import Qd
from Carbon import Qdoffs
from Carbon import QDOffscreen
from Carbon import Res
try:
Merged revisions 68133-68134,68141-68142,68145-68146,68148-68149,68159-68162,68166,68171-68174,68179,68195-68196,68210,68214-68215,68217-68222 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r68133 | antoine.pitrou | 2009-01-01 16:38:03 +0100 (Thu, 01 Jan 2009) | 1 line fill in actual issue number in tests ........ r68134 | hirokazu.yamamoto | 2009-01-01 16:45:39 +0100 (Thu, 01 Jan 2009) | 2 lines Issue #4797: IOError.filename was not set when _fileio.FileIO failed to open file with `str' filename on Windows. ........ r68141 | benjamin.peterson | 2009-01-01 17:43:12 +0100 (Thu, 01 Jan 2009) | 1 line fix highlighting ........ r68142 | benjamin.peterson | 2009-01-01 18:29:49 +0100 (Thu, 01 Jan 2009) | 2 lines welcome to 2009, Python! ........ r68145 | amaury.forgeotdarc | 2009-01-02 01:03:54 +0100 (Fri, 02 Jan 2009) | 5 lines #4801 _collections module fails to build on cygwin. _PyObject_GC_TRACK is the macro version of PyObject_GC_Track, and according to documentation it should not be used for extension modules. ........ r68146 | ronald.oussoren | 2009-01-02 11:44:46 +0100 (Fri, 02 Jan 2009) | 2 lines Fix for issue4472: "configure --enable-shared doesn't work on OSX" ........ r68148 | ronald.oussoren | 2009-01-02 11:48:31 +0100 (Fri, 02 Jan 2009) | 2 lines Forgot to add a NEWS item in my previous checkin ........ r68149 | ronald.oussoren | 2009-01-02 11:50:48 +0100 (Fri, 02 Jan 2009) | 2 lines Fix for issue4780 ........ r68159 | ronald.oussoren | 2009-01-02 15:48:17 +0100 (Fri, 02 Jan 2009) | 2 lines Fix for issue 1627952 ........ r68160 | ronald.oussoren | 2009-01-02 15:52:09 +0100 (Fri, 02 Jan 2009) | 2 lines Fix for issue r1737832 ........ r68161 | ronald.oussoren | 2009-01-02 16:00:05 +0100 (Fri, 02 Jan 2009) | 3 lines Fix for issue 1149804 ........ r68162 | ronald.oussoren | 2009-01-02 16:06:00 +0100 (Fri, 02 Jan 2009) | 3 lines Fix for issue 4472 is incompatible with Cygwin, this patch should fix that. ........ r68166 | benjamin.peterson | 2009-01-02 19:26:23 +0100 (Fri, 02 Jan 2009) | 1 line document PyMemberDef ........ r68171 | georg.brandl | 2009-01-02 21:25:14 +0100 (Fri, 02 Jan 2009) | 3 lines #4811: fix markup glitches (mostly remains of the conversion), found by Gabriel Genellina. ........ r68172 | martin.v.loewis | 2009-01-02 21:32:55 +0100 (Fri, 02 Jan 2009) | 2 lines Issue #4075: Use OutputDebugStringW in Py_FatalError. ........ r68173 | martin.v.loewis | 2009-01-02 21:40:14 +0100 (Fri, 02 Jan 2009) | 2 lines Issue #4051: Prevent conflict of UNICODE macros in cPickle. ........ r68174 | benjamin.peterson | 2009-01-02 21:47:27 +0100 (Fri, 02 Jan 2009) | 1 line fix compilation on non-Windows platforms ........ r68179 | raymond.hettinger | 2009-01-02 22:26:45 +0100 (Fri, 02 Jan 2009) | 1 line Issue #4615. Document how to use itertools for de-duping. ........ r68195 | georg.brandl | 2009-01-03 14:45:15 +0100 (Sat, 03 Jan 2009) | 2 lines Remove useless string literal. ........ r68196 | georg.brandl | 2009-01-03 15:29:53 +0100 (Sat, 03 Jan 2009) | 2 lines Fix indentation. ........ r68210 | georg.brandl | 2009-01-03 20:10:12 +0100 (Sat, 03 Jan 2009) | 2 lines Set eol-style correctly for mp_distributing.py. ........ r68214 | georg.brandl | 2009-01-03 20:44:48 +0100 (Sat, 03 Jan 2009) | 2 lines Make indentation consistent. ........ r68215 | georg.brandl | 2009-01-03 21:15:14 +0100 (Sat, 03 Jan 2009) | 2 lines Fix role name. ........ r68217 | georg.brandl | 2009-01-03 21:30:15 +0100 (Sat, 03 Jan 2009) | 2 lines Add rstlint, a little tool to find subtle markup problems and inconsistencies in the Doc sources. ........ r68218 | georg.brandl | 2009-01-03 21:38:59 +0100 (Sat, 03 Jan 2009) | 2 lines Recognize usage of the default role. ........ r68219 | georg.brandl | 2009-01-03 21:47:01 +0100 (Sat, 03 Jan 2009) | 2 lines Fix uses of the default role. ........ r68220 | georg.brandl | 2009-01-03 21:55:06 +0100 (Sat, 03 Jan 2009) | 2 lines Remove trailing whitespace. ........ r68221 | georg.brandl | 2009-01-03 22:04:55 +0100 (Sat, 03 Jan 2009) | 2 lines Remove tabs from the documentation. ........ r68222 | georg.brandl | 2009-01-03 22:11:58 +0100 (Sat, 03 Jan 2009) | 2 lines Disable the line length checker by default. ........
2009-01-03 17:55:17 -04:00
from Carbon import MediaDescr
except ImportError:
2003-04-09 10:25:43 -03:00
def _audiodescr(data):
return None
else:
2003-04-09 10:25:43 -03:00
def _audiodescr(data):
return MediaDescr.SoundDescription.decode(data)
try:
2003-04-09 10:25:43 -03:00
from imgformat import macrgb
except ImportError:
2003-04-09 10:25:43 -03:00
macrgb = "Macintosh RGB format"
import os
# import audio.format
class VideoFormat:
2003-04-09 10:25:43 -03:00
def __init__(self, name, descr, width, height, format):
self.__name = name
self.__descr = descr
self.__width = width
self.__height = height
self.__format = format
2003-04-09 10:25:43 -03:00
def getname(self):
return self.__name
2003-04-09 10:25:43 -03:00
def getdescr(self):
return self.__descr
2003-04-09 10:25:43 -03:00
def getsize(self):
return self.__width, self.__height
2003-04-09 10:25:43 -03:00
def getformat(self):
return self.__format
class _Reader:
2003-04-09 10:25:43 -03:00
def __init__(self, path):
fd = Qt.OpenMovieFile(path, 0)
self.movie, d1, d2 = Qt.NewMovieFromFile(fd, 0, 0)
self.movietimescale = self.movie.GetMovieTimeScale()
try:
self.audiotrack = self.movie.GetMovieIndTrackType(1,
QuickTime.AudioMediaCharacteristic, QuickTime.movieTrackCharacteristic)
self.audiomedia = self.audiotrack.GetTrackMedia()
except Qt.Error:
self.audiotrack = self.audiomedia = None
self.audiodescr = {}
else:
handle = Res.Handle('')
n = self.audiomedia.GetMediaSampleDescriptionCount()
self.audiomedia.GetMediaSampleDescription(1, handle)
self.audiodescr = _audiodescr(handle.data)
self.audiotimescale = self.audiomedia.GetMediaTimeScale()
del handle
try:
2003-04-09 10:25:43 -03:00
self.videotrack = self.movie.GetMovieIndTrackType(1,
QuickTime.VisualMediaCharacteristic, QuickTime.movieTrackCharacteristic)
self.videomedia = self.videotrack.GetTrackMedia()
except Qt.Error:
self.videotrack = self.videomedia = self.videotimescale = None
if self.videotrack:
self.videotimescale = self.videomedia.GetMediaTimeScale()
x0, y0, x1, y1 = self.movie.GetMovieBox()
self.videodescr = {'width':(x1-x0), 'height':(y1-y0)}
self._initgworld()
self.videocurtime = None
self.audiocurtime = None
2003-04-09 10:25:43 -03:00
def __del__(self):
self.audiomedia = None
self.audiotrack = None
self.videomedia = None
self.videotrack = None
self.movie = None
2003-04-09 10:25:43 -03:00
def _initgworld(self):
old_port, old_dev = Qdoffs.GetGWorld()
try:
movie_w = self.videodescr['width']
movie_h = self.videodescr['height']
movie_rect = (0, 0, movie_w, movie_h)
self.gworld = Qdoffs.NewGWorld(32, movie_rect, None, None, QDOffscreen.keepLocal)
self.pixmap = self.gworld.GetGWorldPixMap()
Qdoffs.LockPixels(self.pixmap)
Qdoffs.SetGWorld(self.gworld.as_GrafPtr(), None)
Qd.EraseRect(movie_rect)
self.movie.SetMovieGWorld(self.gworld.as_GrafPtr(), None)
self.movie.SetMovieBox(movie_rect)
self.movie.SetMovieActive(1)
self.movie.MoviesTask(0)
self.movie.SetMoviePlayHints(QuickTime.hintsHighQuality, QuickTime.hintsHighQuality)
# XXXX framerate
finally:
Qdoffs.SetGWorld(old_port, old_dev)
2003-04-09 10:25:43 -03:00
def _gettrackduration_ms(self, track):
tracktime = track.GetTrackDuration()
return self._movietime_to_ms(tracktime)
2003-04-09 10:25:43 -03:00
def _movietime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.movietimescale, None), 1000)
return value
2003-04-09 10:25:43 -03:00
def _videotime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.videotimescale, None), 1000)
return value
2003-04-09 10:25:43 -03:00
def _audiotime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.audiotimescale, None), 1000)
return value
2003-04-09 10:25:43 -03:00
def _videotime_to_movietime(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.videotimescale, None),
self.movietimescale)
return value
2003-04-09 10:25:43 -03:00
def HasAudio(self):
return not self.audiotrack is None
2003-04-09 10:25:43 -03:00
def HasVideo(self):
return not self.videotrack is None
2003-04-09 10:25:43 -03:00
def GetAudioDuration(self):
if not self.audiotrack:
return 0
return self._gettrackduration_ms(self.audiotrack)
2003-04-09 10:25:43 -03:00
def GetVideoDuration(self):
if not self.videotrack:
return 0
return self._gettrackduration_ms(self.videotrack)
2003-04-09 10:25:43 -03:00
def GetAudioFormat(self):
if not self.audiodescr:
return None, None, None, None, None
bps = self.audiodescr['sampleSize']
nch = self.audiodescr['numChannels']
if nch == 1:
channels = ['mono']
elif nch == 2:
channels = ['left', 'right']
else:
channels = map(lambda x: str(x+1), range(nch))
if bps % 8:
# Funny bits-per sample. We pretend not to understand
blocksize = 0
fpb = 0
else:
# QuickTime is easy (for as far as we support it): samples are always a whole
# number of bytes, so frames are nchannels*samplesize, and there's one frame per block.
blocksize = (bps/8)*nch
fpb = 1
if self.audiodescr['dataFormat'] == 'raw ':
encoding = 'linear-excess'
elif self.audiodescr['dataFormat'] == 'twos':
encoding = 'linear-signed'
else:
encoding = 'quicktime-coding-%s'%self.audiodescr['dataFormat']
## return audio.format.AudioFormatLinear('quicktime_audio', 'QuickTime Audio Format',
2003-04-09 10:25:43 -03:00
## channels, encoding, blocksize=blocksize, fpb=fpb, bps=bps)
return channels, encoding, blocksize, fpb, bps
2003-04-09 10:25:43 -03:00
def GetAudioFrameRate(self):
if not self.audiodescr:
return None
return int(self.audiodescr['sampleRate'])
2003-04-09 10:25:43 -03:00
def GetVideoFormat(self):
width = self.videodescr['width']
height = self.videodescr['height']
return VideoFormat('dummy_format', 'Dummy Video Format', width, height, macrgb)
2003-04-09 10:25:43 -03:00
def GetVideoFrameRate(self):
tv = self.videocurtime
if tv is None:
2003-04-09 10:25:43 -03:00
tv = 0
flags = QuickTime.nextTimeStep|QuickTime.nextTimeEdgeOK
tv, dur = self.videomedia.GetMediaNextInterestingTime(flags, tv, 1.0)
dur = self._videotime_to_ms(dur)
return int((1000.0/dur)+0.5)
2003-04-09 10:25:43 -03:00
def ReadAudio(self, nframes, time=None):
if not time is None:
self.audiocurtime = time
flags = QuickTime.nextTimeStep|QuickTime.nextTimeEdgeOK
if self.audiocurtime is None:
2003-04-09 10:25:43 -03:00
self.audiocurtime = 0
tv = self.audiomedia.GetMediaNextInterestingTimeOnly(flags, self.audiocurtime, 1.0)
if tv < 0 or (self.audiocurtime and tv < self.audiocurtime):
return self._audiotime_to_ms(self.audiocurtime), None
h = Res.Handle('')
desc_h = Res.Handle('')
size, actualtime, sampleduration, desc_index, actualcount, flags = \
self.audiomedia.GetMediaSample(h, 0, tv, desc_h, nframes)
self.audiocurtime = actualtime + actualcount*sampleduration
return self._audiotime_to_ms(actualtime), h.data
2003-04-09 10:25:43 -03:00
def ReadVideo(self, time=None):
if not time is None:
self.videocurtime = time
flags = QuickTime.nextTimeStep
if self.videocurtime is None:
2003-04-09 10:25:43 -03:00
flags = flags | QuickTime.nextTimeEdgeOK
self.videocurtime = 0
tv = self.videomedia.GetMediaNextInterestingTimeOnly(flags, self.videocurtime, 1.0)
if tv < 0 or (self.videocurtime and tv <= self.videocurtime):
return self._videotime_to_ms(self.videocurtime), None
self.videocurtime = tv
moviecurtime = self._videotime_to_movietime(self.videocurtime)
self.movie.SetMovieTimeValue(moviecurtime)
self.movie.MoviesTask(0)
return self._videotime_to_ms(self.videocurtime), self._getpixmapcontent()
2003-04-09 10:25:43 -03:00
def _getpixmapcontent(self):
"""Shuffle the offscreen PixMap data, because it may have funny stride values"""
rowbytes = Qdoffs.GetPixRowBytes(self.pixmap)
width = self.videodescr['width']
height = self.videodescr['height']
start = 0
rv = ''
for i in range(height):
nextline = Qdoffs.GetPixMapBytes(self.pixmap, start, width*4)
start = start + rowbytes
rv = rv + nextline
return rv
def reader(url):
2003-04-09 10:25:43 -03:00
try:
rdr = _Reader(url)
except IOError:
return None
return rdr
def _test():
2003-04-09 10:25:43 -03:00
import EasyDialogs
try:
import img
except ImportError:
img = None
import MacOS
Qt.EnterMovies()
path = EasyDialogs.AskFileForOpen(message='Video to convert')
if not path: sys.exit(0)
rdr = reader(path)
if not rdr:
sys.exit(1)
dstdir = EasyDialogs.AskFileForSave(message='Name for output folder')
if not dstdir: sys.exit(0)
num = 0
os.mkdir(dstdir)
videofmt = rdr.GetVideoFormat()
imgfmt = videofmt.getformat()
imgw, imgh = videofmt.getsize()
timestamp, data = rdr.ReadVideo()
while data:
fname = 'frame%04.4d.jpg'%num
num = num+1
pname = os.path.join(dstdir, fname)
if not img: print 'Not',
print 'Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data))
if img:
wrt = img.writer(imgfmt, pname)
wrt.width = imgw
wrt.height = imgh
wrt.write(data)
timestamp, data = rdr.ReadVideo()
MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG')
if num > 20:
2003-04-09 10:25:43 -03:00
print 'stopping at 20 frames so your disk does not fill up:-)'
break
print 'Total frames:', num
if __name__ == '__main__':
2003-04-09 10:25:43 -03:00
_test()
sys.exit(1)