CameraDeviceClient.cpp revision b2119af7f4ced0ecfefd4c7388f86b4e3a3ea7d8
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
17#define LOG_TAG "CameraDeviceClient"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20
21#include <cutils/properties.h>
22#include <utils/Log.h>
23#include <utils/Trace.h>
24#include <gui/Surface.h>
25#include <camera/camera2/CaptureRequest.h>
26
27#include "common/CameraDeviceBase.h"
28#include "api2/CameraDeviceClient.h"
29
30
31
32namespace android {
33using namespace camera2;
34
35CameraDeviceClientBase::CameraDeviceClientBase(
36        const sp<CameraService>& cameraService,
37        const sp<ICameraDeviceCallbacks>& remoteCallback,
38        const String16& clientPackageName,
39        int cameraId,
40        int cameraFacing,
41        int clientPid,
42        uid_t clientUid,
43        int servicePid) :
44    BasicClient(cameraService, remoteCallback->asBinder(), clientPackageName,
45                cameraId, cameraFacing, clientPid, clientUid, servicePid),
46    mRemoteCallback(remoteCallback) {
47}
48
49// Interface used by CameraService
50
51CameraDeviceClient::CameraDeviceClient(const sp<CameraService>& cameraService,
52                                   const sp<ICameraDeviceCallbacks>& remoteCallback,
53                                   const String16& clientPackageName,
54                                   int cameraId,
55                                   int cameraFacing,
56                                   int clientPid,
57                                   uid_t clientUid,
58                                   int servicePid) :
59    Camera2ClientBase(cameraService, remoteCallback, clientPackageName,
60                cameraId, cameraFacing, clientPid, clientUid, servicePid),
61    mRequestIdCounter(0) {
62
63    ATRACE_CALL();
64    ALOGI("CameraDeviceClient %d: Opened", cameraId);
65}
66
67status_t CameraDeviceClient::initialize(camera_module_t *module)
68{
69    ATRACE_CALL();
70    status_t res;
71
72    res = Camera2ClientBase::initialize(module);
73    if (res != OK) {
74        return res;
75    }
76
77    String8 threadName;
78    mFrameProcessor = new FrameProcessorBase(mDevice);
79    threadName = String8::format("CDU-%d-FrameProc", mCameraId);
80    mFrameProcessor->run(threadName.string());
81
82    mFrameProcessor->registerListener(FRAME_PROCESSOR_LISTENER_MIN_ID,
83                                      FRAME_PROCESSOR_LISTENER_MAX_ID,
84                                      /*listener*/this,
85                                      /*quirkSendPartials*/true);
86
87    return OK;
88}
89
90CameraDeviceClient::~CameraDeviceClient() {
91}
92
93status_t CameraDeviceClient::submitRequest(sp<CaptureRequest> request,
94                                         bool streaming,
95                                         /*out*/
96                                         int64_t* lastFrameNumber) {
97    List<sp<CaptureRequest> > requestList;
98    requestList.push_back(request);
99    return submitRequestList(requestList, streaming, lastFrameNumber);
100}
101
102status_t CameraDeviceClient::submitRequestList(List<sp<CaptureRequest> > requests,
103                                               bool streaming, int64_t* lastFrameNumber) {
104    ATRACE_CALL();
105    ALOGV("%s-start of function. Request list size %d", __FUNCTION__, requests.size());
106
107    status_t res;
108    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
109
110    Mutex::Autolock icl(mBinderSerializationLock);
111
112    if (!mDevice.get()) return DEAD_OBJECT;
113
114    if (requests.empty()) {
115        ALOGE("%s: Camera %d: Sent null request. Rejecting request.",
116              __FUNCTION__, mCameraId);
117        return BAD_VALUE;
118    }
119
120    List<const CameraMetadata> metadataRequestList;
121    int32_t requestId = mRequestIdCounter;
122    uint32_t loopCounter = 0;
123
124    for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end(); ++it) {
125        sp<CaptureRequest> request = *it;
126        if (request == 0) {
127            ALOGE("%s: Camera %d: Sent null request.",
128                    __FUNCTION__, mCameraId);
129            return BAD_VALUE;
130        }
131
132        CameraMetadata metadata(request->mMetadata);
133        if (metadata.isEmpty()) {
134            ALOGE("%s: Camera %d: Sent empty metadata packet. Rejecting request.",
135                   __FUNCTION__, mCameraId);
136            return BAD_VALUE;
137        } else if (request->mSurfaceList.isEmpty()) {
138            ALOGE("%s: Camera %d: Requests must have at least one surface target. "
139                  "Rejecting request.", __FUNCTION__, mCameraId);
140            return BAD_VALUE;
141        }
142
143        if (!enforceRequestPermissions(metadata)) {
144            // Callee logs
145            return PERMISSION_DENIED;
146        }
147
148        /**
149         * Write in the output stream IDs which we calculate from
150         * the capture request's list of surface targets
151         */
152        Vector<int32_t> outputStreamIds;
153        outputStreamIds.setCapacity(request->mSurfaceList.size());
154        for (size_t i = 0; i < request->mSurfaceList.size(); ++i) {
155            sp<Surface> surface = request->mSurfaceList[i];
156            if (surface == 0) continue;
157
158            sp<IGraphicBufferProducer> gbp = surface->getIGraphicBufferProducer();
159            int idx = mStreamMap.indexOfKey(gbp->asBinder());
160
161            // Trying to submit request with surface that wasn't created
162            if (idx == NAME_NOT_FOUND) {
163                ALOGE("%s: Camera %d: Tried to submit a request with a surface that"
164                      " we have not called createStream on",
165                      __FUNCTION__, mCameraId);
166                return BAD_VALUE;
167            }
168
169            int streamId = mStreamMap.valueAt(idx);
170            outputStreamIds.push_back(streamId);
171            ALOGV("%s: Camera %d: Appending output stream %d to request",
172                  __FUNCTION__, mCameraId, streamId);
173        }
174
175        metadata.update(ANDROID_REQUEST_OUTPUT_STREAMS, &outputStreamIds[0],
176                        outputStreamIds.size());
177
178        metadata.update(ANDROID_REQUEST_ID, &requestId, /*size*/1);
179        loopCounter++; // loopCounter starts from 1
180        ALOGV("%s: Camera %d: Creating request with ID %d (%d of %d)",
181              __FUNCTION__, mCameraId, requestId, loopCounter, requests.size());
182
183        metadataRequestList.push_back(metadata);
184    }
185    mRequestIdCounter++;
186
187    if (streaming) {
188        res = mDevice->setStreamingRequestList(metadataRequestList, lastFrameNumber);
189        if (res != OK) {
190            ALOGE("%s: Camera %d:  Got error %d after trying to set streaming "
191                  "request", __FUNCTION__, mCameraId, res);
192        } else {
193            mStreamingRequestList.push_back(requestId);
194        }
195    } else {
196        res = mDevice->captureList(metadataRequestList, lastFrameNumber);
197        if (res != OK) {
198            ALOGE("%s: Camera %d: Got error %d after trying to set capture",
199                __FUNCTION__, mCameraId, res);
200        }
201        ALOGV("%s: requestId = %d ", __FUNCTION__, requestId);
202    }
203
204    ALOGV("%s: Camera %d: End of function", __FUNCTION__, mCameraId);
205    if (res == OK) {
206        return requestId;
207    }
208
209    return res;
210}
211
212status_t CameraDeviceClient::cancelRequest(int requestId, int64_t* lastFrameNumber) {
213    ATRACE_CALL();
214    ALOGV("%s, requestId = %d", __FUNCTION__, requestId);
215
216    status_t res;
217
218    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
219
220    Mutex::Autolock icl(mBinderSerializationLock);
221
222    if (!mDevice.get()) return DEAD_OBJECT;
223
224    Vector<int>::iterator it, end;
225    for (it = mStreamingRequestList.begin(), end = mStreamingRequestList.end();
226         it != end; ++it) {
227        if (*it == requestId) {
228            break;
229        }
230    }
231
232    if (it == end) {
233        ALOGE("%s: Camera%d: Did not find request id %d in list of streaming "
234              "requests", __FUNCTION__, mCameraId, requestId);
235        return BAD_VALUE;
236    }
237
238    res = mDevice->clearStreamingRequest(lastFrameNumber);
239
240    if (res == OK) {
241        ALOGV("%s: Camera %d: Successfully cleared streaming request",
242              __FUNCTION__, mCameraId);
243        mStreamingRequestList.erase(it);
244    }
245
246    return res;
247}
248
249status_t CameraDeviceClient::beginConfigure() {
250    // TODO: Implement this.
251    ALOGE("%s: Not implemented yet.", __FUNCTION__);
252    return OK;
253}
254
255status_t CameraDeviceClient::endConfigure() {
256    // TODO: Implement this.
257    ALOGE("%s: Not implemented yet.", __FUNCTION__);
258    return OK;
259}
260
261status_t CameraDeviceClient::deleteStream(int streamId) {
262    ATRACE_CALL();
263    ALOGV("%s (streamId = 0x%x)", __FUNCTION__, streamId);
264
265    status_t res;
266    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
267
268    Mutex::Autolock icl(mBinderSerializationLock);
269
270    if (!mDevice.get()) return DEAD_OBJECT;
271
272    // Guard against trying to delete non-created streams
273    ssize_t index = NAME_NOT_FOUND;
274    for (size_t i = 0; i < mStreamMap.size(); ++i) {
275        if (streamId == mStreamMap.valueAt(i)) {
276            index = i;
277            break;
278        }
279    }
280
281    if (index == NAME_NOT_FOUND) {
282        ALOGW("%s: Camera %d: Invalid stream ID (%d) specified, no stream "
283              "created yet", __FUNCTION__, mCameraId, streamId);
284        return BAD_VALUE;
285    }
286
287    // Also returns BAD_VALUE if stream ID was not valid
288    res = mDevice->deleteStream(streamId);
289
290    if (res == BAD_VALUE) {
291        ALOGE("%s: Camera %d: Unexpected BAD_VALUE when deleting stream, but we"
292              " already checked and the stream ID (%d) should be valid.",
293              __FUNCTION__, mCameraId, streamId);
294    } else if (res == OK) {
295        mStreamMap.removeItemsAt(index);
296
297    }
298
299    return res;
300}
301
302status_t CameraDeviceClient::createStream(int width, int height, int format,
303                      const sp<IGraphicBufferProducer>& bufferProducer)
304{
305    ATRACE_CALL();
306    ALOGV("%s (w = %d, h = %d, f = 0x%x)", __FUNCTION__, width, height, format);
307
308    status_t res;
309    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
310
311    Mutex::Autolock icl(mBinderSerializationLock);
312
313    if (!mDevice.get()) return DEAD_OBJECT;
314
315    // Don't create multiple streams for the same target surface
316    {
317        ssize_t index = mStreamMap.indexOfKey(bufferProducer->asBinder());
318        if (index != NAME_NOT_FOUND) {
319            ALOGW("%s: Camera %d: Buffer producer already has a stream for it "
320                  "(ID %zd)",
321                  __FUNCTION__, mCameraId, index);
322            return ALREADY_EXISTS;
323        }
324    }
325
326    // HACK b/10949105
327    // Query consumer usage bits to set async operation mode for
328    // GLConsumer using controlledByApp parameter.
329    bool useAsync = false;
330    int32_t consumerUsage;
331    if ((res = bufferProducer->query(NATIVE_WINDOW_CONSUMER_USAGE_BITS,
332            &consumerUsage)) != OK) {
333        ALOGE("%s: Camera %d: Failed to query consumer usage", __FUNCTION__,
334              mCameraId);
335        return res;
336    }
337    if (consumerUsage & GraphicBuffer::USAGE_HW_TEXTURE) {
338        ALOGW("%s: Camera %d: Forcing asynchronous mode for stream",
339                __FUNCTION__, mCameraId);
340        useAsync = true;
341    }
342
343    sp<IBinder> binder;
344    sp<ANativeWindow> anw;
345    if (bufferProducer != 0) {
346        binder = bufferProducer->asBinder();
347        anw = new Surface(bufferProducer, useAsync);
348    }
349
350    // TODO: remove w,h,f since we are ignoring them
351
352    if ((res = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, &width)) != OK) {
353        ALOGE("%s: Camera %d: Failed to query Surface width", __FUNCTION__,
354              mCameraId);
355        return res;
356    }
357    if ((res = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, &height)) != OK) {
358        ALOGE("%s: Camera %d: Failed to query Surface height", __FUNCTION__,
359              mCameraId);
360        return res;
361    }
362    if ((res = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &format)) != OK) {
363        ALOGE("%s: Camera %d: Failed to query Surface format", __FUNCTION__,
364              mCameraId);
365        return res;
366    }
367
368    // FIXME: remove this override since the default format should be
369    //       IMPLEMENTATION_DEFINED. b/9487482
370    if (format >= HAL_PIXEL_FORMAT_RGBA_8888 &&
371        format <= HAL_PIXEL_FORMAT_BGRA_8888) {
372        ALOGW("%s: Camera %d: Overriding format 0x%x to IMPLEMENTATION_DEFINED",
373              __FUNCTION__, mCameraId, format);
374        format = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
375    }
376
377    // TODO: add startConfigure/stopConfigure call to CameraDeviceBase
378    // this will make it so Camera3Device doesn't call configure_streams
379    // after each call, but only once we are done with all.
380
381    int streamId = -1;
382    if (format == HAL_PIXEL_FORMAT_BLOB) {
383        // JPEG buffers need to be sized for maximum possible compressed size
384        CameraMetadata staticInfo = mDevice->info();
385        camera_metadata_entry_t entry = staticInfo.find(ANDROID_JPEG_MAX_SIZE);
386        if (entry.count == 0) {
387            ALOGE("%s: Camera %d: Can't find maximum JPEG size in "
388                    "static metadata!", __FUNCTION__, mCameraId);
389            return INVALID_OPERATION;
390        }
391        int32_t maxJpegSize = entry.data.i32[0];
392        res = mDevice->createStream(anw, width, height, format, maxJpegSize,
393                &streamId);
394    } else {
395        // All other streams are a known size
396        res = mDevice->createStream(anw, width, height, format, /*size*/0,
397                &streamId);
398    }
399
400    if (res == OK) {
401        mStreamMap.add(bufferProducer->asBinder(), streamId);
402
403        ALOGV("%s: Camera %d: Successfully created a new stream ID %d",
404              __FUNCTION__, mCameraId, streamId);
405
406        /**
407         * Set the stream transform flags to automatically
408         * rotate the camera stream for preview use cases.
409         */
410        int32_t transform = 0;
411        res = getRotationTransformLocked(&transform);
412
413        if (res != OK) {
414            // Error logged by getRotationTransformLocked.
415            return res;
416        }
417
418        res = mDevice->setStreamTransform(streamId, transform);
419        if (res != OK) {
420            ALOGE("%s: Failed to set stream transform (stream id %d)",
421                  __FUNCTION__, streamId);
422            return res;
423        }
424
425        return streamId;
426    }
427
428    return res;
429}
430
431// Create a request object from a template.
432status_t CameraDeviceClient::createDefaultRequest(int templateId,
433                                                  /*out*/
434                                                  CameraMetadata* request)
435{
436    ATRACE_CALL();
437    ALOGV("%s (templateId = 0x%x)", __FUNCTION__, templateId);
438
439    status_t res;
440    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
441
442    Mutex::Autolock icl(mBinderSerializationLock);
443
444    if (!mDevice.get()) return DEAD_OBJECT;
445
446    CameraMetadata metadata;
447    if ( (res = mDevice->createDefaultRequest(templateId, &metadata) ) == OK &&
448        request != NULL) {
449
450        request->swap(metadata);
451    }
452
453    return res;
454}
455
456status_t CameraDeviceClient::getCameraInfo(/*out*/CameraMetadata* info)
457{
458    ATRACE_CALL();
459    ALOGV("%s", __FUNCTION__);
460
461    status_t res = OK;
462
463    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
464
465    Mutex::Autolock icl(mBinderSerializationLock);
466
467    if (!mDevice.get()) return DEAD_OBJECT;
468
469    if (info != NULL) {
470        *info = mDevice->info(); // static camera metadata
471        // TODO: merge with device-specific camera metadata
472    }
473
474    return res;
475}
476
477status_t CameraDeviceClient::waitUntilIdle()
478{
479    ATRACE_CALL();
480    ALOGV("%s", __FUNCTION__);
481
482    status_t res = OK;
483    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
484
485    Mutex::Autolock icl(mBinderSerializationLock);
486
487    if (!mDevice.get()) return DEAD_OBJECT;
488
489    // FIXME: Also need check repeating burst.
490    if (!mStreamingRequestList.isEmpty()) {
491        ALOGE("%s: Camera %d: Try to waitUntilIdle when there are active streaming requests",
492              __FUNCTION__, mCameraId);
493        return INVALID_OPERATION;
494    }
495    res = mDevice->waitUntilDrained();
496    ALOGV("%s Done", __FUNCTION__);
497
498    return res;
499}
500
501status_t CameraDeviceClient::flush(int64_t* lastFrameNumber) {
502    ATRACE_CALL();
503    ALOGV("%s", __FUNCTION__);
504
505    status_t res = OK;
506    if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
507
508    Mutex::Autolock icl(mBinderSerializationLock);
509
510    if (!mDevice.get()) return DEAD_OBJECT;
511
512    mStreamingRequestList.clear();
513    return mDevice->flush(lastFrameNumber);
514}
515
516status_t CameraDeviceClient::dump(int fd, const Vector<String16>& args) {
517    String8 result;
518    result.appendFormat("CameraDeviceClient[%d] (%p) PID: %d, dump:\n",
519            mCameraId,
520            getRemoteCallback()->asBinder().get(),
521            mClientPid);
522    result.append("  State: ");
523
524    // TODO: print dynamic/request section from most recent requests
525    mFrameProcessor->dump(fd, args);
526
527    return dumpDevice(fd, args);
528}
529
530void CameraDeviceClient::notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
531                                     const CaptureResultExtras& resultExtras) {
532    // Thread safe. Don't bother locking.
533    sp<ICameraDeviceCallbacks> remoteCb = getRemoteCallback();
534
535    if (remoteCb != 0) {
536        remoteCb->onDeviceError(errorCode, resultExtras);
537    }
538}
539
540void CameraDeviceClient::notifyIdle() {
541    // Thread safe. Don't bother locking.
542    sp<ICameraDeviceCallbacks> remoteCb = getRemoteCallback();
543
544    if (remoteCb != 0) {
545        remoteCb->onDeviceIdle();
546    }
547}
548
549void CameraDeviceClient::notifyShutter(const CaptureResultExtras& resultExtras,
550        nsecs_t timestamp) {
551    // Thread safe. Don't bother locking.
552    sp<ICameraDeviceCallbacks> remoteCb = getRemoteCallback();
553    if (remoteCb != 0) {
554        remoteCb->onCaptureStarted(resultExtras, timestamp);
555    }
556}
557
558// TODO: refactor the code below this with IProCameraUser.
559// it's 100% copy-pasted, so lets not change it right now to make it easier.
560
561void CameraDeviceClient::detachDevice() {
562    if (mDevice == 0) return;
563
564    ALOGV("Camera %d: Stopping processors", mCameraId);
565
566    mFrameProcessor->removeListener(FRAME_PROCESSOR_LISTENER_MIN_ID,
567                                    FRAME_PROCESSOR_LISTENER_MAX_ID,
568                                    /*listener*/this);
569    mFrameProcessor->requestExit();
570    ALOGV("Camera %d: Waiting for threads", mCameraId);
571    mFrameProcessor->join();
572    ALOGV("Camera %d: Disconnecting device", mCameraId);
573
574    // WORKAROUND: HAL refuses to disconnect while there's streams in flight
575    {
576        mDevice->clearStreamingRequest();
577
578        status_t code;
579        if ((code = mDevice->waitUntilDrained()) != OK) {
580            ALOGE("%s: waitUntilDrained failed with code 0x%x", __FUNCTION__,
581                  code);
582        }
583    }
584
585    Camera2ClientBase::detachDevice();
586}
587
588/** Device-related methods */
589void CameraDeviceClient::onResultAvailable(const CaptureResult& result) {
590    ATRACE_CALL();
591    ALOGV("%s", __FUNCTION__);
592
593    // Thread-safe. No lock necessary.
594    sp<ICameraDeviceCallbacks> remoteCb = mRemoteCallback;
595    if (remoteCb != NULL) {
596        remoteCb->onResultReceived(result.mMetadata, result.mResultExtras);
597    }
598}
599
600// TODO: move to Camera2ClientBase
601bool CameraDeviceClient::enforceRequestPermissions(CameraMetadata& metadata) {
602
603    const int pid = IPCThreadState::self()->getCallingPid();
604    const int selfPid = getpid();
605    camera_metadata_entry_t entry;
606
607    /**
608     * Mixin default important security values
609     * - android.led.transmit = defaulted ON
610     */
611    CameraMetadata staticInfo = mDevice->info();
612    entry = staticInfo.find(ANDROID_LED_AVAILABLE_LEDS);
613    for(size_t i = 0; i < entry.count; ++i) {
614        uint8_t led = entry.data.u8[i];
615
616        switch(led) {
617            case ANDROID_LED_AVAILABLE_LEDS_TRANSMIT: {
618                uint8_t transmitDefault = ANDROID_LED_TRANSMIT_ON;
619                if (!metadata.exists(ANDROID_LED_TRANSMIT)) {
620                    metadata.update(ANDROID_LED_TRANSMIT,
621                                    &transmitDefault, 1);
622                }
623                break;
624            }
625        }
626    }
627
628    // We can do anything!
629    if (pid == selfPid) {
630        return true;
631    }
632
633    /**
634     * Permission check special fields in the request
635     * - android.led.transmit = android.permission.CAMERA_DISABLE_TRANSMIT
636     */
637    entry = metadata.find(ANDROID_LED_TRANSMIT);
638    if (entry.count > 0 && entry.data.u8[0] != ANDROID_LED_TRANSMIT_ON) {
639        String16 permissionString =
640            String16("android.permission.CAMERA_DISABLE_TRANSMIT_LED");
641        if (!checkCallingPermission(permissionString)) {
642            const int uid = IPCThreadState::self()->getCallingUid();
643            ALOGE("Permission Denial: "
644                  "can't disable transmit LED pid=%d, uid=%d", pid, uid);
645            return false;
646        }
647    }
648
649    return true;
650}
651
652status_t CameraDeviceClient::getRotationTransformLocked(int32_t* transform) {
653    ALOGV("%s: begin", __FUNCTION__);
654
655    if (transform == NULL) {
656        ALOGW("%s: null transform", __FUNCTION__);
657        return BAD_VALUE;
658    }
659
660    *transform = 0;
661
662    const CameraMetadata& staticInfo = mDevice->info();
663    camera_metadata_ro_entry_t entry = staticInfo.find(ANDROID_SENSOR_ORIENTATION);
664    if (entry.count == 0) {
665        ALOGE("%s: Camera %d: Can't find android.sensor.orientation in "
666                "static metadata!", __FUNCTION__, mCameraId);
667        return INVALID_OPERATION;
668    }
669
670    camera_metadata_ro_entry_t entryFacing = staticInfo.find(ANDROID_LENS_FACING);
671    if (entry.count == 0) {
672        ALOGE("%s: Camera %d: Can't find android.lens.facing in "
673                "static metadata!", __FUNCTION__, mCameraId);
674        return INVALID_OPERATION;
675    }
676
677    int32_t& flags = *transform;
678
679    bool mirror = (entryFacing.data.u8[0] == ANDROID_LENS_FACING_FRONT);
680    int orientation = entry.data.i32[0];
681    if (!mirror) {
682        switch (orientation) {
683            case 0:
684                flags = 0;
685                break;
686            case 90:
687                flags = NATIVE_WINDOW_TRANSFORM_ROT_90;
688                break;
689            case 180:
690                flags = NATIVE_WINDOW_TRANSFORM_ROT_180;
691                break;
692            case 270:
693                flags = NATIVE_WINDOW_TRANSFORM_ROT_270;
694                break;
695            default:
696                ALOGE("%s: Invalid HAL android.sensor.orientation value: %d",
697                      __FUNCTION__, orientation);
698                return INVALID_OPERATION;
699        }
700    } else {
701        switch (orientation) {
702            case 0:
703                flags = HAL_TRANSFORM_FLIP_H;
704                break;
705            case 90:
706                flags = HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90;
707                break;
708            case 180:
709                flags = HAL_TRANSFORM_FLIP_V;
710                break;
711            case 270:
712                flags = HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90;
713                break;
714            default:
715                ALOGE("%s: Invalid HAL android.sensor.orientation value: %d",
716                      __FUNCTION__, orientation);
717                return INVALID_OPERATION;
718        }
719
720    }
721
722    /**
723     * This magic flag makes surfaceflinger un-rotate the buffers
724     * to counter the extra global device UI rotation whenever the user
725     * physically rotates the device.
726     *
727     * By doing this, the camera buffer always ends up aligned
728     * with the physical camera for a "see through" effect.
729     *
730     * In essence, the buffer only gets rotated during preview use-cases.
731     * The user is still responsible to re-create streams of the proper
732     * aspect ratio, or the preview will end up looking non-uniformly
733     * stretched.
734     */
735    flags |= NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
736
737    ALOGV("%s: final transform = 0x%x", __FUNCTION__, flags);
738
739    return OK;
740}
741
742} // namespace android
743