/demultiplexer.py
Python | 260 lines | 255 code | 0 blank | 5 comment | 0 complexity | 454afa063801ff43cef489f0a0c1c53f MD5 | raw file
Possible License(s): Apache-2.0
- #!/usr/bin/python
- # -*- coding:utf-8 -*-
- '''
- Copyright 2010 José María García Pérez
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- '''
- '''
- ToDo
- ----
- 1. Tolerant with multivideo or multiaudio: -vid / -aid
- '''
- isOK = True
- try:
- import os
- import subprocess
- except ImportError:
- raise Exception(u'[ERROR] Es necesario Python 2.6' )
- isOK = False
- try:
- from configuration import Configuration
- except ImportError:
- raise Exception(u'[ERROR] Asegúrate de que "configuration.py" es accesible')
- isOK = False
- try:
- from info import Info
- except ImportError:
- raise Exception(u'[ERROR] Asegúrate de que "info.py" es accesible')
- isOK = False
- class Demultiplexer:
- '''Descompone una película en video y audio'''
- def __init__(self,
- inputfile = None,
- outputdir = None,
- ini = None,
- end = None,
- verbose = False):
- '''inputfile:
- '''
- if inputfile == None or outputdir == None:
- raise Exception('Demultiplexer requires "inputfile" and "outputdir" to be provided')
- # The inputfile is info.Info instance.
- self.inputfile = Info( inputfile = inputfile )
- self.outputdir = outputdir
-
- self.ini = self.__ini__( ini )
- self.end = self.__ini__( end )
- self.verbose = verbose
- def getaudio(self,
- avoidexec = False):
- '''Extrae el audio de un video:
- - Nombre: tmp_audio.wav
- - Formato: PCM
- '''
- # ToDo: Usar un nombre genérico para poder trabajar en paralelo.
- _output_filename = os.path.join( self.outputdir, 'audio.wav' )
- _config = Configuration()
- _mplayer = _config.data['mplayer']
- _params1 = [ _mplayer ]
- # !! Mplayer no entiende rutas absolutas en "pcm:file=...."
- #_output_filename = _output_filename.replace('\\','/')
- _wavfile = os.path.relpath( _output_filename )
- #_output_filename = _output_filename.replace('C:','/cygdrive/c')
- # -idx: es más lento pero demostró evitar cortes en algunos DV.
- _params2 = [ '-quiet',
- '-idx',
- '-vc',
- 'null',
- '-vo',
- 'null',
- '-ao',
- 'pcm:waveheader:file=%s' % _wavfile ]
- _params3 = []
- _params4 = []
- if self.ini != None:
- _params3 = [ '-ss',
- self.ini ]
- if self.end != None:
- _params4 = [ '-endpos',
- self.end ]
- _params5 = [ self.inputfile.filename ]
- _orden = _params1 + _params2 + _params3 + _params4 + _params5
- if self.verbose:
- print u'>>> Extrayendo el audio: %s ..... ' % _output_filename
- try:
- if not avoidexec:
- if self.verbose:
- subprocess.call(_orden)
- else:
- subprocess.call(_orden,
- shell = False,
- stdout = subprocess.PIPE)
- _data = _process.communicate()[0]
-
- if self.verbose:
- print u' [OK]'
- except:
- if self.verbose:
- print u' [FAILED]'
- return os.path.realpath( _output_filename )
- def getvideo( self,
- avoidexec = False ):
- '''Extrae sólo video (sin audio) en el formato original y en el contenedor AVI.
- mencoder <input_file> -of avi -ovc copy -nosound -o tmp_video.avi
- "exe\mencoder.exe" .\video_sources\Nokia\Video005.3gp -of avi -nosound -ovc lavc -fps 7.750984 -ofps 7.750984 -lavcopts vcodec=ffv1:aspect=1.45/1:vstrict=-2:coder=1:context=1:format=bgr32 -o ffv1.avi
-
- FPS:
- * Móvil: 7.750984fps
- '''
- _output_filename = os.path.join( self.outputdir, 'video.avi' )
- _config = Configuration()
- _params1 = [ _config.data['mencoder'] ]
- #'-idx',
- _params2 = [ '-idx',
- '-of',
- 'avi',
- '-nosound',
- '-ovc',
- 'copy']
- _params3 = []
- _params4 = []
- if self.ini != None:
- _params3 = [ '-ss',
- '%s' % self.ini]
- if self.end != None:
- _params4 = [ '-endpos',
- '%s' % self.end]
- _params5 = [ '-fps',
- '%s' % self.inputfile.rate,
- '-ofps',
- '%s' % self.inputfile.rate,
- '-o',
- '%s' % _output_filename,
- self.inputfile.filename]
- _orden = _params1 + _params2 + _params3 + _params4 + _params5
- if self.verbose:
- print u'>>> Extrayendo el video: %s ..... ' % _output_filename
- try:
- if not avoidexec:
- subprocess.call(_orden)
- #if self.verbose:
- # subprocess.call(_orden)
- #else:
- # subprocess.call(_orden,
- # shell = False,
- # stdout = subprocess.PIPE)
- # _data = _process.communicate()[0]
- if self.verbose:
- print u' [OK]'
- except:
- if self.verbose:
- print u' [FAILED]'
- return os.path.realpath( _output_filename )
-
- def __ini__(self, _ini):
- # ToDo: habría que validar los valores proporcionados aquí.
- return _ini
- def __end__(self, _end):
- return _end
- #=======
- # MAIN
- #=======
- if __name__ == '__main__':
- if isOK:
- # Parser
- import optparse
- _usage = u'''
- Propósito: Este programa permite extraer audio/video de una película.
- Uso: %prog [options] input_file output_directory
- Ejemplos:
- - Extrae el audio de los primeros 5 segundos del fichero:
- python demultiplexer.py -a --ini 0:00:00 --end 0:00:05 video.avi ./tmp
- '''
- _parser = optparse.OptionParser( usage = _usage )
- # _parser.add_option("-f", "--force",
- # action="store_true",
- # dest="force",
- # default = False,
- # help = "Sobreescribe en los ficheros preexistentes.")
- _parser.add_option("-i", "--ini",
- action="store",
- dest="ini",
- default = None,
- help = "Marca el inicio del procesado en tiempo")
- _parser.add_option("-e", "--end",
- action="store",
- dest="end",
- default = None,
- help = "Marca el final del procesado en tiempo")
- _parser.add_option("-a", "--audio",
- action="store_true",
- dest="audio",
- default = False,
- help = "Extrae el audio.")
- _parser.add_option("-v", "--video",
- action="store_true",
- dest="video",
- default = False,
- help = "Extrae el video.")
- (_options, _args) = _parser.parse_args()
- # ========================
- # Verificamos las opciones
- # ========================
- # - Fichero de origen.
- _inputfile = os.path.realpath( _args[0] )
- if not os.path.isfile( _inputfile ):
- raise Exception( u'[ERROR] El fichero de entrada no existe' )
- # - Directorio de destino.
- _outputdir = os.path.realpath( _args[1] )
- if not os.path.isdir( _outputdir ):
- try:
- # Si no existe lo creamos.
- os.mkdir( _outputdir )
- except:
- raise Exception( u'[ERROR] El directorio de salida no existe' )
- # =============================
- # Extraemos el audio y el video
- # =============================
-
-
- _demux = Demultiplexer( inputfile = _inputfile,
- outputdir = _outputdir,
- ini = _options.ini,
- end = _options.end)
- if _options.audio:
- _demux.getaudio()
- if _options.video:
- _demux.getvideo()