1 /*
2 * Copyright (C) 2012 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_NDEBUG 0
18 //#define LOG_NNDEBUG 0
19 #include "system/graphics-base-v1.1.h"
20 #define LOG_TAG "EmulatedSensor"
21 #define ATRACE_TAG ATRACE_TAG_CAMERA
22
23 #ifdef LOG_NNDEBUG
24 #define ALOGVV(...) ALOGV(__VA_ARGS__)
25 #else
26 #define ALOGVV(...) ((void)0)
27 #endif
28
29 #include <android/hardware/graphics/common/1.2/types.h>
30 #include <cutils/properties.h>
31 #include <inttypes.h>
32 #include <libyuv.h>
33 #include <memory.h>
34 #include <system/camera_metadata.h>
35 #include <utils/Log.h>
36 #include <utils/Trace.h>
37
38 #include <cmath>
39 #include <cstdlib>
40
41 #include "EmulatedSensor.h"
42 #include "utils/ExifUtils.h"
43 #include "utils/HWLUtils.h"
44
45 namespace android {
46
47 using android::google_camera_hal::ErrorCode;
48 using google_camera_hal::HalCameraMetadata;
49 using google_camera_hal::MessageType;
50 using google_camera_hal::NotifyMessage;
51
52 using android::hardware::graphics::common::V1_2::Dataspace;
53
54 // Copied from ColorSpace.java (see Named)
55 enum ColorSpaceNamed {
56 SRGB,
57 LINEAR_SRGB,
58 EXTENDED_SRGB,
59 LINEAR_EXTENDED_SRGB,
60 BT709,
61 BT2020,
62 DCI_P3,
63 DISPLAY_P3,
64 NTSC_1953,
65 SMPTE_C,
66 ADOBE_RGB,
67 PRO_PHOTO_RGB,
68 ACES,
69 ACESCG,
70 CIE_XYZ,
71 CIE_LAB
72 };
73
74 const uint32_t EmulatedSensor::kRegularSceneHandshake = 1; // Scene handshake divider
75 const uint32_t EmulatedSensor::kReducedSceneHandshake = 2; // Scene handshake divider
76
77 // 1 us - 30 sec
78 const nsecs_t EmulatedSensor::kSupportedExposureTimeRange[2] = {1000LL,
79 30000000000LL};
80
81 // ~1/30 s - 30 sec
82 const nsecs_t EmulatedSensor::kSupportedFrameDurationRange[2] = {33331760LL,
83 30000000000LL};
84
85 const int32_t EmulatedSensor::kSupportedSensitivityRange[2] = {100, 1600};
86 const int32_t EmulatedSensor::kDefaultSensitivity = 100; // ISO
87 const nsecs_t EmulatedSensor::kDefaultExposureTime = ms2ns(15);
88 const nsecs_t EmulatedSensor::kDefaultFrameDuration = ms2ns(33);
89 // Deadline within we should return the results as soon as possible to
90 // avoid skewing the frame cycle due to external delays.
91 const nsecs_t EmulatedSensor::kReturnResultThreshod = 3 * kDefaultFrameDuration;
92
93 // Sensor defaults
94 const uint8_t EmulatedSensor::kSupportedColorFilterArrangement =
95 ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB;
96 const uint32_t EmulatedSensor::kDefaultMaxRawValue = 4000;
97 const uint32_t EmulatedSensor::kDefaultBlackLevelPattern[4] = {1000, 1000, 1000,
98 1000};
99
100 const nsecs_t EmulatedSensor::kMinVerticalBlank = 10000L;
101
102 // Sensor sensitivity
103 const float EmulatedSensor::kSaturationVoltage = 0.520f;
104 const uint32_t EmulatedSensor::kSaturationElectrons = 2000;
105 const float EmulatedSensor::kVoltsPerLuxSecond = 0.100f;
106
107 const float EmulatedSensor::kElectronsPerLuxSecond =
108 EmulatedSensor::kSaturationElectrons / EmulatedSensor::kSaturationVoltage *
109 EmulatedSensor::kVoltsPerLuxSecond;
110
111 const float EmulatedSensor::kReadNoiseStddevBeforeGain = 1.177; // in electrons
112 const float EmulatedSensor::kReadNoiseStddevAfterGain =
113 2.100; // in digital counts
114 const float EmulatedSensor::kReadNoiseVarBeforeGain =
115 EmulatedSensor::kReadNoiseStddevBeforeGain *
116 EmulatedSensor::kReadNoiseStddevBeforeGain;
117 const float EmulatedSensor::kReadNoiseVarAfterGain =
118 EmulatedSensor::kReadNoiseStddevAfterGain *
119 EmulatedSensor::kReadNoiseStddevAfterGain;
120
121 const uint32_t EmulatedSensor::kMaxRAWStreams = 1;
122 const uint32_t EmulatedSensor::kMaxProcessedStreams = 3;
123 const uint32_t EmulatedSensor::kMaxStallingStreams = 2;
124 const uint32_t EmulatedSensor::kMaxInputStreams = 1;
125
126 const uint32_t EmulatedSensor::kMaxLensShadingMapSize[2]{64, 64};
127 const int32_t EmulatedSensor::kFixedBitPrecision = 64; // 6-bit
128 // In fixed-point math, saturation point of sensor after gain
129 const int32_t EmulatedSensor::kSaturationPoint = kFixedBitPrecision * 255;
130 const camera_metadata_rational EmulatedSensor::kNeutralColorPoint[3] = {
131 {255, 1}, {255, 1}, {255, 1}};
132 const float EmulatedSensor::kGreenSplit = 1.f; // No divergence
133 // Reduce memory usage by allowing only one buffer in sensor, one in jpeg
134 // compressor and one pending request to avoid stalls.
135 const uint8_t EmulatedSensor::kPipelineDepth = 3;
136
137 const camera_metadata_rational EmulatedSensor::kDefaultColorTransform[9] = {
138 {1, 1}, {0, 1}, {0, 1}, {0, 1}, {1, 1}, {0, 1}, {0, 1}, {0, 1}, {1, 1}};
139 const float EmulatedSensor::kDefaultColorCorrectionGains[4] = {1.0f, 1.0f, 1.0f,
140 1.0f};
141
142 const float EmulatedSensor::kDefaultToneMapCurveRed[4] = {.0f, .0f, 1.f, 1.f};
143 const float EmulatedSensor::kDefaultToneMapCurveGreen[4] = {.0f, .0f, 1.f, 1.f};
144 const float EmulatedSensor::kDefaultToneMapCurveBlue[4] = {.0f, .0f, 1.f, 1.f};
145
146 // All XY matrix coefficients sourced from
147 // https://developer.android.com/reference/kotlin/android/graphics/ColorSpace.Named
148 // and XYZ coefficients calculated using the method found in
149 // ColorSpace.Rgb.computeXyzMatrix
150 struct XyzMatrix {
151 float xR = 3.2406f;
152 float yR = -1.5372f;
153 float zR = -0.4986f;
154 float xG = -0.9689f;
155 float yG = 1.8758f;
156 float zG = 0.0415f;
157 float xB = 0.0557f;
158 float yB = -0.2040f;
159 float zB = 1.0570f;
160 };
161
162 static const XyzMatrix kSrgbXyzMatrix = {3.2406f, -1.5372f, -0.4986f,
163 -0.9689f, 1.8758f, 0.0415f,
164 0.0557f, -0.2040f, 1.0570f};
165
166 static const XyzMatrix kDisplayP3Matrix = {2.4931f, -0.9316f, -0.4023f,
167 -0.8291f, 1.7627f, 0.0234f,
168 0.0361f, -0.0761f, 0.9570f};
169
170 static const XyzMatrix kBt709Matrix = {3.2410f, -1.5374f, -0.4986f,
171 -0.9692f, 1.8760f, 0.0416f,
172 0.0556f, -0.2040f, 1.0570f};
173
174 static const XyzMatrix kBt2020Matrix = {1.7167f, -0.3556f, -0.2534f,
175 -0.6666f, 1.6164f, 0.0158f,
176 0.0177f, -0.0428f, 0.9421f};
177
178 /** A few utility functions for math, normal distributions */
179
180 // Take advantage of IEEE floating-point format to calculate an approximate
181 // square root. Accurate to within +-3.6%
sqrtf_approx(float r)182 float sqrtf_approx(float r) {
183 // Modifier is based on IEEE floating-point representation; the
184 // manipulations boil down to finding approximate log2, dividing by two, and
185 // then inverting the log2. A bias is added to make the relative error
186 // symmetric about the real answer.
187 const int32_t modifier = 0x1FBB4000;
188
189 int32_t r_i = *(int32_t*)(&r);
190 r_i = (r_i >> 1) + modifier;
191
192 return *(float*)(&r_i);
193 }
194
EmulatedSensor()195 EmulatedSensor::EmulatedSensor() : Thread(false), got_vsync_(false) {
196 gamma_table_sRGB_.resize(kSaturationPoint + 1);
197 gamma_table_smpte170m_.resize(kSaturationPoint + 1);
198 gamma_table_hlg_.resize(kSaturationPoint + 1);
199 for (int32_t i = 0; i <= kSaturationPoint; i++) {
200 gamma_table_sRGB_[i] = ApplysRGBGamma(i, kSaturationPoint);
201 gamma_table_smpte170m_[i] = ApplySMPTE170MGamma(i, kSaturationPoint);
202 gamma_table_hlg_[i] = ApplyHLGGamma(i, kSaturationPoint);
203 }
204 }
205
~EmulatedSensor()206 EmulatedSensor::~EmulatedSensor() {
207 ShutDown();
208 }
209
AreCharacteristicsSupported(const SensorCharacteristics & characteristics)210 bool EmulatedSensor::AreCharacteristicsSupported(
211 const SensorCharacteristics& characteristics) {
212 if ((characteristics.width == 0) || (characteristics.height == 0)) {
213 ALOGE("%s: Invalid sensor size %zux%zu", __FUNCTION__,
214 characteristics.width, characteristics.height);
215 return false;
216 }
217
218 if ((characteristics.full_res_width == 0) ||
219 (characteristics.full_res_height == 0)) {
220 ALOGE("%s: Invalid sensor full res size %zux%zu", __FUNCTION__,
221 characteristics.full_res_width, characteristics.full_res_height);
222 return false;
223 }
224
225 if (characteristics.is_10bit_dynamic_range_capable) {
226 // We support only HLG10 at the moment
227 const auto& hlg10_entry = characteristics.dynamic_range_profiles.find(
228 ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HLG10);
229 if ((characteristics.dynamic_range_profiles.size() != 1) ||
230 (hlg10_entry == characteristics.dynamic_range_profiles.end())) {
231 ALOGE("%s: Only support for HLG10 is available!", __FUNCTION__);
232 return false;
233 }
234 }
235
236 if ((characteristics.exposure_time_range[0] >=
237 characteristics.exposure_time_range[1]) ||
238 ((characteristics.exposure_time_range[0] < kSupportedExposureTimeRange[0]) ||
239 (characteristics.exposure_time_range[1] >
240 kSupportedExposureTimeRange[1]))) {
241 ALOGE("%s: Unsupported exposure range", __FUNCTION__);
242 return false;
243 }
244
245 if ((characteristics.frame_duration_range[0] >=
246 characteristics.frame_duration_range[1]) ||
247 ((characteristics.frame_duration_range[0] <
248 kSupportedFrameDurationRange[0]) ||
249 (characteristics.frame_duration_range[1] >
250 kSupportedFrameDurationRange[1]))) {
251 ALOGE("%s: Unsupported frame duration range", __FUNCTION__);
252 return false;
253 }
254
255 if ((characteristics.sensitivity_range[0] >=
256 characteristics.sensitivity_range[1]) ||
257 ((characteristics.sensitivity_range[0] < kSupportedSensitivityRange[0]) ||
258 (characteristics.sensitivity_range[1] > kSupportedSensitivityRange[1])) ||
259 (!((kDefaultSensitivity >= characteristics.sensitivity_range[0]) &&
260 (kDefaultSensitivity <= characteristics.sensitivity_range[1])))) {
261 ALOGE("%s: Unsupported sensitivity range", __FUNCTION__);
262 return false;
263 }
264
265 if (characteristics.color_arangement != kSupportedColorFilterArrangement) {
266 ALOGE("%s: Unsupported color arrangement!", __FUNCTION__);
267 return false;
268 }
269
270 for (const auto& blackLevel : characteristics.black_level_pattern) {
271 if (blackLevel >= characteristics.max_raw_value) {
272 ALOGE("%s: Black level matches or exceeds max RAW value!", __FUNCTION__);
273 return false;
274 }
275 }
276
277 if ((characteristics.frame_duration_range[0] / characteristics.height) == 0) {
278 ALOGE("%s: Zero row readout time!", __FUNCTION__);
279 return false;
280 }
281
282 if (characteristics.max_raw_streams > kMaxRAWStreams) {
283 ALOGE("%s: RAW streams maximum %u exceeds supported maximum %u",
284 __FUNCTION__, characteristics.max_raw_streams, kMaxRAWStreams);
285 return false;
286 }
287
288 if (characteristics.max_processed_streams > kMaxProcessedStreams) {
289 ALOGE("%s: Processed streams maximum %u exceeds supported maximum %u",
290 __FUNCTION__, characteristics.max_processed_streams,
291 kMaxProcessedStreams);
292 return false;
293 }
294
295 if (characteristics.max_stalling_streams > kMaxStallingStreams) {
296 ALOGE("%s: Stalling streams maximum %u exceeds supported maximum %u",
297 __FUNCTION__, characteristics.max_stalling_streams,
298 kMaxStallingStreams);
299 return false;
300 }
301
302 if (characteristics.max_input_streams > kMaxInputStreams) {
303 ALOGE("%s: Input streams maximum %u exceeds supported maximum %u",
304 __FUNCTION__, characteristics.max_input_streams, kMaxInputStreams);
305 return false;
306 }
307
308 if ((characteristics.lens_shading_map_size[0] > kMaxLensShadingMapSize[0]) ||
309 (characteristics.lens_shading_map_size[1] > kMaxLensShadingMapSize[1])) {
310 ALOGE("%s: Lens shading map [%dx%d] exceeds supprorted maximum [%dx%d]",
311 __FUNCTION__, characteristics.lens_shading_map_size[0],
312 characteristics.lens_shading_map_size[1], kMaxLensShadingMapSize[0],
313 kMaxLensShadingMapSize[1]);
314 return false;
315 }
316
317 if (characteristics.max_pipeline_depth < kPipelineDepth) {
318 ALOGE("%s: Pipeline depth %d smaller than supprorted minimum %d",
319 __FUNCTION__, characteristics.max_pipeline_depth, kPipelineDepth);
320 return false;
321 }
322
323 return true;
324 }
325
SplitStreamCombination(const StreamConfiguration & original_config,StreamConfiguration * default_mode_config,StreamConfiguration * max_resolution_mode_config,StreamConfiguration * input_stream_config)326 static void SplitStreamCombination(
327 const StreamConfiguration& original_config,
328 StreamConfiguration* default_mode_config,
329 StreamConfiguration* max_resolution_mode_config,
330 StreamConfiguration* input_stream_config) {
331 // Go through the streams
332 if (default_mode_config == nullptr || max_resolution_mode_config == nullptr ||
333 input_stream_config == nullptr) {
334 ALOGE("%s: Input stream / output stream configs are nullptr", __FUNCTION__);
335 return;
336 }
337 for (const auto& stream : original_config.streams) {
338 if (stream.stream_type == google_camera_hal::StreamType::kInput) {
339 input_stream_config->streams.push_back(stream);
340 continue;
341 }
342 if (stream.intended_for_default_resolution_mode) {
343 default_mode_config->streams.push_back(stream);
344 }
345 if (stream.intended_for_max_resolution_mode) {
346 max_resolution_mode_config->streams.push_back(stream);
347 }
348 }
349 }
350
IsStreamCombinationSupported(uint32_t logical_id,const StreamConfiguration & config,StreamConfigurationMap & default_config_map,StreamConfigurationMap & max_resolution_config_map,const PhysicalStreamConfigurationMap & physical_map,const PhysicalStreamConfigurationMap & physical_map_max_resolution,const LogicalCharacteristics & sensor_chars)351 bool EmulatedSensor::IsStreamCombinationSupported(
352 uint32_t logical_id, const StreamConfiguration& config,
353 StreamConfigurationMap& default_config_map,
354 StreamConfigurationMap& max_resolution_config_map,
355 const PhysicalStreamConfigurationMap& physical_map,
356 const PhysicalStreamConfigurationMap& physical_map_max_resolution,
357 const LogicalCharacteristics& sensor_chars) {
358 StreamConfiguration default_mode_config, max_resolution_mode_config,
359 input_stream_config;
360 SplitStreamCombination(config, &default_mode_config,
361 &max_resolution_mode_config, &input_stream_config);
362
363 return IsStreamCombinationSupported(logical_id, default_mode_config,
364 default_config_map, physical_map,
365 sensor_chars) &&
366 IsStreamCombinationSupported(
367 logical_id, max_resolution_mode_config, max_resolution_config_map,
368 physical_map_max_resolution, sensor_chars, /*is_max_res*/ true) &&
369
370 (IsStreamCombinationSupported(logical_id, input_stream_config,
371 default_config_map, physical_map,
372 sensor_chars) ||
373 IsStreamCombinationSupported(
374 logical_id, input_stream_config, max_resolution_config_map,
375 physical_map_max_resolution, sensor_chars, /*is_max_res*/ true));
376 }
377
IsStreamCombinationSupported(uint32_t logical_id,const StreamConfiguration & config,StreamConfigurationMap & config_map,const PhysicalStreamConfigurationMap & physical_map,const LogicalCharacteristics & sensor_chars,bool is_max_res)378 bool EmulatedSensor::IsStreamCombinationSupported(
379 uint32_t logical_id, const StreamConfiguration& config,
380 StreamConfigurationMap& config_map,
381 const PhysicalStreamConfigurationMap& physical_map,
382 const LogicalCharacteristics& sensor_chars, bool is_max_res) {
383 uint32_t input_stream_count = 0;
384 // Map from physical camera id to number of streams for that physical camera
385 std::map<uint32_t, uint32_t> raw_stream_count;
386 std::map<uint32_t, uint32_t> processed_stream_count;
387 std::map<uint32_t, uint32_t> stalling_stream_count;
388
389 // Only allow the stream configurations specified in
390 // dynamicSizeStreamConfigurations.
391 for (const auto& stream : config.streams) {
392 bool is_dynamic_output =
393 (stream.is_physical_camera_stream && stream.group_id != -1);
394 if (stream.rotation != google_camera_hal::StreamRotation::kRotation0) {
395 ALOGE("%s: Stream rotation: 0x%x not supported!", __FUNCTION__,
396 stream.rotation);
397 return false;
398 }
399
400 if (stream.stream_type == google_camera_hal::StreamType::kInput) {
401 if (sensor_chars.at(logical_id).max_input_streams == 0) {
402 ALOGE("%s: Input streams are not supported on this device!",
403 __FUNCTION__);
404 return false;
405 }
406
407 auto const& supported_outputs =
408 config_map.GetValidOutputFormatsForInput(stream.format);
409 if (supported_outputs.empty()) {
410 ALOGE("%s: Input stream with format: 0x%x no supported on this device!",
411 __FUNCTION__, stream.format);
412 return false;
413 }
414
415 input_stream_count++;
416 } else {
417 if (stream.is_physical_camera_stream &&
418 physical_map.find(stream.physical_camera_id) == physical_map.end()) {
419 ALOGE("%s: Invalid physical camera id %d", __FUNCTION__,
420 stream.physical_camera_id);
421 return false;
422 }
423
424 if (is_dynamic_output) {
425 auto dynamic_physical_output_formats =
426 physical_map.at(stream.physical_camera_id)
427 ->GetDynamicPhysicalStreamOutputFormats();
428 if (dynamic_physical_output_formats.find(stream.format) ==
429 dynamic_physical_output_formats.end()) {
430 ALOGE("%s: Unsupported physical stream format %d", __FUNCTION__,
431 stream.format);
432 return false;
433 }
434 }
435
436 if (stream.dynamic_profile !=
437 ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD) {
438 const SensorCharacteristics& sensor_char =
439 stream.is_physical_camera_stream
440 ? sensor_chars.at(stream.physical_camera_id)
441 : sensor_chars.at(logical_id);
442 if (!sensor_char.is_10bit_dynamic_range_capable) {
443 ALOGE("%s: 10-bit dynamic range output not supported on this device!",
444 __FUNCTION__);
445 return false;
446 }
447
448 if ((stream.format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) &&
449 (static_cast<android_pixel_format_v1_1_t>(stream.format) !=
450 HAL_PIXEL_FORMAT_YCBCR_P010)) {
451 ALOGE(
452 "%s: 10-bit dynamic range profile 0x%x not supported on a non "
453 "10-bit output stream"
454 " pixel format 0x%x",
455 __FUNCTION__, stream.dynamic_profile, stream.format);
456 return false;
457 }
458
459 if ((static_cast<android_pixel_format_v1_1_t>(stream.format) ==
460 HAL_PIXEL_FORMAT_YCBCR_P010) &&
461 ((stream.data_space !=
462 static_cast<android_dataspace_t>(Dataspace::BT2020_ITU_HLG)) &&
463 (stream.data_space !=
464 static_cast<android_dataspace_t>(Dataspace::BT2020_HLG)) &&
465 (stream.data_space !=
466 static_cast<android_dataspace_t>(Dataspace::UNKNOWN)))) {
467 ALOGE(
468 "%s: Unsupported stream data space 0x%x for 10-bit YUV "
469 "output",
470 __FUNCTION__, stream.data_space);
471 return false;
472 }
473 }
474
475 switch (stream.format) {
476 case HAL_PIXEL_FORMAT_BLOB:
477 if ((stream.data_space != HAL_DATASPACE_V0_JFIF) &&
478 (stream.data_space != HAL_DATASPACE_UNKNOWN)) {
479 ALOGE("%s: Unsupported Blob dataspace 0x%x", __FUNCTION__,
480 stream.data_space);
481 return false;
482 }
483 if (stream.is_physical_camera_stream) {
484 stalling_stream_count[stream.physical_camera_id]++;
485 } else {
486 for (const auto& p : physical_map) {
487 stalling_stream_count[p.first]++;
488 }
489 }
490 break;
491 case HAL_PIXEL_FORMAT_RAW16: {
492 const SensorCharacteristics& sensor_char =
493 stream.is_physical_camera_stream
494 ? sensor_chars.at(stream.physical_camera_id)
495 : sensor_chars.at(logical_id);
496 auto sensor_height =
497 is_max_res ? sensor_char.full_res_height : sensor_char.height;
498 auto sensor_width =
499 is_max_res ? sensor_char.full_res_width : sensor_char.width;
500 if (stream.height != sensor_height || stream.width != sensor_width) {
501 ALOGE(
502 "%s, RAW16 buffer height %d and width %d must match sensor "
503 "height: %zu"
504 " and width: %zu",
505 __FUNCTION__, stream.height, stream.width, sensor_height,
506 sensor_width);
507 return false;
508 }
509 if (stream.is_physical_camera_stream) {
510 raw_stream_count[stream.physical_camera_id]++;
511 } else {
512 for (const auto& p : physical_map) {
513 raw_stream_count[p.first]++;
514 }
515 }
516 } break;
517 default:
518 if (stream.is_physical_camera_stream) {
519 processed_stream_count[stream.physical_camera_id]++;
520 } else {
521 for (const auto& p : physical_map) {
522 processed_stream_count[p.first]++;
523 }
524 }
525 }
526
527 auto output_sizes =
528 is_dynamic_output
529 ? physical_map.at(stream.physical_camera_id)
530 ->GetDynamicPhysicalStreamOutputSizes(stream.format)
531 : stream.is_physical_camera_stream
532 ? physical_map.at(stream.physical_camera_id)
533 ->GetOutputSizes(stream.format)
534 : config_map.GetOutputSizes(stream.format);
535
536 auto stream_size = std::make_pair(stream.width, stream.height);
537 if (output_sizes.find(stream_size) == output_sizes.end()) {
538 ALOGE("%s: Stream with size %dx%d and format 0x%x is not supported!",
539 __FUNCTION__, stream.width, stream.height, stream.format);
540 return false;
541 }
542 }
543
544 if (!sensor_chars.at(logical_id).support_stream_use_case) {
545 if (stream.use_case != ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT) {
546 ALOGE("%s: Camera device doesn't support non-default stream use case!",
547 __FUNCTION__);
548 return false;
549 }
550 } else if (stream.use_case >
551 sensor_chars.at(logical_id).end_valid_stream_use_case) {
552 ALOGE("%s: Stream with use case %d is not supported!", __FUNCTION__,
553 stream.use_case);
554 return false;
555 } else if (stream.use_case !=
556 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT) {
557 if (stream.use_case ==
558 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE) {
559 if (stream.format != HAL_PIXEL_FORMAT_YCBCR_420_888 &&
560 stream.format != HAL_PIXEL_FORMAT_BLOB) {
561 ALOGE("%s: Stream with use case %d isn't compatible with format %d",
562 __FUNCTION__, stream.use_case, stream.format);
563 return false;
564 }
565 } else if ((stream.format == HAL_PIXEL_FORMAT_RAW16) ^
566 (stream.use_case ==
567 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW)) {
568 // Either both stream use case == CROPPED_RAW and format == RAW16, or
569 // stream use case != CROPPED_RAW and format != RAW16 for the
570 // combination to be valid.
571 ALOGE(
572 "%s: Stream with use case CROPPED_RAW isn't compatible with non "
573 "RAW_SENSOR formats",
574 __FUNCTION__);
575 return false;
576
577 } else if (stream.format != HAL_PIXEL_FORMAT_YCBCR_420_888 &&
578 stream.format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
579 stream.format != HAL_PIXEL_FORMAT_RAW16) {
580 ALOGE("%s: Stream with use case %d isn't compatible with format %d",
581 __FUNCTION__, stream.use_case, stream.format);
582 return false;
583 }
584 }
585 }
586
587 for (const auto& raw_count : raw_stream_count) {
588 unsigned int max_raw_streams =
589 sensor_chars.at(raw_count.first).max_raw_streams +
590 (is_max_res
591 ? 1
592 : 0); // The extra raw stream is allowed for remosaic reprocessing.
593 if (raw_count.second > max_raw_streams) {
594 ALOGE("%s: RAW streams maximum %u exceeds supported maximum %u",
595 __FUNCTION__, raw_count.second, max_raw_streams);
596 return false;
597 }
598 }
599
600 for (const auto& stalling_count : stalling_stream_count) {
601 if (stalling_count.second >
602 sensor_chars.at(stalling_count.first).max_stalling_streams) {
603 ALOGE("%s: Stalling streams maximum %u exceeds supported maximum %u",
604 __FUNCTION__, stalling_count.second,
605 sensor_chars.at(stalling_count.first).max_stalling_streams);
606 return false;
607 }
608 }
609
610 for (const auto& processed_count : processed_stream_count) {
611 if (processed_count.second >
612 sensor_chars.at(processed_count.first).max_processed_streams) {
613 ALOGE("%s: Processed streams maximum %u exceeds supported maximum %u",
614 __FUNCTION__, processed_count.second,
615 sensor_chars.at(processed_count.first).max_processed_streams);
616 return false;
617 }
618 }
619
620 if (input_stream_count > sensor_chars.at(logical_id).max_input_streams) {
621 ALOGE("%s: Input stream maximum %u exceeds supported maximum %u",
622 __FUNCTION__, input_stream_count,
623 sensor_chars.at(logical_id).max_input_streams);
624 return false;
625 }
626
627 return true;
628 }
629
StartUp(uint32_t logical_camera_id,std::unique_ptr<LogicalCharacteristics> logical_chars)630 status_t EmulatedSensor::StartUp(
631 uint32_t logical_camera_id,
632 std::unique_ptr<LogicalCharacteristics> logical_chars) {
633 if (isRunning()) {
634 return OK;
635 }
636
637 if (logical_chars.get() == nullptr) {
638 return BAD_VALUE;
639 }
640
641 chars_ = std::move(logical_chars);
642 auto device_chars = chars_->find(logical_camera_id);
643 if (device_chars == chars_->end()) {
644 ALOGE(
645 "%s: Logical camera id: %u absent from logical camera characteristics!",
646 __FUNCTION__, logical_camera_id);
647 return BAD_VALUE;
648 }
649
650 for (const auto& it : *chars_) {
651 if (!AreCharacteristicsSupported(it.second)) {
652 ALOGE("%s: Sensor characteristics for camera id: %u not supported!",
653 __FUNCTION__, it.first);
654 return BAD_VALUE;
655 }
656 }
657
658 logical_camera_id_ = logical_camera_id;
659 scene_ = std::make_unique<EmulatedScene>(
660 device_chars->second.full_res_width, device_chars->second.full_res_height,
661 kElectronsPerLuxSecond, device_chars->second.orientation,
662 device_chars->second.is_front_facing);
663 jpeg_compressor_ = std::make_unique<JpegCompressor>();
664
665 auto res = run(LOG_TAG, ANDROID_PRIORITY_URGENT_DISPLAY);
666 if (res != OK) {
667 ALOGE("Unable to start up sensor capture thread: %d", res);
668 }
669
670 return res;
671 }
672
ShutDown()673 status_t EmulatedSensor::ShutDown() {
674 int res;
675 res = requestExitAndWait();
676 if (res != OK) {
677 ALOGE("Unable to shut down sensor capture thread: %d", res);
678 }
679 return res;
680 }
681
SetCurrentRequest(std::unique_ptr<LogicalCameraSettings> logical_settings,std::unique_ptr<HwlPipelineResult> result,std::unique_ptr<Buffers> input_buffers,std::unique_ptr<Buffers> output_buffers)682 void EmulatedSensor::SetCurrentRequest(
683 std::unique_ptr<LogicalCameraSettings> logical_settings,
684 std::unique_ptr<HwlPipelineResult> result,
685 std::unique_ptr<Buffers> input_buffers,
686 std::unique_ptr<Buffers> output_buffers) {
687 Mutex::Autolock lock(control_mutex_);
688 current_settings_ = std::move(logical_settings);
689 current_result_ = std::move(result);
690 current_input_buffers_ = std::move(input_buffers);
691 current_output_buffers_ = std::move(output_buffers);
692 }
693
WaitForVSyncLocked(nsecs_t reltime)694 bool EmulatedSensor::WaitForVSyncLocked(nsecs_t reltime) {
695 got_vsync_ = false;
696 while (!got_vsync_) {
697 auto res = vsync_.waitRelative(control_mutex_, reltime);
698 if (res != OK && res != TIMED_OUT) {
699 ALOGE("%s: Error waiting for VSync signal: %d", __FUNCTION__, res);
700 return false;
701 }
702 }
703
704 return got_vsync_;
705 }
706
WaitForVSync(nsecs_t reltime)707 bool EmulatedSensor::WaitForVSync(nsecs_t reltime) {
708 Mutex::Autolock lock(control_mutex_);
709
710 return WaitForVSyncLocked(reltime);
711 }
712
Flush()713 status_t EmulatedSensor::Flush() {
714 Mutex::Autolock lock(control_mutex_);
715 auto ret = WaitForVSyncLocked(kSupportedFrameDurationRange[1]);
716
717 // First recreate the jpeg compressor. This will abort any ongoing processing
718 // and flush any pending jobs.
719 jpeg_compressor_ = std::make_unique<JpegCompressor>();
720
721 // Then return any pending frames here
722 if ((current_input_buffers_.get() != nullptr) &&
723 (!current_input_buffers_->empty())) {
724 current_input_buffers_->clear();
725 }
726 if ((current_output_buffers_.get() != nullptr) &&
727 (!current_output_buffers_->empty())) {
728 for (const auto& buffer : *current_output_buffers_) {
729 buffer->stream_buffer.status = BufferStatus::kError;
730 }
731
732 if ((current_result_.get() != nullptr) &&
733 (current_result_->result_metadata.get() != nullptr)) {
734 if (current_output_buffers_->at(0)->callback.notify != nullptr) {
735 NotifyMessage msg{
736 .type = MessageType::kError,
737 .message.error = {
738 .frame_number = current_output_buffers_->at(0)->frame_number,
739 .error_stream_id = -1,
740 .error_code = ErrorCode::kErrorResult,
741 }};
742
743 current_output_buffers_->at(0)->callback.notify(
744 current_result_->pipeline_id, msg);
745 }
746 }
747
748 current_output_buffers_->clear();
749 }
750
751 return ret ? OK : TIMED_OUT;
752 }
753
threadLoop()754 bool EmulatedSensor::threadLoop() {
755 ATRACE_CALL();
756 /**
757 * Sensor capture operation main loop.
758 *
759 */
760
761 /**
762 * Stage 1: Read in latest control parameters
763 */
764 std::unique_ptr<Buffers> next_buffers;
765 std::unique_ptr<Buffers> next_input_buffer;
766 std::unique_ptr<HwlPipelineResult> next_result;
767 std::unique_ptr<LogicalCameraSettings> settings;
768 HwlPipelineCallback callback = {nullptr, nullptr};
769 {
770 Mutex::Autolock lock(control_mutex_);
771 std::swap(settings, current_settings_);
772 std::swap(next_buffers, current_output_buffers_);
773 std::swap(next_input_buffer, current_input_buffers_);
774 std::swap(next_result, current_result_);
775
776 // Signal VSync for start of readout
777 ALOGVV("Sensor VSync");
778 got_vsync_ = true;
779 vsync_.signal();
780 }
781
782 auto frame_duration = EmulatedSensor::kSupportedFrameDurationRange[0];
783 auto exposure_time = EmulatedSensor::kSupportedExposureTimeRange[0];
784 // Frame duration must always be the same among all physical devices
785 if ((settings.get() != nullptr) && (!settings->empty())) {
786 frame_duration = settings->begin()->second.frame_duration;
787 exposure_time = settings->begin()->second.exposure_time;
788 }
789
790 nsecs_t start_real_time = systemTime();
791 // Stagefright cares about system time for timestamps, so base simulated
792 // time on that.
793 nsecs_t frame_end_real_time = start_real_time + frame_duration;
794
795 /**
796 * Stage 2: Capture new image
797 */
798 next_capture_time_ = frame_end_real_time;
799 next_readout_time_ = frame_end_real_time + exposure_time;
800
801 sensor_binning_factor_info_.clear();
802
803 bool reprocess_request = false;
804 if ((next_input_buffer.get() != nullptr) && (!next_input_buffer->empty())) {
805 if (next_input_buffer->size() > 1) {
806 ALOGW("%s: Reprocess supports only single input!", __FUNCTION__);
807 }
808
809 camera_metadata_ro_entry_t entry;
810 auto ret =
811 next_result->result_metadata->Get(ANDROID_SENSOR_TIMESTAMP, &entry);
812 if ((ret == OK) && (entry.count == 1)) {
813 next_capture_time_ = entry.data.i64[0];
814 } else {
815 ALOGW("%s: Reprocess timestamp absent!", __FUNCTION__);
816 }
817
818 ret = next_result->result_metadata->Get(ANDROID_SENSOR_EXPOSURE_TIME,
819 &entry);
820 if ((ret == OK) && (entry.count == 1)) {
821 next_readout_time_ = next_capture_time_ + entry.data.i64[0];
822 } else {
823 next_readout_time_ = next_capture_time_;
824 }
825
826 reprocess_request = true;
827 }
828
829 if ((next_buffers != nullptr) && (settings != nullptr)) {
830 callback = next_buffers->at(0)->callback;
831 if (callback.notify != nullptr) {
832 NotifyMessage msg{
833 .type = MessageType::kShutter,
834 .message.shutter = {
835 .frame_number = next_buffers->at(0)->frame_number,
836 .timestamp_ns = static_cast<uint64_t>(next_capture_time_),
837 .readout_timestamp_ns =
838 static_cast<uint64_t>(next_readout_time_)}};
839 callback.notify(next_result->pipeline_id, msg);
840 }
841 auto b = next_buffers->begin();
842 while (b != next_buffers->end()) {
843 auto device_settings = settings->find((*b)->camera_id);
844 if (device_settings == settings->end()) {
845 ALOGE("%s: Sensor settings absent for device: %d", __func__,
846 (*b)->camera_id);
847 b = next_buffers->erase(b);
848 continue;
849 }
850
851 auto device_chars = chars_->find((*b)->camera_id);
852 if (device_chars == chars_->end()) {
853 ALOGE("%s: Sensor characteristics absent for device: %d", __func__,
854 (*b)->camera_id);
855 b = next_buffers->erase(b);
856 continue;
857 }
858
859 sensor_binning_factor_info_[(*b)->camera_id].quad_bayer_sensor =
860 device_chars->second.quad_bayer_sensor;
861
862 ALOGVV("Starting next capture: Exposure: %" PRIu64 " ms, gain: %d",
863 ns2ms(device_settings->second.exposure_time),
864 device_settings->second.gain);
865
866 scene_->Initialize(device_chars->second.full_res_width,
867 device_chars->second.full_res_height,
868 kElectronsPerLuxSecond);
869 scene_->SetExposureDuration((float)device_settings->second.exposure_time /
870 1e9);
871 scene_->SetColorFilterXYZ(device_chars->second.color_filter.rX,
872 device_chars->second.color_filter.rY,
873 device_chars->second.color_filter.rZ,
874 device_chars->second.color_filter.grX,
875 device_chars->second.color_filter.grY,
876 device_chars->second.color_filter.grZ,
877 device_chars->second.color_filter.gbX,
878 device_chars->second.color_filter.gbY,
879 device_chars->second.color_filter.gbZ,
880 device_chars->second.color_filter.bX,
881 device_chars->second.color_filter.bY,
882 device_chars->second.color_filter.bZ);
883 scene_->SetTestPattern(device_settings->second.test_pattern_mode ==
884 ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR);
885 scene_->SetTestPatternData(device_settings->second.test_pattern_data);
886 scene_->SetScreenRotation(device_settings->second.screen_rotation);
887
888 uint32_t handshake_divider =
889 (device_settings->second.video_stab ==
890 ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_ON) ||
891 (device_settings->second.video_stab ==
892 ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_PREVIEW_STABILIZATION)
893 ? kReducedSceneHandshake
894 : kRegularSceneHandshake;
895 scene_->CalculateScene(next_capture_time_, handshake_divider);
896
897 (*b)->stream_buffer.status = BufferStatus::kOk;
898 bool max_res_mode = device_settings->second.sensor_pixel_mode;
899 sensor_binning_factor_info_[(*b)->camera_id].max_res_request =
900 max_res_mode;
901 switch ((*b)->format) {
902 case PixelFormat::RAW16:
903 sensor_binning_factor_info_[(*b)->camera_id].has_raw_stream = true;
904 if (!sensor_binning_factor_info_[(*b)->camera_id]
905 .has_cropped_raw_stream &&
906 (*b)->use_case ==
907 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW) {
908 sensor_binning_factor_info_[(*b)->camera_id].has_cropped_raw_stream =
909 true;
910 }
911 break;
912 default:
913 sensor_binning_factor_info_[(*b)->camera_id].has_non_raw_stream = true;
914 }
915
916 // TODO: remove hack. Implement RAW -> YUV / JPEG reprocessing http://b/192382904
917 bool treat_as_reprocess =
918 (device_chars->second.quad_bayer_sensor && reprocess_request &&
919 (*next_input_buffer->begin())->format == PixelFormat::RAW16)
920 ? false
921 : reprocess_request;
922
923 if ((*b)->color_space !=
924 ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED) {
925 CalculateRgbRgbMatrix((*b)->color_space, device_chars->second);
926 }
927
928 switch ((*b)->format) {
929 case PixelFormat::RAW16:
930 if (!reprocess_request) {
931 uint64_t min_full_res_raw_size =
932 2 * device_chars->second.full_res_width *
933 device_chars->second.full_res_height;
934 uint64_t min_default_raw_size =
935 2 * device_chars->second.width * device_chars->second.height;
936 bool default_mode_for_qb =
937 device_chars->second.quad_bayer_sensor && !max_res_mode;
938 size_t buffer_size = (*b)->plane.img.buffer_size;
939 if (default_mode_for_qb) {
940 if (buffer_size < min_default_raw_size) {
941 ALOGE(
942 "%s: Output buffer size too small for RAW capture in "
943 "default "
944 "mode, "
945 "expected %" PRIu64 ", got %zu, for camera id %d",
946 __FUNCTION__, min_default_raw_size, buffer_size,
947 (*b)->camera_id);
948 (*b)->stream_buffer.status = BufferStatus::kError;
949 break;
950 }
951 } else if (buffer_size < min_full_res_raw_size) {
952 ALOGE(
953 "%s: Output buffer size too small for RAW capture in max res "
954 "mode, "
955 "expected %" PRIu64 ", got %zu, for camera id %d",
956 __FUNCTION__, min_full_res_raw_size, buffer_size,
957 (*b)->camera_id);
958 (*b)->stream_buffer.status = BufferStatus::kError;
959 break;
960 }
961 if (default_mode_for_qb) {
962 if (device_settings->second.zoom_ratio > 2.0f &&
963 ((*b)->use_case ==
964 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW)) {
965 sensor_binning_factor_info_[(*b)->camera_id]
966 .raw_in_sensor_zoom_applied = true;
967 CaptureRawInSensorZoom(
968 (*b)->plane.img.img, (*b)->plane.img.stride_in_bytes,
969 device_settings->second.gain, device_chars->second);
970
971 } else {
972 CaptureRawBinned(
973 (*b)->plane.img.img, (*b)->plane.img.stride_in_bytes,
974 device_settings->second.gain, device_chars->second);
975 }
976 } else {
977 CaptureRawFullRes(
978 (*b)->plane.img.img, (*b)->plane.img.stride_in_bytes,
979 device_settings->second.gain, device_chars->second);
980 }
981 } else {
982 if (!device_chars->second.quad_bayer_sensor) {
983 ALOGE(
984 "%s: Reprocess requests with output format %x no supported!",
985 __FUNCTION__, (*b)->format);
986 (*b)->stream_buffer.status = BufferStatus::kError;
987 break;
988 }
989 // Remosaic the RAW input buffer
990 if ((*next_input_buffer->begin())->width != (*b)->width ||
991 (*next_input_buffer->begin())->height != (*b)->height) {
992 ALOGE(
993 "%s: RAW16 input dimensions %dx%d don't match output buffer "
994 "dimensions %dx%d",
995 __FUNCTION__, (*next_input_buffer->begin())->width,
996 (*next_input_buffer->begin())->height, (*b)->width,
997 (*b)->height);
998 (*b)->stream_buffer.status = BufferStatus::kError;
999 break;
1000 }
1001 ALOGV("%s remosaic Raw16 Image", __FUNCTION__);
1002 RemosaicRAW16Image(
1003 (uint16_t*)(*next_input_buffer->begin())->plane.img.img,
1004 (uint16_t*)(*b)->plane.img.img, (*b)->plane.img.stride_in_bytes,
1005 device_chars->second);
1006 }
1007 break;
1008 case PixelFormat::RGB_888:
1009 if (!reprocess_request) {
1010 CaptureRGB((*b)->plane.img.img, (*b)->width, (*b)->height,
1011 (*b)->plane.img.stride_in_bytes, RGBLayout::RGB,
1012 device_settings->second.gain, (*b)->color_space,
1013 device_chars->second);
1014 } else {
1015 ALOGE("%s: Reprocess requests with output format %x no supported!",
1016 __FUNCTION__, (*b)->format);
1017 (*b)->stream_buffer.status = BufferStatus::kError;
1018 }
1019 break;
1020 case PixelFormat::RGBA_8888:
1021 if (!reprocess_request) {
1022 CaptureRGB((*b)->plane.img.img, (*b)->width, (*b)->height,
1023 (*b)->plane.img.stride_in_bytes, RGBLayout::RGBA,
1024 device_settings->second.gain, (*b)->color_space,
1025 device_chars->second);
1026 } else {
1027 ALOGE("%s: Reprocess requests with output format %x no supported!",
1028 __FUNCTION__, (*b)->format);
1029 (*b)->stream_buffer.status = BufferStatus::kError;
1030 }
1031 break;
1032 case PixelFormat::BLOB:
1033 if ((*b)->dataSpace == HAL_DATASPACE_V0_JFIF) {
1034 YUV420Frame yuv_input{
1035 .width = treat_as_reprocess
1036 ? (*next_input_buffer->begin())->width
1037 : 0,
1038 .height = treat_as_reprocess
1039 ? (*next_input_buffer->begin())->height
1040 : 0,
1041 .planes = treat_as_reprocess
1042 ? (*next_input_buffer->begin())->plane.img_y_crcb
1043 : YCbCrPlanes{}};
1044 auto jpeg_input = std::make_unique<JpegYUV420Input>();
1045 jpeg_input->width = (*b)->width;
1046 jpeg_input->height = (*b)->height;
1047 jpeg_input->color_space = (*b)->color_space;
1048 auto img =
1049 new uint8_t[(jpeg_input->width * jpeg_input->height * 3) / 2];
1050 jpeg_input->yuv_planes = {
1051 .img_y = img,
1052 .img_cb = img + jpeg_input->width * jpeg_input->height,
1053 .img_cr = img + (jpeg_input->width * jpeg_input->height * 5) / 4,
1054 .y_stride = jpeg_input->width,
1055 .cbcr_stride = jpeg_input->width / 2,
1056 .cbcr_step = 1};
1057 jpeg_input->buffer_owner = true;
1058 YUV420Frame yuv_output{.width = jpeg_input->width,
1059 .height = jpeg_input->height,
1060 .planes = jpeg_input->yuv_planes};
1061
1062 bool rotate =
1063 device_settings->second.rotate_and_crop == ANDROID_SCALER_ROTATE_AND_CROP_90;
1064 ProcessType process_type =
1065 treat_as_reprocess ? REPROCESS
1066 : (device_settings->second.edge_mode ==
1067 ANDROID_EDGE_MODE_HIGH_QUALITY)
1068 ? HIGH_QUALITY
1069 : REGULAR;
1070 auto ret = ProcessYUV420(yuv_input, yuv_output,
1071 device_settings->second.gain, process_type,
1072 device_settings->second.zoom_ratio, rotate,
1073 (*b)->color_space, device_chars->second);
1074 if (ret != 0) {
1075 (*b)->stream_buffer.status = BufferStatus::kError;
1076 break;
1077 }
1078
1079 auto jpeg_job = std::make_unique<JpegYUV420Job>();
1080 jpeg_job->exif_utils = std::unique_ptr<ExifUtils>(
1081 ExifUtils::Create(device_chars->second));
1082 jpeg_job->input = std::move(jpeg_input);
1083 // If jpeg compression is successful, then the jpeg compressor
1084 // must set the corresponding status.
1085 (*b)->stream_buffer.status = BufferStatus::kError;
1086 std::swap(jpeg_job->output, *b);
1087 jpeg_job->result_metadata =
1088 HalCameraMetadata::Clone(next_result->result_metadata.get());
1089
1090 Mutex::Autolock lock(control_mutex_);
1091 jpeg_compressor_->QueueYUV420(std::move(jpeg_job));
1092 } else {
1093 ALOGE("%s: Format %x with dataspace %x is TODO", __FUNCTION__,
1094 (*b)->format, (*b)->dataSpace);
1095 (*b)->stream_buffer.status = BufferStatus::kError;
1096 }
1097 break;
1098 case PixelFormat::YCRCB_420_SP:
1099 case PixelFormat::YCBCR_420_888: {
1100 YUV420Frame yuv_input{
1101 .width =
1102 treat_as_reprocess ? (*next_input_buffer->begin())->width : 0,
1103 .height =
1104 treat_as_reprocess ? (*next_input_buffer->begin())->height : 0,
1105 .planes = treat_as_reprocess
1106 ? (*next_input_buffer->begin())->plane.img_y_crcb
1107 : YCbCrPlanes{}};
1108 YUV420Frame yuv_output{.width = (*b)->width,
1109 .height = (*b)->height,
1110 .planes = (*b)->plane.img_y_crcb};
1111 bool rotate =
1112 device_settings->second.rotate_and_crop == ANDROID_SCALER_ROTATE_AND_CROP_90;
1113 ProcessType process_type = treat_as_reprocess
1114 ? REPROCESS
1115 : (device_settings->second.edge_mode ==
1116 ANDROID_EDGE_MODE_HIGH_QUALITY)
1117 ? HIGH_QUALITY
1118 : REGULAR;
1119 auto ret =
1120 ProcessYUV420(yuv_input, yuv_output, device_settings->second.gain,
1121 process_type, device_settings->second.zoom_ratio,
1122 rotate, (*b)->color_space, device_chars->second);
1123 if (ret != 0) {
1124 (*b)->stream_buffer.status = BufferStatus::kError;
1125 }
1126 } break;
1127 case PixelFormat::Y16:
1128 if (!reprocess_request) {
1129 if ((*b)->dataSpace == HAL_DATASPACE_DEPTH) {
1130 CaptureDepth((*b)->plane.img.img, device_settings->second.gain,
1131 (*b)->width, (*b)->height,
1132 (*b)->plane.img.stride_in_bytes,
1133 device_chars->second);
1134 } else {
1135 ALOGE("%s: Format %x with dataspace %x is TODO", __FUNCTION__,
1136 (*b)->format, (*b)->dataSpace);
1137 (*b)->stream_buffer.status = BufferStatus::kError;
1138 }
1139 } else {
1140 ALOGE("%s: Reprocess requests with output format %x no supported!",
1141 __FUNCTION__, (*b)->format);
1142 (*b)->stream_buffer.status = BufferStatus::kError;
1143 }
1144 break;
1145 case PixelFormat::YCBCR_P010:
1146 if (!reprocess_request) {
1147 bool rotate = device_settings->second.rotate_and_crop ==
1148 ANDROID_SCALER_ROTATE_AND_CROP_90;
1149 CaptureYUV420((*b)->plane.img_y_crcb, (*b)->width, (*b)->height,
1150 device_settings->second.gain,
1151 device_settings->second.zoom_ratio, rotate,
1152 (*b)->color_space, device_chars->second);
1153 } else {
1154 ALOGE(
1155 "%s: Reprocess requests with output format %x no supported!",
1156 __FUNCTION__, (*b)->format);
1157 (*b)->stream_buffer.status = BufferStatus::kError;
1158 }
1159 break;
1160 default:
1161 ALOGE("%s: Unknown format %x, no output", __FUNCTION__, (*b)->format);
1162 (*b)->stream_buffer.status = BufferStatus::kError;
1163 break;
1164 }
1165
1166 b = next_buffers->erase(b);
1167 }
1168 }
1169
1170 if (reprocess_request) {
1171 auto input_buffer = next_input_buffer->begin();
1172 while (input_buffer != next_input_buffer->end()) {
1173 (*input_buffer++)->stream_buffer.status = BufferStatus::kOk;
1174 }
1175 next_input_buffer->clear();
1176 }
1177
1178 nsecs_t work_done_real_time = systemTime();
1179 // Returning the results at this point is not entirely correct from timing
1180 // perspective. Under ideal conditions where 'ReturnResults' completes
1181 // in less than 'time_accuracy' we need to return the results after the
1182 // frame cycle expires. However under real conditions various system
1183 // components like SurfaceFlinger, Encoder, LMK etc. could be consuming most
1184 // of the resources and the duration of "ReturnResults" can get comparable to
1185 // 'kDefaultFrameDuration'. This will skew the frame cycle and can result in
1186 // potential frame drops. To avoid this scenario when we are running under
1187 // tight deadlines (less than 'kReturnResultThreshod') try to return the
1188 // results immediately. In all other cases with more relaxed deadlines
1189 // the occasional bump during 'ReturnResults' should not have any
1190 // noticeable effect.
1191 if ((work_done_real_time + kReturnResultThreshod) > frame_end_real_time) {
1192 ReturnResults(callback, std::move(settings), std::move(next_result),
1193 reprocess_request);
1194 }
1195
1196 work_done_real_time = systemTime();
1197 ALOGVV("Sensor vertical blanking interval");
1198 const nsecs_t time_accuracy = 2e6; // 2 ms of imprecision is ok
1199 if (work_done_real_time < frame_end_real_time - time_accuracy) {
1200 timespec t;
1201 t.tv_sec = (frame_end_real_time - work_done_real_time) / 1000000000L;
1202 t.tv_nsec = (frame_end_real_time - work_done_real_time) % 1000000000L;
1203
1204 int ret;
1205 do {
1206 ret = nanosleep(&t, &t);
1207 } while (ret != 0);
1208 }
1209
1210 ReturnResults(callback, std::move(settings), std::move(next_result),
1211 reprocess_request);
1212
1213 return true;
1214 };
1215
ReturnResults(HwlPipelineCallback callback,std::unique_ptr<LogicalCameraSettings> settings,std::unique_ptr<HwlPipelineResult> result,bool reprocess_request)1216 void EmulatedSensor::ReturnResults(
1217 HwlPipelineCallback callback,
1218 std::unique_ptr<LogicalCameraSettings> settings,
1219 std::unique_ptr<HwlPipelineResult> result, bool reprocess_request) {
1220 if ((callback.process_pipeline_result != nullptr) &&
1221 (result.get() != nullptr) && (result->result_metadata.get() != nullptr)) {
1222 auto logical_settings = settings->find(logical_camera_id_);
1223 if (logical_settings == settings->end()) {
1224 ALOGE("%s: Logical camera id: %u not found in settings!", __FUNCTION__,
1225 logical_camera_id_);
1226 return;
1227 }
1228 auto device_chars = chars_->find(logical_camera_id_);
1229 if (device_chars == chars_->end()) {
1230 ALOGE("%s: Sensor characteristics absent for device: %d", __func__,
1231 logical_camera_id_);
1232 return;
1233 }
1234 result->result_metadata->Set(ANDROID_SENSOR_TIMESTAMP, &next_capture_time_,
1235 1);
1236 uint8_t raw_binned_factor_used = false;
1237 if (sensor_binning_factor_info_.find(logical_camera_id_) !=
1238 sensor_binning_factor_info_.end()) {
1239 auto& info = sensor_binning_factor_info_[logical_camera_id_];
1240 // Logical stream was included in the request
1241 if (!reprocess_request && info.quad_bayer_sensor && info.max_res_request &&
1242 info.has_raw_stream && !info.has_non_raw_stream) {
1243 raw_binned_factor_used = true;
1244 }
1245 result->result_metadata->Set(ANDROID_SENSOR_RAW_BINNING_FACTOR_USED,
1246 &raw_binned_factor_used, 1);
1247 if (info.has_cropped_raw_stream) {
1248 if (info.raw_in_sensor_zoom_applied) {
1249 result->result_metadata->Set(
1250 ANDROID_SCALER_RAW_CROP_REGION,
1251 device_chars->second.raw_crop_region_zoomed, 4);
1252
1253 } else {
1254 result->result_metadata->Set(
1255 ANDROID_SCALER_RAW_CROP_REGION,
1256 device_chars->second.raw_crop_region_unzoomed, 4);
1257 }
1258 }
1259 }
1260 if (logical_settings->second.lens_shading_map_mode ==
1261 ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_ON) {
1262 if ((device_chars->second.lens_shading_map_size[0] > 0) &&
1263 (device_chars->second.lens_shading_map_size[1] > 0)) {
1264 // Perfect lens, no actual shading needed.
1265 std::vector<float> lens_shading_map(
1266 device_chars->second.lens_shading_map_size[0] *
1267 device_chars->second.lens_shading_map_size[1] * 4,
1268 1.f);
1269
1270 result->result_metadata->Set(ANDROID_STATISTICS_LENS_SHADING_MAP,
1271 lens_shading_map.data(),
1272 lens_shading_map.size());
1273 }
1274 }
1275 if (logical_settings->second.report_video_stab) {
1276 result->result_metadata->Set(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE,
1277 &logical_settings->second.video_stab, 1);
1278 }
1279 if (logical_settings->second.report_edge_mode) {
1280 result->result_metadata->Set(ANDROID_EDGE_MODE,
1281 &logical_settings->second.edge_mode, 1);
1282 }
1283 if (logical_settings->second.report_neutral_color_point) {
1284 result->result_metadata->Set(ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
1285 kNeutralColorPoint,
1286 ARRAY_SIZE(kNeutralColorPoint));
1287 }
1288 if (logical_settings->second.report_green_split) {
1289 result->result_metadata->Set(ANDROID_SENSOR_GREEN_SPLIT, &kGreenSplit, 1);
1290 }
1291 if (logical_settings->second.report_noise_profile) {
1292 CalculateAndAppendNoiseProfile(
1293 logical_settings->second.gain,
1294 GetBaseGainFactor(device_chars->second.max_raw_value),
1295 result->result_metadata.get());
1296 }
1297 if (logical_settings->second.report_rotate_and_crop) {
1298 result->result_metadata->Set(ANDROID_SCALER_ROTATE_AND_CROP,
1299 &logical_settings->second.rotate_and_crop, 1);
1300 }
1301
1302 if (!result->physical_camera_results.empty()) {
1303 for (auto& it : result->physical_camera_results) {
1304 auto physical_settings = settings->find(it.first);
1305 if (physical_settings == settings->end()) {
1306 ALOGE("%s: Physical settings for camera id: %u are absent!",
1307 __FUNCTION__, it.first);
1308 continue;
1309 }
1310 uint8_t raw_binned_factor_used = false;
1311 if (sensor_binning_factor_info_.find(it.first) !=
1312 sensor_binning_factor_info_.end()) {
1313 auto& info = sensor_binning_factor_info_[it.first];
1314 // physical stream was included in the request
1315 if (!reprocess_request && info.quad_bayer_sensor &&
1316 info.max_res_request && info.has_raw_stream &&
1317 !info.has_non_raw_stream) {
1318 raw_binned_factor_used = true;
1319 }
1320 it.second->Set(ANDROID_SENSOR_RAW_BINNING_FACTOR_USED,
1321 &raw_binned_factor_used, 1);
1322 }
1323 // Sensor timestamp for all physical devices must be the same.
1324 it.second->Set(ANDROID_SENSOR_TIMESTAMP, &next_capture_time_, 1);
1325 if (physical_settings->second.report_neutral_color_point) {
1326 it.second->Set(ANDROID_SENSOR_NEUTRAL_COLOR_POINT, kNeutralColorPoint,
1327 ARRAY_SIZE(kNeutralColorPoint));
1328 }
1329 if (physical_settings->second.report_green_split) {
1330 it.second->Set(ANDROID_SENSOR_GREEN_SPLIT, &kGreenSplit, 1);
1331 }
1332 if (physical_settings->second.report_noise_profile) {
1333 auto device_chars = chars_->find(it.first);
1334 if (device_chars == chars_->end()) {
1335 ALOGE("%s: Sensor characteristics absent for device: %d", __func__,
1336 it.first);
1337 }
1338 CalculateAndAppendNoiseProfile(
1339 physical_settings->second.gain,
1340 GetBaseGainFactor(device_chars->second.max_raw_value),
1341 it.second.get());
1342 }
1343 }
1344 }
1345
1346 callback.process_pipeline_result(std::move(result));
1347 }
1348 }
1349
CalculateAndAppendNoiseProfile(float gain,float base_gain_factor,HalCameraMetadata * result)1350 void EmulatedSensor::CalculateAndAppendNoiseProfile(
1351 float gain /*in ISO*/, float base_gain_factor,
1352 HalCameraMetadata* result /*out*/) {
1353 if (result != nullptr) {
1354 float total_gain = gain / 100.0 * base_gain_factor;
1355 float noise_var_gain = total_gain * total_gain;
1356 float read_noise_var =
1357 kReadNoiseVarBeforeGain * noise_var_gain + kReadNoiseVarAfterGain;
1358 // Noise profile is the same across all 4 CFA channels
1359 double noise_profile[2 * 4] = {
1360 noise_var_gain, read_noise_var, noise_var_gain, read_noise_var,
1361 noise_var_gain, read_noise_var, noise_var_gain, read_noise_var};
1362 result->Set(ANDROID_SENSOR_NOISE_PROFILE, noise_profile,
1363 ARRAY_SIZE(noise_profile));
1364 }
1365 }
1366
GetQuadBayerColor(uint32_t x,uint32_t y)1367 EmulatedScene::ColorChannels EmulatedSensor::GetQuadBayerColor(uint32_t x,
1368 uint32_t y) {
1369 // Row within larger set of quad bayer filter
1370 uint32_t row_mod = y % 4;
1371 // Column within larger set of quad bayer filter
1372 uint32_t col_mod = x % 4;
1373
1374 // Row is within the left quadrants of a quad bayer sensor
1375 if (row_mod < 2) {
1376 if (col_mod < 2) {
1377 return EmulatedScene::ColorChannels::R;
1378 }
1379 return EmulatedScene::ColorChannels::Gr;
1380 } else {
1381 if (col_mod < 2) {
1382 return EmulatedScene::ColorChannels::Gb;
1383 }
1384 return EmulatedScene::ColorChannels::B;
1385 }
1386 }
1387
RemosaicQuadBayerBlock(uint16_t * img_in,uint16_t * img_out,int xstart,int ystart,int row_stride_in_bytes)1388 void EmulatedSensor::RemosaicQuadBayerBlock(uint16_t* img_in, uint16_t* img_out,
1389 int xstart, int ystart,
1390 int row_stride_in_bytes) {
1391 uint32_t quad_block_copy_idx_map[16] = {0, 2, 1, 3, 8, 10, 6, 11,
1392 4, 9, 5, 7, 12, 14, 13, 15};
1393 uint16_t quad_block_copy[16];
1394 uint32_t i = 0;
1395 for (uint32_t row = 0; row < 4; row++) {
1396 uint16_t* quad_bayer_row =
1397 img_in + (ystart + row) * (row_stride_in_bytes / 2) + xstart;
1398 for (uint32_t j = 0; j < 4; j++, i++) {
1399 quad_block_copy[i] = quad_bayer_row[j];
1400 }
1401 }
1402
1403 for (uint32_t row = 0; row < 4; row++) {
1404 uint16_t* regular_bayer_row =
1405 img_out + (ystart + row) * (row_stride_in_bytes / 2) + xstart;
1406 for (uint32_t j = 0; j < 4; j++, i++) {
1407 uint32_t idx = quad_block_copy_idx_map[row + 4 * j];
1408 regular_bayer_row[j] = quad_block_copy[idx];
1409 }
1410 }
1411 }
1412
RemosaicRAW16Image(uint16_t * img_in,uint16_t * img_out,size_t row_stride_in_bytes,const SensorCharacteristics & chars)1413 status_t EmulatedSensor::RemosaicRAW16Image(uint16_t* img_in, uint16_t* img_out,
1414 size_t row_stride_in_bytes,
1415 const SensorCharacteristics& chars) {
1416 if (chars.full_res_width % 2 != 0 || chars.full_res_height % 2 != 0) {
1417 ALOGE(
1418 "%s RAW16 Image with quad CFA, height %zu and width %zu, not multiples "
1419 "of 4",
1420 __FUNCTION__, chars.full_res_height, chars.full_res_width);
1421 return BAD_VALUE;
1422 }
1423 for (uint32_t i = 0; i < chars.full_res_width; i += 4) {
1424 for (uint32_t j = 0; j < chars.full_res_height; j += 4) {
1425 RemosaicQuadBayerBlock(img_in, img_out, i, j, row_stride_in_bytes);
1426 }
1427 }
1428 return OK;
1429 }
1430
CaptureRawBinned(uint8_t * img,size_t row_stride_in_bytes,uint32_t gain,const SensorCharacteristics & chars)1431 void EmulatedSensor::CaptureRawBinned(uint8_t* img, size_t row_stride_in_bytes,
1432 uint32_t gain,
1433 const SensorCharacteristics& chars) {
1434 CaptureRaw(img, row_stride_in_bytes, gain, chars, /*in_sensor_zoom*/ false,
1435 /*binned*/ true);
1436 return;
1437 }
1438
CaptureRawInSensorZoom(uint8_t * img,size_t row_stride_in_bytes,uint32_t gain,const SensorCharacteristics & chars)1439 void EmulatedSensor::CaptureRawInSensorZoom(uint8_t* img,
1440 size_t row_stride_in_bytes,
1441 uint32_t gain,
1442 const SensorCharacteristics& chars) {
1443 CaptureRaw(img, row_stride_in_bytes, gain, chars, /*in_sensor_zoom*/ true,
1444 /*binned*/ false);
1445 return;
1446 }
1447
CaptureRawFullRes(uint8_t * img,size_t row_stride_in_bytes,uint32_t gain,const SensorCharacteristics & chars)1448 void EmulatedSensor::CaptureRawFullRes(uint8_t* img, size_t row_stride_in_bytes,
1449 uint32_t gain,
1450 const SensorCharacteristics& chars) {
1451 CaptureRaw(img, row_stride_in_bytes, gain, chars, /*inSensorZoom*/ false,
1452 /*binned*/ false);
1453 return;
1454 }
1455
CaptureRaw(uint8_t * img,size_t row_stride_in_bytes,uint32_t gain,const SensorCharacteristics & chars,bool in_sensor_zoom,bool binned)1456 void EmulatedSensor::CaptureRaw(uint8_t* img, size_t row_stride_in_bytes,
1457 uint32_t gain,
1458 const SensorCharacteristics& chars,
1459 bool in_sensor_zoom, bool binned) {
1460 ATRACE_CALL();
1461 if (in_sensor_zoom && binned) {
1462 ALOGE("%s: Can't perform in-sensor zoom in binned mode", __FUNCTION__);
1463 return;
1464 }
1465 float total_gain = gain / 100.0 * GetBaseGainFactor(chars.max_raw_value);
1466 float noise_var_gain = total_gain * total_gain;
1467 float read_noise_var =
1468 kReadNoiseVarBeforeGain * noise_var_gain + kReadNoiseVarAfterGain;
1469
1470 scene_->SetReadoutPixel(0, 0);
1471 // RGGB
1472 int bayer_select[4] = {EmulatedScene::R, EmulatedScene::Gr, EmulatedScene::Gb,
1473 EmulatedScene::B};
1474 const float raw_zoom_ratio = in_sensor_zoom ? 2.0f : 1.0f;
1475 unsigned int image_width =
1476 in_sensor_zoom || binned ? chars.width : chars.full_res_width;
1477 unsigned int image_height =
1478 in_sensor_zoom || binned ? chars.height : chars.full_res_height;
1479 const float norm_left_top = 0.5f - 0.5f / raw_zoom_ratio;
1480 for (unsigned int out_y = 0; out_y < image_height; out_y++) {
1481 int* bayer_row = bayer_select + (out_y & 0x1) * 2;
1482 uint16_t* px = (uint16_t*)img + out_y * (row_stride_in_bytes / 2);
1483
1484 float norm_y = out_y / (image_height * raw_zoom_ratio);
1485 int y = static_cast<int>(chars.full_res_height * (norm_left_top + norm_y));
1486 y = std::min(std::max(y, 0), (int)chars.full_res_height - 1);
1487
1488 for (unsigned int out_x = 0; out_x < image_width; out_x++) {
1489 int color_idx = chars.quad_bayer_sensor && !(in_sensor_zoom || binned)
1490 ? GetQuadBayerColor(out_x, out_y)
1491 : bayer_row[out_x & 0x1];
1492 float norm_x = out_x / (image_width * raw_zoom_ratio);
1493 int x = static_cast<int>(chars.full_res_width * (norm_left_top + norm_x));
1494 x = std::min(std::max(x, 0), (int)chars.full_res_width - 1);
1495
1496 uint32_t electron_count;
1497 scene_->SetReadoutPixel(x, y);
1498 electron_count = scene_->GetPixelElectrons()[color_idx];
1499
1500 // TODO: Better pixel saturation curve?
1501 electron_count = (electron_count < kSaturationElectrons)
1502 ? electron_count
1503 : kSaturationElectrons;
1504
1505 // TODO: Better A/D saturation curve?
1506 uint16_t raw_count = electron_count * total_gain;
1507 raw_count =
1508 (raw_count < chars.max_raw_value) ? raw_count : chars.max_raw_value;
1509
1510 // Calculate noise value
1511 // TODO: Use more-correct Gaussian instead of uniform noise
1512 float photon_noise_var = electron_count * noise_var_gain;
1513 float noise_stddev = sqrtf_approx(read_noise_var + photon_noise_var);
1514 // Scaled to roughly match gaussian/uniform noise stddev
1515 float noise_sample = rand_r(&rand_seed_) * (2.5 / (1.0 + RAND_MAX)) - 1.25;
1516
1517 raw_count += chars.black_level_pattern[color_idx];
1518 raw_count += noise_stddev * noise_sample;
1519
1520 *px++ = raw_count;
1521 }
1522 // TODO: Handle this better
1523 // simulatedTime += mRowReadoutTime;
1524 }
1525 ALOGVV("Raw sensor image captured");
1526 }
1527
CaptureRGB(uint8_t * img,uint32_t width,uint32_t height,uint32_t stride,RGBLayout layout,uint32_t gain,int32_t color_space,const SensorCharacteristics & chars)1528 void EmulatedSensor::CaptureRGB(uint8_t* img, uint32_t width, uint32_t height,
1529 uint32_t stride, RGBLayout layout,
1530 uint32_t gain, int32_t color_space,
1531 const SensorCharacteristics& chars) {
1532 ATRACE_CALL();
1533 float total_gain = gain / 100.0 * GetBaseGainFactor(chars.max_raw_value);
1534 // In fixed-point math, calculate total scaling from electrons to 8bpp
1535 int scale64x = 64 * total_gain * 255 / chars.max_raw_value;
1536 uint32_t inc_h = ceil((float)chars.full_res_width / width);
1537 uint32_t inc_v = ceil((float)chars.full_res_height / height);
1538
1539 for (unsigned int y = 0, outy = 0; y < chars.full_res_height;
1540 y += inc_v, outy++) {
1541 scene_->SetReadoutPixel(0, y);
1542 uint8_t* px = img + outy * stride;
1543 for (unsigned int x = 0; x < chars.full_res_width; x += inc_h) {
1544 uint32_t r_count, g_count, b_count;
1545 // TODO: Perfect demosaicing is a cheat
1546 const uint32_t* pixel = scene_->GetPixelElectrons();
1547 r_count = pixel[EmulatedScene::R] * scale64x;
1548 g_count = pixel[EmulatedScene::Gr] * scale64x;
1549 b_count = pixel[EmulatedScene::B] * scale64x;
1550
1551 if (color_space !=
1552 ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED) {
1553 RgbToRgb(&r_count, &g_count, &b_count);
1554 }
1555
1556 uint8_t r = r_count < 255 * 64 ? r_count / 64 : 255;
1557 uint8_t g = g_count < 255 * 64 ? g_count / 64 : 255;
1558 uint8_t b = b_count < 255 * 64 ? b_count / 64 : 255;
1559 switch (layout) {
1560 case RGB:
1561 *px++ = r;
1562 *px++ = g;
1563 *px++ = b;
1564 break;
1565 case RGBA:
1566 *px++ = r;
1567 *px++ = g;
1568 *px++ = b;
1569 *px++ = 255;
1570 break;
1571 case ARGB:
1572 *px++ = 255;
1573 *px++ = r;
1574 *px++ = g;
1575 *px++ = b;
1576 break;
1577 default:
1578 ALOGE("%s: RGB layout: %d not supported", __FUNCTION__, layout);
1579 return;
1580 }
1581 for (unsigned int j = 1; j < inc_h; j++) scene_->GetPixelElectrons();
1582 }
1583 }
1584 ALOGVV("RGB sensor image captured");
1585 }
1586
CaptureYUV420(YCbCrPlanes yuv_layout,uint32_t width,uint32_t height,uint32_t gain,float zoom_ratio,bool rotate,int32_t color_space,const SensorCharacteristics & chars)1587 void EmulatedSensor::CaptureYUV420(YCbCrPlanes yuv_layout, uint32_t width,
1588 uint32_t height, uint32_t gain,
1589 float zoom_ratio, bool rotate,
1590 int32_t color_space,
1591 const SensorCharacteristics& chars) {
1592 ATRACE_CALL();
1593 float total_gain = gain / 100.0 * GetBaseGainFactor(chars.max_raw_value);
1594 // Using fixed-point math with 6 bits of fractional precision.
1595 // In fixed-point math, calculate total scaling from electrons to 8bpp
1596 const int scale64x =
1597 kFixedBitPrecision * total_gain * 255 / chars.max_raw_value;
1598 // Fixed-point coefficients for RGB-YUV transform
1599 // Based on JFIF RGB->YUV transform.
1600 // Cb/Cr offset scaled by 64x twice since they're applied post-multiply
1601 const int rgb_to_y[] = {19, 37, 7};
1602 const int rgb_to_cb[] = {-10, -21, 32, 524288};
1603 const int rgb_to_cr[] = {32, -26, -5, 524288};
1604 // Scale back to 8bpp non-fixed-point
1605 const int scale_out = 64;
1606 const int scale_out_sq = scale_out * scale_out; // after multiplies
1607
1608 // inc = how many pixels to skip while reading every next pixel
1609 const float aspect_ratio = static_cast<float>(width) / height;
1610
1611 // precalculate normalized coordinates and dimensions
1612 const float norm_left_top = 0.5f - 0.5f / zoom_ratio;
1613 const float norm_rot_top = norm_left_top;
1614 const float norm_width = 1 / zoom_ratio;
1615 const float norm_rot_width = norm_width / aspect_ratio;
1616 const float norm_rot_height = norm_width;
1617 const float norm_rot_left =
1618 norm_left_top + (norm_width + norm_rot_width) * 0.5f;
1619
1620 for (unsigned int out_y = 0; out_y < height; out_y++) {
1621 uint8_t* px_y = yuv_layout.img_y + out_y * yuv_layout.y_stride;
1622 uint8_t* px_cb = yuv_layout.img_cb + (out_y / 2) * yuv_layout.cbcr_stride;
1623 uint8_t* px_cr = yuv_layout.img_cr + (out_y / 2) * yuv_layout.cbcr_stride;
1624
1625 for (unsigned int out_x = 0; out_x < width; out_x++) {
1626 int x, y;
1627 float norm_x = out_x / (width * zoom_ratio);
1628 float norm_y = out_y / (height * zoom_ratio);
1629 if (rotate) {
1630 x = static_cast<int>(chars.full_res_width *
1631 (norm_rot_left - norm_y * norm_rot_width));
1632 y = static_cast<int>(chars.full_res_height *
1633 (norm_rot_top + norm_x * norm_rot_height));
1634 } else {
1635 x = static_cast<int>(chars.full_res_width * (norm_left_top + norm_x));
1636 y = static_cast<int>(chars.full_res_height * (norm_left_top + norm_y));
1637 }
1638 x = std::min(std::max(x, 0), (int)chars.full_res_width - 1);
1639 y = std::min(std::max(y, 0), (int)chars.full_res_height - 1);
1640 scene_->SetReadoutPixel(x, y);
1641
1642 uint32_t r_count, g_count, b_count;
1643 // TODO: Perfect demosaicing is a cheat
1644 const uint32_t* pixel = rotate ? scene_->GetPixelElectronsColumn()
1645 : scene_->GetPixelElectrons();
1646 r_count = pixel[EmulatedScene::R] * scale64x;
1647 g_count = pixel[EmulatedScene::Gr] * scale64x;
1648 b_count = pixel[EmulatedScene::B] * scale64x;
1649
1650 if (color_space !=
1651 ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED) {
1652 RgbToRgb(&r_count, &g_count, &b_count);
1653 }
1654
1655 r_count = r_count < kSaturationPoint ? r_count : kSaturationPoint;
1656 g_count = g_count < kSaturationPoint ? g_count : kSaturationPoint;
1657 b_count = b_count < kSaturationPoint ? b_count : kSaturationPoint;
1658
1659 // Gamma correction
1660 r_count = GammaTable(r_count, color_space);
1661 g_count = GammaTable(g_count, color_space);
1662 b_count = GammaTable(b_count, color_space);
1663
1664 uint8_t y8 = (rgb_to_y[0] * r_count + rgb_to_y[1] * g_count +
1665 rgb_to_y[2] * b_count) /
1666 scale_out_sq;
1667 if (yuv_layout.bytesPerPixel == 1) {
1668 *px_y = y8;
1669 } else if (yuv_layout.bytesPerPixel == 2) {
1670 *(reinterpret_cast<uint16_t*>(px_y)) = htole16(y8 << 8);
1671 } else {
1672 ALOGE("%s: Unsupported bytes per pixel value: %zu", __func__,
1673 yuv_layout.bytesPerPixel);
1674 return;
1675 }
1676 px_y += yuv_layout.bytesPerPixel;
1677
1678 if (out_y % 2 == 0 && out_x % 2 == 0) {
1679 uint8_t cb8 = (rgb_to_cb[0] * r_count + rgb_to_cb[1] * g_count +
1680 rgb_to_cb[2] * b_count + rgb_to_cb[3]) /
1681 scale_out_sq;
1682 uint8_t cr8 = (rgb_to_cr[0] * r_count + rgb_to_cr[1] * g_count +
1683 rgb_to_cr[2] * b_count + rgb_to_cr[3]) /
1684 scale_out_sq;
1685 if (yuv_layout.bytesPerPixel == 1) {
1686 *px_cb = cb8;
1687 *px_cr = cr8;
1688 } else if (yuv_layout.bytesPerPixel == 2) {
1689 *(reinterpret_cast<uint16_t*>(px_cb)) = htole16(cb8 << 8);
1690 *(reinterpret_cast<uint16_t*>(px_cr)) = htole16(cr8 << 8);
1691 } else {
1692 ALOGE("%s: Unsupported bytes per pixel value: %zu", __func__,
1693 yuv_layout.bytesPerPixel);
1694 return;
1695 }
1696 px_cr += yuv_layout.cbcr_step;
1697 px_cb += yuv_layout.cbcr_step;
1698 }
1699 }
1700 }
1701 ALOGVV("YUV420 sensor image captured");
1702 }
1703
CaptureDepth(uint8_t * img,uint32_t gain,uint32_t width,uint32_t height,uint32_t stride,const SensorCharacteristics & chars)1704 void EmulatedSensor::CaptureDepth(uint8_t* img, uint32_t gain, uint32_t width,
1705 uint32_t height, uint32_t stride,
1706 const SensorCharacteristics& chars) {
1707 ATRACE_CALL();
1708 float total_gain = gain / 100.0 * GetBaseGainFactor(chars.max_raw_value);
1709 // In fixed-point math, calculate scaling factor to 13bpp millimeters
1710 int scale64x = 64 * total_gain * 8191 / chars.max_raw_value;
1711 uint32_t inc_h = ceil((float)chars.full_res_width / width);
1712 uint32_t inc_v = ceil((float)chars.full_res_height / height);
1713
1714 for (unsigned int y = 0, out_y = 0; y < chars.full_res_height;
1715 y += inc_v, out_y++) {
1716 scene_->SetReadoutPixel(0, y);
1717 uint16_t* px = (uint16_t*)(img + (out_y * stride));
1718 for (unsigned int x = 0; x < chars.full_res_width; x += inc_h) {
1719 uint32_t depth_count;
1720 // TODO: Make up real depth scene instead of using green channel
1721 // as depth
1722 const uint32_t* pixel = scene_->GetPixelElectrons();
1723 depth_count = pixel[EmulatedScene::Gr] * scale64x;
1724
1725 *px++ = depth_count < 8191 * 64 ? depth_count / 64 : 0;
1726 for (unsigned int j = 1; j < inc_h; j++) scene_->GetPixelElectrons();
1727 }
1728 // TODO: Handle this better
1729 // simulatedTime += mRowReadoutTime;
1730 }
1731 ALOGVV("Depth sensor image captured");
1732 }
1733
ProcessYUV420(const YUV420Frame & input,const YUV420Frame & output,uint32_t gain,ProcessType process_type,float zoom_ratio,bool rotate_and_crop,int32_t color_space,const SensorCharacteristics & chars)1734 status_t EmulatedSensor::ProcessYUV420(const YUV420Frame& input,
1735 const YUV420Frame& output, uint32_t gain,
1736 ProcessType process_type,
1737 float zoom_ratio, bool rotate_and_crop,
1738 int32_t color_space,
1739 const SensorCharacteristics& chars) {
1740 ATRACE_CALL();
1741 size_t input_width, input_height;
1742 YCbCrPlanes input_planes, output_planes;
1743 std::vector<uint8_t> temp_yuv, temp_output_uv, temp_input_uv;
1744
1745 // Overwrite HIGH_QUALITY to REGULAR for Emulator if property
1746 // ro.boot.qemu.camera_hq_edge_processing is false;
1747 if (process_type == HIGH_QUALITY &&
1748 !property_get_bool("ro.boot.qemu.camera_hq_edge_processing", true)) {
1749 process_type = REGULAR;
1750 }
1751
1752 switch (process_type) {
1753 case HIGH_QUALITY:
1754 CaptureYUV420(output.planes, output.width, output.height, gain,
1755 zoom_ratio, rotate_and_crop, color_space, chars);
1756 return OK;
1757 case REPROCESS:
1758 input_width = input.width;
1759 input_height = input.height;
1760 input_planes = input.planes;
1761
1762 // libyuv only supports planar YUV420 during scaling.
1763 // Split the input U/V plane in separate planes if needed.
1764 if (input_planes.cbcr_step == 2) {
1765 temp_input_uv.resize(input_width * input_height / 2);
1766 auto temp_uv_buffer = temp_input_uv.data();
1767 input_planes.img_cb = temp_uv_buffer;
1768 input_planes.img_cr = temp_uv_buffer + (input_width * input_height) / 4;
1769 input_planes.cbcr_stride = input_width / 2;
1770 if (input.planes.img_cb < input.planes.img_cr) {
1771 libyuv::SplitUVPlane(input.planes.img_cb, input.planes.cbcr_stride,
1772 input_planes.img_cb, input_planes.cbcr_stride,
1773 input_planes.img_cr, input_planes.cbcr_stride,
1774 input_width / 2, input_height / 2);
1775 } else {
1776 libyuv::SplitUVPlane(input.planes.img_cr, input.planes.cbcr_stride,
1777 input_planes.img_cr, input_planes.cbcr_stride,
1778 input_planes.img_cb, input_planes.cbcr_stride,
1779 input_width / 2, input_height / 2);
1780 }
1781 }
1782 break;
1783 case REGULAR:
1784 default:
1785 // Generate the smallest possible frame with the expected AR and
1786 // then scale using libyuv.
1787 float aspect_ratio = static_cast<float>(output.width) / output.height;
1788 zoom_ratio = std::max(1.f, zoom_ratio);
1789 input_width = EmulatedScene::kSceneWidth * aspect_ratio;
1790 input_height = EmulatedScene::kSceneHeight;
1791 temp_yuv.reserve((input_width * input_height * 3) / 2);
1792 auto temp_yuv_buffer = temp_yuv.data();
1793 input_planes = {
1794 .img_y = temp_yuv_buffer,
1795 .img_cb = temp_yuv_buffer + input_width * input_height,
1796 .img_cr = temp_yuv_buffer + (input_width * input_height * 5) / 4,
1797 .y_stride = static_cast<uint32_t>(input_width),
1798 .cbcr_stride = static_cast<uint32_t>(input_width) / 2,
1799 .cbcr_step = 1};
1800 CaptureYUV420(input_planes, input_width, input_height, gain, zoom_ratio,
1801 rotate_and_crop, color_space, chars);
1802 }
1803
1804 output_planes = output.planes;
1805 // libyuv only supports planar YUV420 during scaling.
1806 // Treat the output UV space as planar first and then
1807 // interleave in the second step.
1808 if (output_planes.cbcr_step == 2) {
1809 temp_output_uv.resize(output.width * output.height / 2);
1810 auto temp_uv_buffer = temp_output_uv.data();
1811 output_planes.img_cb = temp_uv_buffer;
1812 output_planes.img_cr = temp_uv_buffer + output.width * output.height / 4;
1813 output_planes.cbcr_stride = output.width / 2;
1814 }
1815
1816 auto ret = I420Scale(
1817 input_planes.img_y, input_planes.y_stride, input_planes.img_cb,
1818 input_planes.cbcr_stride, input_planes.img_cr, input_planes.cbcr_stride,
1819 input_width, input_height, output_planes.img_y, output_planes.y_stride,
1820 output_planes.img_cb, output_planes.cbcr_stride, output_planes.img_cr,
1821 output_planes.cbcr_stride, output.width, output.height,
1822 libyuv::kFilterNone);
1823 if (ret != 0) {
1824 ALOGE("%s: Failed during YUV scaling: %d", __FUNCTION__, ret);
1825 return ret;
1826 }
1827
1828 // Merge U/V Planes for the interleaved case
1829 if (output_planes.cbcr_step == 2) {
1830 if (output.planes.img_cb < output.planes.img_cr) {
1831 libyuv::MergeUVPlane(output_planes.img_cb, output_planes.cbcr_stride,
1832 output_planes.img_cr, output_planes.cbcr_stride,
1833 output.planes.img_cb, output.planes.cbcr_stride,
1834 output.width / 2, output.height / 2);
1835 } else {
1836 libyuv::MergeUVPlane(output_planes.img_cr, output_planes.cbcr_stride,
1837 output_planes.img_cb, output_planes.cbcr_stride,
1838 output.planes.img_cr, output.planes.cbcr_stride,
1839 output.width / 2, output.height / 2);
1840 }
1841 }
1842
1843 return ret;
1844 }
1845
ApplysRGBGamma(int32_t value,int32_t saturation)1846 int32_t EmulatedSensor::ApplysRGBGamma(int32_t value, int32_t saturation) {
1847 float n_value = (static_cast<float>(value) / saturation);
1848 n_value = (n_value <= 0.0031308f)
1849 ? n_value * 12.92f
1850 : 1.055f * pow(n_value, 0.4166667f) - 0.055f;
1851 return n_value * saturation;
1852 }
1853
ApplySMPTE170MGamma(int32_t value,int32_t saturation)1854 int32_t EmulatedSensor::ApplySMPTE170MGamma(int32_t value, int32_t saturation) {
1855 float n_value = (static_cast<float>(value) / saturation);
1856 n_value = (n_value <= 0.018f) ? n_value * 4.5f
1857 : 1.099f * pow(n_value, 0.45f) - 0.099f;
1858 return n_value * saturation;
1859 }
1860
ApplyST2084Gamma(int32_t value,int32_t saturation)1861 int32_t EmulatedSensor::ApplyST2084Gamma(int32_t value, int32_t saturation) {
1862 float n_value = (static_cast<float>(value) / saturation);
1863 float c2 = 32.f * 2413.f / 4096.f;
1864 float c3 = 32.f * 2392.f / 4096.f;
1865 float c1 = c3 - c2 + 1.f;
1866 float m = 128.f * 2523.f / 4096.f;
1867 float n = 0.25f * 2610.f / 4096.f;
1868 n_value = pow((c1 + c2 * pow(n_value, n)) / (1 + c3 * pow(n_value, n)), m);
1869 return n_value * saturation;
1870 }
1871
ApplyHLGGamma(int32_t value,int32_t saturation)1872 int32_t EmulatedSensor::ApplyHLGGamma(int32_t value, int32_t saturation) {
1873 float n_value = (static_cast<float>(value) / saturation);
1874 // The full HLG gamma curve has additional parameters for n_value > 1, but n_value
1875 // in the emulated camera is always <= 1 due to lack of HDR display features.
1876 n_value = 0.5f * pow(n_value, 0.5f);
1877 return n_value * saturation;
1878 }
1879
GammaTable(int32_t value,int32_t color_space)1880 int32_t EmulatedSensor::GammaTable(int32_t value, int32_t color_space) {
1881 switch (color_space) {
1882 case ColorSpaceNamed::BT709:
1883 return gamma_table_smpte170m_[value];
1884 case ColorSpaceNamed::BT2020:
1885 return gamma_table_hlg_[value]; // Assume HLG
1886 case ColorSpaceNamed::DISPLAY_P3:
1887 case ColorSpaceNamed::SRGB:
1888 default:
1889 return gamma_table_sRGB_[value];
1890 }
1891
1892 return 0;
1893 }
1894
RgbToRgb(uint32_t * r_count,uint32_t * g_count,uint32_t * b_count)1895 void EmulatedSensor::RgbToRgb(uint32_t* r_count, uint32_t* g_count,
1896 uint32_t* b_count) {
1897 uint32_t r = *r_count;
1898 uint32_t g = *g_count;
1899 uint32_t b = *b_count;
1900 *r_count = (uint32_t)std::max(
1901 r * rgb_rgb_matrix_.rR + g * rgb_rgb_matrix_.gR + b * rgb_rgb_matrix_.bR,
1902 0.0f);
1903 *g_count = (uint32_t)std::max(
1904 r * rgb_rgb_matrix_.rG + g * rgb_rgb_matrix_.gG + b * rgb_rgb_matrix_.bG,
1905 0.0f);
1906 *b_count = (uint32_t)std::max(
1907 r * rgb_rgb_matrix_.rB + g * rgb_rgb_matrix_.gB + b * rgb_rgb_matrix_.bB,
1908 0.0f);
1909 }
1910
CalculateRgbRgbMatrix(int32_t color_space,const SensorCharacteristics & chars)1911 void EmulatedSensor::CalculateRgbRgbMatrix(int32_t color_space,
1912 const SensorCharacteristics& chars) {
1913 const XyzMatrix* xyzMatrix;
1914 switch (color_space) {
1915 case ColorSpaceNamed::DISPLAY_P3:
1916 xyzMatrix = &kDisplayP3Matrix;
1917 break;
1918 case ColorSpaceNamed::BT709:
1919 xyzMatrix = &kBt709Matrix;
1920 break;
1921 case ColorSpaceNamed::BT2020:
1922 xyzMatrix = &kBt2020Matrix;
1923 break;
1924 case ColorSpaceNamed::SRGB:
1925 default:
1926 xyzMatrix = &kSrgbXyzMatrix;
1927 break;
1928 }
1929
1930 rgb_rgb_matrix_.rR = xyzMatrix->xR * chars.forward_matrix.rX +
1931 xyzMatrix->yR * chars.forward_matrix.rY +
1932 xyzMatrix->zR * chars.forward_matrix.rZ;
1933 rgb_rgb_matrix_.gR = xyzMatrix->xR * chars.forward_matrix.gX +
1934 xyzMatrix->yR * chars.forward_matrix.gY +
1935 xyzMatrix->zR * chars.forward_matrix.gZ;
1936 rgb_rgb_matrix_.bR = xyzMatrix->xR * chars.forward_matrix.bX +
1937 xyzMatrix->yR * chars.forward_matrix.bY +
1938 xyzMatrix->zR * chars.forward_matrix.bZ;
1939 rgb_rgb_matrix_.rG = xyzMatrix->xG * chars.forward_matrix.rX +
1940 xyzMatrix->yG * chars.forward_matrix.rY +
1941 xyzMatrix->zG * chars.forward_matrix.rZ;
1942 rgb_rgb_matrix_.gG = xyzMatrix->xG * chars.forward_matrix.gX +
1943 xyzMatrix->yG * chars.forward_matrix.gY +
1944 xyzMatrix->zG * chars.forward_matrix.gZ;
1945 rgb_rgb_matrix_.bG = xyzMatrix->xG * chars.forward_matrix.bX +
1946 xyzMatrix->yG * chars.forward_matrix.bY +
1947 xyzMatrix->zG * chars.forward_matrix.bZ;
1948 rgb_rgb_matrix_.rB = xyzMatrix->xB * chars.forward_matrix.rX +
1949 xyzMatrix->yB * chars.forward_matrix.rY +
1950 xyzMatrix->zB * chars.forward_matrix.rZ;
1951 rgb_rgb_matrix_.gB = xyzMatrix->xB * chars.forward_matrix.gX +
1952 xyzMatrix->yB * chars.forward_matrix.gY +
1953 xyzMatrix->zB * chars.forward_matrix.gZ;
1954 rgb_rgb_matrix_.bB = xyzMatrix->xB * chars.forward_matrix.bX +
1955 xyzMatrix->yB * chars.forward_matrix.bY +
1956 xyzMatrix->zB * chars.forward_matrix.bZ;
1957 }
1958
1959 } // namespace android
1960