Update of /cvsroot/freevo/kaa/thumb/src
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21497

Modified Files:
        __init__.py interface.py 
Added Files:
        videothumb.py 
Log Message:
add freevo videothumb module

Index: interface.py
===================================================================
RCS file: /cvsroot/freevo/kaa/thumb/src/interface.py,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -d -r1.3 -r1.4
*** interface.py        7 Jul 2005 17:59:06 -0000       1.3
--- interface.py        27 Aug 2005 15:26:33 -0000      1.4
***************
*** 83,87 ****
  
  
- 
  def check(file, size = NORMAL, destdir = DOT_THUMBNAIL, url = None):
      """
--- 83,86 ----

--- NEW FILE: videothumb.py ---
# -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------------
# videothumb - create a thumbnail for video files
# -----------------------------------------------------------------------------
# $Id: videothumb.py,v 1.1 2005/08/27 15:26:33 dischi Exp $
#
# This file provides a function to create video thumbnails in the background.
# It will start a mplayer childapp to create the thumbnail. It uses the
# notifier loop to do this without blocking.
#
# Loosly based on videothumb.py commited to the freevo wiki
#
# -----------------------------------------------------------------------------
# Freevo - A Home Theater PC framework
# Copyright (C) 2002-2004 Krister Lagerstrom, Dirk Meyer, et al.
#
# First Edition: Dirk Meyer <[EMAIL PROTECTED]>
# Maintainer:    Dirk Meyer <[EMAIL PROTECTED]>
#
# Please see the file freevo/Docs/CREDITS for a complete list of authors.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MER-
# CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# -----------------------------------------------------------------------------

# python imports
import sys
import os
import kaa.metadata
import glob
import tempfile
import logging
import popen2

from stat import *

# kaa imports
import kaa.notifier
from kaa import mevas

# get logging object
log = logging.getLogger()

# internal thumbnail queue
_runqueue = []

class MplayerThumbnail(kaa.notifier.Process):
    """
    Mplayer thumbnailing process
    """
    def __init__( self, app, imagefile):
        self.imagefile = imagefile
        kaa.notifier.Process.__init__(self, app)
        self.signals["stdout"].connect(self.debug)
        self.signals["stderr"].connect(self.debug)
        self.signals["completed"].connect(self.finished)


    def debug(self, line):
        """
        print debug from child as warning
        """
        line.strip(' \t\n')
        if line:
            log.warning('>> %s' % line)


    def finished(self, exit_code):
        """
        Job finished, run next if there is more
        """
        global _runqueue
        _runqueue = _runqueue[1:]

        if not os.path.isfile(self.imagefile):
            log.warning('no imagefile found')
        if _runqueue:
            MplayerThumbnail(*_runqueue[0]).start()



def snapshot(videofile, imagefile=None, pos=None, update=True):
    """
    make a snapshot of the videofile at position pos to imagefile
    """
    global _runqueue
    if not imagefile:
        imagefile = os.path.splitext(videofile)[0] + '.jpg'

    if not update and os.path.isfile(imagefile) and \
           os.stat(videofile)[ST_MTIME] <= os.stat(imagefile)[ST_MTIME]:
        return

    for r, r_image in _runqueue:
        if r_image == imagefile:
            return

    log.info('generate %s' % imagefile)
    args = [ videofile, imagefile ]

    if pos != None:
        args.append(str(pos))

    job = ( [ 'python', os.path.abspath(__file__) ] + args, imagefile )
    _runqueue.append(job)
    if len(_runqueue) == 1:
        MplayerThumbnail(*_runqueue[0]).start()

        
#
# main function, will be called when this file is executed, not imported
# args: mplayer, videofile, imagefile, [ pos ]
#

if __name__ == "__main__":
    filename  = os.path.abspath(sys.argv[1])
    imagefile = os.path.abspath(sys.argv[2])

    try:
        position = sys.argv[3]
    except IndexError:
        try:
            mminfo = kaa.metadata.parse(filename)
            position = str(int(mminfo.video[0].length / 2.0))
            if hasattr(mminfo, 'type'):
                if mminfo.type in ('MPEG-TS', 'MPEG-PES'):
                    position = str(int(mminfo.video[0].length / 20.0))
        except:
            # else arbitrary consider that file is 1Mbps and grab position
            # at 10%
            position = os.stat(filename)[ST_SIZE]/1024/1024/10.0
            if position < 10:
                position = '10'
            else:
                position = str(int(position))

    # chdir to tmp so we have write access
    tmpdir = tempfile.mkdtemp('tmp', 'videothumb', '/tmp/')
    os.chdir(tmpdir)

    # call mplayer to get the image
    child = popen2.Popen3(('mplayer', '-nosound', '-vo', 'png', '-frames', '8',
                           '-ss', position, '-zoom', filename), 1, 100)
    child_output = ''
    while(1):
        data = child.fromchild.readline()
        if not data:
            break
        child_output += data
    for line in child.childerr.readlines():
        child_output += line

    child.wait()
    child.fromchild.close()
    child.childerr.close()
    child.tochild.close()

    # store the correct thumbnail
    captures = glob.glob('000000??.png')
    if not captures:
        # strange, print debug to find the problem
        print "error creating capture for %s" % filename
        print child_output
        os.chdir('/')
        os.rmdir(tmpdir)
        sys.exit(1)
    
    capture = captures[-1]

    try:
        image = mevas.imagelib.open(capture)
        if image.width > 255 or image.height > 255:
            image.scale_preserve_aspect((255,255))
        if image.width * 3 > image.height * 4:
            # fix image with blank bars to be 4:3
            nh = (image.width*3)/4
            ni = mevas.imagelib.new((image.width, nh))
            ni.blend(image, (0,(nh- image.height) / 2))
            image = ni
        elif image.width * 3 < image.height * 4:
            # strange aspect, let's guess it's 4:3
            new_size = (image.width, (image.width*3)/4)
            image.scale((new_size))
        try:
            image.save(imagefile)
        except:
            print 'unable to write file %s: %s' % (imagefile, e)

    except (OSError, IOError), e:
        # strange, print debug to find the problem
        print 'error saving image %s: %s' % (imagefile, e)

    for capture in captures:
        try:
            os.remove(capture)
        except:
            print "error removing temporary captures for %s" % filename

    os.chdir('/')
    os.rmdir(tmpdir)
    sys.exit(0)

Index: __init__.py
===================================================================
RCS file: /cvsroot/freevo/kaa/thumb/src/__init__.py,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** __init__.py 4 Jul 2005 18:28:46 -0000       1.2
--- __init__.py 27 Aug 2005 15:26:33 -0000      1.3
***************
*** 31,32 ****
--- 31,33 ----
  
  from interface import create, check, NORMAL, LARGE, FAILED, MISSING
+ from videothumb import snapshot as videothumb



-------------------------------------------------------
SF.Net email is Sponsored by the Better Software Conference & EXPO
September 19-22, 2005 * San Francisco, CA * Development Lifecycle Practices
Agile & Plan-Driven Development * Managing Projects & Teams * Testing & QA
Security * Process Improvement & Measurement * http://www.sqe.com/bsce5sf
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog

Reply via email to