# AVSLib :: 'filters' package :: 'utility' module
# Copyright (c) 2005 George Zarkadas (gzarkadas@users.sourceforge.net)

# This program is free software; you can redistribute it and/or modify it under the terms of 
# the GNU General Public License as published by the Free Software Foundation; either 
# version 2 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
# PURPOSE.  See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program; 
# if not, write to the "Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
# MA  02111-1307  USA"

__lib__ = "avslib" #$$ [__lib__ = "avslib-debug"]

DefineModule(__lib__, "filters", "utility")

global __load__ = Eval("""
	LoadModule(__lib__, "base", "constants")
	LoadModule(__lib__, "clip", "core")
	LoadModule(__lib__, "array", "core")
	""")

# convert base to target's colorspace
#
Function ConvertToTarget(clip base, clip target)
{
	return Eval("base.ConvertTo" + target.ColorSpace)
}

# scale (a yuv) clip from tv to pc (full) range
#
Function ScaleToPC(clip c)
{
	return c.IsYUV ? c.ColorYUV(levels="tv->pc") : c
}

# scale (a yuv) clip from pc (full) to tv range
#
Function ScaleToTV(clip c)
{
	return c.IsYUV ? c.ColorYUV(levels="pc->tv") : c
}

# apply a filter multiple times with the same set of parameters
#
Function FilterChain(clip c, string filter, int times, string "fparams")
{
	fparams = Default(fparams, "")
	# use OOP notation in Eval to avoid dealing with initial comma
	# and to allow chaining filters inside filter arg
	flt = times > 0 ? Eval("c." + filter + "(" + fparams + ")") : c
	return times > 0 \
		? FilterChain(flt, filter, times - 1, fparams) \
		: flt
}

# apply a filter multiple times with varying sets of parameters
#
# var_times: an array of times to apply filter
# var_params: settings for each times element
# format: """2, 4, "text"
# 3, 4, "petr" """
#
Function FilterVarChain(clip c, string filter, string var_times, string var_params)
{
	tlen = var_times.ArrayLen()
	times = tlen > 0 ? var_times.ArrayGet(0) : 0
	var_times = tlen > 0 ? var_times.ArrayDelete(0) : var_times
	old = ArrayDelimiterSet(CRLF)
	plen = var_params.ArrayLen()
	Assert(tlen == plen, \
		"FilterChainV: 'var_times' and 'var_params' have different lengths")
	# use ArrayGetString to avoid evaluation of elmt at this 
	# stage; it will be done (once) inside FilterChain
	fparams = plen > 0 ? var_params.ArrayGetString(0) : ""
	var_params = plen > 0 ? var_params.ArrayDelete(0) : var_params
	old = ArrayDelimiterSet(old)
	flt = tlen > 0 ? FilterChain(c, filter, times, fparams) : c
	return tlen > 0 \
		? FilterVarChain(flt, filter, var_times, var_params) \
		: flt
}

