summaryrefslogtreecommitdiffstats
path: root/camera2/public/src/com/android/ex/camera2/blocking/BlockingStateListener.java
blob: 02c2ba383bb28275031a2904f205df8d70755c18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
 * Copyright 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.ex.camera2.blocking;

import android.hardware.camera2.CameraDevice;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;

import com.android.ex.camera2.exceptions.TimeoutRuntimeException;

import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;


/**
 * A camera device listener that implements blocking operations on state changes.
 *
 * <p>Provides wait calls that block until the next unobserved state of the
 * requested type arrives. Unobserved states are states that have occurred since
 * the last wait, or that will be received from the camera device in the
 * future.</p>
 *
 * <p>Pass-through all StateListener changes to the proxy.</p>
 *
 */
public class BlockingStateListener extends CameraDevice.StateListener {
    private static final String TAG = "BlockingStateListener";
    private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE);

    private final CameraDevice.StateListener mProxy;

    // Guards mWaiting
    private final Object mLock = new Object();
    private boolean mWaiting = false;

    private final LinkedBlockingQueue<Integer> mRecentStates =
            new LinkedBlockingQueue<Integer>();

    private void setCurrentState(int state) {
        if (VERBOSE) Log.v(TAG, "Camera device state now " + stateToString(state));
        try {
            mRecentStates.put(state);
        } catch(InterruptedException e) {
            throw new RuntimeException("Unable to set device state", e);
        }
    }

    private static final String[] mStateNames = {
        "STATE_UNINITIALIZED",
        "STATE_OPENED",
        "STATE_CLOSED",
        "STATE_DISCONNECTED",
        "STATE_ERROR"
    };

    /**
     * Device has not reported any state yet
     */
    public static final int STATE_UNINITIALIZED = -1;

    /**
     * Device is in the first-opened state (transitory)
     */
    public static final int STATE_OPENED = 0;

    /**
     * Device is closed
     */
    public static final int STATE_CLOSED = 1;

    /**
     * Device is disconnected
     */
    public static final int STATE_DISCONNECTED = 2;

    /**
     * Device has encountered a fatal error
     */
    public static final int STATE_ERROR = 3;

    /**
     * Total number of reachable states
     */
    private static int NUM_STATES = 4;

    public BlockingStateListener() {
        mProxy = null;
    }

    public BlockingStateListener(CameraDevice.StateListener listener) {
        mProxy = listener;
    }

    @Override
    public void onOpened(CameraDevice camera) {
        if (mProxy != null) mProxy.onOpened(camera);
        setCurrentState(STATE_OPENED);
    }

    @Override
    public void onDisconnected(CameraDevice camera) {
        if (mProxy != null) mProxy.onDisconnected(camera);
        setCurrentState(STATE_DISCONNECTED);
    }

    @Override
    public void onError(CameraDevice camera, int error) {
        if (mProxy != null) mProxy.onError(camera, error);
        setCurrentState(STATE_ERROR);
    }

    @Override
    public void onClosed(CameraDevice camera) {
        if (mProxy != null) mProxy.onClosed(camera);
        setCurrentState(STATE_CLOSED);
    }

    /**
     * Wait until the desired state is observed, checking all state
     * transitions since the last state that was waited on.
     *
     * <p>Note: Only one waiter allowed at a time!</p>
     *
     * @param desired state to observe a transition to
     * @param timeout how long to wait in milliseconds
     *
     * @throws TimeoutRuntimeException if the desired state is not observed before timeout.
     */
    public void waitForState(int state, long timeout) {
        Integer[] stateArray = { state };

        waitForAnyOfStates(Arrays.asList(stateArray), timeout);
    }

    /**
     * Wait until the one of the desired states is observed, checking all
     * state transitions since the last state that was waited on.
     *
     * <p>Note: Only one waiter allowed at a time!</p>
     *
     * @param states Set of desired states to observe a transition to.
     * @param timeout how long to wait in milliseconds
     *
     * @return the state reached
     * @throws TimeoutRuntimeException if none of the states is observed before timeout.
     *
     */
    public int waitForAnyOfStates(Collection<Integer> states, final long timeout) {
        synchronized(mLock) {
            if (mWaiting) throw new IllegalStateException("Only one waiter allowed at a time");
            mWaiting = true;
        }
        if (VERBOSE) {
            StringBuilder s = new StringBuilder("Waiting for state(s) ");
            appendStates(s, states);
            Log.v(TAG, s.toString());
        }

        Integer nextState = null;
        long timeoutLeft = timeout;
        long startMs = SystemClock.elapsedRealtime();
        try {
            while ((nextState = mRecentStates.poll(timeoutLeft, TimeUnit.MILLISECONDS))
                    != null) {
                if (VERBOSE) {
                    Log.v(TAG, "  Saw transition to " + stateToString(nextState));
                }
                if (states.contains(nextState)) break;
                long endMs = SystemClock.elapsedRealtime();
                timeoutLeft -= (endMs - startMs);
                startMs = endMs;
            }
        } catch (InterruptedException e) {
            throw new UnsupportedOperationException("Does not support interrupts on waits", e);
        }

        synchronized(mLock) {
            mWaiting = false;
        }

        if (!states.contains(nextState)) {
            StringBuilder s = new StringBuilder("Timed out after ");
            s.append(timeout);
            s.append(" ms waiting for state(s) ");
            appendStates(s, states);

            throw new TimeoutRuntimeException(s.toString());
        }

        return nextState;
    }

    /**
     * Convert state integer to a String
     */
    public static String stateToString(int state) {
        return mStateNames[state + 1];
    }

    /**
     * Append all states to string
     */
    public static void appendStates(StringBuilder s, Collection<Integer> states) {
        boolean start = true;
        for (Integer state: states) {
            if (!start) s.append(" ");
            s.append(stateToString(state));
            start = false;
        }
    }
}