#!/usr/bin/env python

__author__ = "Renato Filho"
__author_email__ = "renato.filho@indt.org.br"
__license__ = "GPL"
__version__ = "0.2"

import os
import sys
import shlex
import signal
import subprocess
import time

import select
import fcntl

import lib.utils as utils
import lib.server as server
import lib.transcoder as transcoder

__all__ = ("TranscoderGMencoder",)

class TranscoderGMencoder(transcoder.Transcoder):
    gmencoder_path = utils.which("gmencoder")
    name = "gmencoder"
    priority = -1
    proc = None

    def __init__(self, params):
        self.status = 0
        transcoder.Transcoder.__init__(self, params)
        self.opts = []
        self.opts.append (self.gmencoder_path)
        self.opts.append ("-d")
        self._parser_params ()

    # __init__()

    def _insert_param (self, name, value):
        if (value != ""):
            self.opts.append(name)
            self.opts.append(value)

    def _parser_params (self):
        self._insert_param("-i", \
            "%s://%s" % (self.params_first("type", "file"),
                         self.params_first("uri", "")))
        self._insert_param("--video-encode", self.params_first("ve", "ffenc_mpeg1video"))
        self._insert_param("--video-opts", "bitrate=300000,pass=512,quantizer=0.01,quant-type=1")
        #self._insert_param("--video-fps", self.params_first("fps", ""))
        self._insert_param("--video-fps", self.params_first("fps", "10"))
        self._insert_param("--video-width", self.params_first("width", "320"))
        self._insert_param("--video-height", self.params_first("height", "240"))
        self._insert_param("--audio-rate", "32000")
        self._insert_param("--audio-encode", self.params_first("ae", ""))
    # _parse_params

    def start(self, outfd):
        outfile = self.params_first("outfile", "")

        if outfile != "":
            path = os.path.join(utils.config.get_transcoded_location(), outfile)
            self._insert_param("-o", "file://%s" % path)
        else:
            self._insert_param ("-o", "fd://%d" % outfd.fileno())

        cmd = " ".join(self.opts)
        self.log.info(self.tid, "GMencoder: %s" % cmd)

        try:
            self.proc = subprocess.Popen(self.opts, stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE)

	    if outfile:
           	outfd.write("OK   ")

        except Exception, e:
            self.log.error(self.tid, "Error: executing GMencoder: %s" % e)
            outfd.write("Error: GMencoder: %s" % e)
            return False

        try:
	    if not outfile:
	    	p = select.poll()
	    	p.register (outfd, select.POLLNVAL | select.POLLERR |
                            select.POLLHUP)
            tries = 0
            while (self.proc and self.proc.poll() == None):
                r, w, x = select.select([self.proc.stdout], [], [], 1)
                if self.proc.stdout in r:
                    progress = self.proc.stdout.readline()
                    if (progress.find ("PROGRESS") >= 0):
                        self.status = progress.split (":")[1]
		    elif (progress.find ("Erro") >= 0):
                        self.log.error(self.tid, "Detected problem @ gmencoder:"
                                       " %s" % progress)
                        if tries < 50:
                            tries += 1
                        else:
                            return False

		    if not outfile:
			    ret = p.poll(0)
			    if ret:
			    	self.log.info(self.tid, "* Lost connection *")
		    		self.stop ()
			    	return False

        except Exception, e:
            self.log.error(self.tid, "Problems handling data: %s" % e)
            return False

        self.status = 100;


        return True
    # start()


    def stop(self):
        if self.proc:
            self.log.info(self.tid, "Stopped GMencoder plugin")
            try:
                os.kill(self.proc.pid, signal.SIGKILL)
                self.proc.wait()
            except Exception, e:
                pass

            self.proc = None
    # stop()

    def get_progress(self):
        return self.status

    def get_lenght(self):
        return -1

# TranscoderGMencoder
