summaryrefslogtreecommitdiffstats
path: root/camera2/public/src/com/android/ex/camera2/pos/AutoFocusStateMachine.java
blob: 23959e47a194be89fc7dc9bf1b8ba582c536008a (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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
 * 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.pos;

import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraMetadata.Key;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.util.Log;

import com.android.ex.camera2.utils.SysTrace;

/**
 * Manage the auto focus state machine for CameraDevice.
 *
 * <p>Requests are created only when the AF needs to be manipulated from the user,
 * but automatic camera-caused AF state changes are broadcasted from any new result.</p>
 */
public class AutoFocusStateMachine {

    /**
     * Observe state AF state transitions triggered by
     * {@link AutoFocusStateMachine#onCaptureCompleted onCaptureCompleted}.
     */
    public interface AutoFocusStateListener {
        /**
         * The camera is currently focused (either active or passive).
         *
         * @param locked True if the lens has been locked from moving, false otherwise.
         */
        void onAutoFocusSuccess(CaptureResult result, boolean locked);

        /**
         * The camera is currently not focused (either active or passive).
         *
         * @param locked False if the AF is still scanning, true if needs a restart.
         */
        void onAutoFocusFail(CaptureResult result, boolean locked);

        /**
         * The camera is currently scanning (either active or passive)
         * and has not yet converged.
         *
         * <p>This is not called for results where the AF either succeeds or fails.</p>
         */
        void onAutoFocusScan(CaptureResult result);

        /**
         * The camera is currently not doing anything with the autofocus.
         *
         * <p>Autofocus could be off, or this could be an intermediate state transition as
         * scanning restarts.</p>
         */
        void onAutoFocusInactive(CaptureResult result);
    }

    private static final String TAG = "AutoFocusStateMachine";
    private static final boolean DEBUG_LOGGING = Log.isLoggable(TAG, Log.DEBUG);
    private static final boolean VERBOSE_LOGGING = Log.isLoggable(TAG, Log.VERBOSE);
    private static final int AF_UNINITIALIZED = -1;

    private final AutoFocusStateListener mListener;
    private int mLastAfState = AF_UNINITIALIZED;
    private int mLastAfMode = AF_UNINITIALIZED;
    private int mCurrentAfMode = AF_UNINITIALIZED;
    private int mCurrentAfTrigger = AF_UNINITIALIZED;

    private int mCurrentAfCookie = AF_UNINITIALIZED;
    private String mCurrentAfTrace = "";
    private int mLastAfCookie = 0;

    public AutoFocusStateMachine(AutoFocusStateListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("listener should not be null");
        }
        mListener = listener;
    }

    /**
     * Invoke every time we get a new CaptureResult via
     * {@link CameraDevice.CaptureListener#onCaptureCompleted}.
     *
     * <p>This function is responsible for dispatching updates via the
     * {@link AutoFocusStateListener} so without calling this on a regular basis, no
     * AF changes will be observed.</p>
     *
     * @param result CaptureResult
     */
    public synchronized void onCaptureCompleted(CaptureResult result) {

        /**
         * Work-around for b/11269834
         * Although these should never-ever happen, harden for ship
         */
        if (result == null) {
            Log.w(TAG, "onCaptureCompleted - missing result, skipping AF update");
            return;
        }

        Key<Integer> keyAfState = CaptureResult.CONTROL_AF_STATE;
        if (keyAfState == null) {
            Log.e(TAG, "onCaptureCompleted - missing android.control.afState key, " +
                    "skipping AF update");
            return;
        }

        Key<Integer> keyAfMode = CaptureResult.CONTROL_AF_MODE;
        if (keyAfMode == null) {
            Log.e(TAG, "onCaptureCompleted - missing android.control.afMode key, " +
                    "skipping AF update");
            return;
        }

        Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
        Integer afMode = result.get(CaptureResult.CONTROL_AF_MODE);

        /**
         * Work-around for b/11238865
         * This is a HAL bug as these fields should be there always.
         */
        if (afState == null) {
            Log.w(TAG, "onCaptureCompleted - missing android.control.afState !");
            return;
        } else if (afMode == null) {
            Log.w(TAG, "onCaptureCompleted - missing android.control.afMode !");
            return;
        }

        if (DEBUG_LOGGING) Log.d(TAG, "onCaptureCompleted - new AF mode = " + afMode +
                " new AF state = " + afState);

        if (mLastAfState == afState && afMode == mLastAfMode) {
            // Same AF state as last time, nothing else needs to be done.
            return;
        }

        if (VERBOSE_LOGGING) Log.v(TAG, "onCaptureCompleted - new AF mode = " + afMode +
                " new AF state = " + afState);

        mLastAfState = afState;
        mLastAfMode = afMode;

        switch (afState) {
            case CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED:
                mListener.onAutoFocusSuccess(result, /*locked*/true);
                endTraceAsync();
                break;
            case CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED:
                mListener.onAutoFocusFail(result, /*locked*/true);
                endTraceAsync();
                break;
            case CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED:
                mListener.onAutoFocusSuccess(result, /*locked*/false);
                break;
            case CaptureResult.CONTROL_AF_STATE_PASSIVE_UNFOCUSED:
                mListener.onAutoFocusFail(result, /*locked*/false);
                break;
            case CaptureResult.CONTROL_AF_STATE_ACTIVE_SCAN:
                mListener.onAutoFocusScan(result);
                break;
            case CaptureResult.CONTROL_AF_STATE_PASSIVE_SCAN:
                mListener.onAutoFocusScan(result);
                break;
            case CaptureResult.CONTROL_AF_STATE_INACTIVE:
                mListener.onAutoFocusInactive(result);
                break;
        }
    }

    /**
     * Reset the current AF state.
     *
     * <p>
     * When dropping capture results (by not invoking {@link #onCaptureCompleted} when a new
     * {@link CaptureResult} is available), call this function to reset the state. Otherwise
     * the next time a new state is observed this class may incorrectly consider it as the same
     * state as before, and not issue any callbacks by {@link AutoFocusStateListener}.
     * </p>
     */
    public synchronized void resetState() {
        if (VERBOSE_LOGGING) Log.v(TAG, "resetState - last state was " + mLastAfState);

        mLastAfState = AF_UNINITIALIZED;
    }

    /**
     * Lock the lens from moving. Typically used before taking a picture.
     *
     * <p>After calling this function, submit the new requestBuilder as a separate capture.
     * Do not submit it as a repeating request or the AF lock will be repeated every time.</p>
     *
     * <p>Create a new repeating request from repeatingBuilder and set that as the updated
     * repeating request.</p>
     *
     * <p>If the lock succeeds, {@link AutoFocusStateListener#onAutoFocusSuccess} with
     * {@code locked == true} will be invoked. If the lock fails,
     * {@link AutoFocusStateListener#onAutoFocusFail} with {@code scanning == false} will be
     * invoked.</p>
     *
     * @param repeatingBuilder Builder for a repeating request.
     * @param requestBuilder Builder for a non-repeating request.
     *
     */
    public synchronized void lockAutoFocus(CaptureRequest.Builder repeatingBuilder,
            CaptureRequest.Builder requestBuilder) {

        if (VERBOSE_LOGGING) Log.v(TAG, "lockAutoFocus");

        if (mCurrentAfMode == AF_UNINITIALIZED) {
            throw new IllegalStateException("AF mode was not enabled");
        }

        beginTraceAsync("AFSM_lockAutoFocus");

        mCurrentAfTrigger = CaptureRequest.CONTROL_AF_TRIGGER_START;

        repeatingBuilder.set(CaptureRequest.CONTROL_AF_MODE, mCurrentAfMode);
        requestBuilder.set(CaptureRequest.CONTROL_AF_MODE, mCurrentAfMode);

        repeatingBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CaptureRequest.CONTROL_AF_TRIGGER_IDLE);
        requestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CaptureRequest.CONTROL_AF_TRIGGER_START);
    }

    /**
     * Unlock the lens, allowing it to move again. Typically used after taking a picture.
     *
     * <p>After calling this function, submit the new requestBuilder as a separate capture.
     * Do not submit it as a repeating request or the AF lock will be repeated every time.</p>
     *
     * <p>Create a new repeating request from repeatingBuilder and set that as the updated
     * repeating request.</p>
     *
     * <p>Once the unlock takes effect, {@link AutoFocusStateListener#onAutoFocusInactive} is
     * invoked, and after that the effects depend on which mode you were in:
     * <ul>
     * <li>Passive - Scanning restarts with {@link AutoFocusStateListener#onAutoFocusScan}</li>
     * <li>Active - The lens goes back to a default position (no callbacks)</li>
     * </ul>
     * </p>
     *
     * @param repeatingBuilder Builder for a repeating request.
     * @param requestBuilder Builder for a non-repeating request.
     *
     */
    public synchronized void unlockAutoFocus(CaptureRequest.Builder repeatingBuilder,
            CaptureRequest.Builder requestBuilder) {

        if (VERBOSE_LOGGING) Log.v(TAG, "unlockAutoFocus");

        if (mCurrentAfMode == AF_UNINITIALIZED) {
            throw new IllegalStateException("AF mode was not enabled");
        }

        mCurrentAfTrigger = CaptureRequest.CONTROL_AF_TRIGGER_CANCEL;

        repeatingBuilder.set(CaptureRequest.CONTROL_AF_MODE, mCurrentAfMode);
        requestBuilder.set(CaptureRequest.CONTROL_AF_MODE, mCurrentAfMode);

        repeatingBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CaptureRequest.CONTROL_AF_TRIGGER_IDLE);
        requestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CaptureRequest.CONTROL_AF_TRIGGER_CANCEL);
    }

    /**
     * Enable active auto focus, immediately triggering a converging scan.
     *
     * <p>This is typically only used when locking the passive AF has failed.</p>
     *
     * <p>Once active AF scanning starts, {@link AutoFocusStateListener#onAutoFocusScan} will be
     * invoked.</p>
     *
     * <p>If the active scan succeeds, {@link AutoFocusStateListener#onAutoFocusSuccess} with
     * {@code locked == true} will be invoked. If the active scan fails,
     * {@link AutoFocusStateListener#onAutoFocusFail} with {@code scanning == false} will be
     * invoked.</p>
     *
     * <p>After calling this function, submit the new requestBuilder as a separate capture.
     * Do not submit it as a repeating request or the AF trigger will be repeated every time.</p>
     *
     * <p>Create a new repeating request from repeatingBuilder and set that as the updated
     * repeating request.</p>
     *
     * @param repeatingBuilder Builder for a repeating request.
     * @param requestBuilder Builder for a non-repeating request.
     *
     * @param repeatingBuilder Builder for a repeating request.
     */
    public synchronized void setActiveAutoFocus(CaptureRequest.Builder repeatingBuilder,
            CaptureRequest.Builder requestBuilder) {
        if (VERBOSE_LOGGING) Log.v(TAG, "setActiveAutoFocus");

        beginTraceAsync("AFSM_setActiveAutoFocus");

        mCurrentAfMode = CaptureRequest.CONTROL_AF_MODE_AUTO;

        repeatingBuilder.set(CaptureRequest.CONTROL_AF_MODE, mCurrentAfMode);
        requestBuilder.set(CaptureRequest.CONTROL_AF_MODE, mCurrentAfMode);

        repeatingBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CaptureRequest.CONTROL_AF_TRIGGER_IDLE);
        requestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CaptureRequest.CONTROL_AF_TRIGGER_START);
    }

    /**
     * Enable passive autofocus, immediately triggering a non-converging scan.
     *
     * <p>While passive autofocus is enabled, use {@link #lockAutoFocus} to lock
     * the lens before taking a picture. Once a picture is taken, use {@link #unlockAutoFocus}
     * to let the lens go back into passive scanning.</p>
     *
     * <p>Once passive AF scanning starts, {@link AutoFocusStateListener#onAutoFocusScan} will be
     * invoked.</p>
     *
     * @param repeatingBuilder Builder for a repeating request.
     * @param picture True for still capture AF, false for video AF.
     */
    public synchronized void setPassiveAutoFocus(boolean picture,
            CaptureRequest.Builder repeatingBuilder) {
        if (VERBOSE_LOGGING) Log.v(TAG, "setPassiveAutoFocus - picture " + picture);

        if (picture) {
            mCurrentAfMode = CaptureResult.CONTROL_AF_MODE_CONTINUOUS_PICTURE;
        } else {
            mCurrentAfMode = CaptureResult.CONTROL_AF_MODE_CONTINUOUS_VIDEO;
        }

        repeatingBuilder.set(CaptureRequest.CONTROL_AF_MODE, mCurrentAfMode);
    }

    private synchronized void beginTraceAsync(String sectionName) {
        if (mCurrentAfCookie != AF_UNINITIALIZED) {
            // Terminate any currently active async sections before beginning another section
            SysTrace.endSectionAsync(mCurrentAfTrace, mCurrentAfCookie);
        }

        mLastAfCookie++;
        mCurrentAfCookie = mLastAfCookie;
        mCurrentAfTrace = sectionName;

        SysTrace.beginSectionAsync(sectionName, mCurrentAfCookie);
    }

    private synchronized void endTraceAsync() {
        if (mCurrentAfCookie == AF_UNINITIALIZED) {
            Log.w(TAG, "endTraceAsync - no current trace active");
            return;
        }

        SysTrace.endSectionAsync(mCurrentAfTrace, mCurrentAfCookie);
        mCurrentAfCookie = AF_UNINITIALIZED;
    }
}