#!/usr/bin/python
# coding: UTF-8
# Rec10 TS Recording Tools
# Copyright (C) 2009-2011 Yukikaze

import commands
import os
import re
import shutil
import time
import os.path
import subprocess
import signal

import configreader
import recdblist

def wav2aac_nero(pin,pout):
    os.environ['LANG']="ja_JP.UTF-8"
    neroaac=configreader.getConfPath('NeroAAC')
    exe=neroaac+" -br 128000 -2pass -if \""+pin+"\" -of \""+pout+"\""
    try:
        txt=commands.getoutput(exe.encode('utf-8'))
        recdblist.addLog(pin, exe, u"Wav2aac_Neroログ-コマンド")
        recdblist.addLog(pin, txt, u"Wav2aac_Neroログ-詳細")
    except:
        if not os.path.exists(pout):
            lame="lame"
            exe=lame+" -b 128 \""+pin+"\" \""+pout+"\""
            txt=commands.getoutput(exe.encode('utf-8'))
            recdblist.addLog(pin, exe, u"Wav2aac_Lameログ-コマンド")
            recdblist.addLog(pin, txt, u"Wav2aac_Lameログ-詳細")
def wav2mp3_lame(pin,pout):
    os.environ['LANG']="ja_JP.UTF-8"
    lame=configreader.getConfPath('lame')
    exe=lame+" -b 128 \""+pin+"\" \""+pout+"\""
    try:
        txt=commands.getoutput(exe.encode('utf-8'))
    except:
        ""
    recdblist.addLog(pin, exe, u"Wav2aac_Lameログ-コマンド")
    recdblist.addLog(pin, txt, u"Wav2aac_Lameログ-詳細")
def ts2single_audio(pts,opts):
    paac=pts.replace(".ts",".aac")
    ffmpeg=configreader.getConfPath("ffmpeg")
    e0=ffmpeg+" -i \""+pts+"\" -y -vn -acodec copy \""+paac+"\""
    p0=subprocess.Popen(e0,shell=True)
    os.waitpid(p0.pid, 0)
    if p0.poll==None:#実行中
        if os.path.exists(paac):
            if os.path.getsize(paac)<1000:#1mで1kb以下の場合自動で終了
                try:
                    logt=unicode(p0.communicate()[0], "UTF-8")
                    recdblist.addLog(pts,e0, "FFmpeg音声取り出しログ-コマンド")
                    recdblist.addLog(pts,logt, "FFmpeg音声取り出しログ-詳細")
                except:
                    ""
                recdblist.addCommonlogEX("[Error]", "ffmpeg aac getting. (ts2single_audio@tv2audio.py)", u"AAC demux error(ffmpeg)", "", verbose_level=200, log_level=200)
                os.kill(p0.pid,signal.SIGKILL)
                os.remove(paac)
                ts2single_mp3_ffmpeg(pts)
                if not os.path.exists(pts.replace(".ts",".mp3")):
                    ts2single_fp_BonTsDemux(pts,opts)
            else:
                logt=unicode(p0.communicate()[0], "UTF-8")
                recdblist.addLog(pts,e0, "FFmpeg音声取り出しログ-コマンド")
                recdblist.addLog(pts,logt, "FFmpeg音声取り出しログ-詳細")
        else:
            try:
                logt=unicode(p0.communicate()[0], "UTF-8")
                recdblist.addLog(pts,e0, "FFmpeg音声取り出しログ-コマンド")
                recdblist.addLog(pts,logt, "FFmpeg音声取り出しログ-詳細")
            except:
                ""
            recdblist.addCommonlogEX("[Error]", "ffmpeg aac getting. (ts2single_audio@tv2audio.py)", u"AAC demux error(ffmpeg)", "", verbose_level=200, log_level=200)
            try:
                os.kill(p0.pid,signal.SIGKILL)
            except:
                ""
            ts2single_mp3_ffmpeg(pts)
            if not os.path.exists(pts.replace(".ts",".mp3")):
                ts2single_fp_BonTsDemux(pts,opts)
    else:
        if os.path.exists(paac):
            if os.path.getsize(paac)<1000:#1mで1kb以下の場合自動で終了
                try:
                    logt=unicode(p0.communicate()[0], "UTF-8")
                    recdblist.addLog(pts,e0, "FFmpeg音声取り出しログ-コマンド")
                    recdblist.addLog(pts,logt, "FFmpeg音声取り出しログ-詳細")
                except:
                    ""
                recdblist.addCommonlogEX("[Error]", "ffmpeg aac getting. (ts2single_audio@tv2audio.py)", u"AAC demux error(ffmpeg)", "", verbose_level=200, log_level=200)
                os.remove(paac)
                ts2single_mp3_ffmpeg(pts)
                if not os.path.exists(pts.replace(".ts",".mp3")):
                    ts2single_fp_BonTsDemux(pts,opts)
            else:
                try:
                    logt=unicode(p0.communicate()[0], "UTF-8")
                    recdblist.addLog(pts,e0, "FFmpeg音声取り出しログ-コマンド")
                    recdblist.addLog(pts,logt, "FFmpeg音声取り出しログ-詳細")
                except:
                    ""
        else:
            try:
                logt=unicode(p0.communicate()[0], "UTF-8")
                recdblist.addLog(pts,e0, "FFmpeg音声取り出しログ-コマンド")
                recdblist.addLog(pts,logt, "FFmpeg音声取り出しログ-詳細")
            except:
                ""
            recdblist.addCommonlogEX("[Error]", "ffmpeg aac getting. (ts2single_audio@tv2audio.py)", u"AAC demux error(ffmpeg)", "", verbose_level=200, log_level=200)
            ts2single_mp3_ffmpeg(pts)
            if not os.path.exists(pts.replace(".ts",".mp3")):
                ts2single_fp_BonTsDemux(pts,opts)
def ts2singlewav(pts,opts):
    bontsdemux = configreader.getConfPath('bontsdemux')
    bonpin = "Z:\\" + pts[1:]
    outf = os.path.splitext(pts)[0]
    bonpout = "Z:\\" + outf[1:]
    delayt=""
    exe = 'wine ' + bontsdemux + " -i \"" + bonpin + "\" "+delayt+" -nd -sound 0 -o \"" + bonpout + "\""
    #recdblist.printutf8(exe)
    recdblist.printutf8(exe)
    txt=commands.getoutput(exe.encode('utf-8'))
    recdblist.addCommandLog(pts, u"BonTsDemux 音声取り出し", exe, txt)
def ts2single_mp3_ffmpeg(pts):
    pmp3=pts.replace(".ts",".mp3")
    ffmpeg=configreader.getConfPath("ffmpeg")
    e0=ffmpeg+" -i \""+pts+"\" -y -vn -ab 128k \""+pmp3+"\""
    p0=subprocess.Popen(e0,shell=True)
    os.waitpid(p0.pid, 0)
    try:
        logt=unicode(p0.communicate()[0], "UTF-8")
        recdblist.addLog(pts,e0, "FFmpeg_mp3音声取り出しログ-コマンド")
        recdblist.addLog(pts,logt, "FFmpeg_mp3音声取り出しログ-詳細")
    except:
        ""
def ts2single_aac_ffmpeg(pts):
    ts2singlewav(pts,opts)
    aout=pts.replace(".ts",".aac")
    ain=pts.replace(".ts",".wav")
    wav2aac_ffmpeg(ain,aout)
def wav2aac_ffmpeg(pin,pout):
    paac=pts.replace(".ts",".aac")
    ffmpeg=configreader.getConfPath("ffmpeg")
    e0=ffmpeg+" -i \""+pin+"\" -y \""+pout+"\""
    p0=subprocess.Popen(e0,shell=True)
    os.waitpid(p0.pid, 0)
    try:
        logt=unicode(p0.communicate()[0], "UTF-8")
        recdblist.addLog(pts,e0, "FFmpeg_wav2aac音声取り出しログ-コマンド")
        recdblist.addLog(pts,logt, "FFmpeg_wav2aac音声取り出しログ-詳細")
    except:
        ""
def ts2single_fp_BonTsDemux(pts,opts):
    useNero=0
    try:
        if configreader.getConfPath("useNeroAAC")=="1" and os.path.exists(configreader.getConfPath("NeroAAC")):
            useNero=1
    except:
        useNero=0
    if useNero==1:
        ts2single_aac_BonTsDemux_Nero(pts,opts)
    else:
        ts2single_aac_ffmpeg(pts)
    if not os.path.exists(pts.replace(".ts",".aac")):
        ts2single_mp3_BonTsDemux(pts,opts)
def ts2single_aac_BonTsDemux_Nero(pts,opts):
    ts2singlewav(pts,opts)
    aout=pts.replace(".ts",".aac")
    ain=pts.replace(".ts",".wav")
    wav2aac_nero(ain,aout)
def ts2single_mp3_BonTsDemux(pts,opts):
    ts2singlewav(pts,opts)
    aout=pts.replace(".ts",".mp3")
    ain=pts.replace(".ts",".wav")
    wav2mp3_lame(ain,aout)
def ts2dualaudio_BonTsDemux(pin, delay,opts):
    """
    delay is string
    """
    bontsdemux = configreader.getConfPath('bontsdemux')
    wine = configreader.getConfPath('wine')
    bonpin = "Z:\\" + pin[1:]
    outf = os.path.splitext(pin)[0]
    bonpout = "Z:\\" + outf[1:]
    exe = wine + ' ' + bontsdemux + " -i \"" + bonpin + "\" -delay " + delay + " -nd -sound 1 -o \"" + bonpout + "\""
    recdblist.printutf8(exe)
    txt=commands.getoutput(exe.encode('utf-8'))
    try:
        recdblist.addCommandLog(pin, u"BonTsDemux 第一音声取り出し", exe, txt)
    except:
        ""
    ffpin = pin.replace(".ts", "")
    ffpin1 = pin.replace("ts", "wav")
    ffpin2 = pin.replace("ts", "m2v")
    ffpout1 = ffpin + "_1.wav"
    ffpout2 = ffpin + "_2.wav"
    ffpout3 = ffpin + ".m2v"
    shutil.move(ffpin1, ffpout1)
    exe = wine + ' ' + bontsdemux + " -i \"" + bonpin + "\" -delay " + delay + " -nd -sound 2 -encode Demux\(wav\) -o \"" + bonpout + "\""
    recdblist.printutf8(exe)
    txt=commands.getoutput(exe.encode('utf-8'))
    try:
        recdblist.addCommandLog(pin, u"BonTsDemux 第二音声取り出し", exe, txt)
    except:
        ""
    #os.system(exe)
    shutil.move(ffpin1, ffpout2)
    shutil.move(ffpin2, ffpout3)
    ffpout21=ffpout1.replace(".wav",".mp3")
    ffpout22=ffpout2.replace(".wav",".mp3")
    useNero=0
    try:
        if os.path.exists(configreader.getConfPath("NeroAAC")):
            useNero=1
    except:
        useNero=0
    if useNero==1:
        ffpout21=ffpout1.replace(".wav",".aac")
        ffpout22=ffpout2.replace(".wav",".aac")
        wav2aac_nero(ffpout1, ffpout21)
        wav2aac_nero(ffpout2, ffpout22)
    else:
        wav2mp3_lame(ffpout1, ffpout21)
        wav2mp3_lame(ffpout2, ffpout22)
    time.sleep(3)
    os.remove(ffpout1)
    os.remove(ffpout2)
def ts2pentaaudio_BonTsDemux(pin, delay,opts):
    bontsdemux = configreader.getConfPath('bontsdemux')
    wine = configreader.getConfPath('wine')
    bonpin = "Z:\\" + pin[1:]
    outf = os.path.splitext(pin)[0]
    bonpout = "Z:\\" + outf[1:]
    exe = wine + ' ' + bontsdemux + " -i \"" + bonpin + "\" -delay "+delay+" -nd -sound 3 -o \"" + bonpout + "\""
    recdblist.printutf8(exe)
    txt=commands.getoutput(exe.encode('utf-8'))
    try:
        recdblist.addCommandLog(pin, u"BonTsDemux5.1ch 第一音声取り出し", exe, txt)
    except:
        ""
    ffpin = pin.replace(".ts", "")
    ffpin1 = pin.replace("ts", "wav")
    ffpin2 = pin.replace("ts", "m2v")
    ffpout1 = ffpin + "_1.wav"
    ffpout2 = ffpin + "_2.aac"
    shutil.move(ffpin1, ffpout1)
    exe = "ffmpeg -i '"+pin+"' -vn -f aac -acodec copy '"+ffpout2+"'"
    recdblist.printutf8(exe)
    txt=commands.getoutput(exe.encode('utf-8'))
    try:
        recdblist.addCommandLog(pin, u"FFmpeg 5.1ch 第二音声(raw AAC)取り出し", exe, txt)
    except:
        ""
    ffpout21=ffpout1.replace(".wav",".mp3")
    useNero=0
    try:
        if os.path.exists(configreader.getConfPath("NeroAAC")):
            useNero=1
    except:
        useNero=0
    if useNero==1:
        ffpout21=ffpout1.replace(".wav",".aac")
        wav2aac_nero(ffpout1, ffpout21)
    else:
        wav2mp3_lame(ffpout1, ffpout21)
    if not os.path.exists(ffpout21):
        exe = wine + ' ' + bontsdemux + " -i \"" + bonpin + "\" -delay "+delay+" -nd -sound 0 -o \"" + bonpout + "\""
        recdblist.printutf8(exe)
        txt=commands.getoutput(exe.encode('utf-8'))
        try:
            recdblist.addCommandLog(pin, u"BonTsDemux 修正版第二音声(2chDownmix)取り出し", exe, txt)
        except:
            ""
        shutil.move(ffpin1, ffpout1)
        if useNero==1:
            ffpout21=ffpout1.replace(".wav",".aac")
            wav2aac_nero(ffpout1, ffpout21)
        else:
            wav2mp3_lame(ffpout1, ffpout21)
        time.sleep(3)
    ffpout21=ffpout1.replace(".wav",".aac")
    if os.path.exists(ffpout21):
        if os.path.getsize(ffpout21)>10*1000*1000:
            os.remove(ffpout1)
