summaryrefslogtreecommitdiffstats
path: root/services/camera/libcameraservice/api_pro/ProCamera2Client.cpp
blob: 59e5083685d31698fb33b5eac9260ee3a13ac5f0 (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
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
/*
 * Copyright (C) 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.
 */

#define LOG_TAG "ProCamera2Client"
#define ATRACE_TAG ATRACE_TAG_CAMERA
//#define LOG_NDEBUG 0

#include <utils/Log.h>
#include <utils/Trace.h>

#include <cutils/properties.h>
#include <gui/Surface.h>
#include <gui/Surface.h>

#include "api_pro/ProCamera2Client.h"
#include "common/CameraDeviceBase.h"

namespace android {
using namespace camera2;

// Interface used by CameraService

ProCamera2Client::ProCamera2Client(const sp<CameraService>& cameraService,
                                   const sp<IProCameraCallbacks>& remoteCallback,
                                   const String16& clientPackageName,
                                   int cameraId,
                                   int cameraFacing,
                                   int clientPid,
                                   uid_t clientUid,
                                   int servicePid) :
    Camera2ClientBase(cameraService, remoteCallback, clientPackageName,
                cameraId, cameraFacing, clientPid, clientUid, servicePid)
{
    ATRACE_CALL();
    ALOGI("ProCamera %d: Opened", cameraId);

    mExclusiveLock = false;
}

status_t ProCamera2Client::initialize(camera_module_t *module)
{
    ATRACE_CALL();
    status_t res;

    res = Camera2ClientBase::initialize(module);
    if (res != OK) {
        return res;
    }

    String8 threadName;
    mFrameProcessor = new FrameProcessorBase(mDevice);
    threadName = String8::format("PC2-%d-FrameProc", mCameraId);
    mFrameProcessor->run(threadName.string());

    mFrameProcessor->registerListener(FRAME_PROCESSOR_LISTENER_MIN_ID,
                                      FRAME_PROCESSOR_LISTENER_MAX_ID,
                                      /*listener*/this);

    return OK;
}

ProCamera2Client::~ProCamera2Client() {
}

status_t ProCamera2Client::exclusiveTryLock() {
    ATRACE_CALL();
    ALOGV("%s", __FUNCTION__);

    Mutex::Autolock icl(mBinderSerializationLock);
    SharedCameraCallbacks::Lock l(mSharedCameraCallbacks);

    if (!mDevice.get()) return PERMISSION_DENIED;

    if (!mExclusiveLock) {
        mExclusiveLock = true;

        if (mRemoteCallback != NULL) {
            mRemoteCallback->onLockStatusChanged(
                              IProCameraCallbacks::LOCK_ACQUIRED);
        }

        ALOGV("%s: exclusive lock acquired", __FUNCTION__);

        return OK;
    }

    // TODO: have a PERMISSION_DENIED case for when someone else owns the lock

    // don't allow recursive locking
    ALOGW("%s: exclusive lock already exists - recursive locking is not"
          "allowed", __FUNCTION__);

    return ALREADY_EXISTS;
}

status_t ProCamera2Client::exclusiveLock() {
    ATRACE_CALL();
    ALOGV("%s", __FUNCTION__);

    Mutex::Autolock icl(mBinderSerializationLock);
    SharedCameraCallbacks::Lock l(mSharedCameraCallbacks);

    if (!mDevice.get()) return PERMISSION_DENIED;

    /**
     * TODO: this should asynchronously 'wait' until the lock becomes available
     * if another client already has an exclusive lock.
     *
     * once we have proper sharing support this will need to do
     * more than just return immediately
     */
    if (!mExclusiveLock) {
        mExclusiveLock = true;

        if (mRemoteCallback != NULL) {
            mRemoteCallback->onLockStatusChanged(IProCameraCallbacks::LOCK_ACQUIRED);
        }

        ALOGV("%s: exclusive lock acquired", __FUNCTION__);

        return OK;
    }

    // don't allow recursive locking
    ALOGW("%s: exclusive lock already exists - recursive locking is not allowed"
                                                                , __FUNCTION__);
    return ALREADY_EXISTS;
}

status_t ProCamera2Client::exclusiveUnlock() {
    ATRACE_CALL();
    ALOGV("%s", __FUNCTION__);

    Mutex::Autolock icl(mBinderSerializationLock);
    SharedCameraCallbacks::Lock l(mSharedCameraCallbacks);

    // don't allow unlocking if we have no lock
    if (!mExclusiveLock) {
        ALOGW("%s: cannot unlock, no lock was held in the first place",
              __FUNCTION__);
        return BAD_VALUE;
    }

    mExclusiveLock = false;
    if (mRemoteCallback != NULL ) {
        mRemoteCallback->onLockStatusChanged(
                                       IProCameraCallbacks::LOCK_RELEASED);
    }
    ALOGV("%s: exclusive lock released", __FUNCTION__);

    return OK;
}

bool ProCamera2Client::hasExclusiveLock() {
    Mutex::Autolock icl(mBinderSerializationLock);
    return mExclusiveLock;
}

void ProCamera2Client::onExclusiveLockStolen() {
    ALOGV("%s: ProClient lost exclusivity (id %d)",
          __FUNCTION__, mCameraId);

    Mutex::Autolock icl(mBinderSerializationLock);
    SharedCameraCallbacks::Lock l(mSharedCameraCallbacks);

    if (mExclusiveLock && mRemoteCallback.get() != NULL) {
        mRemoteCallback->onLockStatusChanged(
                                       IProCameraCallbacks::LOCK_STOLEN);
    }

    mExclusiveLock = false;

    //TODO: we should not need to detach the device, merely reset it.
    detachDevice();
}

status_t ProCamera2Client::submitRequest(camera_metadata_t* request,
                                         bool streaming) {
    ATRACE_CALL();
    ALOGV("%s", __FUNCTION__);

    Mutex::Autolock icl(mBinderSerializationLock);

    if (!mDevice.get()) return DEAD_OBJECT;

    if (!mExclusiveLock) {
        return PERMISSION_DENIED;
    }

    CameraMetadata metadata(request);

    if (!enforceRequestPermissions(metadata)) {
        return PERMISSION_DENIED;
    }

    if (streaming) {
        return mDevice->setStreamingRequest(metadata);
    } else {
        return mDevice->capture(metadata);
    }

    // unreachable. thx gcc for a useless warning
    return OK;
}

status_t ProCamera2Client::cancelRequest(int requestId) {
    (void)requestId;
    ATRACE_CALL();
    ALOGV("%s", __FUNCTION__);

    Mutex::Autolock icl(mBinderSerializationLock);

    if (!mDevice.get()) return DEAD_OBJECT;

    if (!mExclusiveLock) {
        return PERMISSION_DENIED;
    }

    // TODO: implement
    ALOGE("%s: not fully implemented yet", __FUNCTION__);
    return INVALID_OPERATION;
}

status_t ProCamera2Client::deleteStream(int streamId) {
    ATRACE_CALL();
    ALOGV("%s (streamId = 0x%x)", __FUNCTION__, streamId);

    status_t res;
    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;

    Mutex::Autolock icl(mBinderSerializationLock);

    if (!mDevice.get()) return DEAD_OBJECT;
    mDevice->clearStreamingRequest();

    status_t code;
    if ((code = mDevice->waitUntilDrained()) != OK) {
        ALOGE("%s: waitUntilDrained failed with code 0x%x", __FUNCTION__, code);
    }

    return mDevice->deleteStream(streamId);
}

status_t ProCamera2Client::createStream(int width, int height, int format,
                      const sp<IGraphicBufferProducer>& bufferProducer,
                      /*out*/
                      int* streamId)
{
    if (streamId) {
        *streamId = -1;
    }

    ATRACE_CALL();
    ALOGV("%s (w = %d, h = %d, f = 0x%x)", __FUNCTION__, width, height, format);

    status_t res;
    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;

    Mutex::Autolock icl(mBinderSerializationLock);

    if (!mDevice.get()) return DEAD_OBJECT;

    sp<IBinder> binder;
    sp<ANativeWindow> window;
    if (bufferProducer != 0) {
        binder = IInterface::asBinder(bufferProducer);
        window = new Surface(bufferProducer);
    }

    return mDevice->createStream(window, width, height, format,
                                 streamId);
}

// Create a request object from a template.
// -- Caller owns the newly allocated metadata
status_t ProCamera2Client::createDefaultRequest(int templateId,
                             /*out*/
                              camera_metadata** request)
{
    ATRACE_CALL();
    ALOGV("%s (templateId = 0x%x)", __FUNCTION__, templateId);

    if (request) {
        *request = NULL;
    }

    status_t res;
    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;

    Mutex::Autolock icl(mBinderSerializationLock);

    if (!mDevice.get()) return DEAD_OBJECT;

    CameraMetadata metadata;
    if ( (res = mDevice->createDefaultRequest(templateId, &metadata) ) == OK) {
        *request = metadata.release();
    }

    return res;
}

status_t ProCamera2Client::getCameraInfo(int cameraId,
                                         /*out*/
                                         camera_metadata** info)
{
    if (cameraId != mCameraId) {
        return INVALID_OPERATION;
    }

    Mutex::Autolock icl(mBinderSerializationLock);

    if (!mDevice.get()) return DEAD_OBJECT;

    CameraMetadata deviceInfo = mDevice->info();
    *info = deviceInfo.release();

    return OK;
}

status_t ProCamera2Client::dump(int fd, const Vector<String16>& args) {
    String8 result;
    result.appendFormat("ProCamera2Client[%d] (%p) PID: %d, dump:\n",
            mCameraId,
            (getRemoteCallback() != NULL ?
                    IInterface::asBinder(getRemoteCallback()).get() : NULL),
            mClientPid);
    result.append("  State:\n");
    write(fd, result.string(), result.size());

    // TODO: print dynamic/request section from most recent requests
    mFrameProcessor->dump(fd, args);
    return dumpDevice(fd, args);
}

// IProCameraUser interface

void ProCamera2Client::detachDevice() {
    if (mDevice == 0) return;

    ALOGV("Camera %d: Stopping processors", mCameraId);

    mFrameProcessor->removeListener(FRAME_PROCESSOR_LISTENER_MIN_ID,
                                    FRAME_PROCESSOR_LISTENER_MAX_ID,
                                    /*listener*/this);
    mFrameProcessor->requestExit();
    ALOGV("Camera %d: Waiting for threads", mCameraId);
    mFrameProcessor->join();
    ALOGV("Camera %d: Disconnecting device", mCameraId);

    // WORKAROUND: HAL refuses to disconnect while there's streams in flight
    {
        mDevice->clearStreamingRequest();

        status_t code;
        if ((code = mDevice->waitUntilDrained()) != OK) {
            ALOGE("%s: waitUntilDrained failed with code 0x%x", __FUNCTION__,
                  code);
        }
    }

    Camera2ClientBase::detachDevice();
}

void ProCamera2Client::onResultAvailable(const CaptureResult& result) {
    ATRACE_CALL();
    ALOGV("%s", __FUNCTION__);

    Mutex::Autolock icl(mBinderSerializationLock);
    SharedCameraCallbacks::Lock l(mSharedCameraCallbacks);

    if (mRemoteCallback != NULL) {
        CameraMetadata tmp(result.mMetadata);
        camera_metadata_t* meta = tmp.release();
        ALOGV("%s: meta = %p ", __FUNCTION__, meta);
        mRemoteCallback->onResultReceived(result.mResultExtras.requestId, meta);
        tmp.acquire(meta);
    }
}

bool ProCamera2Client::enforceRequestPermissions(CameraMetadata& metadata) {

    const int pid = IPCThreadState::self()->getCallingPid();
    const int selfPid = getpid();
    camera_metadata_entry_t entry;

    /**
     * Mixin default important security values
     * - android.led.transmit = defaulted ON
     */
    CameraMetadata staticInfo = mDevice->info();
    entry = staticInfo.find(ANDROID_LED_AVAILABLE_LEDS);
    for(size_t i = 0; i < entry.count; ++i) {
        uint8_t led = entry.data.u8[i];

        switch(led) {
            case ANDROID_LED_AVAILABLE_LEDS_TRANSMIT: {
                uint8_t transmitDefault = ANDROID_LED_TRANSMIT_ON;
                if (!metadata.exists(ANDROID_LED_TRANSMIT)) {
                    metadata.update(ANDROID_LED_TRANSMIT,
                                    &transmitDefault, 1);
                }
                break;
            }
        }
    }

    // We can do anything!
    if (pid == selfPid) {
        return true;
    }

    /**
     * Permission check special fields in the request
     * - android.led.transmit = android.permission.CAMERA_DISABLE_TRANSMIT
     */
    entry = metadata.find(ANDROID_LED_TRANSMIT);
    if (entry.count > 0 && entry.data.u8[0] != ANDROID_LED_TRANSMIT_ON) {
        String16 permissionString =
            String16("android.permission.CAMERA_DISABLE_TRANSMIT_LED");
        if (!checkCallingPermission(permissionString)) {
            const int uid = IPCThreadState::self()->getCallingUid();
            ALOGE("Permission Denial: "
                  "can't disable transmit LED pid=%d, uid=%d", pid, uid);
            return false;
        }
    }

    return true;
}

} // namespace android