summaryrefslogtreecommitdiffstats
path: root/services/camera/libcameraservice/CameraFlashlight.cpp
blob: a00a49f19febfa4bebb67bf2e9b14a753f281cc0 (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
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
626
/*
 * Copyright (C) 2015 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 "CameraFlashlight"
#define ATRACE_TAG ATRACE_TAG_CAMERA
// #define LOG_NDEBUG 0

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

#include "camera/CameraMetadata.h"
#include "CameraFlashlight.h"
#include "gui/IGraphicBufferConsumer.h"
#include "gui/BufferQueue.h"
#include "camera/camera2/CaptureRequest.h"
#include "CameraDeviceFactory.h"


namespace android {

/////////////////////////////////////////////////////////////////////
// CameraFlashlight implementation begins
// used by camera service to control flashflight.
/////////////////////////////////////////////////////////////////////
CameraFlashlight::CameraFlashlight(CameraModule& cameraModule,
        const camera_module_callbacks_t& callbacks) :
        mCameraModule(&cameraModule),
        mCallbacks(&callbacks),
        mFlashlightMapInitialized(false) {
}

CameraFlashlight::~CameraFlashlight() {
}

status_t CameraFlashlight::createFlashlightControl(const String8& cameraId) {
    ALOGV("%s: creating a flash light control for camera %s", __FUNCTION__,
            cameraId.string());
    if (mFlashControl != NULL) {
        return INVALID_OPERATION;
    }

    status_t res = OK;

    if (mCameraModule->getRawModule()->module_api_version >=
            CAMERA_MODULE_API_VERSION_2_4) {
        mFlashControl = new ModuleFlashControl(*mCameraModule, *mCallbacks);
        if (mFlashControl == NULL) {
            ALOGV("%s: cannot create flash control for module api v2.4+",
                     __FUNCTION__);
            return NO_MEMORY;
        }
    } else {
        uint32_t deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;

        if (mCameraModule->getRawModule()->module_api_version >=
                CAMERA_MODULE_API_VERSION_2_0) {
            camera_info info;
            res = mCameraModule->getCameraInfo(
                    atoi(String8(cameraId).string()), &info);
            if (res) {
                ALOGE("%s: failed to get camera info for camera %s",
                        __FUNCTION__, cameraId.string());
                return res;
            }
            deviceVersion = info.device_version;
        }

        if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
            CameraDeviceClientFlashControl *flashControl =
                    new CameraDeviceClientFlashControl(*mCameraModule,
                                                       *mCallbacks);
            if (!flashControl) {
                return NO_MEMORY;
            }

            mFlashControl = flashControl;
        } else {
            // todo: implement for device api 1
            return INVALID_OPERATION;
        }
    }

    return OK;
}

status_t CameraFlashlight::setTorchMode(const String8& cameraId, bool enabled) {
    if (!mFlashlightMapInitialized) {
        ALOGE("%s: findFlashUnits() must be called before this method.");
        return NO_INIT;
    }

    ALOGV("%s: set torch mode of camera %s to %d", __FUNCTION__,
            cameraId.string(), enabled);

    status_t res = OK;
    Mutex::Autolock l(mLock);

    if (mFlashControl == NULL) {
        if (enabled == false) {
            return OK;
        }

        res = createFlashlightControl(cameraId);
        if (res) {
            return res;
        }
        res =  mFlashControl->setTorchMode(cameraId, enabled);
        return res;
    }

    // if flash control already exists, turning on torch mode may fail if it's
    // tied to another camera device for module v2.3 and below.
    res = mFlashControl->setTorchMode(cameraId, enabled);
    if (res == BAD_INDEX) {
        // flash control is tied to another camera device, need to close it and
        // try again.
        mFlashControl.clear();
        res = createFlashlightControl(cameraId);
        if (res) {
            return res;
        }
        res = mFlashControl->setTorchMode(cameraId, enabled);
    }

    return res;
}

status_t CameraFlashlight::findFlashUnits() {
    Mutex::Autolock l(mLock);
    status_t res;
    int32_t numCameras = mCameraModule->getNumberOfCameras();

    mHasFlashlightMap.clear();
    mFlashlightMapInitialized = false;

    for (int32_t i = 0; i < numCameras; i++) {
        bool hasFlash = false;
        String8 id = String8::format("%d", i);

        res = createFlashlightControl(id);
        if (res) {
            ALOGE("%s: failed to create flash control for %s", __FUNCTION__,
                    id.string());
        } else {
            res = mFlashControl->hasFlashUnit(id, &hasFlash);
            if (res == -EUSERS || res == -EBUSY) {
                ALOGE("%s: failed to check if camera %s has a flash unit. Some "
                        "camera devices may be opened", __FUNCTION__,
                        id.string());
                return res;
            } else if (res) {
                ALOGE("%s: failed to check if camera %s has a flash unit. %s"
                        " (%d)", __FUNCTION__, id.string(), strerror(-res),
                        res);
            }

            mFlashControl.clear();
        }
        mHasFlashlightMap.add(id, hasFlash);
    }

    mFlashlightMapInitialized = true;
    return OK;
}

bool CameraFlashlight::hasFlashUnit(const String8& cameraId) {
    status_t res;

    Mutex::Autolock l(mLock);
    return hasFlashUnitLocked(cameraId);
}

bool CameraFlashlight::hasFlashUnitLocked(const String8& cameraId) {
    if (!mFlashlightMapInitialized) {
        ALOGE("%s: findFlashUnits() must be called before this method.");
        return false;
    }

    ssize_t index = mHasFlashlightMap.indexOfKey(cameraId);
    if (index == NAME_NOT_FOUND) {
        ALOGE("%s: camera %s not present when findFlashUnits() was called",
                __FUNCTION__, cameraId.string());
        return false;
    }

    return mHasFlashlightMap.valueAt(index);
}

status_t CameraFlashlight::prepareDeviceOpen(const String8& cameraId) {
    ALOGV("%s: prepare for device open", __FUNCTION__);

    Mutex::Autolock l(mLock);
    if (!mFlashlightMapInitialized) {
        ALOGE("%s: findFlashUnits() must be called before this method.");
        return NO_INIT;
    }

    if (mCameraModule->getRawModule()->module_api_version <
            CAMERA_MODULE_API_VERSION_2_4) {
        // framework is going to open a camera device, all flash light control
        // should be closed for backward compatible support.
        mFlashControl.clear();

        if (mOpenedCameraIds.size() == 0) {
            // notify torch unavailable for all cameras with a flash
            int numCameras = mCameraModule->getNumberOfCameras();
            for (int i = 0; i < numCameras; i++) {
                if (hasFlashUnitLocked(String8::format("%d", i))) {
                    mCallbacks->torch_mode_status_change(mCallbacks,
                            String8::format("%d", i).string(),
                            TORCH_MODE_STATUS_NOT_AVAILABLE);
                }
            }
        }

        // close flash control that may be opened by calling hasFlashUnitLocked.
        mFlashControl.clear();
    }

    if (mOpenedCameraIds.indexOf(cameraId) == NAME_NOT_FOUND) {
        mOpenedCameraIds.add(cameraId);
    }

    return OK;
}

status_t CameraFlashlight::deviceClosed(const String8& cameraId) {
    ALOGV("%s: device %s is closed", __FUNCTION__, cameraId.string());

    Mutex::Autolock l(mLock);
    if (!mFlashlightMapInitialized) {
        ALOGE("%s: findFlashUnits() must be called before this method.");
        return NO_INIT;
    }

    ssize_t index = mOpenedCameraIds.indexOf(cameraId);
    if (index == NAME_NOT_FOUND) {
        ALOGE("%s: couldn't find camera %s in the opened list", __FUNCTION__,
                cameraId.string());
    } else {
        mOpenedCameraIds.removeAt(index);
    }

    // Cannot do anything until all cameras are closed.
    if (mOpenedCameraIds.size() != 0)
        return OK;

    if (mCameraModule->getRawModule()->module_api_version <
            CAMERA_MODULE_API_VERSION_2_4) {
        // notify torch available for all cameras with a flash
        int numCameras = mCameraModule->getNumberOfCameras();
        for (int i = 0; i < numCameras; i++) {
            if (hasFlashUnitLocked(String8::format("%d", i))) {
                mCallbacks->torch_mode_status_change(mCallbacks,
                        String8::format("%d", i).string(),
                        TORCH_MODE_STATUS_AVAILABLE_OFF);
            }
        }
    }

    return OK;
}
// CameraFlashlight implementation ends


FlashControlBase::~FlashControlBase() {
}

/////////////////////////////////////////////////////////////////////
// ModuleFlashControl implementation begins
// Flash control for camera module v2.4 and above.
/////////////////////////////////////////////////////////////////////
ModuleFlashControl::ModuleFlashControl(CameraModule& cameraModule,
        const camera_module_callbacks_t& callbacks) :
    mCameraModule(&cameraModule) {
}

ModuleFlashControl::~ModuleFlashControl() {
}

status_t ModuleFlashControl::hasFlashUnit(const String8& cameraId, bool *hasFlash) {
    if (!hasFlash) {
        return BAD_VALUE;
    }

    *hasFlash = false;
    Mutex::Autolock l(mLock);

    camera_info info;
    status_t res = mCameraModule->getCameraInfo(atoi(cameraId.string()),
            &info);
    if (res != 0) {
        return res;
    }

    CameraMetadata metadata;
    metadata = info.static_camera_characteristics;
    camera_metadata_entry flashAvailable =
            metadata.find(ANDROID_FLASH_INFO_AVAILABLE);
    if (flashAvailable.count == 1 && flashAvailable.data.u8[0] == 1) {
        *hasFlash = true;
    }

    return OK;
}

status_t ModuleFlashControl::setTorchMode(const String8& cameraId, bool enabled) {
    ALOGV("%s: set camera %s torch mode to %d", __FUNCTION__,
            cameraId.string(), enabled);

    Mutex::Autolock l(mLock);
    return mCameraModule->setTorchMode(cameraId.string(), enabled);
}
// ModuleFlashControl implementation ends

/////////////////////////////////////////////////////////////////////
// CameraDeviceClientFlashControl implementation begins
// Flash control for camera module <= v2.3 and camera HAL v2-v3
/////////////////////////////////////////////////////////////////////
CameraDeviceClientFlashControl::CameraDeviceClientFlashControl(
        CameraModule& cameraModule,
        const camera_module_callbacks_t& callbacks) :
        mCameraModule(&cameraModule),
        mCallbacks(&callbacks),
        mTorchEnabled(false),
        mMetadata(NULL),
        mStreaming(false) {
}

CameraDeviceClientFlashControl::~CameraDeviceClientFlashControl() {
    disconnectCameraDevice();
    if (mMetadata) {
        delete mMetadata;
    }

    mAnw.clear();
    mSurfaceTexture.clear();
    mProducer.clear();
    mConsumer.clear();

    if (mTorchEnabled) {
        if (mCallbacks) {
            ALOGV("%s: notify the framework that torch was turned off",
                    __FUNCTION__);
            mCallbacks->torch_mode_status_change(mCallbacks,
                    mCameraId.string(), TORCH_MODE_STATUS_AVAILABLE_OFF);
        }
    }
}

status_t CameraDeviceClientFlashControl::initializeSurface(
        sp<CameraDeviceBase> &device, int32_t width, int32_t height) {
    status_t res;
    BufferQueue::createBufferQueue(&mProducer, &mConsumer);

    mSurfaceTexture = new GLConsumer(mConsumer, 0, GLConsumer::TEXTURE_EXTERNAL,
            true, true);
    if (mSurfaceTexture == NULL) {
        return NO_MEMORY;
    }

    int32_t format = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
    res = mSurfaceTexture->setDefaultBufferSize(width, height);
    if (res) {
        return res;
    }
    res = mSurfaceTexture->setDefaultBufferFormat(format);
    if (res) {
        return res;
    }

    mAnw = new Surface(mProducer, /*useAsync*/ true);
    if (mAnw == NULL) {
        return NO_MEMORY;
    }
    res = device->createStream(mAnw, width, height, format, &mStreamId);
    if (res) {
        return res;
    }

    res = device->configureStreams();
    if (res) {
        return res;
    }

    return res;
}

status_t CameraDeviceClientFlashControl::getSmallestSurfaceSize(
        const camera_info& info, int32_t *width, int32_t *height) {
    if (!width || !height) {
        return BAD_VALUE;
    }

    int32_t w = INT32_MAX;
    int32_t h = 1;

    CameraMetadata metadata;
    metadata = info.static_camera_characteristics;
    camera_metadata_entry streamConfigs =
            metadata.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
    for (size_t i = 0; i < streamConfigs.count; i += 4) {
        int32_t fmt = streamConfigs.data.i32[i];
        if (fmt == ANDROID_SCALER_AVAILABLE_FORMATS_IMPLEMENTATION_DEFINED) {
            int32_t ww = streamConfigs.data.i32[i + 1];
            int32_t hh = streamConfigs.data.i32[i + 2];

            if (w * h > ww * hh) {
                w = ww;
                h = hh;
            }
        }
    }

    // if stream configuration is not found, try available processed sizes.
    if (streamConfigs.count == 0) {
        camera_metadata_entry availableProcessedSizes =
            metadata.find(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES);
        for (size_t i = 0; i < availableProcessedSizes.count; i += 2) {
            int32_t ww = availableProcessedSizes.data.i32[i];
            int32_t hh = availableProcessedSizes.data.i32[i + 1];
            if (w * h > ww * hh) {
                w = ww;
                h = hh;
            }
        }
    }

    if (w == INT32_MAX) {
        return NAME_NOT_FOUND;
    }

    *width = w;
    *height = h;

    return OK;
}

status_t CameraDeviceClientFlashControl::connectCameraDevice(
        const String8& cameraId) {
    camera_info info;
    status_t res = mCameraModule->getCameraInfo(atoi(cameraId.string()), &info);
    if (res != 0) {
        ALOGE("%s: failed to get camera info for camera %s", __FUNCTION__,
                cameraId.string());
        return res;
    }

    sp<CameraDeviceBase> device =
            CameraDeviceFactory::createDevice(atoi(cameraId.string()));
    if (device == NULL) {
        return NO_MEMORY;
    }

    res = device->initialize(mCameraModule);
    if (res) {
        return res;
    }

    int32_t width, height;
    res = getSmallestSurfaceSize(info, &width, &height);
    if (res) {
        return res;
    }
    res = initializeSurface(device, width, height);
    if (res) {
        return res;
    }

    mCameraId = cameraId;
    mStreaming = (info.device_version <= CAMERA_DEVICE_API_VERSION_3_1);
    mDevice = device;

    return OK;
}

status_t CameraDeviceClientFlashControl::disconnectCameraDevice() {
    if (mDevice != NULL) {
        mDevice->disconnect();
        mDevice.clear();
    }

    return OK;
}



status_t CameraDeviceClientFlashControl::hasFlashUnit(const String8& cameraId,
        bool *hasFlash) {
    ALOGV("%s: checking if camera %s has a flash unit", __FUNCTION__,
            cameraId.string());

    Mutex::Autolock l(mLock);
    return hasFlashUnitLocked(cameraId, hasFlash);

}

status_t CameraDeviceClientFlashControl::hasFlashUnitLocked(
        const String8& cameraId, bool *hasFlash) {
    if (!hasFlash) {
        return BAD_VALUE;
    }

    camera_info info;
    status_t res = mCameraModule->getCameraInfo(
            atoi(cameraId.string()), &info);
    if (res != 0) {
        ALOGE("%s: failed to get camera info for camera %s", __FUNCTION__,
                cameraId.string());
        return res;
    }

    CameraMetadata metadata;
    metadata = info.static_camera_characteristics;
    camera_metadata_entry flashAvailable =
            metadata.find(ANDROID_FLASH_INFO_AVAILABLE);
    if (flashAvailable.count == 1 && flashAvailable.data.u8[0] == 1) {
        *hasFlash = true;
    }

    return OK;
}

status_t CameraDeviceClientFlashControl::submitTorchEnabledRequest() {
    status_t res;

    if (mMetadata == NULL) {
        mMetadata = new CameraMetadata();
        if (mMetadata == NULL) {
            return NO_MEMORY;
        }
        res = mDevice->createDefaultRequest(
                CAMERA3_TEMPLATE_PREVIEW, mMetadata);
        if (res) {
            return res;
        }
    }

    uint8_t torchOn = ANDROID_FLASH_MODE_TORCH;
    mMetadata->update(ANDROID_FLASH_MODE, &torchOn, 1);
    mMetadata->update(ANDROID_REQUEST_OUTPUT_STREAMS, &mStreamId, 1);

    uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON;
    mMetadata->update(ANDROID_CONTROL_AE_MODE, &aeMode, 1);

    int32_t requestId = 0;
    mMetadata->update(ANDROID_REQUEST_ID, &requestId, 1);

    if (mStreaming) {
        res = mDevice->setStreamingRequest(*mMetadata);
    } else {
        res = mDevice->capture(*mMetadata);
    }
    return res;
}




status_t CameraDeviceClientFlashControl::setTorchMode(
        const String8& cameraId, bool enabled) {
    bool hasFlash = false;

    Mutex::Autolock l(mLock);
    status_t res = hasFlashUnitLocked(cameraId, &hasFlash);

    // pre-check
    if (enabled) {
        // invalid camera?
        if (res) {
            return -EINVAL;
        }
        // no flash unit?
        if (!hasFlash) {
            return -ENOSYS;
        }
        // already opened for a different device?
        if (mDevice != NULL && cameraId != mCameraId) {
            return BAD_INDEX;
        }
    } else if (mDevice == NULL || cameraId != mCameraId) {
        // disabling the torch mode of an un-opened or different device.
        return OK;
    } else {
        // disabling the torch mode of currently opened device
        disconnectCameraDevice();
        mTorchEnabled = false;
        mCallbacks->torch_mode_status_change(mCallbacks,
            cameraId.string(), TORCH_MODE_STATUS_AVAILABLE_OFF);
        return OK;
    }

    if (mDevice == NULL) {
        res = connectCameraDevice(cameraId);
        if (res) {
            return res;
        }
    }

    res = submitTorchEnabledRequest();
    if (res) {
        return res;
    }

    mTorchEnabled = true;
    mCallbacks->torch_mode_status_change(mCallbacks,
            cameraId.string(), TORCH_MODE_STATUS_AVAILABLE_ON);
    return OK;
}
// CameraDeviceClientFlashControl implementation ends

}