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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
|
/*
* Copyright (C) 2014 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 android.hardware.camera2.legacy;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.ICameraDeviceCallbacks;
import android.hardware.camera2.ICameraDeviceUser;
import android.hardware.camera2.utils.LongParcelable;
import android.hardware.camera2.impl.CameraMetadataNative;
import android.hardware.camera2.impl.CaptureResultExtras;
import android.hardware.camera2.params.OutputConfiguration;
import android.hardware.camera2.utils.CameraBinderDecorator;
import android.hardware.camera2.utils.CameraRuntimeException;
import android.os.ConditionVariable;
import android.os.IBinder;
import android.os.Looper;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.util.SparseArray;
import android.view.Surface;
import java.util.ArrayList;
import java.util.List;
/**
* Compatibility implementation of the Camera2 API binder interface.
*
* <p>
* This is intended to be called from the same process as client
* {@link android.hardware.camera2.CameraDevice}, and wraps a
* {@link android.hardware.camera2.legacy.LegacyCameraDevice} that emulates Camera2 service using
* the Camera1 API.
* </p>
*
* <p>
* Keep up to date with ICameraDeviceUser.aidl.
* </p>
*/
@SuppressWarnings("deprecation")
public class CameraDeviceUserShim implements ICameraDeviceUser {
private static final String TAG = "CameraDeviceUserShim";
private static final boolean DEBUG = Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.DEBUG);
private static final int OPEN_CAMERA_TIMEOUT_MS = 5000; // 5 sec (same as api1 cts timeout)
private final LegacyCameraDevice mLegacyDevice;
private final Object mConfigureLock = new Object();
private int mSurfaceIdCounter;
private boolean mConfiguring;
private final SparseArray<Surface> mSurfaces;
private final CameraCharacteristics mCameraCharacteristics;
private final CameraLooper mCameraInit;
private final CameraCallbackThread mCameraCallbacks;
protected CameraDeviceUserShim(int cameraId, LegacyCameraDevice legacyCamera,
CameraCharacteristics characteristics, CameraLooper cameraInit,
CameraCallbackThread cameraCallbacks) {
mLegacyDevice = legacyCamera;
mConfiguring = false;
mSurfaces = new SparseArray<Surface>();
mCameraCharacteristics = characteristics;
mCameraInit = cameraInit;
mCameraCallbacks = cameraCallbacks;
mSurfaceIdCounter = 0;
}
private static int translateErrorsFromCamera1(int errorCode) {
switch (errorCode) {
case CameraBinderDecorator.EACCES:
return CameraBinderDecorator.PERMISSION_DENIED;
default:
return errorCode;
}
}
/**
* Create a separate looper/thread for the camera to run on; open the camera.
*
* <p>Since the camera automatically latches on to the current thread's looper,
* it's important that we have our own thread with our own looper to guarantee
* that the camera callbacks get correctly posted to our own thread.</p>
*/
private static class CameraLooper implements Runnable, AutoCloseable {
private final int mCameraId;
private Looper mLooper;
private volatile int mInitErrors;
private final Camera mCamera = Camera.openUninitialized();
private final ConditionVariable mStartDone = new ConditionVariable();
private final Thread mThread;
/**
* Spin up a new thread, immediately open the camera in the background.
*
* <p>Use {@link #waitForOpen} to block until the camera is finished opening.</p>
*
* @param cameraId numeric camera Id
*
* @see #waitForOpen
*/
public CameraLooper(int cameraId) {
mCameraId = cameraId;
mThread = new Thread(this);
mThread.start();
}
public Camera getCamera() {
return mCamera;
}
@Override
public void run() {
// Set up a looper to be used by camera.
Looper.prepare();
// Save the looper so that we can terminate this thread
// after we are done with it.
mLooper = Looper.myLooper();
mInitErrors = translateErrorsFromCamera1(mCamera.cameraInitUnspecified(mCameraId));
mStartDone.open();
Looper.loop(); // Blocks forever until #close is called.
}
/**
* Quit the looper safely; then join until the thread shuts down.
*/
@Override
public void close() {
if (mLooper == null) {
return;
}
mLooper.quitSafely();
try {
mThread.join();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
mLooper = null;
}
/**
* Block until the camera opens; then return its initialization error code (if any).
*
* @param timeoutMs timeout in milliseconds
*
* @return int error code
*
* @throws CameraRuntimeException if the camera open times out with ({@code CAMERA_ERROR})
*/
public int waitForOpen(int timeoutMs) {
// Block until the camera is open asynchronously
if (!mStartDone.block(timeoutMs)) {
Log.e(TAG, "waitForOpen - Camera failed to open after timeout of "
+ OPEN_CAMERA_TIMEOUT_MS + " ms");
try {
mCamera.release();
} catch (RuntimeException e) {
Log.e(TAG, "connectBinderShim - Failed to release camera after timeout ", e);
}
throw new CameraRuntimeException(CameraAccessException.CAMERA_ERROR);
}
return mInitErrors;
}
}
/**
* A thread to process callbacks to send back to the camera client.
*
* <p>This effectively emulates one-way binder semantics when in the same process as the
* callee.</p>
*/
private static class CameraCallbackThread implements ICameraDeviceCallbacks {
private static final int CAMERA_ERROR = 0;
private static final int CAMERA_IDLE = 1;
private static final int CAPTURE_STARTED = 2;
private static final int RESULT_RECEIVED = 3;
private final HandlerThread mHandlerThread;
private Handler mHandler;
private final ICameraDeviceCallbacks mCallbacks;
public CameraCallbackThread(ICameraDeviceCallbacks callbacks) {
mCallbacks = callbacks;
mHandlerThread = new HandlerThread("LegacyCameraCallback");
mHandlerThread.start();
}
public void close() {
mHandlerThread.quitSafely();
}
@Override
public void onDeviceError(final int errorCode, final CaptureResultExtras resultExtras) {
Message msg = getHandler().obtainMessage(CAMERA_ERROR,
/*arg1*/ errorCode, /*arg2*/ 0,
/*obj*/ resultExtras);
getHandler().sendMessage(msg);
}
@Override
public void onDeviceIdle() {
Message msg = getHandler().obtainMessage(CAMERA_IDLE);
getHandler().sendMessage(msg);
}
@Override
public void onCaptureStarted(final CaptureResultExtras resultExtras, final long timestamp) {
Message msg = getHandler().obtainMessage(CAPTURE_STARTED,
/*arg1*/ (int) (timestamp & 0xFFFFFFFFL),
/*arg2*/ (int) ( (timestamp >> 32) & 0xFFFFFFFFL),
/*obj*/ resultExtras);
getHandler().sendMessage(msg);
}
@Override
public void onResultReceived(final CameraMetadataNative result,
final CaptureResultExtras resultExtras) {
Object[] resultArray = new Object[] { result, resultExtras };
Message msg = getHandler().obtainMessage(RESULT_RECEIVED,
/*obj*/ resultArray);
getHandler().sendMessage(msg);
}
@Override
public IBinder asBinder() {
// This is solely intended to be used for in-process binding.
return null;
}
private Handler getHandler() {
if (mHandler == null) {
mHandler = new CallbackHandler(mHandlerThread.getLooper());
}
return mHandler;
}
private class CallbackHandler extends Handler {
public CallbackHandler(Looper l) {
super(l);
}
@Override
public void handleMessage(Message msg) {
try {
switch (msg.what) {
case CAMERA_ERROR: {
int errorCode = msg.arg1;
CaptureResultExtras resultExtras = (CaptureResultExtras) msg.obj;
mCallbacks.onDeviceError(errorCode, resultExtras);
break;
}
case CAMERA_IDLE:
mCallbacks.onDeviceIdle();
break;
case CAPTURE_STARTED: {
long timestamp = msg.arg2 & 0xFFFFFFFFL;
timestamp = (timestamp << 32) | (msg.arg1 & 0xFFFFFFFFL);
CaptureResultExtras resultExtras = (CaptureResultExtras) msg.obj;
mCallbacks.onCaptureStarted(resultExtras, timestamp);
break;
}
case RESULT_RECEIVED: {
Object[] resultArray = (Object[]) msg.obj;
CameraMetadataNative result = (CameraMetadataNative) resultArray[0];
CaptureResultExtras resultExtras = (CaptureResultExtras) resultArray[1];
mCallbacks.onResultReceived(result, resultExtras);
break;
}
default:
throw new IllegalArgumentException(
"Unknown callback message " + msg.what);
}
} catch (RemoteException e) {
throw new IllegalStateException(
"Received remote exception during camera callback " + msg.what, e);
}
}
}
}
public static CameraDeviceUserShim connectBinderShim(ICameraDeviceCallbacks callbacks,
int cameraId) {
if (DEBUG) {
Log.d(TAG, "Opening shim Camera device");
}
/*
* Put the camera open on a separate thread with its own looper; otherwise
* if the main thread is used then the callbacks might never get delivered
* (e.g. in CTS which run its own default looper only after tests)
*/
CameraLooper init = new CameraLooper(cameraId);
CameraCallbackThread threadCallbacks = new CameraCallbackThread(callbacks);
// TODO: Make this async instead of blocking
int initErrors = init.waitForOpen(OPEN_CAMERA_TIMEOUT_MS);
Camera legacyCamera = init.getCamera();
// Check errors old HAL initialization
CameraBinderDecorator.throwOnError(initErrors);
// Disable shutter sounds (this will work unconditionally) for api2 clients
legacyCamera.disableShutterSound();
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(cameraId, info);
Camera.Parameters legacyParameters = null;
try {
legacyParameters = legacyCamera.getParameters();
} catch (RuntimeException e) {
throw new CameraRuntimeException(CameraAccessException.CAMERA_ERROR,
"Unable to get initial parameters", e);
}
CameraCharacteristics characteristics =
LegacyMetadataMapper.createCharacteristics(legacyParameters, info);
LegacyCameraDevice device = new LegacyCameraDevice(
cameraId, legacyCamera, characteristics, threadCallbacks);
return new CameraDeviceUserShim(cameraId, device, characteristics, init, threadCallbacks);
}
@Override
public void disconnect() {
if (DEBUG) {
Log.d(TAG, "disconnect called.");
}
if (mLegacyDevice.isClosed()) {
Log.w(TAG, "Cannot disconnect, device has already been closed.");
}
try {
mLegacyDevice.close();
} finally {
mCameraInit.close();
mCameraCallbacks.close();
}
}
@Override
public int submitRequest(CaptureRequest request, boolean streaming,
/*out*/LongParcelable lastFrameNumber) {
if (DEBUG) {
Log.d(TAG, "submitRequest called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot submit request, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
synchronized(mConfigureLock) {
if (mConfiguring) {
Log.e(TAG, "Cannot submit request, configuration change in progress.");
return CameraBinderDecorator.INVALID_OPERATION;
}
}
return mLegacyDevice.submitRequest(request, streaming, lastFrameNumber);
}
@Override
public int submitRequestList(List<CaptureRequest> request, boolean streaming,
/*out*/LongParcelable lastFrameNumber) {
if (DEBUG) {
Log.d(TAG, "submitRequestList called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot submit request list, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
synchronized(mConfigureLock) {
if (mConfiguring) {
Log.e(TAG, "Cannot submit request, configuration change in progress.");
return CameraBinderDecorator.INVALID_OPERATION;
}
}
return mLegacyDevice.submitRequestList(request, streaming, lastFrameNumber);
}
@Override
public int cancelRequest(int requestId, /*out*/LongParcelable lastFrameNumber) {
if (DEBUG) {
Log.d(TAG, "cancelRequest called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot cancel request, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
synchronized(mConfigureLock) {
if (mConfiguring) {
Log.e(TAG, "Cannot cancel request, configuration change in progress.");
return CameraBinderDecorator.INVALID_OPERATION;
}
}
long lastFrame = mLegacyDevice.cancelRequest(requestId);
lastFrameNumber.setNumber(lastFrame);
return CameraBinderDecorator.NO_ERROR;
}
@Override
public int beginConfigure() {
if (DEBUG) {
Log.d(TAG, "beginConfigure called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot begin configure, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
synchronized(mConfigureLock) {
if (mConfiguring) {
Log.e(TAG, "Cannot begin configure, configuration change already in progress.");
return CameraBinderDecorator.INVALID_OPERATION;
}
mConfiguring = true;
}
return CameraBinderDecorator.NO_ERROR;
}
@Override
public int endConfigure() {
if (DEBUG) {
Log.d(TAG, "endConfigure called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot end configure, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
ArrayList<Surface> surfaces = null;
synchronized(mConfigureLock) {
if (!mConfiguring) {
Log.e(TAG, "Cannot end configure, no configuration change in progress.");
return CameraBinderDecorator.INVALID_OPERATION;
}
int numSurfaces = mSurfaces.size();
if (numSurfaces > 0) {
surfaces = new ArrayList<>();
for (int i = 0; i < numSurfaces; ++i) {
surfaces.add(mSurfaces.valueAt(i));
}
}
mConfiguring = false;
}
return mLegacyDevice.configureOutputs(surfaces);
}
@Override
public int deleteStream(int streamId) {
if (DEBUG) {
Log.d(TAG, "deleteStream called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot delete stream, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
synchronized(mConfigureLock) {
if (!mConfiguring) {
Log.e(TAG, "Cannot delete stream, beginConfigure hasn't been called yet.");
return CameraBinderDecorator.INVALID_OPERATION;
}
int index = mSurfaces.indexOfKey(streamId);
if (index < 0) {
Log.e(TAG, "Cannot delete stream, stream id " + streamId + " doesn't exist.");
return CameraBinderDecorator.BAD_VALUE;
}
mSurfaces.removeAt(index);
}
return CameraBinderDecorator.NO_ERROR;
}
@Override
public int createStream(OutputConfiguration outputConfiguration) {
if (DEBUG) {
Log.d(TAG, "createStream called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot create stream, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
synchronized(mConfigureLock) {
if (!mConfiguring) {
Log.e(TAG, "Cannot create stream, beginConfigure hasn't been called yet.");
return CameraBinderDecorator.INVALID_OPERATION;
}
if (outputConfiguration.getRotation() != OutputConfiguration.ROTATION_0) {
Log.e(TAG, "Cannot create stream, stream rotation is not supported.");
return CameraBinderDecorator.INVALID_OPERATION;
}
int id = ++mSurfaceIdCounter;
mSurfaces.put(id, outputConfiguration.getSurface());
return id;
}
}
@Override
public int createInputStream(int width, int height, int format) {
Log.e(TAG, "creating input stream is not supported on legacy devices");
return CameraBinderDecorator.INVALID_OPERATION;
}
@Override
public int getInputSurface(/*out*/ Surface surface) {
Log.e(TAG, "getting input surface is not supported on legacy devices");
return CameraBinderDecorator.INVALID_OPERATION;
}
@Override
public int createDefaultRequest(int templateId, /*out*/CameraMetadataNative request) {
if (DEBUG) {
Log.d(TAG, "createDefaultRequest called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot create default request, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
CameraMetadataNative template;
try {
template =
LegacyMetadataMapper.createRequestTemplate(mCameraCharacteristics, templateId);
} catch (IllegalArgumentException e) {
Log.e(TAG, "createDefaultRequest - invalid templateId specified");
return CameraBinderDecorator.BAD_VALUE;
}
request.swap(template);
return CameraBinderDecorator.NO_ERROR;
}
@Override
public int getCameraInfo(/*out*/CameraMetadataNative info) {
if (DEBUG) {
Log.d(TAG, "getCameraInfo called.");
}
// TODO: implement getCameraInfo.
Log.e(TAG, "getCameraInfo unimplemented.");
return CameraBinderDecorator.NO_ERROR;
}
@Override
public int waitUntilIdle() throws RemoteException {
if (DEBUG) {
Log.d(TAG, "waitUntilIdle called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot wait until idle, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
synchronized(mConfigureLock) {
if (mConfiguring) {
Log.e(TAG, "Cannot wait until idle, configuration change in progress.");
return CameraBinderDecorator.INVALID_OPERATION;
}
}
mLegacyDevice.waitUntilIdle();
return CameraBinderDecorator.NO_ERROR;
}
@Override
public int flush(/*out*/LongParcelable lastFrameNumber) {
if (DEBUG) {
Log.d(TAG, "flush called.");
}
if (mLegacyDevice.isClosed()) {
Log.e(TAG, "Cannot flush, device has been closed.");
return CameraBinderDecorator.ENODEV;
}
synchronized(mConfigureLock) {
if (mConfiguring) {
Log.e(TAG, "Cannot flush, configuration change in progress.");
return CameraBinderDecorator.INVALID_OPERATION;
}
}
long lastFrame = mLegacyDevice.flush();
if (lastFrameNumber != null) {
lastFrameNumber.setNumber(lastFrame);
}
return CameraBinderDecorator.NO_ERROR;
}
@Override
public IBinder asBinder() {
// This is solely intended to be used for in-process binding.
return null;
}
}
|