Author: dmeyer
Date: Sun Feb 19 20:20:40 2006
New Revision: 1203

Modified:
   trunk/WIP/thumb2/setup.py
   trunk/WIP/thumb2/src/__init__.py
   trunk/WIP/thumb2/src/server.py
   trunk/WIP/thumb2/src/thumbnail.c
   trunk/WIP/thumb2/src/videothumb.py

Log:
create server side of the thumbnail module

Modified: trunk/WIP/thumb2/setup.py
==============================================================================
--- trunk/WIP/thumb2/setup.py   (original)
+++ trunk/WIP/thumb2/setup.py   Sun Feb 19 20:20:40 2006
@@ -37,7 +37,7 @@
     print 'kaa.base not installed'
     sys.exit(1)
     
-thumbnailer = Extension("kaa.thumb._thumbnailer",
+thumbnailer = Extension("kaa.thumb2.thumbnailer",
                         ["src/thumbnail.c", "src/png.c" ],
                         config='src/config.h')
 
@@ -60,5 +60,5 @@
 setup(module      = 'thumb2',
       version     = '0.1',
       ext_modules = [ thumbnailer ],
-      scripts     = [ 'bin/kaa-thumb2' ],
+      scripts     = [ 'bin/kaa-thumb' ],
       )

Modified: trunk/WIP/thumb2/src/__init__.py
==============================================================================
--- trunk/WIP/thumb2/src/__init__.py    (original)
+++ trunk/WIP/thumb2/src/__init__.py    Sun Feb 19 20:20:40 2006
@@ -29,5 +29,3 @@
 #
 # -----------------------------------------------------------------------------
 
-from interface import create, check, NORMAL, LARGE, FAILED, MISSING
-from videothumb import snapshot as videothumb

Modified: trunk/WIP/thumb2/src/server.py
==============================================================================
--- trunk/WIP/thumb2/src/server.py      (original)
+++ trunk/WIP/thumb2/src/server.py      Sun Feb 19 20:20:40 2006
@@ -1,125 +1,71 @@
-import stat
+# -*- coding: iso-8859-1 -*-
+# -----------------------------------------------------------------------------
+# server.py - Server interface for the thumbnailer
+# -----------------------------------------------------------------------------
+# $Id$
+#
+# -----------------------------------------------------------------------------
+# kaa-thumb - Thumbnailing module
+# Copyright (C) 2005-2006 Dirk Meyer, et al.
+#
+# First Edition: Dirk Meyer <[EMAIL PROTECTED]>
+# Maintainer:    Dirk Meyer <[EMAIL PROTECTED]>
+#
+# Please see the file AUTHORS 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 os
-import glob
+import sys
+
+# insert kaa path information
+__site__ = '../lib/python%s.%s/site-packages' % sys.version_info[:2]
+__site__ = os.path.normpath(os.path.join(os.path.dirname(__file__), __site__))
+if not __site__ in sys.path:
+    sys.path.insert(0, __site__)
 
+# kaa imports
 from kaa.base import ipc
 import kaa.notifier
 import kaa.metadata
 import kaa.imlib2
 
-from _thumbnailer import epeg_thumbnail, png_thumbnail, fail_thumbnail
+# kaa.thumb imports
+from thumbnailer import epeg, png, failed
+from videothumb import VideoThumb
 
-jobs = []
 
 class Job(object):
+    """
+    A job with thumbnail information.
+    """
     def __init__(self, id, filename, imagefile, size, update):
         self.client, self.id = id
         self.filename = filename
         self.imagefile = imagefile
         self.size = size
         self.update = update
-        
-
-class VideoThumb(object):
-    def __init__(self, thumbnailer):
-        self._jobs = []
-        self._current = None
-
-        self._notify_client = thumbnailer._notify_client
-        self._create_failed_image = thumbnailer._create_failed_image
-
-        self.child = kaa.notifier.Process(['mplayer', '-nosound', '-vo', 'png',
-                                           '-frames', '8', '-zoom', '-ss' ])
-        self.child.signals['completed'].connect(self._completed)
-        self.child.signals['stdout'].connect(self._handle_std)
-        self.child.signals['stderr'].connect(self._handle_std)
 
 
-    def append(self, job):
-        self._jobs.append(job)
-        self._run()
-
-        
-    def _handle_std(self, line):
-        self._child_std.append(line)
-
-
-    def _run(self):
-        if self.child.is_alive() or not self._jobs or self._current:
-            return True
-        self._current = self._jobs.pop(0)
-
-        try:
-            mminfo = self._current.metadata
-            pos = str(int(mminfo.video[0].length / 2.0))
-            if hasattr(mminfo, 'type'):
-                if mminfo.type in ('MPEG-TS', 'MPEG-PES'):
-                    pos = str(int(mminfo.video[0].length / 20.0))
-        except:
-            # else arbitrary consider that file is 1Mbps and grab position
-            # at 10%
-            try:
-                pos = 
os.stat(self._current.filename)[stat.ST_SIZE]/1024/1024/10.0
-            except (OSError, IOError):
-                # send message to client, we are done here
-                self._create_failed_image(self._current)
-                self._notify_client()
-                return
-            if pos < 10:
-                pos = '10'
-            else:
-                pos = str(int(pos))
-            
-        self._child_std = []
-        self.child.start([pos, self._current.filename])
-
-
-    def _completed(self, code):
-        # find thumbnails
-        captures = glob.glob('000000??.png')
-        if not captures:
-            # strange, no image files found
-            print "error creating capture for %s" % self._current.filename
-            for e in self._child_std:
-                print e
-            self._create_failed_image(self._current)
-            self._notify_client(self._current)
-            self._current = None
-            self._run()
-            return
-
-        # scale thumbnail
-        width, height = self._current.size
-        image = kaa.imlib2.open(captures[-1])
-        if image.width > width or image.height > height:
-            image = image.scale_preserve_aspect((width,height))
-        if image.width * 3 > image.height * 4:
-            # fix image with blank bars to be 4:3
-            nh = (image.width*3)/4
-            ni = kaa.imlib2.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 = image.scale((new_size))
-
-        # FIXME: use png code to add metadata
-        image.save(self._current.imagefile)
-
-        # remove old stuff
-        for capture in captures:
-            os.remove(capture)
-
-        # notify client and start next video
-        self._notify_client(self._current)
-        self._current = None
-        self._run()
-        
-
-    
 class Thumbnailer(object):
-
+    """
+    Main thumbnailer class.
+    """
     def __init__(self, tmpdir):
         self.next_client_id = 0
         self.clients = []
@@ -131,69 +77,83 @@
 
         # video module
         self.videothumb = VideoThumb(self)
-        
+
+
+    def _debug(self, client, messages):
+        for id, callback in self.clients:
+            if id == client:
+                callback(0, messages, __ipc_oneway=True, 
__ipc_noproxy_args=True)
+                return
+
 
     def _notify_client(self, job):
         for id, callback in self.clients:
             if id == job.client:
                 callback(job.id, job.filename, job.imagefile,
                          __ipc_oneway=True, __ipc_noproxy_args=True)
+                return
+
 
-        
     def _create_failed_image(self, job):
         dirname = os.path.dirname(os.path.dirname(job.imagefile)) + 
'/failed/kaa/'
         job.imagefile = dirname + os.path.basename(job.imagefile) + '.png'
         if not os.path.isdir(dirname):
             os.makedirs(dirname, 0700)
-        fail_thumbnail(job.filename, job.imagefile)
+        failed(job.filename, job.imagefile)
         return
-    
+
+
     def _run(self):
         if not self._jobs:
             return False
-        
+
         job = self._jobs.pop(0)
 
         # FIXME: check if there is already a file and update is False
 
         if job.filename.lower().endswith('jpg'):
             try:
-                epeg_thumbnail(job.filename, job.imagefile + '.jpg', job.size)
+                epeg(job.filename, job.imagefile + '.jpg', job.size)
                 job.imagefile += '.jpg'
                 self._notify_client(job)
                 return True
-            except IOError:
+            except (IOError, ValueError):
                 pass
 
         try:
-            png_thumbnail(job.filename, job.imagefile + '.png', size)
+            png(job.filename, job.imagefile + '.png', job.size)
             job.imagefile += '.png'
             self._notify_client(job)
             return True
-        except:
+        except (IOError, ValueError):
             pass
-        
+
         # maybe this is no image
         metadata = kaa.metadata.parse(job.filename)
         if metadata and metadata['media'] == 'video':
             # video file
-            print 'video'
             job.metadata = metadata
             self.videothumb.append(job)
             return True
 
         if metadata and metadata['raw_image']:
-            print 'FIXME: store raw data'
-            self._create_failed_image(job)
+            try:
+                image = kaa.imlib2.open_from_memory(metadata['raw_image'])
+                png(job.filename, job.imagefile, job.size, image)
+            except (IOError, ValueError):
+                # raw image is broken
+                self._debug(job.client, ['bad image in %s' % job.filename])
+                self._create_failed_image(job)
             self._notify_client(job)
             return True
-            
+
         # broken file
+        self._debug(job.client, ['unable to create thumbnail for %s' % 
job.filename])
         self._create_failed_image(job)
         self._notify_client(job)
         return True
 
-    
+
     def connect(self, callback):
         self.next_client_id += 1
         self.clients.append((self.next_client_id, callback))
@@ -206,27 +166,48 @@
         if not self._timer.active():
             self._timer.start(0.001)
 
-    
+
     def _client_closed(self, client):
         for client_info in self.clients[:]:
             id, c = client_info
             if ipc.get_ipc_from_proxy(c) == client:
-                print 'found'
                 for j in self._jobs[:]:
                     if j.client == id:
-                        print 'rm', j
                         self._jobs.remove(j)
                 for j in self.videothumb._jobs[:]:
                     if j.client == id:
-                        print 'rm', j
                         self.videothumb._jobs.remove(j)
                 self.clients.remove(client_info)
                 return
 
-tmpdir = os.path.join(kaa.TEMP, 'thumb')
-if not os.path.isdir(tmpdir):
-    os.mkdir(tmpdir)
-os.chdir(tmpdir)
 
-Thumbnailer(tmpdir)
-kaa.notifier.loop()
+if __name__ == "__main__":
+
+    shutdown_timer = 5
+
+    @kaa.notifier.execute_in_timer(kaa.notifier.Timer, 1)
+    def autoshutdown(server):
+        global shutdown_timer
+        if len(server.clients) > 0:
+            shutdown_timer = 5
+            return True
+        shutdown_timer -= 1
+        if shutdown_timer == 0:
+            sys.exit(0)
+        return True
+    
+
+    # create tmp dir and change directory to it
+    tmpdir = os.path.join(kaa.TEMP, 'thumb')
+    if not os.path.isdir(tmpdir):
+        os.mkdir(tmpdir)
+    os.chdir(tmpdir)
+
+    # create thumbnailer object
+    thumbnailer = Thumbnailer(tmpdir)
+
+    # start autoshutdown
+    autoshutdown(thumbnailer)
+
+    # loop
+    kaa.notifier.loop()

Modified: trunk/WIP/thumb2/src/thumbnail.c
==============================================================================
--- trunk/WIP/thumb2/src/thumbnail.c    (original)
+++ trunk/WIP/thumb2/src/thumbnail.c    Sun Feb 19 20:20:40 2006
@@ -41,6 +41,11 @@
 #include <sys/stat.h>
 #include <fcntl.h>
 
+/* kaa.imlib2 usage */
+Imlib_Image *(*imlib_image_from_pyobject)(PyObject *pyimg);
+PyTypeObject *Image_PyObject_Type;
+
+
 /* png write function stolen from epsilon (see png.c) */
 extern int _png_write (const char *file, DATA32 * ptr,
                        int tw, int th, int sw, int sh, char *imformat,
@@ -54,7 +59,6 @@
     char *dest;
 
     Epeg_Image *im;
-    Epeg_Thumbnail_Info info;
     
     if (!PyArg_ParseTuple(args, "ss(ii)", &source, &dest, &tw, &th))
         return NULL;
@@ -110,46 +114,55 @@
     struct stat filestatus;
     Imlib_Image tmp = NULL;
     Imlib_Image src = NULL;
+    PyObject *pyimg = NULL;
 
-    if (!PyArg_ParseTuple(args, "ss(ii)", &source, &dest, &tw, &th))
+    if (!PyArg_ParseTuple(args, "ss(ii)|O!", &source, &dest, &tw, &th,
+                         Image_PyObject_Type, &pyimg))
         return NULL;
 
     if (stat (source, &filestatus) != 0) {
-        PyErr_SetString(PyExc_ValueError, "pyimlib2: unable to load image");
+        PyErr_SetString(PyExc_ValueError, "thumbnail: no such file");
         return NULL;
     }
       
     mtime = filestatus.st_mtime;
-    if ((tmp = imlib_load_image_immediately_without_cache (source))) {
-        imlib_context_set_image (tmp);
-        snprintf (format, 32, "image/%s", imlib_image_format ());
-        iw = imlib_image_get_width ();
-        ih = imlib_image_get_height ();
-        if (iw > tw || ih > th) {
-            if (iw / tw > ih / th)
-                th = (ih * tw) / iw;
-            else
-                tw = (iw * th) / ih;
 
-           /* scale image down to thumbnail size */
-           imlib_context_set_cliprect (0, 0, tw, th);
-           src = imlib_create_cropped_scaled_image (0, 0, iw, ih, tw, th);
-           if (!src) {
-               imlib_free_image_and_decache ();
-               PyErr_SetString(PyExc_IOError, "pyimlib2 scale error");
-               return NULL;
-           }
-           /* free original image and set context to new one */
+    if (!pyimg) {
+       /* load source file */
+       if (!(tmp = imlib_load_image_immediately_without_cache (source))) {
+           PyErr_SetString(PyExc_ValueError, "pyimlib2: unable to load image");
+           return NULL;
+       } 
+    } else {
+       /* extract from kaa.imlib2 object */
+       tmp = imlib_image_from_pyobject(pyimg);
+    }
+    
+    imlib_context_set_image (tmp);
+    snprintf (format, 32, "image/%s", imlib_image_format ());
+    iw = imlib_image_get_width ();
+    ih = imlib_image_get_height ();
+    if (iw > tw || ih > th) {
+       if (iw / tw > ih / th)
+           th = (ih * tw) / iw;
+       else
+           tw = (iw * th) / ih;
+
+       /* scale image down to thumbnail size */
+       imlib_context_set_cliprect (0, 0, tw, th);
+       src = imlib_create_cropped_scaled_image (0, 0, iw, ih, tw, th);
+       if (!src) {
            imlib_free_image_and_decache ();
-           imlib_context_set_image (src);
+           PyErr_SetString(PyExc_IOError, "pyimlib2 scale error");
+           return NULL;
+       }
+       /* free original image and set context to new one */
+       imlib_free_image_and_decache ();
+       imlib_context_set_image (src);
              
-        } else {
-            tw = iw;
-            th = ih;
-        }
     } else {
-        PyErr_SetString(PyExc_ValueError, "pyimlib2: unable to load image");
-        return NULL;
+       tw = iw;
+       th = ih;
     }
     
     imlib_image_set_has_alpha (1);
@@ -199,14 +212,41 @@
 
 
 PyMethodDef thumbnail_methods[] = {
-    { "epeg_thumbnail", epeg_thumbnail, METH_VARARGS }, 
-    { "png_thumbnail", png_thumbnail, METH_VARARGS }, 
-    { "fail_thumbnail", fail_thumbnail, METH_VARARGS }, 
+    { "epeg", epeg_thumbnail, METH_VARARGS }, 
+    { "png", png_thumbnail, METH_VARARGS }, 
+    { "failed", fail_thumbnail, METH_VARARGS }, 
     { NULL }
 };
 
 
-void init_thumbnailer()
+void **get_module_api(char *module)
+{
+    PyObject *m, *c_api;
+    void **ptrs;
+
+    m = PyImport_ImportModule(module);
+    if (m == NULL)
+       return NULL;
+    c_api = PyObject_GetAttrString(m, "_C_API");
+    if (c_api == NULL || !PyCObject_Check(c_api))
+        return NULL;
+    ptrs = (void **)PyCObject_AsVoidPtr(c_api);
+    Py_DECREF(c_api);
+    return ptrs;
+}
+
+
+void initthumbnailer()
 {
-    Py_InitModule("_thumbnailer", thumbnail_methods);
+    PyObject *m;
+    void **imlib2_api_ptrs;
+
+    m = Py_InitModule("thumbnailer", thumbnail_methods);
+
+    // Import kaa-imlib2's C api
+    imlib2_api_ptrs = get_module_api("kaa.imlib2._Imlib2");
+    if (imlib2_api_ptrs == NULL)
+        return;
+    imlib_image_from_pyobject = imlib2_api_ptrs[0];
+    Image_PyObject_Type = imlib2_api_ptrs[1];
 }

Modified: trunk/WIP/thumb2/src/videothumb.py
==============================================================================
--- trunk/WIP/thumb2/src/videothumb.py  (original)
+++ trunk/WIP/thumb2/src/videothumb.py  Sun Feb 19 20:20:40 2006
@@ -4,20 +4,20 @@
 # -----------------------------------------------------------------------------
 # $Id$
 #
-# 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.
+# This file provides a function to create video thumbnails in the
+# background.  It will start a mplayer 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.
+# kaa-thumb - Thumbnailing module
+# Copyright (C) 2005-2006 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.
+# Please see the file AUTHORS 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
@@ -36,178 +36,117 @@
 # -----------------------------------------------------------------------------
 
 # python imports
-import sys
-import os
-import kaa.metadata
 import glob
-import tempfile
-import logging
-import popen2
-
-from stat import *
+import os
+import stat
 
 # kaa imports
 import kaa.notifier
-from kaa import mevas
+import kaa.imlib2
 
-# get logging object
-log = logging.getLogger()
+# kaa.thumb imports
+from thumbnailer import epeg, png, failed
 
-# internal thumbnail queue
-_runqueue = []
 
-class MplayerThumbnail(kaa.notifier.Process):
+class VideoThumb(object):
     """
-    Mplayer thumbnailing process
+    Class to handle video thumbnailing.
     """
-    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 __init__(self, thumbnailer):
+        self._jobs = []
+        self._current = None
 
+        self._notify_client = thumbnailer._notify_client
+        self._create_failed_image = thumbnailer._create_failed_image
+        self._debug = thumbnailer._debug
 
+        self.child = kaa.notifier.Process(['mplayer', '-nosound', '-vo', 'png',
+                                           '-frames', '8', '-zoom', '-ss' ])
+        self.child.signals['completed'].connect(self._completed)
+        self.child.signals['stdout'].connect(self._handle_std)
+        self.child.signals['stderr'].connect(self._handle_std)
 
-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 ]
+    def append(self, job):
+        self._jobs.append(job)
+        self._run()
 
-    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()
+    def _handle_std(self, line):
+        self._child_std.append(line)
 
-        
-#
-# 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])
+    def _run(self):
+        if self.child.is_alive() or not self._jobs or self._current:
+            return True
+        self._current = self._jobs.pop(0)
 
-    try:
-        position = sys.argv[3]
-    except IndexError:
         try:
-            mminfo = kaa.metadata.parse(filename)
-            position = str(int(mminfo.video[0].length / 2.0))
+            mminfo = self._current.metadata
+            pos = 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))
+                    pos = 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'
+            try:
+                pos = 
os.stat(self._current.filename)[stat.ST_SIZE]/1024/1024/10.0
+            except (OSError, IOError):
+                # send message to client, we are done here
+                self._create_failed_image(self._current)
+                self._notify_client()
+                return
+            if pos < 10:
+                pos = '10'
             else:
-                position = str(int(position))
+                pos = str(int(pos))
 
-    # 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))
+        self._child_std = []
+        self.child.start([pos, self._current.filename])
+
+
+    def _completed(self, code):
+        job = self._current
+        self._current = None
+
+        # find thumbnails
+        captures = glob.glob('000000??.png')
+        if not captures:
+            # strange, no image files found
+            self._debug(job.client, self._child_std)
+            self._create_failed_image(job)
+            self._notify_client(job)
+            job = None
+            self._run()
+            return
+
+        # scale thumbnail
+        width, height = job.size
+        image = kaa.imlib2.open(captures[-1])
+        if image.width > width or image.height > height:
+            image = image.scale_preserve_aspect((width,height))
         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 = kaa.imlib2.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)
+            image = image.scale((new_size))
 
-    for capture in captures:
         try:
+            png(job.filename, job.imagefile + '.png', job.size, image._image)
+            job.imagefile += '.png'
+        except (IOError, ValueError):
+            self._create_failed_image(job)
+
+        # remove old stuff
+        for capture in captures:
             os.remove(capture)
-        except:
-            print "error removing temporary captures for %s" % filename
 
-    os.chdir('/')
-    os.rmdir(tmpdir)
-    sys.exit(0)
+        # notify client and start next video
+        self._notify_client(job)
+        self._run()


-------------------------------------------------------
This SF.net email is sponsored by: Splunk Inc. Do you grep through log files
for problems?  Stop!  Download the new AJAX search engine that makes
searching your log files as easy as surfing the  web.  DOWNLOAD SPLUNK!
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=103432&bid=230486&dat=121642
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog

Reply via email to