summaryrefslogtreecommitdiff
path: root/guest/hals/camera/EmulatedCameraDevice.cpp
blob: d741b737cdadf74c1c335f7cdf4101132e271b70 (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
/*
 * Copyright (C) 2011 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.
 */

/*
 * Contains implementation of an abstract class EmulatedCameraDevice that
 * defines functionality expected from an emulated physical camera device:
 *  - Obtaining and setting camera parameters
 *  - Capturing frames
 *  - Streaming video
 *  - etc.
 */

#define LOG_NDEBUG 0
#define LOG_TAG "EmulatedCamera_Device"
#include "EmulatedCameraDevice.h"
#include <log/log.h>
#include <sys/select.h>
#include <algorithm>
#include <cmath>
#include "EmulatedCamera.h"

namespace android {

const float GAMMA_CORRECTION = 2.2f;
EmulatedCameraDevice::EmulatedCameraDevice(EmulatedCamera* camera_hal)
    : mObjectLock(),
      mCurFrameTimestamp(0),
      mCameraHAL(camera_hal),
      mCurrentFrame(NULL),
      mExposureCompensation(1.0f),
      mWhiteBalanceScale(NULL),
      mIsFocusing(false),
      mSupportedWhiteBalanceScale(),
      mState(ECDS_CONSTRUCTED) {}

EmulatedCameraDevice::~EmulatedCameraDevice() {
  ALOGV("EmulatedCameraDevice destructor");
  if (mCurrentFrame != NULL) {
    delete[] mCurrentFrame;
  }
  for (size_t i = 0; i < mSupportedWhiteBalanceScale.size(); ++i) {
    if (mSupportedWhiteBalanceScale.valueAt(i) != NULL) {
      delete[] mSupportedWhiteBalanceScale.valueAt(i);
    }
  }
}

/****************************************************************************
 * Emulated camera device public API
 ***************************************************************************/

status_t EmulatedCameraDevice::Initialize() {
  if (isInitialized()) {
    ALOGW("%s: Emulated camera device is already initialized: mState = %d",
          __FUNCTION__, mState);
    return NO_ERROR;
  }

  /* Instantiate worker thread object. */
  mWorkerThread = new WorkerThread(this);
  if (getWorkerThread() == NULL) {
    ALOGE("%s: Unable to instantiate worker thread object", __FUNCTION__);
    return ENOMEM;
  }

  mState = ECDS_INITIALIZED;

  return NO_ERROR;
}

status_t EmulatedCameraDevice::startDeliveringFrames(bool one_burst) {
  ALOGV("%s", __FUNCTION__);

  if (!isStarted()) {
    ALOGE("%s: Device is not started", __FUNCTION__);
    return EINVAL;
  }

  /* Frames will be delivered from the thread routine. */
  const status_t res = startWorkerThread(one_burst);
  ALOGE_IF(res != NO_ERROR, "%s: startWorkerThread failed", __FUNCTION__);
  return res;
}

status_t EmulatedCameraDevice::stopDeliveringFrames() {
  ALOGV("%s", __FUNCTION__);

  if (!isStarted()) {
    ALOGW("%s: Device is not started", __FUNCTION__);
    return NO_ERROR;
  }

  const status_t res = stopWorkerThread();
  ALOGE_IF(res != NO_ERROR, "%s: startWorkerThread failed", __FUNCTION__);
  return res;
}

void EmulatedCameraDevice::setExposureCompensation(const float ev) {
  ALOGV("%s", __FUNCTION__);

  if (!isStarted()) {
    ALOGW("%s: Fake camera device is not started.", __FUNCTION__);
  }

  mExposureCompensation = std::pow(2.0f, ev / GAMMA_CORRECTION);
  ALOGV("New exposure compensation is %f", mExposureCompensation);
}

void EmulatedCameraDevice::initializeWhiteBalanceModes(const char* mode,
                                                       const float r_scale,
                                                       const float b_scale) {
  ALOGV("%s with %s, %f, %f", __FUNCTION__, mode, r_scale, b_scale);
  float* value = new float[3];
  value[0] = r_scale;
  value[1] = 1.0f;
  value[2] = b_scale;
  mSupportedWhiteBalanceScale.add(String8(mode), value);
}

void EmulatedCameraDevice::setWhiteBalanceMode(const char* mode) {
  ALOGV("%s with white balance %s", __FUNCTION__, mode);
  mWhiteBalanceScale = mSupportedWhiteBalanceScale.valueFor(String8(mode));
}

void EmulatedCameraDevice::startAutoFocus() { mIsFocusing = true; }

/* Computes the pixel value after adjusting the white balance to the current
 * one. The input the y, u, v channel of the pixel and the adjusted value will
 * be stored in place. The adjustment is done in RGB space.
 */
void EmulatedCameraDevice::changeWhiteBalance(uint8_t& y, uint8_t& u,
                                              uint8_t& v) const {
  float r_scale = mWhiteBalanceScale[0];
  float b_scale = mWhiteBalanceScale[2];
  int r = static_cast<float>(YUV2R(y, u, v)) / r_scale;
  int g = YUV2G(y, u, v);
  int b = static_cast<float>(YUV2B(y, u, v)) / b_scale;

  y = RGB2Y(r, g, b);
  u = RGB2U(r, g, b);
  v = RGB2V(r, g, b);
}

void EmulatedCameraDevice::simulateAutoFocus() {
  if (mIsFocusing) {
    ALOGV("%s: Simulating auto-focus", __FUNCTION__);
    mCameraHAL->onCameraFocusAcquired();
    mIsFocusing = false;
  }
}

status_t EmulatedCameraDevice::getCurrentPreviewFrame(void* buffer) {
  if (!isStarted()) {
    ALOGE("%s: Device is not started", __FUNCTION__);
    return EINVAL;
  }
  if (mCurrentFrame == NULL || buffer == NULL) {
    ALOGE("%s: No framebuffer", __FUNCTION__);
    return EINVAL;
  }

  /* In emulation the framebuffer is never RGB. */
  switch (mPixelFormat) {
    case V4L2_PIX_FMT_YVU420:
      YV12ToRGB32(mCurrentFrame, buffer, mFrameWidth, mFrameHeight);
      return NO_ERROR;
    case V4L2_PIX_FMT_YUV420:
      YU12ToRGB32(mCurrentFrame, buffer, mFrameWidth, mFrameHeight);
      return NO_ERROR;
    case V4L2_PIX_FMT_NV21:
      NV21ToRGB32(mCurrentFrame, buffer, mFrameWidth, mFrameHeight);
      return NO_ERROR;
    case V4L2_PIX_FMT_NV12:
      NV12ToRGB32(mCurrentFrame, buffer, mFrameWidth, mFrameHeight);
      return NO_ERROR;

    default:
      ALOGE("%s: Unknown pixel format %.4s", __FUNCTION__,
            reinterpret_cast<const char*>(&mPixelFormat));
      return EINVAL;
  }
}

/****************************************************************************
 * Emulated camera device private API
 ***************************************************************************/

status_t EmulatedCameraDevice::commonStartDevice(int width, int height,
                                                 uint32_t pix_fmt, int fps) {
  /* Validate pixel format, and calculate framebuffer size at the same time. */
  switch (pix_fmt) {
    case V4L2_PIX_FMT_YVU420:
    case V4L2_PIX_FMT_YUV420:
    case V4L2_PIX_FMT_NV21:
    case V4L2_PIX_FMT_NV12:
      mFrameBufferSize = (width * height * 12) / 8;
      break;

    default:
      ALOGE("%s: Unknown pixel format %.4s", __FUNCTION__,
            reinterpret_cast<const char*>(&pix_fmt));
      return EINVAL;
  }

  /* Cache framebuffer info. */
  mFrameWidth = width;
  mFrameHeight = height;
  mPixelFormat = pix_fmt;
  mTotalPixels = width * height;
  mTargetFps = fps;

  /* Allocate framebuffer. */
  mCurrentFrame = new uint8_t[mFrameBufferSize];
  if (mCurrentFrame == NULL) {
    ALOGE("%s: Unable to allocate framebuffer", __FUNCTION__);
    return ENOMEM;
  }
  ALOGV("%s: Allocated %p %zu bytes for %d pixels in %.4s[%dx%d] frame",
        __FUNCTION__, mCurrentFrame, mFrameBufferSize, mTotalPixels,
        reinterpret_cast<const char*>(&mPixelFormat), mFrameWidth,
        mFrameHeight);
  return NO_ERROR;
}

void EmulatedCameraDevice::commonStopDevice() {
  mFrameWidth = mFrameHeight = mTotalPixels = 0;
  mPixelFormat = 0;
  mTargetFps = 0;

  if (mCurrentFrame != NULL) {
    delete[] mCurrentFrame;
    mCurrentFrame = NULL;
  }
}

const CameraParameters* EmulatedCameraDevice::getCameraParameters() {
  return mCameraHAL->getCameraParameters();
}

/****************************************************************************
 * Worker thread management.
 ***************************************************************************/

status_t EmulatedCameraDevice::startWorkerThread(bool one_burst) {
  ALOGV("%s", __FUNCTION__);

  if (!isInitialized()) {
    ALOGE("%s: Emulated camera device is not initialized", __FUNCTION__);
    return EINVAL;
  }

  const status_t res = getWorkerThread()->startThread(one_burst);
  ALOGE_IF(res != NO_ERROR, "%s: Unable to start worker thread", __FUNCTION__);
  return res;
}

status_t EmulatedCameraDevice::stopWorkerThread() {
  ALOGV("%s", __FUNCTION__);

  if (!isInitialized()) {
    ALOGE("%s: Emulated camera device is not initialized", __FUNCTION__);
    return EINVAL;
  }

  const status_t res = getWorkerThread()->stopThread();
  ALOGE_IF(res != NO_ERROR, "%s: Unable to stop worker thread", __FUNCTION__);
  return res;
}

bool EmulatedCameraDevice::inWorkerThread() {
  /* This will end the thread loop, and will terminate the thread. Derived
   * classes must override this method. */
  return false;
}

/****************************************************************************
 * Worker thread implementation.
 ***************************************************************************/

status_t EmulatedCameraDevice::WorkerThread::readyToRun() {
  ALOGV("Starting emulated camera device worker thread...");

  ALOGW_IF(mThreadControl >= 0 || mControlFD >= 0,
           "%s: Thread control FDs are opened", __FUNCTION__);
  /* Create a pair of FDs that would be used to control the thread. */
  int thread_fds[2];
  status_t ret;
  Mutex::Autolock lock(mCameraDevice->mObjectLock);
  if (pipe(thread_fds) == 0) {
    mThreadControl = thread_fds[1];
    mControlFD = thread_fds[0];
    ALOGV("Emulated device's worker thread has been started.");
    ret = NO_ERROR;
  } else {
    ALOGE("%s: Unable to create thread control FDs: %d -> %s", __FUNCTION__,
          errno, strerror(errno));
    ret = errno;
  }

  mSetup.signal();
  return ret;
}

status_t EmulatedCameraDevice::WorkerThread::stopThread() {
  ALOGV("Stopping emulated camera device's worker thread...");

  status_t res = EINVAL;

  // Limit the scope of the Autolock
  {
    // If thread is running and readyToRun() has not finished running,
    //    then wait until it is done.
    Mutex::Autolock lock(mCameraDevice->mObjectLock);
    if (isRunning() && (mThreadControl < 0 || mControlFD < 0)) {
      mSetup.wait(mCameraDevice->mObjectLock);
    }
  }

  if (mThreadControl >= 0) {
    /* Send "stop" message to the thread loop. */
    const ControlMessage msg = THREAD_STOP;
    const int wres =
        TEMP_FAILURE_RETRY(write(mThreadControl, &msg, sizeof(msg)));
    if (wres == sizeof(msg)) {
      /* Stop the thread, and wait till it's terminated. */
      res = requestExitAndWait();
      if (res == NO_ERROR) {
        /* Close control FDs. */
        if (mThreadControl >= 0) {
          close(mThreadControl);
          mThreadControl = -1;
        }
        if (mControlFD >= 0) {
          close(mControlFD);
          mControlFD = -1;
        }
        ALOGV("Emulated camera device's worker thread has been stopped.");
      } else {
        ALOGE("%s: requestExitAndWait failed: %d -> %s", __FUNCTION__, res,
              strerror(-res));
      }
    } else {
      ALOGE("%s: Unable to send THREAD_STOP message: %d -> %s", __FUNCTION__,
            errno, strerror(errno));
      res = errno ? errno : EINVAL;
    }
  } else {
    ALOGE("%s: Thread control FDs are not opened", __FUNCTION__);
  }

  return res;
}

EmulatedCameraDevice::WorkerThread::SelectRes
EmulatedCameraDevice::WorkerThread::Select(int fd, int timeout) {
  fd_set fds[1];
  struct timeval tv, *tvp = NULL;

  mCameraDevice->simulateAutoFocus();

  const int fd_num = (fd >= 0) ? std::max(fd, mControlFD) + 1 : mControlFD + 1;
  FD_ZERO(fds);
  FD_SET(mControlFD, fds);
  if (fd >= 0) {
    FD_SET(fd, fds);
  }
  if (timeout) {
    tv.tv_sec = timeout / 1000000;
    tv.tv_usec = timeout % 1000000;
    tvp = &tv;
  }
  int res = TEMP_FAILURE_RETRY(select(fd_num, fds, NULL, NULL, tvp));
  if (res < 0) {
    ALOGE("%s: select returned %d and failed: %d -> %s", __FUNCTION__, res,
          errno, strerror(errno));
    return ERROR;
  } else if (res == 0) {
    /* Timeout. */
    return TIMEOUT;
  } else if (FD_ISSET(mControlFD, fds)) {
    /* A control event. Lets read the message. */
    ControlMessage msg;
    res = TEMP_FAILURE_RETRY(read(mControlFD, &msg, sizeof(msg)));
    if (res != sizeof(msg)) {
      ALOGE("%s: Unexpected message size %d, or an error %d -> %s",
            __FUNCTION__, res, errno, strerror(errno));
      return ERROR;
    }
    /* THREAD_STOP is the only message expected here. */
    if (msg == THREAD_STOP) {
      ALOGV("%s: THREAD_STOP message is received", __FUNCTION__);
      return EXIT_THREAD;
    } else {
      ALOGE("Unknown worker thread message %d", msg);
      return ERROR;
    }
  } else {
    /* Must be an FD. */
    ALOGW_IF(fd < 0 || !FD_ISSET(fd, fds), "%s: Undefined 'select' result",
             __FUNCTION__);
    return READY;
  }
}

}; /* namespace android */