CameraManager.java revision b6a781066e6b0f2578cafefdc61c9ba18c0efc2e
1/*
2 * Copyright (C) 2013 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
17package android.hardware.camera2;
18
19import android.content.Context;
20import android.hardware.ICameraService;
21import android.hardware.ICameraServiceListener;
22import android.hardware.camera2.impl.CameraMetadataNative;
23import android.hardware.camera2.legacy.CameraDeviceUserShim;
24import android.hardware.camera2.utils.CameraBinderDecorator;
25import android.hardware.camera2.utils.CameraRuntimeException;
26import android.hardware.camera2.utils.BinderHolder;
27import android.os.IBinder;
28import android.os.Handler;
29import android.os.Looper;
30import android.os.RemoteException;
31import android.os.ServiceManager;
32import android.util.Log;
33import android.util.ArrayMap;
34
35import java.util.ArrayList;
36
37/**
38 * <p>An interface for iterating, listing, and connecting to
39 * {@link CameraDevice CameraDevices}.</p>
40 *
41 * <p>You can get an instance of this class by calling
42 * {@link android.content.Context#getSystemService(String) Context.getSystemService()}.</p>
43 *
44 * <pre>CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);</pre>
45 *
46 * <p>For more details about communicating with camera devices, read the Camera
47 * developer guide or the {@link android.hardware.camera2 camera2}
48 * package documentation.</p>
49 */
50public final class CameraManager {
51
52    private static final String TAG = "CameraManager";
53
54    /**
55     * This should match the ICameraService definition
56     */
57    private static final String CAMERA_SERVICE_BINDER_NAME = "media.camera";
58    private static final int USE_CALLING_UID = -1;
59
60    private final ICameraService mCameraService;
61    private ArrayList<String> mDeviceIdList;
62
63    private final ArrayMap<AvailabilityListener, Handler> mListenerMap =
64            new ArrayMap<AvailabilityListener, Handler>();
65
66    private final Context mContext;
67    private final Object mLock = new Object();
68
69    /**
70     * @hide
71     */
72    public CameraManager(Context context) {
73        mContext = context;
74
75        IBinder cameraServiceBinder = ServiceManager.getService(CAMERA_SERVICE_BINDER_NAME);
76        ICameraService cameraServiceRaw = ICameraService.Stub.asInterface(cameraServiceBinder);
77
78        /**
79         * Wrap the camera service in a decorator which automatically translates return codes
80         * into exceptions, and RemoteExceptions into other exceptions.
81         */
82        mCameraService = CameraBinderDecorator.newInstance(cameraServiceRaw);
83
84        try {
85            CameraBinderDecorator.throwOnError(
86                    CameraMetadataNative.nativeSetupGlobalVendorTagDescriptor());
87        } catch (CameraRuntimeException e) {
88            handleRecoverableSetupErrors(e, "Failed to set up vendor tags");
89        }
90
91        try {
92            mCameraService.addListener(new CameraServiceListener());
93        } catch(CameraRuntimeException e) {
94            throw new IllegalStateException("Failed to register a camera service listener",
95                    e.asChecked());
96        } catch (RemoteException e) {
97            // impossible
98        }
99    }
100
101    /**
102     * Return the list of currently connected camera devices by
103     * identifier.
104     *
105     * <p>Non-removable cameras use integers starting at 0 for their
106     * identifiers, while removable cameras have a unique identifier for each
107     * individual device, even if they are the same model.</p>
108     *
109     * @return The list of currently connected camera devices.
110     */
111    public String[] getCameraIdList() throws CameraAccessException {
112        synchronized (mLock) {
113            try {
114                return getOrCreateDeviceIdListLocked().toArray(new String[0]);
115            } catch(CameraAccessException e) {
116                // this should almost never happen, except if mediaserver crashes
117                throw new IllegalStateException(
118                        "Failed to query camera service for device ID list", e);
119            }
120        }
121    }
122
123    /**
124     * Register a listener to be notified about camera device availability.
125     *
126     * <p>Registering the same listener again will replace the handler with the
127     * new one provided.</p>
128     *
129     * @param listener The new listener to send camera availability notices to
130     * @param handler The handler on which the listener should be invoked, or
131     * {@code null} to use the current thread's {@link android.os.Looper looper}.
132     */
133    public void addAvailabilityListener(AvailabilityListener listener, Handler handler) {
134        if (handler == null) {
135            Looper looper = Looper.myLooper();
136            if (looper == null) {
137                throw new IllegalArgumentException(
138                        "No handler given, and current thread has no looper!");
139            }
140            handler = new Handler(looper);
141        }
142
143        synchronized (mLock) {
144            mListenerMap.put(listener, handler);
145        }
146    }
147
148    /**
149     * Remove a previously-added listener; the listener will no longer receive
150     * connection and disconnection callbacks.
151     *
152     * <p>Removing a listener that isn't registered has no effect.</p>
153     *
154     * @param listener The listener to remove from the notification list
155     */
156    public void removeAvailabilityListener(AvailabilityListener listener) {
157        synchronized (mLock) {
158            mListenerMap.remove(listener);
159        }
160    }
161
162    /**
163     * <p>Query the capabilities of a camera device. These capabilities are
164     * immutable for a given camera.</p>
165     *
166     * @param cameraId The id of the camera device to query
167     * @return The properties of the given camera
168     *
169     * @throws IllegalArgumentException if the cameraId does not match any
170     * currently connected camera device.
171     * @throws CameraAccessException if the camera is disabled by device policy.
172     * @throws SecurityException if the application does not have permission to
173     * access the camera
174     *
175     * @see #getCameraIdList
176     * @see android.app.admin.DevicePolicyManager#setCameraDisabled
177     */
178    public CameraCharacteristics getCameraCharacteristics(String cameraId)
179            throws CameraAccessException {
180
181        synchronized (mLock) {
182            if (!getOrCreateDeviceIdListLocked().contains(cameraId)) {
183                throw new IllegalArgumentException(String.format("Camera id %s does not match any" +
184                        " currently connected camera device", cameraId));
185            }
186        }
187
188        CameraMetadataNative info = new CameraMetadataNative();
189        try {
190            mCameraService.getCameraCharacteristics(Integer.valueOf(cameraId), info);
191        } catch(CameraRuntimeException e) {
192            throw e.asChecked();
193        } catch(RemoteException e) {
194            // impossible
195            return null;
196        }
197        return new CameraCharacteristics(info);
198    }
199
200    /**
201     * Helper for openning a connection to a camera with the given ID.
202     *
203     * @param cameraId The unique identifier of the camera device to open
204     * @param listener The listener for the camera. Must not be null.
205     * @param handler  The handler to call the listener on. Must not be null.
206     *
207     * @throws CameraAccessException if the camera is disabled by device policy,
208     * or too many camera devices are already open, or the cameraId does not match
209     * any currently available camera device.
210     *
211     * @throws SecurityException if the application does not have permission to
212     * access the camera
213     * @throws IllegalArgumentException if listener or handler is null.
214     * @return A handle to the newly-created camera device.
215     *
216     * @see #getCameraIdList
217     * @see android.app.admin.DevicePolicyManager#setCameraDisabled
218     */
219    private CameraDevice openCameraDeviceUserAsync(String cameraId,
220            CameraDevice.StateListener listener, Handler handler)
221            throws CameraAccessException {
222        CameraDevice device = null;
223        try {
224
225            synchronized (mLock) {
226
227                ICameraDeviceUser cameraUser;
228
229                android.hardware.camera2.impl.CameraDevice deviceImpl =
230                        new android.hardware.camera2.impl.CameraDevice(
231                                cameraId,
232                                listener,
233                                handler);
234
235                BinderHolder holder = new BinderHolder();
236
237                ICameraDeviceCallbacks callbacks = deviceImpl.getCallbacks();
238                int id = Integer.parseInt(cameraId);
239                try {
240                    mCameraService.connectDevice(callbacks, id, mContext.getPackageName(),
241                            USE_CALLING_UID, holder);
242                    cameraUser = ICameraDeviceUser.Stub.asInterface(holder.getBinder());
243                } catch (CameraRuntimeException e) {
244                    if (e.getReason() == CameraAccessException.CAMERA_DEPRECATED_HAL) {
245                        // Use legacy camera implementation for HAL1 devices
246                        Log.i(TAG, "Using legacy camera HAL.");
247                        cameraUser = CameraDeviceUserShim.connectBinderShim(callbacks, id);
248                    } else {
249                        // Rethrow otherwise
250                        throw e;
251                    }
252                }
253
254                // TODO: factor out listener to be non-nested, then move setter to constructor
255                // For now, calling setRemoteDevice will fire initial
256                // onOpened/onUnconfigured callbacks.
257                deviceImpl.setRemoteDevice(cameraUser);
258                device = deviceImpl;
259            }
260
261        } catch (NumberFormatException e) {
262            throw new IllegalArgumentException("Expected cameraId to be numeric, but it was: "
263                    + cameraId);
264        } catch (CameraRuntimeException e) {
265            throw e.asChecked();
266        } catch (RemoteException e) {
267            // impossible
268        }
269        return device;
270    }
271
272    /**
273     * Open a connection to a camera with the given ID.
274     *
275     * <p>Use {@link #getCameraIdList} to get the list of available camera
276     * devices. Note that even if an id is listed, open may fail if the device
277     * is disconnected between the calls to {@link #getCameraIdList} and
278     * {@link #openCamera}.</p>
279     *
280     * <p>Once the camera is successfully opened, {@link CameraDevice.StateListener#onOpened} will
281     * be invoked with the newly opened {@link CameraDevice}. The camera device can then be set up
282     * for operation by calling {@link CameraDevice#createCaptureSession} and
283     * {@link CameraDevice#createCaptureRequest}</p>
284     *
285     * <!--
286     * <p>Since the camera device will be opened asynchronously, any asynchronous operations done
287     * on the returned CameraDevice instance will be queued up until the device startup has
288     * completed and the listener's {@link CameraDevice.StateListener#onOpened onOpened} method is
289     * called. The pending operations are then processed in order.</p>
290     * -->
291     * <p>If the camera becomes disconnected during initialization
292     * after this function call returns,
293     * {@link CameraDevice.StateListener#onDisconnected} with a
294     * {@link CameraDevice} in the disconnected state (and
295     * {@link CameraDevice.StateListener#onOpened} will be skipped).</p>
296     *
297     * <p>If opening the camera device fails, then the device listener's
298     * {@link CameraDevice.StateListener#onError onError} method will be called, and subsequent
299     * calls on the camera device will throw an {@link IllegalStateException}.</p>
300     *
301     * @param cameraId
302     *             The unique identifier of the camera device to open
303     * @param listener
304     *             The listener which is invoked once the camera is opened
305     * @param handler
306     *             The handler on which the listener should be invoked, or
307     *             {@code null} to use the current thread's {@link android.os.Looper looper}.
308     *
309     * @throws CameraAccessException if the camera is disabled by device policy,
310     * or the camera has become or was disconnected.
311     *
312     * @throws IllegalArgumentException if cameraId or the listener was null,
313     * or the cameraId does not match any currently or previously available
314     * camera device.
315     *
316     * @throws SecurityException if the application does not have permission to
317     * access the camera
318     *
319     * @see #getCameraIdList
320     * @see android.app.admin.DevicePolicyManager#setCameraDisabled
321     */
322    public void openCamera(String cameraId, final CameraDevice.StateListener listener,
323            Handler handler)
324            throws CameraAccessException {
325
326        if (cameraId == null) {
327            throw new IllegalArgumentException("cameraId was null");
328        } else if (listener == null) {
329            throw new IllegalArgumentException("listener was null");
330        } else if (handler == null) {
331            if (Looper.myLooper() != null) {
332                handler = new Handler();
333            } else {
334                throw new IllegalArgumentException(
335                        "Looper doesn't exist in the calling thread");
336            }
337        }
338
339        openCameraDeviceUserAsync(cameraId, listener, handler);
340    }
341
342    /**
343     * Interface for listening to camera devices becoming available or
344     * unavailable.
345     *
346     * <p>Cameras become available when they are no longer in use, or when a new
347     * removable camera is connected. They become unavailable when some
348     * application or service starts using a camera, or when a removable camera
349     * is disconnected.</p>
350     *
351     * @see addAvailabilityListener
352     */
353    public static abstract class AvailabilityListener {
354
355        /**
356         * A new camera has become available to use.
357         *
358         * <p>The default implementation of this method does nothing.</p>
359         *
360         * @param cameraId The unique identifier of the new camera.
361         */
362        public void onCameraAvailable(String cameraId) {
363            // default empty implementation
364        }
365
366        /**
367         * A previously-available camera has become unavailable for use.
368         *
369         * <p>If an application had an active CameraDevice instance for the
370         * now-disconnected camera, that application will receive a
371         * {@link CameraDevice.StateListener#onDisconnected disconnection error}.</p>
372         *
373         * <p>The default implementation of this method does nothing.</p>
374         *
375         * @param cameraId The unique identifier of the disconnected camera.
376         */
377        public void onCameraUnavailable(String cameraId) {
378            // default empty implementation
379        }
380    }
381
382    private ArrayList<String> getOrCreateDeviceIdListLocked() throws CameraAccessException {
383        if (mDeviceIdList == null) {
384            int numCameras = 0;
385
386            try {
387                numCameras = mCameraService.getNumberOfCameras();
388            } catch(CameraRuntimeException e) {
389                throw e.asChecked();
390            } catch (RemoteException e) {
391                // impossible
392                return null;
393            }
394
395            mDeviceIdList = new ArrayList<String>();
396            CameraMetadataNative info = new CameraMetadataNative();
397            for (int i = 0; i < numCameras; ++i) {
398                // Non-removable cameras use integers starting at 0 for their
399                // identifiers
400                boolean isDeviceSupported = false;
401                try {
402                    mCameraService.getCameraCharacteristics(i, info);
403                    if (!info.isEmpty()) {
404                        isDeviceSupported = true;
405                    } else {
406                        throw new AssertionError("Expected to get non-empty characteristics");
407                    }
408                } catch(IllegalArgumentException  e) {
409                    // Got a BAD_VALUE from service, meaning that this
410                    // device is not supported.
411                } catch(CameraRuntimeException e) {
412                    throw e.asChecked();
413                } catch(RemoteException e) {
414                    // impossible
415                }
416
417                if (isDeviceSupported) {
418                    mDeviceIdList.add(String.valueOf(i));
419                }
420            }
421
422        }
423        return mDeviceIdList;
424    }
425
426    private void handleRecoverableSetupErrors(CameraRuntimeException e, String msg) {
427        int problem = e.getReason();
428        switch (problem) {
429            case CameraAccessException.CAMERA_DISCONNECTED:
430                String errorMsg = CameraAccessException.getDefaultMessage(problem);
431                Log.w(TAG, msg + ": " + errorMsg);
432                break;
433            default:
434                throw new IllegalStateException(msg, e.asChecked());
435        }
436    }
437
438    // TODO: this class needs unit tests
439    // TODO: extract class into top level
440    private class CameraServiceListener extends ICameraServiceListener.Stub {
441
442        // Keep up-to-date with ICameraServiceListener.h
443
444        // Device physically unplugged
445        public static final int STATUS_NOT_PRESENT = 0;
446        // Device physically has been plugged in
447        // and the camera can be used exclusively
448        public static final int STATUS_PRESENT = 1;
449        // Device physically has been plugged in
450        // but it will not be connect-able until enumeration is complete
451        public static final int STATUS_ENUMERATING = 2;
452        // Camera is in use by another app and cannot be used exclusively
453        public static final int STATUS_NOT_AVAILABLE = 0x80000000;
454
455        // Camera ID -> Status map
456        private final ArrayMap<String, Integer> mDeviceStatus = new ArrayMap<String, Integer>();
457
458        private static final String TAG = "CameraServiceListener";
459
460        @Override
461        public IBinder asBinder() {
462            return this;
463        }
464
465        private boolean isAvailable(int status) {
466            switch (status) {
467                case STATUS_PRESENT:
468                    return true;
469                default:
470                    return false;
471            }
472        }
473
474        private boolean validStatus(int status) {
475            switch (status) {
476                case STATUS_NOT_PRESENT:
477                case STATUS_PRESENT:
478                case STATUS_ENUMERATING:
479                case STATUS_NOT_AVAILABLE:
480                    return true;
481                default:
482                    return false;
483            }
484        }
485
486        @Override
487        public void onStatusChanged(int status, int cameraId) throws RemoteException {
488            synchronized(CameraManager.this.mLock) {
489
490                Log.v(TAG,
491                        String.format("Camera id %d has status changed to 0x%x", cameraId, status));
492
493                final String id = String.valueOf(cameraId);
494
495                if (!validStatus(status)) {
496                    Log.e(TAG, String.format("Ignoring invalid device %d status 0x%x", cameraId,
497                            status));
498                    return;
499                }
500
501                Integer oldStatus = mDeviceStatus.put(id, status);
502
503                if (oldStatus != null && oldStatus == status) {
504                    Log.v(TAG, String.format(
505                            "Device status changed to 0x%x, which is what it already was",
506                            status));
507                    return;
508                }
509
510                // TODO: consider abstracting out this state minimization + transition
511                // into a separate
512                // more easily testable class
513                // i.e. (new State()).addState(STATE_AVAILABLE)
514                //                   .addState(STATE_NOT_AVAILABLE)
515                //                   .addTransition(STATUS_PRESENT, STATE_AVAILABLE),
516                //                   .addTransition(STATUS_NOT_PRESENT, STATE_NOT_AVAILABLE)
517                //                   .addTransition(STATUS_ENUMERATING, STATE_NOT_AVAILABLE);
518                //                   .addTransition(STATUS_NOT_AVAILABLE, STATE_NOT_AVAILABLE);
519
520                // Translate all the statuses to either 'available' or 'not available'
521                //  available -> available         => no new update
522                //  not available -> not available => no new update
523                if (oldStatus != null && isAvailable(status) == isAvailable(oldStatus)) {
524
525                    Log.v(TAG,
526                            String.format(
527                                    "Device status was previously available (%d), " +
528                                            " and is now again available (%d)" +
529                                            "so no new client visible update will be sent",
530                                    isAvailable(status), isAvailable(status)));
531                    return;
532                }
533
534                final int listenerCount = mListenerMap.size();
535                for (int i = 0; i < listenerCount; i++) {
536                    Handler handler = mListenerMap.valueAt(i);
537                    final AvailabilityListener listener = mListenerMap.keyAt(i);
538                    if (isAvailable(status)) {
539                        handler.post(
540                            new Runnable() {
541                                @Override
542                                public void run() {
543                                    listener.onCameraAvailable(id);
544                                }
545                            });
546                    } else {
547                        handler.post(
548                            new Runnable() {
549                                @Override
550                                public void run() {
551                                    listener.onCameraUnavailable(id);
552                                }
553                            });
554                    }
555                } // for
556            } // synchronized
557        } // onStatusChanged
558    } // CameraServiceListener
559} // CameraManager
560