'''
 # GMyth-Stream
 #
 # @file main.py
 #
 # @brief <p> Plugin for GMyth-Stream
 #
 # Copyright (C) 2007 INdT - Instituto Nokia de Tecnologia.
 # @author Artur Duque de Souza <artur.souza@indt.org.br>
 #
 #
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU Lesser 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
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU Lesser 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
 #
 '''

import os
import sys
import time
import socket
import ConfigParser

class Media:

    def __init__(self, config):

        self.config = config
        self.pipe = ""
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.path = config.get("Vlc", "path")
        self.host = config.get("Vlc", "host")
        self.port = int(config.get("Vlc", "port"))
        self.pwd = config.get("Vlc", "pwd")

        # exec VLC
        pid = os.fork()
        if (pid == 0):
            #child
            print "ESTOU EM CHILD"
            self.path += " -I telnet -d 1> /dev/null 2> /dev/null &"
            os.system(self.path)
            sys.exit(0)

        print "ESTOU EM PARENT 1"
        time.sleep(3)
        print "ESTOU EM PARENT 2"
        self.sock.connect( (self.host, self.port) )
        self.sock.send("%s\n" % self.pwd)


    def insert_file(self, filename):

        self.sock.send("setup output0 input %s\n" % filename)


    def setup(self, filename, codec, bitrate, width, height, port):

        self.filename = filename
        self.codec = codec
        self.bitrate = int(bitrate)
        self.width = int(width)
        self.height = int(height)
        self.port = int(port)

        self.pipe = "#transcode{vcodec=%s,vb=%d,"\
                    "fps=25.0,scale=1,acodec=mpga,"\
                    "ab=64,channels=1,width=%d,height=%d}"\
                    ":duplicate{dst=std{access=http,"\
                    "mux=mpeg1,dst=:%d}}" % (self.codec, self.bitrate,\
                                             self.widht, self.height,\
                                             self.port)

        self.sock.send("setup output0 broadcast %s\n" % self.pipe)
        self.insert_file(self.filename)

    def play(self):

        print "Trying to play: %s" % self.pipe
        self.sock.send("control output0 play\n")


    def stop(self):

        print "Trying to stop: %s" % self.pipe
        self.sock.send("control output0 stop\n")


