CameraManager.java revision 5b02e9f65f52bbdd6fbb05b1ad73b71b72ef077c
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        CameraCharacteristics characteristics = getCameraCharacteristics(cameraId);
223        CameraDevice device = null;
224        try {
225
226            synchronized (mLock) {
227
228                ICameraDeviceUser cameraUser;
229
230                android.hardware.camera2.impl.CameraDevice deviceImpl =
231                        new android.hardware.camera2.impl.CameraDevice(
232                                cameraId,
233                                listener,
234                                handler,
235                                characteristics);
236
237                BinderHolder holder = new BinderHolder();
238
239                ICameraDeviceCallbacks callbacks = deviceImpl.getCallbacks();
240                int id = Integer.parseInt(cameraId);
241                try {
242                    mCameraService.connectDevice(callbacks, id, mContext.getPackageName(),
243                            USE_CALLING_UID, holder);
244                    cameraUser = ICameraDeviceUser.Stub.asInterface(holder.getBinder());
245                } catch (CameraRuntimeException e) {
246                    if (e.getReason() == CameraAccessException.CAMERA_DEPRECATED_HAL) {
247                        // Use legacy camera implementation for HAL1 devices
248                        Log.i(TAG, "Using legacy camera HAL.");
249                        cameraUser = CameraDeviceUserShim.connectBinderShim(callbacks, id);
250                    } else {
251                        // Rethrow otherwise
252                        throw e;
253                    }
254                }
255
256                // TODO: factor out listener to be non-nested, then move setter to constructor
257                // For now, calling setRemoteDevice will fire initial
258                // onOpened/onUnconfigured callbacks.
259                deviceImpl.setRemoteDevice(cameraUser);
260                device = deviceImpl;
261            }
262
263        } catch (NumberFormatException e) {
264            throw new IllegalArgumentException("Expected cameraId to be numeric, but it was: "
265                    + cameraId);
266        } catch (CameraRuntimeException e) {
267            throw e.asChecked();
268        } catch (RemoteException e) {
269            // impossible
270        }
271        return device;
272    }
273
274    /**
275     * Open a connection to a camera with the given ID.
276     *
277     * <p>Use {@link #getCameraIdList} to get the list of available camera
278     * devices. Note that even if an id is listed, open may fail if the device
279     * is disconnected between the calls to {@link #getCameraIdList} and
280     * {@link #openCamera}.</p>
281     *
282     * <p>Once the camera is successfully opened, {@link CameraDevice.StateListener#onOpened} will
283     * be invoked with the newly opened {@link CameraDevice}. The camera device can then be set up
284     * for operation by calling {@link CameraDevice#createCaptureSession} and
285     * {@link CameraDevice#createCaptureRequest}</p>
286     *
287     * <!--
288     * <p>Since the camera device will be opened asynchronously, any asynchronous operations done
289     * on the returned CameraDevice instance will be queued up until the device startup has
290     * completed and the listener's {@link CameraDevice.StateListener#onOpened onOpened} method is
291     * called. The pending operations are then processed in order.</p>
292     * -->
293     * <p>If the camera becomes disconnected during initialization
294     * after this function call returns,
295     * {@link CameraDevice.StateListener#onDisconnected} with a
296     * {@link CameraDevice} in the disconnected state (and
297     * {@link CameraDevice.StateListener#onOpened} will be skipped).</p>
298     *
299     * <p>If opening the camera device fails, then the device listener's
300     * {@link CameraDevice.StateListener#onError onError} method will be called, and subsequent
301     * calls on the camera device will throw an {@link IllegalStateException}.</p>
302     *
303     * @param cameraId
304     *             The unique identifier of the camera device to open
305     * @param listener
306     *             The listener which is invoked once the camera is opened
307     * @param handler
308     *             The handler on which the listener should be invoked, or
309     *             {@code null} to use the current thread's {@link android.os.Looper looper}.
310     *
311     * @throws CameraAccessException if the camera is disabled by device policy,
312     * or the camera has become or was disconnected.
313     *
314     * @throws IllegalArgumentException if cameraId or the listener was null,
315     * or the cameraId does not match any currently or previously available
316     * camera device.
317     *
318     * @throws SecurityException if the application does not have permission to
319     * access the camera
320     *
321     * @see #getCameraIdList
322     * @see android.app.admin.DevicePolicyManager#setCameraDisabled
323     */
324    public void openCamera(String cameraId, final CameraDevice.StateListener listener,
325            Handler handler)
326            throws CameraAccessException {
327
328        if (cameraId == null) {
329            throw new IllegalArgumentException("cameraId was null");
330        } else if (listener == null) {
331            throw new IllegalArgumentException("listener was null");
332        } else if (handler == null) {
333            if (Looper.myLooper() != null) {
334                handler = new Handler();
335            } else {
336                throw new IllegalArgumentException(
337                        "Looper doesn't exist in the calling thread");
338            }
339        }
340
341        openCameraDeviceUserAsync(cameraId, listener, handler);
342    }
343
344    /**
345     * Interface for listening to camera devices becoming available or
346     * unavailable.
347     *
348     * <p>Cameras become available when they are no longer in use, or when a new
349     * removable camera is connected. They become unavailable when some
350     * application or service starts using a camera, or when a removable camera
351     * is disconnected.</p>
352     *
353     * @see addAvailabilityListener
354     */
355    public static abstract class AvailabilityListener {
356
357        /**
358         * A new camera has become available to use.
359         *
360         * <p>The default implementation of this method does nothing.</p>
361         *
362         * @param cameraId The unique identifier of the new camera.
363         */
364        public void onCameraAvailable(String cameraId) {
365            // default empty implementation
366        }
367
368        /**
369         * A previously-available camera has become unavailable for use.
370         *
371         * <p>If an application had an active CameraDevice instance for the
372         * now-disconnected camera, that application will receive a
373         * {@link CameraDevice.StateListener#onDisconnected disconnection error}.</p>
374         *
375         * <p>The default implementation of this method does nothing.</p>
376         *
377         * @param cameraId The unique identifier of the disconnected camera.
378         */
379        public void onCameraUnavailable(String cameraId) {
380            // default empty implementation
381        }
382    }
383
384    private ArrayList<String> getOrCreateDeviceIdListLocked() throws CameraAccessException {
385        if (mDeviceIdList == null) {
386            int numCameras = 0;
387
388            try {
389                numCameras = mCameraService.getNumberOfCameras();
390            } catch(CameraRuntimeException e) {
391                throw e.asChecked();
392            } catch (RemoteException e) {
393                // impossible
394                return null;
395            }
396
397            mDeviceIdList = new ArrayList<String>();
398            CameraMetadataNative info = new CameraMetadataNative();
399            for (int i = 0; i < numCameras; ++i) {
400                // Non-removable cameras use integers starting at 0 for their
401                // identifiers
402                boolean isDeviceSupported = false;
403                try {
404                    mCameraService.getCameraCharacteristics(i, info);
405                    if (!info.isEmpty()) {
406                        isDeviceSupported = true;
407                    } else {
408                        throw new AssertionError("Expected to get non-empty characteristics");
409                    }
410                } catch(IllegalArgumentException  e) {
411                    // Got a BAD_VALUE from service, meaning that this
412                    // device is not supported.
413                } catch(CameraRuntimeException e) {
414                    throw e.asChecked();
415                } catch(RemoteException e) {
416                    // impossible
417                }
418
419                if (isDeviceSupported) {
420                    mDeviceIdList.add(String.valueOf(i));
421                }
422            }
423
424        }
425        return mDeviceIdList;
426    }
427
428    private void handleRecoverableSetupErrors(CameraRuntimeException e, String msg) {
429        int problem = e.getReason();
430        switch (problem) {
431            case CameraAccessException.CAMERA_DISCONNECTED:
432                String errorMsg = CameraAccessException.getDefaultMessage(problem);
433                Log.w(TAG, msg + ": " + errorMsg);
434                break;
435            default:
436                throw new IllegalStateException(msg, e.asChecked());
437        }
438    }
439
440    // TODO: this class needs unit tests
441    // TODO: extract class into top level
442    private class CameraServiceListener extends ICameraServiceListener.Stub {
443
444        // Keep up-to-date with ICameraServiceListener.h
445
446        // Device physically unplugged
447        public static final int STATUS_NOT_PRESENT = 0;
448        // Device physically has been plugged in
449        // and the camera can be used exclusively
450        public static final int STATUS_PRESENT = 1;
451        // Device physically has been plugged in
452        // but it will not be connect-able until enumeration is complete
453        public static final int STATUS_ENUMERATING = 2;
454        // Camera is in use by another app and cannot be used exclusively
455        public static final int STATUS_NOT_AVAILABLE = 0x80000000;
456
457        // Camera ID -> Status map
458        private final ArrayMap<String, Integer> mDeviceStatus = new ArrayMap<String, Integer>();
459
460        private static final String TAG = "CameraServiceListener";
461
462        @Override
463        public IBinder asBinder() {
464            return this;
465        }
466
467        private boolean isAvailable(int status) {
468            switch (status) {
469                case STATUS_PRESENT:
470                    return true;
471                default:
472                    return false;
473            }
474        }
475
476        private boolean validStatus(int status) {
477            switch (status) {
478                case STATUS_NOT_PRESENT:
479                case STATUS_PRESENT:
480                case STATUS_ENUMERATING:
481                case STATUS_NOT_AVAILABLE:
482                    return true;
483                default:
484                    return false;
485            }
486        }
487
488        @Override
489        public void onStatusChanged(int status, int cameraId) throws RemoteException {
490            synchronized(CameraManager.this.mLock) {
491
492                Log.v(TAG,
493                        String.format("Camera id %d has status changed to 0x%x", cameraId, status));
494
495                final String id = String.valueOf(cameraId);
496
497                if (!validStatus(status)) {
498                    Log.e(TAG, String.format("Ignoring invalid device %d status 0x%x", cameraId,
499                            status));
500                    return;
501                }
502
503                Integer oldStatus = mDeviceStatus.put(id, status);
504
505                if (oldStatus != null && oldStatus == status) {
506                    Log.v(TAG, String.format(
507                            "Device status changed to 0x%x, which is what it already was",
508                            status));
509                    return;
510                }
511
512                // TODO: consider abstracting out this state minimization + transition
513                // into a separate
514                // more easily testable class
515                // i.e. (new State()).addState(STATE_AVAILABLE)
516                //                   .addState(STATE_NOT_AVAILABLE)
517                //                   .addTransition(STATUS_PRESENT, STATE_AVAILABLE),
518                //                   .addTransition(STATUS_NOT_PRESENT, STATE_NOT_AVAILABLE)
519                //                   .addTransition(STATUS_ENUMERATING, STATE_NOT_AVAILABLE);
520                //                   .addTransition(STATUS_NOT_AVAILABLE, STATE_NOT_AVAILABLE);
521
522                // Translate all the statuses to either 'available' or 'not available'
523                //  available -> available         => no new update
524                //  not available -> not available => no new update
525                if (oldStatus != null && isAvailable(status) == isAvailable(oldStatus)) {
526
527                    Log.v(TAG,
528                            String.format(
529                                    "Device status was previously available (%d), " +
530                                            " and is now again available (%d)" +
531                                            "so no new client visible update will be sent",
532                                    isAvailable(status), isAvailable(status)));
533                    return;
534                }
535
536                final int listenerCount = mListenerMap.size();
537                for (int i = 0; i < listenerCount; i++) {
538                    Handler handler = mListenerMap.valueAt(i);
539                    final AvailabilityListener listener = mListenerMap.keyAt(i);
540                    if (isAvailable(status)) {
541                        handler.post(
542                            new Runnable() {
543                                @Override
544                                public void run() {
545                                    listener.onCameraAvailable(id);
546                                }
547                            });
548                    } else {
549                        handler.post(
550                            new Runnable() {
551                                @Override
552                                public void run() {
553                                    listener.onCameraUnavailable(id);
554                                }
555                            });
556                    }
557                } // for
558            } // synchronized
559        } // onStatusChanged
560    } // CameraServiceListener
561} // CameraManager
562