1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18package android.filterfw.core;
19
20/**
21 * @hide
22 */
23public class StreamPort extends InputPort {
24
25    private Frame mFrame;
26    private boolean mPersistent;
27
28    public StreamPort(Filter filter, String name) {
29        super(filter, name);
30    }
31
32    @Override
33    public void clear() {
34        if (mFrame != null) {
35            mFrame.release();
36            mFrame = null;
37        }
38    }
39
40    @Override
41    public void setFrame(Frame frame) {
42        assignFrame(frame, true);
43    }
44
45    @Override
46    public void pushFrame(Frame frame) {
47        assignFrame(frame, false);
48    }
49
50    protected synchronized void assignFrame(Frame frame, boolean persistent) {
51        assertPortIsOpen();
52        checkFrameType(frame, persistent);
53
54        if (persistent) {
55            if (mFrame != null) {
56                mFrame.release();
57            }
58        } else if (mFrame != null) {
59            throw new RuntimeException(
60                "Attempting to push more than one frame on port: " + this + "!");
61        }
62        mFrame = frame.retain();
63        mFrame.markReadOnly();
64        mPersistent = persistent;
65    }
66
67    @Override
68    public synchronized Frame pullFrame() {
69        // Make sure we have a frame
70        if (mFrame == null) {
71            throw new RuntimeException("No frame available to pull on port: " + this + "!");
72        }
73
74        // Return a retained result
75        Frame result = mFrame;
76        if (mPersistent) {
77            mFrame.retain();
78        } else {
79            mFrame = null;
80        }
81        return result;
82    }
83
84    @Override
85    public synchronized boolean hasFrame() {
86        return mFrame != null;
87    }
88
89    @Override
90    public String toString() {
91        return "input " + super.toString();
92    }
93
94    @Override
95    public synchronized void transfer(FilterContext context) {
96        if (mFrame != null) {
97            checkFrameManager(mFrame, context);
98        }
99    }
100}
101