FileDocCategorySizeDatePackage
Filter.javaAPI DocAndroid 5.1 API25697Thu Mar 12 22:22:30 GMT 2015android.filterfw.core

Filter

public abstract class Filter extends Object
hide

Fields Summary
static final int
STATUS_PREINIT
static final int
STATUS_UNPREPARED
static final int
STATUS_PREPARED
static final int
STATUS_PROCESSING
static final int
STATUS_SLEEPING
static final int
STATUS_FINISHED
static final int
STATUS_ERROR
static final int
STATUS_RELEASED
private String
mName
private int
mInputCount
private int
mOutputCount
private HashMap
mInputPorts
private HashMap
mOutputPorts
private HashSet
mFramesToRelease
private HashMap
mFramesToSet
private int
mStatus
private boolean
mIsOpen
private int
mSleepDelay
private long
mCurrentTimestamp
private boolean
mLogVerbose
private static final String
TAG
Constructors Summary
public Filter(String name)


       
        mName = name;
        mFramesToRelease = new HashSet<Frame>();
        mFramesToSet = new HashMap<String, Frame>();
        mStatus = STATUS_PREINIT;

        mLogVerbose = Log.isLoggable(TAG, Log.VERBOSE);
    
Methods Summary
private final voidaddAndSetFinalPorts(android.filterfw.core.KeyValueMap values)

        Class filterClass = getClass();
        Annotation annotation;
        for (Field field : filterClass.getDeclaredFields()) {
            if ((annotation = field.getAnnotation(GenerateFinalPort.class)) != null) {
                GenerateFinalPort generator = (GenerateFinalPort)annotation;
                String name = generator.name().isEmpty() ? field.getName() : generator.name();
                boolean hasDefault = generator.hasDefault();
                addFieldPort(name, field, hasDefault, true);
                if (values.containsKey(name)) {
                    setImmediateInputValue(name, values.get(name));
                    values.remove(name);
                } else if (!generator.hasDefault()) {
                    throw new RuntimeException("No value specified for final input port '"
                        + name + "' of filter " + this + "!");
                }
            }
        }
    
private final voidaddAnnotatedPorts()

        Class filterClass = getClass();
        Annotation annotation;
        for (Field field : filterClass.getDeclaredFields()) {
            if ((annotation = field.getAnnotation(GenerateFieldPort.class)) != null) {
                GenerateFieldPort generator = (GenerateFieldPort)annotation;
                addFieldGenerator(generator, field);
            } else if ((annotation = field.getAnnotation(GenerateProgramPort.class)) != null) {
                GenerateProgramPort generator = (GenerateProgramPort)annotation;
                addProgramGenerator(generator, field);
            } else if ((annotation = field.getAnnotation(GenerateProgramPorts.class)) != null) {
                GenerateProgramPorts generators = (GenerateProgramPorts)annotation;
                for (GenerateProgramPort generator : generators.value()) {
                    addProgramGenerator(generator, field);
                }
            }
        }
    
private final voidaddFieldGenerator(GenerateFieldPort generator, java.lang.reflect.Field field)

        String name = generator.name().isEmpty() ? field.getName() : generator.name();
        boolean hasDefault = generator.hasDefault();
        addFieldPort(name, field, hasDefault, false);
    
protected voidaddFieldPort(java.lang.String name, java.lang.reflect.Field field, boolean hasDefault, boolean isFinal)

        // Make sure field is accessible
        field.setAccessible(true);

        // Create port for this input
        InputPort fieldPort = isFinal
            ? new FinalPort(this, name, field, hasDefault)
            : new FieldPort(this, name, field, hasDefault);

        // Create format for this input
        if (mLogVerbose) Log.v(TAG, "Filter " + this + " adding " + fieldPort);
        MutableFrameFormat format = ObjectFormat.fromClass(field.getType(),
                                                           FrameFormat.TARGET_SIMPLE);
        fieldPort.setPortFormat(format);

        // Add port
        mInputPorts.put(name, fieldPort);
    
protected voidaddInputPort(java.lang.String name)
Adds an input port to the filter. You should call this from within setupPorts, if your filter has input ports. No type-checking is performed on the input. If you would like to check against a type mask, use {@link #addMaskedInputPort(String, FrameFormat) addMaskedInputPort} instead.

param
name the name of the input port

        addMaskedInputPort(name, null);
    
protected voidaddMaskedInputPort(java.lang.String name, FrameFormat formatMask)
Adds an input port to the filter. You should call this from within setupPorts, if your filter has input ports. When type-checking is performed, the input format is checked against the provided format mask. An exception is thrown in case of a conflict.

param
name the name of the input port
param
formatMask a format mask, which filters the allowable input types

        InputPort port = new StreamPort(this, name);
        if (mLogVerbose) Log.v(TAG, "Filter " + this + " adding " + port);
        mInputPorts.put(name, port);
        port.setPortFormat(formatMask);
    
protected voidaddOutputBasedOnInput(java.lang.String outputName, java.lang.String inputName)
Adds an output port to the filter. You should call this from within setupPorts, if your filter has output ports. Using this method indicates that the output format for this particular port, depends on the format of an input port. You MUST also override {@link #getOutputFormat(String, FrameFormat) getOutputFormat} to specify what format your filter will output for a given input. If the output format of your filter port does not depend on the input, use {@link #addOutputPort(String, FrameFormat) addOutputPort} instead.

param
outputName the name of the output port
param
inputName the name of the input port, that this output depends on

        OutputPort port = new OutputPort(this, outputName);
        if (mLogVerbose) Log.v(TAG, "Filter " + this + " adding " + port);
        port.setBasePort(getInputPort(inputName));
        mOutputPorts.put(outputName, port);
    
protected voidaddOutputPort(java.lang.String name, FrameFormat format)
Adds an output port to the filter with a fixed output format. You should call this from within setupPorts, if your filter has output ports. You cannot use this method, if your output format depends on the input format (e.g. in a pass-through filter). In this case, use {@link #addOutputBasedOnInput(String, String) addOutputBasedOnInput} instead.

param
name the name of the output port
param
format the fixed output format of this port

        OutputPort port = new OutputPort(this, name);
        if (mLogVerbose) Log.v(TAG, "Filter " + this + " adding " + port);
        port.setPortFormat(format);
        mOutputPorts.put(name, port);
    
private final voidaddProgramGenerator(GenerateProgramPort generator, java.lang.reflect.Field field)

        String name = generator.name();
        String varName = generator.variableName().isEmpty() ? name
                                                            : generator.variableName();
        Class varType = generator.type();
        boolean hasDefault = generator.hasDefault();
        addProgramPort(name, varName, field, varType, hasDefault);
    
protected voidaddProgramPort(java.lang.String name, java.lang.String varName, java.lang.reflect.Field field, java.lang.Class varType, boolean hasDefault)

        // Make sure field is accessible
        field.setAccessible(true);

        // Create port for this input
        InputPort programPort = new ProgramPort(this, name, varName, field, hasDefault);

        // Create format for this input
        if (mLogVerbose) Log.v(TAG, "Filter " + this + " adding " + programPort);
        MutableFrameFormat format = ObjectFormat.fromClass(varType,
                                                           FrameFormat.TARGET_SIMPLE);
        programPort.setPortFormat(format);

        // Add port
        mInputPorts.put(name, programPort);
    
final synchronized booleancanProcess()

        if (mLogVerbose) Log.v(TAG, "Checking if can process: " + this + " (" + mStatus + ").");
        if (mStatus <= STATUS_PROCESSING) {
            return inputConditionsMet() && outputConditionsMet();
        } else {
            return false;
        }
    
final voidclearInputs()

        for (InputPort inputPort : mInputPorts.values()) {
            inputPort.clear();
        }
    
final voidclearOutputs()

        for (OutputPort outputPort : mOutputPorts.values()) {
            outputPort.clear();
        }
    
public voidclose(android.filterfw.core.FilterContext context)

    
protected voidcloseOutputPort(java.lang.String name)

        getOutputPort(name).close();
    
private final voidclosePorts()

        if (mLogVerbose) Log.v(TAG, "Closing all ports on " + this + "!");
        for (InputPort inputPort : mInputPorts.values()) {
            inputPort.close();
        }
        for (OutputPort outputPort : mOutputPorts.values()) {
            outputPort.close();
        }
    
protected voiddelayNextProcess(int millisecs)

        mSleepDelay = millisecs;
        mStatus = STATUS_SLEEPING;
    
public voidfieldPortValueUpdated(java.lang.String name, android.filterfw.core.FilterContext context)

    
private final booleanfilterMustClose()

        for (InputPort inputPort : mInputPorts.values()) {
            if (inputPort.filterMustClose()) {
                if (mLogVerbose) Log.v(TAG, "Filter " + this + " must close due to port " + inputPort);
                return true;
            }
        }
        for (OutputPort outputPort : mOutputPorts.values()) {
            if (outputPort.filterMustClose()) {
                if (mLogVerbose) Log.v(TAG, "Filter " + this + " must close due to port " + outputPort);
                return true;
            }
        }
        return false;
    
public java.lang.StringgetFilterClassName()

        return getClass().getSimpleName();
    
public final FrameFormatgetInputFormat(java.lang.String portName)

        InputPort inputPort = getInputPort(portName);
        return inputPort.getSourceFormat();
    
public final InputPortgetInputPort(java.lang.String portName)

        if (mInputPorts == null) {
            throw new NullPointerException("Attempting to access input port '" + portName
                + "' of " + this + " before Filter has been initialized!");
        }
        InputPort result = mInputPorts.get(portName);
        if (result == null) {
            throw new IllegalArgumentException("Unknown input port '" + portName + "' on filter "
                + this + "!");
        }
        return result;
    
final java.util.CollectiongetInputPorts()

        return mInputPorts.values();
    
public final java.lang.StringgetName()

        return mName;
    
public final intgetNumberOfConnectedInputs()

        int c = 0;
        for (InputPort inputPort : mInputPorts.values()) {
            if (inputPort.isConnected()) {
                ++c;
            }
        }
        return c;
    
public final intgetNumberOfConnectedOutputs()

        int c = 0;
        for (OutputPort outputPort : mOutputPorts.values()) {
            if (outputPort.isConnected()) {
                ++c;
            }
        }
        return c;
    
public final intgetNumberOfInputs()

        return mOutputPorts == null ? 0 : mInputPorts.size();
    
public final intgetNumberOfOutputs()

        return mInputPorts == null ? 0 : mOutputPorts.size();
    
public FrameFormatgetOutputFormat(java.lang.String portName, FrameFormat inputFormat)

        return null;
    
public final OutputPortgetOutputPort(java.lang.String portName)

        if (mInputPorts == null) {
            throw new NullPointerException("Attempting to access output port '" + portName
                + "' of " + this + " before Filter has been initialized!");
        }
        OutputPort result = mOutputPorts.get(portName);
        if (result == null) {
            throw new IllegalArgumentException("Unknown output port '" + portName + "' on filter "
                + this + "!");
        }
        return result;
    
final java.util.CollectiongetOutputPorts()

        return mOutputPorts.values();
    
public final intgetSleepDelay()

        return 250;
    
final synchronized intgetStatus()

        return mStatus;
    
public final voidinit()

        KeyValueMap valueMap = new KeyValueMap();
        initWithValueMap(valueMap);
    
private final voidinitFinalPorts(android.filterfw.core.KeyValueMap values)

        mInputPorts = new HashMap<String, InputPort>();
        mOutputPorts = new HashMap<String, OutputPort>();
        addAndSetFinalPorts(values);
    
protected voidinitProgramInputs(Program program, android.filterfw.core.FilterContext context)
Assigns all program variables to the ports they are connected to. Call this after constructing a Program instance with attached ProgramPorts.

        if (program != null) {
            for (InputPort inputPort : mInputPorts.values()) {
                if (inputPort.getTarget() == program) {
                    inputPort.transfer(context);
                }
            }
        }
    
private final voidinitRemainingPorts(android.filterfw.core.KeyValueMap values)

        addAnnotatedPorts();
        setupPorts();   // TODO: rename to addFilterPorts() ?
        setInitialInputValues(values);
    
public final voidinitWithAssignmentList(java.lang.Object keyValues)

        KeyValueMap valueMap = new KeyValueMap();
        valueMap.setKeyValues(keyValues);
        initWithValueMap(valueMap);
    
public final voidinitWithAssignmentString(java.lang.String assignments)

        try {
            KeyValueMap valueMap = new TextGraphReader().readKeyValueAssignments(assignments);
            initWithValueMap(valueMap);
        } catch (GraphIOException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    
public final voidinitWithValueMap(android.filterfw.core.KeyValueMap valueMap)

        // Initialization
        initFinalPorts(valueMap);

        // Setup remaining ports
        initRemainingPorts(valueMap);

        // This indicates that final ports can no longer be set
        mStatus = STATUS_UNPREPARED;
    
private final booleaninputConditionsMet()

        for (FilterPort port : mInputPorts.values()) {
            if (!port.isReady()) {
                if (mLogVerbose) Log.v(TAG, "Input condition not met: " + port + "!");
                return false;
            }
        }
        return true;
    
public static final booleanisAvailable(java.lang.String filterName)
Tests to see if a given filter is installed on the system. Requires full filter package name, including filterpack.

        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Class filterClass;
        // First see if a class of that name exists
        try {
            filterClass = contextClassLoader.loadClass(filterName);
        } catch (ClassNotFoundException e) {
            return false;
        }
        // Then make sure it's a subclass of Filter.
        try {
            filterClass.asSubclass(Filter.class);
        } catch (ClassCastException e) {
            return false;
        }
        return true;
    
public booleanisOpen()

        return mIsOpen;
    
final voidnotifyFieldPortValueUpdated(java.lang.String name, android.filterfw.core.FilterContext context)

        if (mStatus == STATUS_PROCESSING || mStatus == STATUS_PREPARED) {
            fieldPortValueUpdated(name, context);
        }
    
public voidopen(android.filterfw.core.FilterContext context)

    
final voidopenOutputs()

        if (mLogVerbose) Log.v(TAG, "Opening all output ports on " + this + "!");
        for (OutputPort outputPort : mOutputPorts.values()) {
            if (!outputPort.isOpen()) {
                outputPort.open();
            }
        }
    
private final booleanoutputConditionsMet()

        for (FilterPort port : mOutputPorts.values()) {
            if (!port.isReady()) {
                if (mLogVerbose) Log.v(TAG, "Output condition not met: " + port + "!");
                return false;
            }
        }
        return true;
    
protected voidparametersUpdated(java.util.Set updated)

    
final synchronized voidperformClose(android.filterfw.core.FilterContext context)

        if (mIsOpen) {
            if (mLogVerbose) Log.v(TAG, "Closing " + this);
            mIsOpen = false;
            mStatus = STATUS_PREPARED;
            close(context);
            closePorts();
        }
    
final synchronized voidperformOpen(android.filterfw.core.FilterContext context)

        if (!mIsOpen) {
            if (mStatus == STATUS_UNPREPARED) {
                if (mLogVerbose) Log.v(TAG, "Preparing " + this);
                prepare(context);
                mStatus = STATUS_PREPARED;
            }
            if (mStatus == STATUS_PREPARED) {
                if (mLogVerbose) Log.v(TAG, "Opening " + this);
                open(context);
                mStatus = STATUS_PROCESSING;
            }
            if (mStatus != STATUS_PROCESSING) {
                throw new RuntimeException("Filter " + this + " was brought into invalid state during "
                    + "opening (state: " + mStatus + ")!");
            }
            mIsOpen = true;
        }
    
final synchronized voidperformProcess(android.filterfw.core.FilterContext context)

        if (mStatus == STATUS_RELEASED) {
            throw new RuntimeException("Filter " + this + " is already torn down!");
        }
        transferInputFrames(context);
        if (mStatus < STATUS_PROCESSING) {
            performOpen(context);
        }
        if (mLogVerbose) Log.v(TAG, "Processing " + this);
        mCurrentTimestamp = Frame.TIMESTAMP_UNKNOWN;
        process(context);
        releasePulledFrames(context);
        if (filterMustClose()) {
            performClose(context);
        }
    
final synchronized voidperformTearDown(android.filterfw.core.FilterContext context)

        performClose(context);
        if (mStatus != STATUS_RELEASED) {
            tearDown(context);
            mStatus = STATUS_RELEASED;
        }
    
protected voidprepare(android.filterfw.core.FilterContext context)

    
public abstract voidprocess(android.filterfw.core.FilterContext context)

protected final FramepullInput(java.lang.String name)

        Frame result = getInputPort(name).pullFrame();
        if (mCurrentTimestamp == Frame.TIMESTAMP_UNKNOWN) {
            mCurrentTimestamp = result.getTimestamp();
            if (mLogVerbose) Log.v(TAG, "Default-setting current timestamp from input port " + name + " to " + mCurrentTimestamp);
        }
        // As result is retained, we add it to the release pool here
        mFramesToRelease.add(result);

        return result;
    
final synchronized voidpushInputFrame(java.lang.String inputName, Frame frame)

        FilterPort port = getInputPort(inputName);
        if (!port.isOpen()) {
            port.open();
        }
        port.pushFrame(frame);
    
final synchronized voidpushInputValue(java.lang.String inputName, java.lang.Object value)

        pushInputFrame(inputName, wrapInputValue(inputName, value));
    
protected final voidpushOutput(java.lang.String name, Frame frame)

        if (frame.getTimestamp() == Frame.TIMESTAMP_NOT_SET) {
            if (mLogVerbose) Log.v(TAG, "Default-setting output Frame timestamp on port " + name + " to " + mCurrentTimestamp);
            frame.setTimestamp(mCurrentTimestamp);
        }
        getOutputPort(name).pushFrame(frame);
    
private final voidreleasePulledFrames(android.filterfw.core.FilterContext context)

        for (Frame frame : mFramesToRelease) {
            context.getFrameManager().releaseFrame(frame);
        }
        mFramesToRelease.clear();
    
private final voidsetImmediateInputValue(java.lang.String name, java.lang.Object value)

        if (mLogVerbose) Log.v(TAG, "Setting immediate value " + value + " for port " + name + "!");
        FilterPort port = getInputPort(name);
        port.open();
        port.setFrame(SimpleFrame.wrapObject(value, null));
    
private final voidsetInitialInputValues(android.filterfw.core.KeyValueMap values)

        for (Entry<String, Object> entry : values.entrySet()) {
            setInputValue(entry.getKey(), entry.getValue());
        }
    
public voidsetInputFrame(java.lang.String inputName, Frame frame)

        FilterPort port = getInputPort(inputName);
        if (!port.isOpen()) {
            port.open();
        }
        port.setFrame(frame);
    
public final voidsetInputValue(java.lang.String inputName, java.lang.Object value)

        setInputFrame(inputName, wrapInputValue(inputName, value));
    
protected voidsetWaitsOnInputPort(java.lang.String portName, boolean waits)
Specifies whether the filter should not be scheduled until a frame is available on that input port. Note, that setting this to false, does not block a new frame from coming in (though there is no necessity to pull that frame for processing).

param
portName the name of the input port.
param
waits true, if the filter should wait for a frame on this port.

        getInputPort(portName).setBlocking(waits);
    
protected voidsetWaitsOnOutputPort(java.lang.String portName, boolean waits)
Specifies whether the filter should not be scheduled until the output port is free, i.e. there is no frame waiting on that output.

param
portName the name of the output port.
param
waits true, if the filter should wait for the port to become free.

        getOutputPort(portName).setBlocking(waits);
    
public abstract voidsetupPorts()

public voidtearDown(android.filterfw.core.FilterContext context)

    
public java.lang.StringtoString()

        return "'" + getName() + "' (" + getFilterClassName() + ")";
    
private final voidtransferInputFrames(android.filterfw.core.FilterContext context)

        for (InputPort inputPort : mInputPorts.values()) {
            inputPort.transfer(context);
        }
    
protected voidtransferInputPortFrame(java.lang.String name, android.filterfw.core.FilterContext context)
Transfers any frame from an input port to its destination. This is useful to force a transfer from a FieldPort or ProgramPort to its connected target (field or program variable).

        getInputPort(name).transfer(context);
    
final synchronized voidunsetStatus(int flag)

        mStatus &= ~flag;
    
private final FramewrapInputValue(java.lang.String inputName, java.lang.Object value)

        MutableFrameFormat inputFormat = ObjectFormat.fromObject(value, FrameFormat.TARGET_SIMPLE);
        if (value == null) {
            // If the value is null, the format cannot guess the class, so we adjust it to the
            // class of the input port here
            FrameFormat portFormat = getInputPort(inputName).getPortFormat();
            Class portClass = (portFormat == null) ? null : portFormat.getObjectClass();
            inputFormat.setObjectClass(portClass);
        }

        // Serialize if serializable, and type is not an immutable primitive.
        boolean shouldSerialize = !(value instanceof Number)
            && !(value instanceof Boolean)
            && !(value instanceof String)
            && value instanceof Serializable;

        // Create frame wrapper
        Frame frame = shouldSerialize
            ? new SerializedFrame(inputFormat, null)
            : new SimpleFrame(inputFormat, null);
        frame.setObjectValue(value);
        return frame;