[mythtv-users] Announcing new program for transcoding recordings.

Esben Skov Pedersen spam at geek.linux.dk
Sat Jun 26 13:12:40 EDT 2004


For some reason nuvexport didn't work om my system (mdk9.2. myth rpms 
from plf) I decided to write my own. It has a simple interface and 
supports divx and xvid. It is also possible to transcode multiple shows 
in a batch.

If you has changed mysql-settings for mythtv you have to change them in 
the top of the script. You must have mplayer and xvid/divx installed for 
it to work.

Here goes. Paste the code into /usr/local/bin/legend.py. chmod +x 
/usr/local/bin/legend.py. Then just type legend.py in the console.

<---Start--->

#!/usr/bin/python

#You might want to change these settings

#mysql info. Read "man mysql"
mysql='mysql -umythtv -pmythtv mythconverg'

qualitySet={
    3:  {'bitrate': 1000, 'scale':(400, 320)},
    6:  {'bitrate': 1200, 'scale': (360, 288)},
    9:  {'bitrate': 1200, 'scale': (400, 320)},
    99: {'bitrate': 0, 'scale': (0, 0)}
}   
quality=9

#VBR sound quality (0-9, 0=best)
lameQuality=4

#2-pass? Takes longer time to encode
twoPass=True

#Cut some of the edges. -1 means center
#crop=(420, 326, -1, -1)
bitrate=qualitySet[quality]['bitrate']

divx="-ovc lavc -lavcopts vbitrate=%d:vcodec=mpeg4 "%( bitrate )
xvid="-ovc xvid -xvidencopts bitrate=%d "% ( bitrate )

if twoPass:
    divx+="-lavcopts vpass=%n "
    xvid+="-xvidencopts pass=%n "
   
#Video codec See http://mplayerhq.hu/DOCS/man/en/manpage.html for 
further options
videoCodec=divx

#Length of movie (seconds). Go nuts and try the different codecs much faster
#movieLength=20
#Note The movies will end up i the current directory as title.avi
########################################################################
##Don't edit anything below this line unless you know what you are doing
########################################################################


import os
import sys
import time
import re

def skrivStatus(prefix, done, eta):
    status="%3s%% Done ETA:%3sm"%( done, eta )
    sys.stdout.write("\r%-55s %s"%(prefix[:52], status ))
    sys.stdout.flush()
   
def parseMencoder(prefix, prog):
    skrivStatus(prefix, 0, "")
    v, encoder=os.popen4(prog)
    findEta=re.compile('Trem:\s*(\d+)min')
    findStatus=re.compile('\(\s*(\d+)%\)')
    c=-1
    status=""
    try:
        while True:
            c+=1
            raw=encoder.read(80)
            if not raw: break
        #    sys.stdout.write(raw)
            if c%100!=0 or c<40: continue
       #     tail=raw[-1:]
            eta=findEta.search(raw)
            try:
                done=findStatus.search(raw).group(1)
                finish=findEta.search(raw).group(1)
                status="%3s%% Done ETA:%3sm"%( done, finish )
            except AttributeError: continue
            skrivStatus(prefix, done, finish)
    except KeyboardInterrupt:
        print
        sys.exit()
    if c<50:
        print "\r"
        print "Mplayer does seem to be installed correctly"
        sys.exit(1)
    else:
        skrivStatus(prefix, 100, 0)
    print
scale=qualitySet[quality]['scale']

t=os.popen("echo \"select data from settings where 
value='RecordFilePrefix'\" | %s"%mysql)
t.readline()
recDir=t.readline().strip()

shows=os.popen("echo \"SELECT concat('%s/', chanid, '_', starttime, '_', 
endtime, '.nuv') as Filnavn, title from recorded ORDER by starttime 
DESC\"  | %s"%(recDir, mysql))

shows.readline()
showsData=[]
for show in shows.readlines():
    try:
        f=show.split('\t')
        showsData.append(( unicode(f[1][:-1], 'utf-8'), f[0] ))
    except : continue
print "Legend.py: Encodes mythtv-recordings to xvid or divx"
print "Edit top of Legend.py to change resolution, "
print "bitrate, multi-pass and crop-settings"
print " Show %57s"%'date'

for key in range(0, len(showsData)):
    try:
        d=int(showsData[key][1][-27:-25])
        m=int(showsData[key][1][-29:-27])
        date="[ %d/%d ]"%(d, m)
    except ValueError:
        date=""
    print " %-2d %-50s %s"%(key+1, showsData[key][0], date )

while True:
    print "Choose shows ( comma separated ) ",
    try:
        choices=[]
        r=raw_input()
        for a in r.split(','):
           # print a
            k=int(a)-1
            ( showName, inFile ) = showsData[k]
            choices.append( ( showName, inFile ) )
        break
    except KeyboardInterrupt:
        print
        sys.exit()
    except ValueError:
        print "Not a number \"%s\""%a
        continue
    except IndexError:
        print "No such show \"%d\""% (k+1)
        continue

count=0
n=''
for showName, inFile in choices:
    if count != 0: n=".%d"%count
    outFile="%s%s.avi"%( showName.replace( ",", " - ").replace(':', ' - 
'), n )
    if os.path.isfile(outFile):
        print "%-50s [Y/n]"%( "\"%s\" exists. 
Overwrite?"%os.path.basename(outFile)[:46] ) ,
        try:
            ans=raw_input()
        except KeyboardInterrupt:
            print
            sys.exit()
        if not (ans =='' or ans[0].lower()=='y' ):
            sys.exit()
    count+=1
count=0
n=''
print
for showName, inFile in choices:
    program="mencoder "
   # program="false "
    if count != 0: n=".%d"%count
    outFile="%s%s.avi"%( showName.replace( ",", " - ").replace(':', ' - 
'), n )
    program+="\"%s\" -o \"%s\" "%( inFile, outFile )
    try:
        program+="-vf crop=%d:%d:%d:%d " %crop
    except NameError: pass
    program+="-vf scale=%d:%d " %scale
    program+=videoCodec
    program+="-oac mp3lame "
    program+="-lameopts q=%d "%lameQuality
    try:
        program+="-endpos %d "%movieLength
    except NameError: pass
    msg="%s First pass of \"%s\""%( time.strftime('%H:%M'), outFile )
    if twoPass:
        parseMencoder(msg, program.replace('%n', '1'))
        msg="%s Second pass of \"%s\""%( time.strftime('%H:%M'), outFile )
        parseMencoder(msg, program.replace('%n', '2'))
    else:
        parseMencoder(msg, program)
    count+=1
print time.strftime('%H:%M'), "All Done"

<--- legend.py end --- >

Thats it. Enjoy /Esben


More information about the mythtv-users mailing list