#!/usr/bin/python


Import('env')

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

if env['OURPLATFORM'] == 'win32-mingw':
    ffmpeg_switches = "--disable-shared --enable-liba52bin --enable-gpl --disable-network --disable-zlib --disable-vhook --disable-ffserver --disable-ffplay --enable-swscaler --enable-pthreads --enable-libx264 --enable-libxvid --enable-libmp3lame"
else:
    ffmpeg_switches = "--disable-shared --enable-liba52bin --enable-gpl --disable-network --disable-zlib --disable-vhook --disable-ffserver --disable-ffplay --enable-swscaler --enable-memalign-hack --enable-libx264 --enable-libxvid --enable-libmp3lame"

#--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]

        iter = makevarsubst.finditer(line[:])
        for obj in iter:
            (name) = obj.group(1)
            s = ""
            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 = ""
    if "OBJS-yes" in vars:
        objs += vars['OBJS-yes']
    if "OBJS" in vars:
        objs += vars['OBJS']

    objs += " "
    objs = objs.replace(".o ", ".c ")

    asm_objs = ""
    if "ASM_OBJS" in vars:
        asm_objs += vars["ASM_OBJS"]

    asm_objs += " "
    asm_objs = asm_objs.replace(".o ", ".S ")

    objs += asm_objs;
    
    sources = list(Set(objs.split()))
    sources = [lib + "/" + x for x in sources]

    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)

    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))
