#!/usr/bin/python


Import('env')

all_libs = ['libavformat', 'libavcodec', 'libswscale', 'libavutil', 'libavdevice']
root = "extern/ffmpeg"

if env['OURPLATFORM'] == 'win32-mingw':
    ffmpeg_switches = "--disable-shared --enable-gpl --enable-zlib --disable-vhook --disable-ffserver --disable-ffplay --enable-swscale --enable-pthreads --enable-libx264 --enable-libxvid --enable-libmp3lame"
else:
    ffmpeg_switches = "--disable-shared --enable-gpl --enable-zlib --disable-vhook --disable-ffserver --disable-ffplay --enable-swscale --enable-memalign-hack --enable-libx264 --enable-libxvid --enable-libmp3lame --disable-bzlib --disable-outdevs --disable-demuxer=alsa"
    if env['OURPLATFORM'] == 'darwin':
        ffmpeg_switches += " --disable-mmx"

if env['WITH_BF_OGG']:
    ffmpeg_switches += " --enable-libtheora --enable-libvorbis"

#--enable-libx264
extra_variables = { }
extra_includes = [ "../x264", "../xvidcore/src", "../libmp3lame" ]
#

import sys
import os
import re
import shutil

from sets import Set

ff_env = env.Copy();
ff_env.Replace(CCFLAGS = '')
ff_env.Replace(BF_DEBUG_FLAGS = '')

makevardef = re.compile('^([a-zA-Z0-9_-]+)[ \t]*(\+?)=(.*)')
makevarsubst = re.compile('\$\(([^\)]+)\)')
makeifeq = re.compile('if(n?)eq \(([^,]*),([^\)]*)\)')

def makeparseblock(fp, variables):
    pendingline = ''
    while 1:
        line = fp.readline()
        if pendingline:
            line = pendingline + line
            pendingline = ''
        if not line:
            return
        if line.endswith('\\\n'):
            pendingline = line[:-2]
            continue 

        i = line.find('#')
        if i >= 0:
            line = line[:i]

        while makevarsubst.search(line):
            iter = makevarsubst.finditer(line[:])
            for obj in iter:
                (name) = obj.group(1)
                s = ""
                i = name.find(':')
                if i >= 0:
                    subst = name[i+1:].split("=")
                    nname = name[:i]
                    if nname in variables:
                        s = variables[nname]
                    sl = list(Set(s.split()))
                    fin = ""
                    for x in sl:
                        s_from = subst[0][:]
                        s_to = subst[1][:]
                        s_from = s_from.replace("%", x)
                        s_to = s_to.replace("%", x)
                        fin += x.replace(s_from, s_to) + " "
                    s = fin
                else:
                    if name in variables:
                        s = variables[name]
                line = line.replace('$(' + name + ')', s)

        matchobj = makevardef.match(line)
        if matchobj:
            (name, op, value) = matchobj.group(1, 2, 3)

            value = value.rstrip()

            if op == '+' and name in variables:
                 variables[name] += value
            else:
                 variables[name] = value
            continue
        matchobj = makeifeq.match(line)
        if matchobj:
            (op, name1, name2) = matchobj.group(1, 2, 3)
            if (op == '' and name1 == name2) or (op == 'n' and name1 != name2):
                makeparseblock(fp, variables)
            else:
                tempvars = {}
                makeparseblock(fp, tempvars)
            continue
        line = line.strip()
        if line == 'endif':
            return
                
def getmakevars(filenames):
    variables = extra_variables.copy()
    for filename in filenames:
       fp = open(filename)
       print "Processing makefile: " + filename
       try:
             makeparseblock(fp, variables)
       finally:
             fp.close()

    return variables

print "Configuring ffmpeg..."

if not os.path.isfile(root + "/config.mak"):
    os.chdir(root);
    os.system("sh -c './configure " + ffmpeg_switches + "'")
    os.chdir("../..");
else:
    print "(skipped, config.mak already exists)"
    
if not os.path.isdir(root + "/include"):
    os.mkdir(root + "/include");
if not os.path.isdir(root + "/include/ffmpeg"):
    os.mkdir(root + "/include/ffmpeg");

for lib in all_libs:
    vars = getmakevars([root + '/config.mak', root + "/" + lib + '/Makefile'])
    objs = ""

    for v in [ "OBJS-yes", "OBJS", "ASM_OBJS" ]:
        if v in vars:
            objs += vars[v] + " "

    sources_ = list(Set(objs.split()))
    sources = []

    for s in sources_:
        s = lib + "/" + s
        s = s.replace(".o", "")
        for ext in [ ".S", ".c", ".asm" ]:
            if os.path.isfile(root + "/" + s + ext):
                s += ext
                break
        sources.append(s)
        
    if env['OURPLATFORM'] in ['win32-mingw', 'win32-vc' , 'darwin'] :
    	defs = "HAVE_AV_CONFIG_H  _ISOC9X_SOURCE"
    else :
    	defs = "HAVE_AV_CONFIG_H _FILE_OFFSET_BITS=64 _LARGEFILE_SOURCE _ISOC9X_SOURCE"

    if env['BF_FFMPEG_EXTRA']:
        cflags = env['BF_FFMPEG_EXTRA']
    else :
        cflags = ""
    
    if "CFLAGS" in vars:
        cflags += " " + vars["CFLAGS"]
    if "OPTFLAGS" in vars:
        cflags += " " + vars["OPTFLAGS"]

    headers = ""
    if "HEADERS" in vars:
        headers += vars["HEADERS"]

    headers = headers.split()

    for h in headers:
        if not os.path.isfile(root + "/include/ffmpeg/" + h):
            shutil.copyfile(root + "/" + lib + "/" + h,
                            root + "/include/ffmpeg/" + h)

    if "YASM" in vars:
        ff_env['AS'] = vars['YASM']
    if "YASMFLAGS" in vars:
        ff_env['ASFLAGS'] = vars['YASMFLAGS']

    ff_env.BlenderLib (libname="extern_" + lib, sources=sources,
                    includes=["."] + all_libs + extra_includes,
                    defines=Split(defs),
                    libtype=['core', 'intern', 'player'],
                    priority = [5, 5, 200],
                    compileflags = Split(cflags))
