cpython/Lib/plat-mac/videoreader.py

292 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
#
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:
2003-04-09 10:25:43 -03:00
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
Merged revisions 62021,62029,62035-62038,62043-62044,62052-62053 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r62021 | benjamin.peterson | 2008-03-28 18:11:01 -0500 (Fri, 28 Mar 2008) | 2 lines NIL => NULL ........ r62029 | amaury.forgeotdarc | 2008-03-28 20:42:31 -0500 (Fri, 28 Mar 2008) | 3 lines Correctly call the base class tearDown(); otherwise running test_logging twice produce the errors we see on all buildbots ........ r62035 | raymond.hettinger | 2008-03-29 05:42:07 -0500 (Sat, 29 Mar 2008) | 1 line Be explicit about what efficient means. ........ r62036 | georg.brandl | 2008-03-29 06:46:18 -0500 (Sat, 29 Mar 2008) | 2 lines Fix capitalization. ........ r62037 | amaury.forgeotdarc | 2008-03-29 07:42:54 -0500 (Sat, 29 Mar 2008) | 5 lines lib2to3 should install a logging handler only when run as a main program, not when used as a library. This may please the buildbots, which fail when test_lib2to3 is run before test_logging. ........ r62043 | benjamin.peterson | 2008-03-29 10:24:25 -0500 (Sat, 29 Mar 2008) | 3 lines #2503 make singletons compared with "is" not == or != Thanks to Wummel for the patch ........ r62044 | gerhard.haering | 2008-03-29 14:11:52 -0500 (Sat, 29 Mar 2008) | 2 lines Documented the lastrowid attribute. ........ r62052 | benjamin.peterson | 2008-03-30 14:35:10 -0500 (Sun, 30 Mar 2008) | 2 lines Updated README regarding doc formats ........ r62053 | georg.brandl | 2008-03-30 14:41:39 -0500 (Sun, 30 Mar 2008) | 2 lines The other download formats will be available for 2.6 too. ........
2008-03-30 22:51:45 -03:00
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
Merged revisions 62021,62029,62035-62038,62043-62044,62052-62053 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r62021 | benjamin.peterson | 2008-03-28 18:11:01 -0500 (Fri, 28 Mar 2008) | 2 lines NIL => NULL ........ r62029 | amaury.forgeotdarc | 2008-03-28 20:42:31 -0500 (Fri, 28 Mar 2008) | 3 lines Correctly call the base class tearDown(); otherwise running test_logging twice produce the errors we see on all buildbots ........ r62035 | raymond.hettinger | 2008-03-29 05:42:07 -0500 (Sat, 29 Mar 2008) | 1 line Be explicit about what efficient means. ........ r62036 | georg.brandl | 2008-03-29 06:46:18 -0500 (Sat, 29 Mar 2008) | 2 lines Fix capitalization. ........ r62037 | amaury.forgeotdarc | 2008-03-29 07:42:54 -0500 (Sat, 29 Mar 2008) | 5 lines lib2to3 should install a logging handler only when run as a main program, not when used as a library. This may please the buildbots, which fail when test_lib2to3 is run before test_logging. ........ r62043 | benjamin.peterson | 2008-03-29 10:24:25 -0500 (Sat, 29 Mar 2008) | 3 lines #2503 make singletons compared with "is" not == or != Thanks to Wummel for the patch ........ r62044 | gerhard.haering | 2008-03-29 14:11:52 -0500 (Sat, 29 Mar 2008) | 2 lines Documented the lastrowid attribute. ........ r62052 | benjamin.peterson | 2008-03-30 14:35:10 -0500 (Sun, 30 Mar 2008) | 2 lines Updated README regarding doc formats ........ r62053 | georg.brandl | 2008-03-30 14:41:39 -0500 (Sun, 30 Mar 2008) | 2 lines The other download formats will be available for 2.6 too. ........
2008-03-30 22:51:45 -03:00
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
Merged revisions 62021,62029,62035-62038,62043-62044,62052-62053 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r62021 | benjamin.peterson | 2008-03-28 18:11:01 -0500 (Fri, 28 Mar 2008) | 2 lines NIL => NULL ........ r62029 | amaury.forgeotdarc | 2008-03-28 20:42:31 -0500 (Fri, 28 Mar 2008) | 3 lines Correctly call the base class tearDown(); otherwise running test_logging twice produce the errors we see on all buildbots ........ r62035 | raymond.hettinger | 2008-03-29 05:42:07 -0500 (Sat, 29 Mar 2008) | 1 line Be explicit about what efficient means. ........ r62036 | georg.brandl | 2008-03-29 06:46:18 -0500 (Sat, 29 Mar 2008) | 2 lines Fix capitalization. ........ r62037 | amaury.forgeotdarc | 2008-03-29 07:42:54 -0500 (Sat, 29 Mar 2008) | 5 lines lib2to3 should install a logging handler only when run as a main program, not when used as a library. This may please the buildbots, which fail when test_lib2to3 is run before test_logging. ........ r62043 | benjamin.peterson | 2008-03-29 10:24:25 -0500 (Sat, 29 Mar 2008) | 3 lines #2503 make singletons compared with "is" not == or != Thanks to Wummel for the patch ........ r62044 | gerhard.haering | 2008-03-29 14:11:52 -0500 (Sat, 29 Mar 2008) | 2 lines Documented the lastrowid attribute. ........ r62052 | benjamin.peterson | 2008-03-30 14:35:10 -0500 (Sun, 30 Mar 2008) | 2 lines Updated README regarding doc formats ........ r62053 | georg.brandl | 2008-03-30 14:41:39 -0500 (Sun, 30 Mar 2008) | 2 lines The other download formats will be available for 2.6 too. ........
2008-03-30 22:51:45 -03:00
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', end=' ')
print('Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data)))
2003-04-09 10:25:43 -03:00
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:
print('stopping at 20 frames so your disk does not fill up:-)')
2003-04-09 10:25:43 -03:00
break
print('Total frames:', num)
if __name__ == '__main__':
2003-04-09 10:25:43 -03:00
_test()
sys.exit(1)