• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   // TODO: Check session parameters. For now assuming all combinations
628   // are supported.
629 
630   return true;
631 }
632 
StartUp(uint32_t logical_camera_id,std::unique_ptr<LogicalCharacteristics> logical_chars)633 status_t EmulatedSensor::StartUp(
634     uint32_t logical_camera_id,
635     std::unique_ptr<LogicalCharacteristics> logical_chars) {
636   if (isRunning()) {
637     return OK;
638   }
639 
640   if (logical_chars.get() == nullptr) {
641     return BAD_VALUE;
642   }
643 
644   chars_ = std::move(logical_chars);
645   auto device_chars = chars_->find(logical_camera_id);
646   if (device_chars == chars_->end()) {
647     ALOGE(
648         "%s: Logical camera id: %u absent from logical camera characteristics!",
649         __FUNCTION__, logical_camera_id);
650     return BAD_VALUE;
651   }
652 
653   for (const auto& it : *chars_) {
654     if (!AreCharacteristicsSupported(it.second)) {
655       ALOGE("%s: Sensor characteristics for camera id: %u not supported!",
656             __FUNCTION__, it.first);
657       return BAD_VALUE;
658     }
659   }
660 
661   logical_camera_id_ = logical_camera_id;
662   scene_ = std::make_unique<EmulatedScene>(
663       device_chars->second.full_res_width, device_chars->second.full_res_height,
664       kElectronsPerLuxSecond, device_chars->second.orientation,
665       device_chars->second.is_front_facing);
666   jpeg_compressor_ = std::make_unique<JpegCompressor>();
667 
668   auto res = run(LOG_TAG, ANDROID_PRIORITY_URGENT_DISPLAY);
669   if (res != OK) {
670     ALOGE("Unable to start up sensor capture thread: %d", res);
671   }
672 
673   return res;
674 }
675 
ShutDown()676 status_t EmulatedSensor::ShutDown() {
677   int res;
678   res = requestExitAndWait();
679   if (res != OK) {
680     ALOGE("Unable to shut down sensor capture thread: %d", res);
681   }
682   return res;
683 }
684 
SetCurrentRequest(std::unique_ptr<LogicalCameraSettings> logical_settings,std::unique_ptr<HwlPipelineResult> result,std::unique_ptr<HwlPipelineResult> partial_result,std::unique_ptr<Buffers> input_buffers,std::unique_ptr<Buffers> output_buffers)685 void EmulatedSensor::SetCurrentRequest(
686     std::unique_ptr<LogicalCameraSettings> logical_settings,
687     std::unique_ptr<HwlPipelineResult> result,
688     std::unique_ptr<HwlPipelineResult> partial_result,
689     std::unique_ptr<Buffers> input_buffers,
690     std::unique_ptr<Buffers> output_buffers) {
691   Mutex::Autolock lock(control_mutex_);
692   current_settings_ = std::move(logical_settings);
693   current_result_ = std::move(result);
694   current_input_buffers_ = std::move(input_buffers);
695   current_output_buffers_ = std::move(output_buffers);
696   partial_result_ = std::move(partial_result);
697 }
698 
WaitForVSyncLocked(nsecs_t reltime)699 bool EmulatedSensor::WaitForVSyncLocked(nsecs_t reltime) {
700   got_vsync_ = false;
701   while (!got_vsync_) {
702     auto res = vsync_.waitRelative(control_mutex_, reltime);
703     if (res != OK && res != TIMED_OUT) {
704       ALOGE("%s: Error waiting for VSync signal: %d", __FUNCTION__, res);
705       return false;
706     }
707   }
708 
709   return got_vsync_;
710 }
711 
WaitForVSync(nsecs_t reltime)712 bool EmulatedSensor::WaitForVSync(nsecs_t reltime) {
713   Mutex::Autolock lock(control_mutex_);
714 
715   return WaitForVSyncLocked(reltime);
716 }
717 
Flush()718 status_t EmulatedSensor::Flush() {
719   Mutex::Autolock lock(control_mutex_);
720   auto ret = WaitForVSyncLocked(kSupportedFrameDurationRange[1]);
721 
722   // First recreate the jpeg compressor. This will abort any ongoing processing
723   // and flush any pending jobs.
724   jpeg_compressor_ = std::make_unique<JpegCompressor>();
725 
726   // Then return any pending frames here
727   if ((current_input_buffers_.get() != nullptr) &&
728       (!current_input_buffers_->empty())) {
729     current_input_buffers_->clear();
730   }
731   if ((current_output_buffers_.get() != nullptr) &&
732       (!current_output_buffers_->empty())) {
733     for (const auto& buffer : *current_output_buffers_) {
734       buffer->stream_buffer.status = BufferStatus::kError;
735     }
736 
737     if ((current_result_.get() != nullptr) &&
738         (current_result_->result_metadata.get() != nullptr)) {
739       if (current_output_buffers_->at(0)->callback.notify != nullptr) {
740         NotifyMessage msg{
741             .type = MessageType::kError,
742             .message.error = {
743                 .frame_number = current_output_buffers_->at(0)->frame_number,
744                 .error_stream_id = -1,
745                 .error_code = ErrorCode::kErrorResult,
746             }};
747 
748         current_output_buffers_->at(0)->callback.notify(
749             current_result_->pipeline_id, msg);
750       }
751     }
752 
753     current_output_buffers_->clear();
754   }
755 
756   return ret ? OK : TIMED_OUT;
757 }
758 
getSystemTimeWithSource(uint32_t timestamp_source)759 nsecs_t EmulatedSensor::getSystemTimeWithSource(uint32_t timestamp_source) {
760   if (timestamp_source == ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
761     return systemTime(SYSTEM_TIME_BOOTTIME);
762   }
763   return systemTime(SYSTEM_TIME_MONOTONIC);
764 }
765 
threadLoop()766 bool EmulatedSensor::threadLoop() {
767   ATRACE_CALL();
768   /**
769    * Sensor capture operation main loop.
770    *
771    */
772 
773   /**
774    * Stage 1: Read in latest control parameters
775    */
776   std::unique_ptr<Buffers> next_buffers;
777   std::unique_ptr<Buffers> next_input_buffer;
778   std::unique_ptr<HwlPipelineResult> next_result;
779   std::unique_ptr<HwlPipelineResult> partial_result;
780   std::unique_ptr<LogicalCameraSettings> settings;
781   HwlPipelineCallback callback = {
782       .process_pipeline_result = nullptr,
783       .process_pipeline_batch_result = nullptr,
784       .notify = nullptr,
785   };
786   {
787     Mutex::Autolock lock(control_mutex_);
788     std::swap(settings, current_settings_);
789     std::swap(next_buffers, current_output_buffers_);
790     std::swap(next_input_buffer, current_input_buffers_);
791     std::swap(next_result, current_result_);
792     std::swap(partial_result, partial_result_);
793 
794     // Signal VSync for start of readout
795     ALOGVV("Sensor VSync");
796     got_vsync_ = true;
797     vsync_.signal();
798   }
799 
800   auto frame_duration = EmulatedSensor::kSupportedFrameDurationRange[0];
801   auto exposure_time = EmulatedSensor::kSupportedExposureTimeRange[0];
802   uint32_t timestamp_source = ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_UNKNOWN;
803   // Frame duration must always be the same among all physical devices
804   if ((settings.get() != nullptr) && (!settings->empty())) {
805     frame_duration = settings->begin()->second.frame_duration;
806     exposure_time = settings->begin()->second.exposure_time;
807     timestamp_source = settings->begin()->second.timestamp_source;
808   }
809 
810   nsecs_t start_real_time = getSystemTimeWithSource(timestamp_source);
811   // Stagefright cares about system time for timestamps, so base simulated
812   // time on that.
813   nsecs_t frame_end_real_time = start_real_time + frame_duration;
814 
815   /**
816    * Stage 2: Capture new image
817    */
818   next_capture_time_ = frame_end_real_time;
819   next_readout_time_ = frame_end_real_time + exposure_time;
820 
821   sensor_binning_factor_info_.clear();
822 
823   bool reprocess_request = false;
824   if ((next_input_buffer.get() != nullptr) && (!next_input_buffer->empty())) {
825     if (next_input_buffer->size() > 1) {
826       ALOGW("%s: Reprocess supports only single input!", __FUNCTION__);
827     }
828 
829       camera_metadata_ro_entry_t entry;
830       auto ret =
831           next_result->result_metadata->Get(ANDROID_SENSOR_TIMESTAMP, &entry);
832       if ((ret == OK) && (entry.count == 1)) {
833         next_capture_time_ = entry.data.i64[0];
834       } else {
835         ALOGW("%s: Reprocess timestamp absent!", __FUNCTION__);
836       }
837 
838       ret = next_result->result_metadata->Get(ANDROID_SENSOR_EXPOSURE_TIME,
839                                               &entry);
840       if ((ret == OK) && (entry.count == 1)) {
841         next_readout_time_ = next_capture_time_ + entry.data.i64[0];
842       } else {
843         next_readout_time_ = next_capture_time_;
844       }
845 
846       reprocess_request = true;
847   }
848 
849   if ((next_buffers != nullptr) && (settings != nullptr)) {
850     callback = next_buffers->at(0)->callback;
851     if (callback.notify != nullptr) {
852       NotifyMessage msg{
853           .type = MessageType::kShutter,
854           .message.shutter = {
855               .frame_number = next_buffers->at(0)->frame_number,
856               .timestamp_ns = static_cast<uint64_t>(next_capture_time_),
857               .readout_timestamp_ns =
858                   static_cast<uint64_t>(next_readout_time_)}};
859       callback.notify(next_result->pipeline_id, msg);
860     }
861     auto b = next_buffers->begin();
862     while (b != next_buffers->end()) {
863       auto device_settings = settings->find((*b)->camera_id);
864       if (device_settings == settings->end()) {
865         ALOGE("%s: Sensor settings absent for device: %d", __func__,
866               (*b)->camera_id);
867         b = next_buffers->erase(b);
868         continue;
869       }
870 
871       auto device_chars = chars_->find((*b)->camera_id);
872       if (device_chars == chars_->end()) {
873         ALOGE("%s: Sensor characteristics absent for device: %d", __func__,
874               (*b)->camera_id);
875         b = next_buffers->erase(b);
876         continue;
877       }
878 
879       sensor_binning_factor_info_[(*b)->camera_id].quad_bayer_sensor =
880           device_chars->second.quad_bayer_sensor;
881 
882       ALOGVV("Starting next capture: Exposure: %" PRIu64 " ms, gain: %d",
883              ns2ms(device_settings->second.exposure_time),
884              device_settings->second.gain);
885 
886       scene_->Initialize(device_chars->second.full_res_width,
887                          device_chars->second.full_res_height,
888                          kElectronsPerLuxSecond);
889       scene_->SetExposureDuration((float)device_settings->second.exposure_time /
890                                   1e9);
891       scene_->SetColorFilterXYZ(device_chars->second.color_filter.rX,
892                                 device_chars->second.color_filter.rY,
893                                 device_chars->second.color_filter.rZ,
894                                 device_chars->second.color_filter.grX,
895                                 device_chars->second.color_filter.grY,
896                                 device_chars->second.color_filter.grZ,
897                                 device_chars->second.color_filter.gbX,
898                                 device_chars->second.color_filter.gbY,
899                                 device_chars->second.color_filter.gbZ,
900                                 device_chars->second.color_filter.bX,
901                                 device_chars->second.color_filter.bY,
902                                 device_chars->second.color_filter.bZ);
903       scene_->SetTestPattern(device_settings->second.test_pattern_mode ==
904                              ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR);
905       scene_->SetTestPatternData(device_settings->second.test_pattern_data);
906       scene_->SetScreenRotation(device_settings->second.screen_rotation);
907 
908       uint32_t handshake_divider =
909           (device_settings->second.video_stab ==
910            ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_ON) ||
911                   (device_settings->second.video_stab ==
912                    ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_PREVIEW_STABILIZATION)
913               ? kReducedSceneHandshake
914               : kRegularSceneHandshake;
915       scene_->CalculateScene(next_capture_time_, handshake_divider);
916 
917       (*b)->stream_buffer.status = BufferStatus::kOk;
918       bool max_res_mode = device_settings->second.sensor_pixel_mode;
919       sensor_binning_factor_info_[(*b)->camera_id].max_res_request =
920           max_res_mode;
921       switch ((*b)->format) {
922         case PixelFormat::RAW16:
923           sensor_binning_factor_info_[(*b)->camera_id].has_raw_stream = true;
924           if (!sensor_binning_factor_info_[(*b)->camera_id]
925                    .has_cropped_raw_stream &&
926               (*b)->use_case ==
927                   ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW) {
928             sensor_binning_factor_info_[(*b)->camera_id].has_cropped_raw_stream =
929                 true;
930           }
931           break;
932         default:
933           sensor_binning_factor_info_[(*b)->camera_id].has_non_raw_stream = true;
934       }
935 
936       // TODO: remove hack. Implement RAW -> YUV / JPEG reprocessing http://b/192382904
937       bool treat_as_reprocess =
938           (device_chars->second.quad_bayer_sensor && reprocess_request &&
939            (*next_input_buffer->begin())->format == PixelFormat::RAW16)
940               ? false
941               : reprocess_request;
942       ProcessType process_type = treat_as_reprocess ? REPROCESS
943                                  : (device_settings->second.edge_mode ==
944                                     ANDROID_EDGE_MODE_HIGH_QUALITY)
945                                      ? HIGH_QUALITY
946                                      : REGULAR;
947 
948       if ((*b)->color_space !=
949           ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED) {
950         CalculateRgbRgbMatrix((*b)->color_space, device_chars->second);
951       }
952 
953       switch ((*b)->format) {
954         case PixelFormat::RAW16:
955           if (!reprocess_request) {
956             uint64_t min_full_res_raw_size =
957                 2 * device_chars->second.full_res_width *
958                 device_chars->second.full_res_height;
959             uint64_t min_default_raw_size =
960                 2 * device_chars->second.width * device_chars->second.height;
961             bool default_mode_for_qb =
962                 device_chars->second.quad_bayer_sensor && !max_res_mode;
963             size_t buffer_size = (*b)->plane.img.buffer_size;
964             if (default_mode_for_qb) {
965               if (buffer_size < min_default_raw_size) {
966                 ALOGE(
967                     "%s: Output buffer size too small for RAW capture in "
968                     "default "
969                     "mode, "
970                     "expected %" PRIu64 ", got %zu, for camera id %d",
971                     __FUNCTION__, min_default_raw_size, buffer_size,
972                     (*b)->camera_id);
973                 (*b)->stream_buffer.status = BufferStatus::kError;
974                 break;
975               }
976             } else if (buffer_size < min_full_res_raw_size) {
977               ALOGE(
978                   "%s: Output buffer size too small for RAW capture in max res "
979                   "mode, "
980                   "expected %" PRIu64 ", got %zu, for camera id %d",
981                   __FUNCTION__, min_full_res_raw_size, buffer_size,
982                   (*b)->camera_id);
983               (*b)->stream_buffer.status = BufferStatus::kError;
984               break;
985             }
986             if (default_mode_for_qb) {
987               if (device_settings->second.zoom_ratio > 2.0f &&
988                   ((*b)->use_case ==
989                    ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW)) {
990                 sensor_binning_factor_info_[(*b)->camera_id]
991                     .raw_in_sensor_zoom_applied = true;
992                 CaptureRawInSensorZoom(
993                     (*b)->plane.img.img, (*b)->plane.img.stride_in_bytes,
994                     device_settings->second.gain, device_chars->second);
995 
996               } else {
997                 CaptureRawBinned(
998                     (*b)->plane.img.img, (*b)->plane.img.stride_in_bytes,
999                     device_settings->second.gain, device_chars->second);
1000               }
1001             } else {
1002               CaptureRawFullRes(
1003                   (*b)->plane.img.img, (*b)->plane.img.stride_in_bytes,
1004                   device_settings->second.gain, device_chars->second);
1005             }
1006           } else {
1007             if (!device_chars->second.quad_bayer_sensor) {
1008               ALOGE(
1009                   "%s: Reprocess requests with output format %x no supported!",
1010                   __FUNCTION__, (*b)->format);
1011               (*b)->stream_buffer.status = BufferStatus::kError;
1012               break;
1013             }
1014             // Remosaic the RAW input buffer
1015             if ((*next_input_buffer->begin())->width != (*b)->width ||
1016                 (*next_input_buffer->begin())->height != (*b)->height) {
1017               ALOGE(
1018                   "%s: RAW16 input dimensions %dx%d don't match output buffer "
1019                   "dimensions %dx%d",
1020                   __FUNCTION__, (*next_input_buffer->begin())->width,
1021                   (*next_input_buffer->begin())->height, (*b)->width,
1022                   (*b)->height);
1023               (*b)->stream_buffer.status = BufferStatus::kError;
1024               break;
1025             }
1026             ALOGV("%s remosaic Raw16 Image", __FUNCTION__);
1027             RemosaicRAW16Image(
1028                 (uint16_t*)(*next_input_buffer->begin())->plane.img.img,
1029                 (uint16_t*)(*b)->plane.img.img, (*b)->plane.img.stride_in_bytes,
1030                 device_chars->second);
1031           }
1032           break;
1033         case PixelFormat::RGB_888:
1034           if (!reprocess_request) {
1035             CaptureRGB((*b)->plane.img.img, (*b)->width, (*b)->height,
1036                        (*b)->plane.img.stride_in_bytes, RGBLayout::RGB,
1037                        device_settings->second.gain, (*b)->color_space,
1038                        device_chars->second);
1039           } else {
1040             ALOGE("%s: Reprocess requests with output format %x no supported!",
1041                   __FUNCTION__, (*b)->format);
1042             (*b)->stream_buffer.status = BufferStatus::kError;
1043           }
1044           break;
1045         case PixelFormat::RGBA_8888:
1046           if (!reprocess_request) {
1047             CaptureRGB((*b)->plane.img.img, (*b)->width, (*b)->height,
1048                        (*b)->plane.img.stride_in_bytes, RGBLayout::RGBA,
1049                        device_settings->second.gain, (*b)->color_space,
1050                        device_chars->second);
1051           } else {
1052             ALOGE("%s: Reprocess requests with output format %x no supported!",
1053                   __FUNCTION__, (*b)->format);
1054             (*b)->stream_buffer.status = BufferStatus::kError;
1055           }
1056           break;
1057         case PixelFormat::BLOB:
1058           if ((*b)->dataSpace == HAL_DATASPACE_V0_JFIF) {
1059             YUV420Frame yuv_input{
1060                 .width = treat_as_reprocess
1061                              ? (*next_input_buffer->begin())->width
1062                              : 0,
1063                 .height = treat_as_reprocess
1064                               ? (*next_input_buffer->begin())->height
1065                               : 0,
1066                 .planes = treat_as_reprocess
1067                               ? (*next_input_buffer->begin())->plane.img_y_crcb
1068                               : YCbCrPlanes{}};
1069             auto jpeg_input = std::make_unique<JpegYUV420Input>();
1070             jpeg_input->width = (*b)->width;
1071             jpeg_input->height = (*b)->height;
1072             jpeg_input->color_space = (*b)->color_space;
1073             auto img =
1074                 new uint8_t[(jpeg_input->width * jpeg_input->height * 3) / 2];
1075             jpeg_input->yuv_planes = {
1076                 .img_y = img,
1077                 .img_cb = img + jpeg_input->width * jpeg_input->height,
1078                 .img_cr = img + (jpeg_input->width * jpeg_input->height * 5) / 4,
1079                 .y_stride = jpeg_input->width,
1080                 .cbcr_stride = jpeg_input->width / 2,
1081                 .cbcr_step = 1};
1082             jpeg_input->buffer_owner = true;
1083             YUV420Frame yuv_output{.width = jpeg_input->width,
1084                                    .height = jpeg_input->height,
1085                                    .planes = jpeg_input->yuv_planes};
1086 
1087             bool rotate = device_settings->second.rotate_and_crop ==
1088                           ANDROID_SCALER_ROTATE_AND_CROP_90;
1089             auto ret = ProcessYUV420(yuv_input, yuv_output,
1090                                      device_settings->second.gain, process_type,
1091                                      device_settings->second.zoom_ratio, rotate,
1092                                      (*b)->color_space, device_chars->second);
1093             if (ret != 0) {
1094               (*b)->stream_buffer.status = BufferStatus::kError;
1095               break;
1096             }
1097 
1098             auto jpeg_job = std::make_unique<JpegYUV420Job>();
1099             jpeg_job->exif_utils = std::unique_ptr<ExifUtils>(
1100                 ExifUtils::Create(device_chars->second));
1101             jpeg_job->input = std::move(jpeg_input);
1102             // If jpeg compression is successful, then the jpeg compressor
1103             // must set the corresponding status.
1104             (*b)->stream_buffer.status = BufferStatus::kError;
1105             std::swap(jpeg_job->output, *b);
1106             jpeg_job->result_metadata =
1107                 HalCameraMetadata::Clone(next_result->result_metadata.get());
1108 
1109             Mutex::Autolock lock(control_mutex_);
1110             jpeg_compressor_->QueueYUV420(std::move(jpeg_job));
1111           } else {
1112             ALOGE("%s: Format %x with dataspace %x is TODO", __FUNCTION__,
1113                   (*b)->format, (*b)->dataSpace);
1114             (*b)->stream_buffer.status = BufferStatus::kError;
1115           }
1116           break;
1117         case PixelFormat::YCRCB_420_SP:
1118         case PixelFormat::YCBCR_420_888: {
1119           YUV420Frame yuv_input{
1120               .width =
1121                   treat_as_reprocess ? (*next_input_buffer->begin())->width : 0,
1122               .height =
1123                   treat_as_reprocess ? (*next_input_buffer->begin())->height : 0,
1124               .planes = treat_as_reprocess
1125                             ? (*next_input_buffer->begin())->plane.img_y_crcb
1126                             : YCbCrPlanes{}};
1127           YUV420Frame yuv_output{.width = (*b)->width,
1128                                  .height = (*b)->height,
1129                                  .planes = (*b)->plane.img_y_crcb};
1130           bool rotate = device_settings->second.rotate_and_crop ==
1131                         ANDROID_SCALER_ROTATE_AND_CROP_90;
1132           auto ret =
1133               ProcessYUV420(yuv_input, yuv_output, device_settings->second.gain,
1134                             process_type, device_settings->second.zoom_ratio,
1135                             rotate, (*b)->color_space, device_chars->second);
1136           if (ret != 0) {
1137             (*b)->stream_buffer.status = BufferStatus::kError;
1138           }
1139         } break;
1140         case PixelFormat::Y16:
1141           if (!reprocess_request) {
1142             if ((*b)->dataSpace == HAL_DATASPACE_DEPTH) {
1143               CaptureDepth((*b)->plane.img.img, device_settings->second.gain,
1144                            (*b)->width, (*b)->height,
1145                            (*b)->plane.img.stride_in_bytes,
1146                            device_chars->second);
1147             } else {
1148               ALOGE("%s: Format %x with dataspace %x is TODO", __FUNCTION__,
1149                     (*b)->format, (*b)->dataSpace);
1150               (*b)->stream_buffer.status = BufferStatus::kError;
1151             }
1152           } else {
1153             ALOGE("%s: Reprocess requests with output format %x no supported!",
1154                   __FUNCTION__, (*b)->format);
1155             (*b)->stream_buffer.status = BufferStatus::kError;
1156           }
1157           break;
1158         case PixelFormat::YCBCR_P010:
1159             if (!reprocess_request) {
1160               bool rotate = device_settings->second.rotate_and_crop ==
1161                             ANDROID_SCALER_ROTATE_AND_CROP_90;
1162               YUV420Frame yuv_input{};
1163               YUV420Frame yuv_output{.width = (*b)->width,
1164                                      .height = (*b)->height,
1165                                      .planes = (*b)->plane.img_y_crcb};
1166               ProcessYUV420(yuv_input, yuv_output, device_settings->second.gain,
1167                             process_type, device_settings->second.zoom_ratio,
1168                             rotate, (*b)->color_space, device_chars->second);
1169             } else {
1170               ALOGE(
1171                   "%s: Reprocess requests with output format %x no supported!",
1172                   __FUNCTION__, (*b)->format);
1173               (*b)->stream_buffer.status = BufferStatus::kError;
1174             }
1175             break;
1176         default:
1177           ALOGE("%s: Unknown format %x, no output", __FUNCTION__, (*b)->format);
1178           (*b)->stream_buffer.status = BufferStatus::kError;
1179           break;
1180       }
1181 
1182       b = next_buffers->erase(b);
1183     }
1184   }
1185 
1186   if (reprocess_request) {
1187     auto input_buffer = next_input_buffer->begin();
1188     while (input_buffer != next_input_buffer->end()) {
1189       (*input_buffer++)->stream_buffer.status = BufferStatus::kOk;
1190     }
1191     next_input_buffer->clear();
1192   }
1193 
1194   nsecs_t work_done_real_time = getSystemTimeWithSource(timestamp_source);
1195   // Returning the results at this point is not entirely correct from timing
1196   // perspective. Under ideal conditions where 'ReturnResults' completes
1197   // in less than 'time_accuracy' we need to return the results after the
1198   // frame cycle expires. However under real conditions various system
1199   // components like SurfaceFlinger, Encoder, LMK etc. could be consuming most
1200   // of the resources and the duration of "ReturnResults" can get comparable to
1201   // 'kDefaultFrameDuration'. This will skew the frame cycle and can result in
1202   // potential frame drops. To avoid this scenario when we are running under
1203   // tight deadlines (less than 'kReturnResultThreshod') try to return the
1204   // results immediately. In all other cases with more relaxed deadlines
1205   // the occasional bump during 'ReturnResults' should not have any
1206   // noticeable effect.
1207   if ((work_done_real_time + kReturnResultThreshod) > frame_end_real_time) {
1208     ReturnResults(callback, std::move(settings), std::move(next_result),
1209                   reprocess_request, std::move(partial_result));
1210   }
1211 
1212   work_done_real_time = getSystemTimeWithSource(timestamp_source);
1213   ALOGVV("Sensor vertical blanking interval");
1214   const nsecs_t time_accuracy = 2e6;  // 2 ms of imprecision is ok
1215   if (work_done_real_time < frame_end_real_time - time_accuracy) {
1216     timespec t;
1217     t.tv_sec = (frame_end_real_time - work_done_real_time) / 1000000000L;
1218     t.tv_nsec = (frame_end_real_time - work_done_real_time) % 1000000000L;
1219 
1220     int ret;
1221     do {
1222       ret = nanosleep(&t, &t);
1223     } while (ret != 0);
1224   }
1225 
1226   ReturnResults(callback, std::move(settings), std::move(next_result),
1227                 reprocess_request, std::move(partial_result));
1228 
1229   return true;
1230 };
1231 
ReturnResults(HwlPipelineCallback callback,std::unique_ptr<LogicalCameraSettings> settings,std::unique_ptr<HwlPipelineResult> result,bool reprocess_request,std::unique_ptr<HwlPipelineResult> partial_result)1232 void EmulatedSensor::ReturnResults(
1233     HwlPipelineCallback callback,
1234     std::unique_ptr<LogicalCameraSettings> settings,
1235     std::unique_ptr<HwlPipelineResult> result, bool reprocess_request,
1236     std::unique_ptr<HwlPipelineResult> partial_result) {
1237   if ((callback.process_pipeline_result != nullptr) &&
1238       (result.get() != nullptr) && (result->result_metadata.get() != nullptr)) {
1239     auto logical_settings = settings->find(logical_camera_id_);
1240     if (logical_settings == settings->end()) {
1241       ALOGE("%s: Logical camera id: %u not found in settings!", __FUNCTION__,
1242             logical_camera_id_);
1243       return;
1244     }
1245     auto device_chars = chars_->find(logical_camera_id_);
1246     if (device_chars == chars_->end()) {
1247       ALOGE("%s: Sensor characteristics absent for device: %d", __func__,
1248             logical_camera_id_);
1249       return;
1250     }
1251     result->result_metadata->Set(ANDROID_SENSOR_TIMESTAMP, &next_capture_time_,
1252                                  1);
1253 
1254     camera_metadata_ro_entry_t lensEntry;
1255     auto lensRet = result->result_metadata->Get(
1256         ANDROID_STATISTICS_LENS_INTRINSIC_SAMPLES, &lensEntry);
1257     if ((lensRet == OK) && (lensEntry.count > 0)) {
1258       result->result_metadata->Set(ANDROID_STATISTICS_LENS_INTRINSIC_TIMESTAMPS,
1259                                    &next_capture_time_, 1);
1260     }
1261 
1262     uint8_t raw_binned_factor_used = false;
1263     if (sensor_binning_factor_info_.find(logical_camera_id_) !=
1264         sensor_binning_factor_info_.end()) {
1265       auto& info = sensor_binning_factor_info_[logical_camera_id_];
1266       // Logical stream was included in the request
1267       if (!reprocess_request && info.quad_bayer_sensor && info.max_res_request &&
1268           info.has_raw_stream && !info.has_non_raw_stream) {
1269         raw_binned_factor_used = true;
1270       }
1271       result->result_metadata->Set(ANDROID_SENSOR_RAW_BINNING_FACTOR_USED,
1272                                    &raw_binned_factor_used, 1);
1273       if (info.has_cropped_raw_stream) {
1274         if (info.raw_in_sensor_zoom_applied) {
1275           result->result_metadata->Set(
1276               ANDROID_SCALER_RAW_CROP_REGION,
1277               device_chars->second.raw_crop_region_zoomed, 4);
1278 
1279         } else {
1280           result->result_metadata->Set(
1281               ANDROID_SCALER_RAW_CROP_REGION,
1282               device_chars->second.raw_crop_region_unzoomed, 4);
1283         }
1284       }
1285     }
1286     if (logical_settings->second.lens_shading_map_mode ==
1287         ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_ON) {
1288       if ((device_chars->second.lens_shading_map_size[0] > 0) &&
1289           (device_chars->second.lens_shading_map_size[1] > 0)) {
1290         // Perfect lens, no actual shading needed.
1291         std::vector<float> lens_shading_map(
1292             device_chars->second.lens_shading_map_size[0] *
1293                 device_chars->second.lens_shading_map_size[1] * 4,
1294             1.f);
1295 
1296         result->result_metadata->Set(ANDROID_STATISTICS_LENS_SHADING_MAP,
1297                                      lens_shading_map.data(),
1298                                      lens_shading_map.size());
1299       }
1300     }
1301     if (logical_settings->second.report_video_stab) {
1302       result->result_metadata->Set(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE,
1303                                    &logical_settings->second.video_stab, 1);
1304     }
1305     if (logical_settings->second.report_edge_mode) {
1306       result->result_metadata->Set(ANDROID_EDGE_MODE,
1307                                    &logical_settings->second.edge_mode, 1);
1308     }
1309     if (logical_settings->second.report_neutral_color_point) {
1310       result->result_metadata->Set(ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
1311                                    kNeutralColorPoint,
1312                                    ARRAY_SIZE(kNeutralColorPoint));
1313     }
1314     if (logical_settings->second.report_green_split) {
1315       result->result_metadata->Set(ANDROID_SENSOR_GREEN_SPLIT, &kGreenSplit, 1);
1316     }
1317     if (logical_settings->second.report_noise_profile) {
1318       CalculateAndAppendNoiseProfile(
1319           logical_settings->second.gain,
1320           GetBaseGainFactor(device_chars->second.max_raw_value),
1321           result->result_metadata.get());
1322     }
1323     if (logical_settings->second.report_rotate_and_crop) {
1324       result->result_metadata->Set(ANDROID_SCALER_ROTATE_AND_CROP,
1325           &logical_settings->second.rotate_and_crop, 1);
1326     }
1327 
1328     if (!result->physical_camera_results.empty()) {
1329       for (auto& it : result->physical_camera_results) {
1330         auto physical_settings = settings->find(it.first);
1331         if (physical_settings == settings->end()) {
1332           ALOGE("%s: Physical settings for camera id: %u are absent!",
1333                 __FUNCTION__, it.first);
1334           continue;
1335         }
1336         uint8_t raw_binned_factor_used = false;
1337         if (sensor_binning_factor_info_.find(it.first) !=
1338             sensor_binning_factor_info_.end()) {
1339           auto& info = sensor_binning_factor_info_[it.first];
1340           // physical stream was included in the request
1341           if (!reprocess_request && info.quad_bayer_sensor &&
1342               info.max_res_request && info.has_raw_stream &&
1343               !info.has_non_raw_stream) {
1344             raw_binned_factor_used = true;
1345           }
1346           it.second->Set(ANDROID_SENSOR_RAW_BINNING_FACTOR_USED,
1347                          &raw_binned_factor_used, 1);
1348         }
1349         // Sensor timestamp for all physical devices must be the same.
1350         it.second->Set(ANDROID_SENSOR_TIMESTAMP, &next_capture_time_, 1);
1351         if (physical_settings->second.report_neutral_color_point) {
1352           it.second->Set(ANDROID_SENSOR_NEUTRAL_COLOR_POINT, kNeutralColorPoint,
1353                          ARRAY_SIZE(kNeutralColorPoint));
1354         }
1355         if (physical_settings->second.report_green_split) {
1356           it.second->Set(ANDROID_SENSOR_GREEN_SPLIT, &kGreenSplit, 1);
1357         }
1358         if (physical_settings->second.report_noise_profile) {
1359           auto device_chars = chars_->find(it.first);
1360           if (device_chars == chars_->end()) {
1361             ALOGE("%s: Sensor characteristics absent for device: %d", __func__,
1362                   it.first);
1363           }
1364           CalculateAndAppendNoiseProfile(
1365               physical_settings->second.gain,
1366               GetBaseGainFactor(device_chars->second.max_raw_value),
1367               it.second.get());
1368         }
1369       }
1370     }
1371 
1372     // Partial result count for partial result is set to a value
1373     // only when partial results are supported
1374     if (partial_result->partial_result != 0) {
1375       callback.process_pipeline_result(std::move(partial_result));
1376     }
1377     callback.process_pipeline_result(std::move(result));
1378   }
1379 }
1380 
CalculateAndAppendNoiseProfile(float gain,float base_gain_factor,HalCameraMetadata * result)1381 void EmulatedSensor::CalculateAndAppendNoiseProfile(
1382     float gain /*in ISO*/, float base_gain_factor,
1383     HalCameraMetadata* result /*out*/) {
1384   if (result != nullptr) {
1385     float total_gain = gain / 100.0 * base_gain_factor;
1386     float noise_var_gain = total_gain * total_gain;
1387     float read_noise_var =
1388         kReadNoiseVarBeforeGain * noise_var_gain + kReadNoiseVarAfterGain;
1389     // Noise profile is the same across all 4 CFA channels
1390     double noise_profile[2 * 4] = {
1391         noise_var_gain, read_noise_var, noise_var_gain, read_noise_var,
1392         noise_var_gain, read_noise_var, noise_var_gain, read_noise_var};
1393     result->Set(ANDROID_SENSOR_NOISE_PROFILE, noise_profile,
1394                 ARRAY_SIZE(noise_profile));
1395   }
1396 }
1397 
GetQuadBayerColor(uint32_t x,uint32_t y)1398 EmulatedScene::ColorChannels EmulatedSensor::GetQuadBayerColor(uint32_t x,
1399                                                                uint32_t y) {
1400   // Row within larger set of quad bayer filter
1401   uint32_t row_mod = y % 4;
1402   // Column within larger set of quad bayer filter
1403   uint32_t col_mod = x % 4;
1404 
1405   // Row is within the left quadrants of a quad bayer sensor
1406   if (row_mod < 2) {
1407     if (col_mod < 2) {
1408       return EmulatedScene::ColorChannels::R;
1409     }
1410     return EmulatedScene::ColorChannels::Gr;
1411   } else {
1412     if (col_mod < 2) {
1413       return EmulatedScene::ColorChannels::Gb;
1414     }
1415     return EmulatedScene::ColorChannels::B;
1416   }
1417 }
1418 
RemosaicQuadBayerBlock(uint16_t * img_in,uint16_t * img_out,int xstart,int ystart,int row_stride_in_bytes)1419 void EmulatedSensor::RemosaicQuadBayerBlock(uint16_t* img_in, uint16_t* img_out,
1420                                             int xstart, int ystart,
1421                                             int row_stride_in_bytes) {
1422   uint32_t quad_block_copy_idx_map[16] = {0, 2, 1, 3, 8,  10, 6,  11,
1423                                           4, 9, 5, 7, 12, 14, 13, 15};
1424   uint16_t quad_block_copy[16];
1425   uint32_t i = 0;
1426   for (uint32_t row = 0; row < 4; row++) {
1427     uint16_t* quad_bayer_row =
1428         img_in + (ystart + row) * (row_stride_in_bytes / 2) + xstart;
1429     for (uint32_t j = 0; j < 4; j++, i++) {
1430       quad_block_copy[i] = quad_bayer_row[j];
1431     }
1432   }
1433 
1434   for (uint32_t row = 0; row < 4; row++) {
1435     uint16_t* regular_bayer_row =
1436         img_out + (ystart + row) * (row_stride_in_bytes / 2) + xstart;
1437     for (uint32_t j = 0; j < 4; j++, i++) {
1438       uint32_t idx = quad_block_copy_idx_map[row + 4 * j];
1439       regular_bayer_row[j] = quad_block_copy[idx];
1440     }
1441   }
1442 }
1443 
RemosaicRAW16Image(uint16_t * img_in,uint16_t * img_out,size_t row_stride_in_bytes,const SensorCharacteristics & chars)1444 status_t EmulatedSensor::RemosaicRAW16Image(uint16_t* img_in, uint16_t* img_out,
1445                                             size_t row_stride_in_bytes,
1446                                             const SensorCharacteristics& chars) {
1447   if (chars.full_res_width % 2 != 0 || chars.full_res_height % 2 != 0) {
1448     ALOGE(
1449         "%s RAW16 Image with quad CFA, height %zu and width %zu, not multiples "
1450         "of 4",
1451         __FUNCTION__, chars.full_res_height, chars.full_res_width);
1452     return BAD_VALUE;
1453   }
1454   for (uint32_t i = 0; i < chars.full_res_width; i += 4) {
1455     for (uint32_t j = 0; j < chars.full_res_height; j += 4) {
1456       RemosaicQuadBayerBlock(img_in, img_out, i, j, row_stride_in_bytes);
1457     }
1458   }
1459   return OK;
1460 }
1461 
CaptureRawBinned(uint8_t * img,size_t row_stride_in_bytes,uint32_t gain,const SensorCharacteristics & chars)1462 void EmulatedSensor::CaptureRawBinned(uint8_t* img, size_t row_stride_in_bytes,
1463                                       uint32_t gain,
1464                                       const SensorCharacteristics& chars) {
1465   CaptureRaw(img, row_stride_in_bytes, gain, chars, /*in_sensor_zoom*/ false,
1466              /*binned*/ true);
1467   return;
1468 }
1469 
CaptureRawInSensorZoom(uint8_t * img,size_t row_stride_in_bytes,uint32_t gain,const SensorCharacteristics & chars)1470 void EmulatedSensor::CaptureRawInSensorZoom(uint8_t* img,
1471                                             size_t row_stride_in_bytes,
1472                                             uint32_t gain,
1473                                             const SensorCharacteristics& chars) {
1474   CaptureRaw(img, row_stride_in_bytes, gain, chars, /*in_sensor_zoom*/ true,
1475              /*binned*/ false);
1476   return;
1477 }
1478 
CaptureRawFullRes(uint8_t * img,size_t row_stride_in_bytes,uint32_t gain,const SensorCharacteristics & chars)1479 void EmulatedSensor::CaptureRawFullRes(uint8_t* img, size_t row_stride_in_bytes,
1480                                        uint32_t gain,
1481                                        const SensorCharacteristics& chars) {
1482   CaptureRaw(img, row_stride_in_bytes, gain, chars, /*inSensorZoom*/ false,
1483              /*binned*/ false);
1484   return;
1485 }
1486 
CaptureRaw(uint8_t * img,size_t row_stride_in_bytes,uint32_t gain,const SensorCharacteristics & chars,bool in_sensor_zoom,bool binned)1487 void EmulatedSensor::CaptureRaw(uint8_t* img, size_t row_stride_in_bytes,
1488                                 uint32_t gain,
1489                                 const SensorCharacteristics& chars,
1490                                 bool in_sensor_zoom, bool binned) {
1491   ATRACE_CALL();
1492   if (in_sensor_zoom && binned) {
1493     ALOGE("%s: Can't perform in-sensor zoom in binned mode", __FUNCTION__);
1494     return;
1495   }
1496   float total_gain = gain / 100.0 * GetBaseGainFactor(chars.max_raw_value);
1497   float noise_var_gain = total_gain * total_gain;
1498   float read_noise_var =
1499       kReadNoiseVarBeforeGain * noise_var_gain + kReadNoiseVarAfterGain;
1500 
1501   scene_->SetReadoutPixel(0, 0);
1502   // RGGB
1503   int bayer_select[4] = {EmulatedScene::R, EmulatedScene::Gr, EmulatedScene::Gb,
1504                          EmulatedScene::B};
1505   const float raw_zoom_ratio = in_sensor_zoom ? 2.0f : 1.0f;
1506   unsigned int image_width =
1507       in_sensor_zoom || binned ? chars.width : chars.full_res_width;
1508   unsigned int image_height =
1509       in_sensor_zoom || binned ? chars.height : chars.full_res_height;
1510   const float norm_left_top = 0.5f - 0.5f / raw_zoom_ratio;
1511   for (unsigned int out_y = 0; out_y < image_height; out_y++) {
1512     int* bayer_row = bayer_select + (out_y & 0x1) * 2;
1513     uint16_t* px = (uint16_t*)img + out_y * (row_stride_in_bytes / 2);
1514 
1515     float norm_y = out_y / (image_height * raw_zoom_ratio);
1516     int y = static_cast<int>(chars.full_res_height * (norm_left_top + norm_y));
1517     y = std::min(std::max(y, 0), (int)chars.full_res_height - 1);
1518 
1519     for (unsigned int out_x = 0; out_x < image_width; out_x++) {
1520       int color_idx = chars.quad_bayer_sensor && !(in_sensor_zoom || binned)
1521                           ? GetQuadBayerColor(out_x, out_y)
1522                           : bayer_row[out_x & 0x1];
1523       float norm_x = out_x / (image_width * raw_zoom_ratio);
1524       int x = static_cast<int>(chars.full_res_width * (norm_left_top + norm_x));
1525       x = std::min(std::max(x, 0), (int)chars.full_res_width - 1);
1526 
1527       uint32_t electron_count;
1528       scene_->SetReadoutPixel(x, y);
1529       electron_count = scene_->GetPixelElectrons()[color_idx];
1530 
1531       // TODO: Better pixel saturation curve?
1532       electron_count = (electron_count < kSaturationElectrons)
1533                            ? electron_count
1534                            : kSaturationElectrons;
1535 
1536       // TODO: Better A/D saturation curve?
1537       uint16_t raw_count = electron_count * total_gain;
1538       raw_count =
1539           (raw_count < chars.max_raw_value) ? raw_count : chars.max_raw_value;
1540 
1541       // Calculate noise value
1542       // TODO: Use more-correct Gaussian instead of uniform noise
1543       float photon_noise_var = electron_count * noise_var_gain;
1544       float noise_stddev = sqrtf_approx(read_noise_var + photon_noise_var);
1545       // Scaled to roughly match gaussian/uniform noise stddev
1546       float noise_sample = rand_r(&rand_seed_) * (2.5 / (1.0 + RAND_MAX)) - 1.25;
1547 
1548       raw_count += chars.black_level_pattern[color_idx];
1549       raw_count += noise_stddev * noise_sample;
1550 
1551       *px++ = raw_count;
1552     }
1553     // TODO: Handle this better
1554     // simulatedTime += mRowReadoutTime;
1555   }
1556   ALOGVV("Raw sensor image captured");
1557 }
1558 
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)1559 void EmulatedSensor::CaptureRGB(uint8_t* img, uint32_t width, uint32_t height,
1560                                 uint32_t stride, RGBLayout layout,
1561                                 uint32_t gain, int32_t color_space,
1562                                 const SensorCharacteristics& chars) {
1563   ATRACE_CALL();
1564   float total_gain = gain / 100.0 * GetBaseGainFactor(chars.max_raw_value);
1565   // In fixed-point math, calculate total scaling from electrons to 8bpp
1566   int scale64x = 64 * total_gain * 255 / chars.max_raw_value;
1567   uint32_t inc_h = ceil((float)chars.full_res_width / width);
1568   uint32_t inc_v = ceil((float)chars.full_res_height / height);
1569 
1570   for (unsigned int y = 0, outy = 0; y < chars.full_res_height;
1571        y += inc_v, outy++) {
1572     scene_->SetReadoutPixel(0, y);
1573     uint8_t* px = img + outy * stride;
1574     for (unsigned int x = 0; x < chars.full_res_width; x += inc_h) {
1575       uint32_t r_count, g_count, b_count;
1576       // TODO: Perfect demosaicing is a cheat
1577       const uint32_t* pixel = scene_->GetPixelElectrons();
1578       r_count = pixel[EmulatedScene::R] * scale64x;
1579       g_count = pixel[EmulatedScene::Gr] * scale64x;
1580       b_count = pixel[EmulatedScene::B] * scale64x;
1581 
1582       if (color_space !=
1583           ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED) {
1584         RgbToRgb(&r_count, &g_count, &b_count);
1585       }
1586 
1587       uint8_t r = r_count < 255 * 64 ? r_count / 64 : 255;
1588       uint8_t g = g_count < 255 * 64 ? g_count / 64 : 255;
1589       uint8_t b = b_count < 255 * 64 ? b_count / 64 : 255;
1590       switch (layout) {
1591         case RGB:
1592           *px++ = r;
1593           *px++ = g;
1594           *px++ = b;
1595           break;
1596         case RGBA:
1597           *px++ = r;
1598           *px++ = g;
1599           *px++ = b;
1600           *px++ = 255;
1601           break;
1602         case ARGB:
1603           *px++ = 255;
1604           *px++ = r;
1605           *px++ = g;
1606           *px++ = b;
1607           break;
1608         default:
1609           ALOGE("%s: RGB layout: %d not supported", __FUNCTION__, layout);
1610           return;
1611       }
1612       for (unsigned int j = 1; j < inc_h; j++) scene_->GetPixelElectrons();
1613     }
1614   }
1615   ALOGVV("RGB sensor image captured");
1616 }
1617 
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)1618 void EmulatedSensor::CaptureYUV420(YCbCrPlanes yuv_layout, uint32_t width,
1619                                    uint32_t height, uint32_t gain,
1620                                    float zoom_ratio, bool rotate,
1621                                    int32_t color_space,
1622                                    const SensorCharacteristics& chars) {
1623   ATRACE_CALL();
1624   float total_gain = gain / 100.0 * GetBaseGainFactor(chars.max_raw_value);
1625   // Using fixed-point math with 6 bits of fractional precision.
1626   // In fixed-point math, calculate total scaling from electrons to 8bpp
1627   const int scale64x =
1628       kFixedBitPrecision * total_gain * 255 / chars.max_raw_value;
1629   // Fixed-point coefficients for RGB-YUV transform
1630   // Based on JFIF RGB->YUV transform.
1631   // Cb/Cr offset scaled by 64x twice since they're applied post-multiply
1632   const int rgb_to_y[] = {19, 37, 7};
1633   const int rgb_to_cb[] = {-10, -21, 32, 524288};
1634   const int rgb_to_cr[] = {32, -26, -5, 524288};
1635   // Scale back to 8bpp non-fixed-point
1636   const int scale_out = 64;
1637   const int scale_out_sq = scale_out * scale_out;  // after multiplies
1638 
1639   // inc = how many pixels to skip while reading every next pixel
1640   const float aspect_ratio = static_cast<float>(width) / height;
1641 
1642   // precalculate normalized coordinates and dimensions
1643   const float norm_left_top = 0.5f - 0.5f / zoom_ratio;
1644   const float norm_rot_top = norm_left_top;
1645   const float norm_width = 1 / zoom_ratio;
1646   const float norm_rot_width = norm_width / aspect_ratio;
1647   const float norm_rot_height = norm_width;
1648   const float norm_rot_left =
1649       norm_left_top + (norm_width + norm_rot_width) * 0.5f;
1650 
1651   for (unsigned int out_y = 0; out_y < height; out_y++) {
1652     uint8_t* px_y = yuv_layout.img_y + out_y * yuv_layout.y_stride;
1653     uint8_t* px_cb = yuv_layout.img_cb + (out_y / 2) * yuv_layout.cbcr_stride;
1654     uint8_t* px_cr = yuv_layout.img_cr + (out_y / 2) * yuv_layout.cbcr_stride;
1655 
1656     for (unsigned int out_x = 0; out_x < width; out_x++) {
1657       int x, y;
1658       float norm_x = out_x / (width * zoom_ratio);
1659       float norm_y = out_y / (height * zoom_ratio);
1660       if (rotate) {
1661         x = static_cast<int>(chars.full_res_width *
1662                              (norm_rot_left - norm_y * norm_rot_width));
1663         y = static_cast<int>(chars.full_res_height *
1664                              (norm_rot_top + norm_x * norm_rot_height));
1665       } else {
1666         x = static_cast<int>(chars.full_res_width * (norm_left_top + norm_x));
1667         y = static_cast<int>(chars.full_res_height * (norm_left_top + norm_y));
1668       }
1669       x = std::min(std::max(x, 0), (int)chars.full_res_width - 1);
1670       y = std::min(std::max(y, 0), (int)chars.full_res_height - 1);
1671       scene_->SetReadoutPixel(x, y);
1672 
1673       uint32_t r_count, g_count, b_count;
1674       // TODO: Perfect demosaicing is a cheat
1675       const uint32_t* pixel = rotate ? scene_->GetPixelElectronsColumn()
1676                                      : scene_->GetPixelElectrons();
1677       r_count = pixel[EmulatedScene::R] * scale64x;
1678       g_count = pixel[EmulatedScene::Gr] * scale64x;
1679       b_count = pixel[EmulatedScene::B] * scale64x;
1680 
1681       if (color_space !=
1682           ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED) {
1683         RgbToRgb(&r_count, &g_count, &b_count);
1684       }
1685 
1686       r_count = r_count < kSaturationPoint ? r_count : kSaturationPoint;
1687       g_count = g_count < kSaturationPoint ? g_count : kSaturationPoint;
1688       b_count = b_count < kSaturationPoint ? b_count : kSaturationPoint;
1689 
1690       // Gamma correction
1691       r_count = GammaTable(r_count, color_space);
1692       g_count = GammaTable(g_count, color_space);
1693       b_count = GammaTable(b_count, color_space);
1694 
1695       uint8_t y8 = (rgb_to_y[0] * r_count + rgb_to_y[1] * g_count +
1696                     rgb_to_y[2] * b_count) /
1697                    scale_out_sq;
1698       if (yuv_layout.bytesPerPixel == 1) {
1699         *px_y = y8;
1700       } else if (yuv_layout.bytesPerPixel == 2) {
1701         *(reinterpret_cast<uint16_t*>(px_y)) = htole16(y8 << 8);
1702       } else {
1703         ALOGE("%s: Unsupported bytes per pixel value: %zu", __func__,
1704               yuv_layout.bytesPerPixel);
1705         return;
1706       }
1707       px_y += yuv_layout.bytesPerPixel;
1708 
1709       if (out_y % 2 == 0 && out_x % 2 == 0) {
1710         uint8_t cb8 = (rgb_to_cb[0] * r_count + rgb_to_cb[1] * g_count +
1711                        rgb_to_cb[2] * b_count + rgb_to_cb[3]) /
1712                       scale_out_sq;
1713         uint8_t cr8 = (rgb_to_cr[0] * r_count + rgb_to_cr[1] * g_count +
1714                        rgb_to_cr[2] * b_count + rgb_to_cr[3]) /
1715                       scale_out_sq;
1716         if (yuv_layout.bytesPerPixel == 1) {
1717           *px_cb = cb8;
1718           *px_cr = cr8;
1719         } else if (yuv_layout.bytesPerPixel == 2) {
1720           *(reinterpret_cast<uint16_t*>(px_cb)) = htole16(cb8 << 8);
1721           *(reinterpret_cast<uint16_t*>(px_cr)) = htole16(cr8 << 8);
1722         } else {
1723           ALOGE("%s: Unsupported bytes per pixel value: %zu", __func__,
1724                 yuv_layout.bytesPerPixel);
1725           return;
1726         }
1727         px_cr += yuv_layout.cbcr_step;
1728         px_cb += yuv_layout.cbcr_step;
1729       }
1730     }
1731   }
1732   ALOGVV("YUV420 sensor image captured");
1733 }
1734 
CaptureDepth(uint8_t * img,uint32_t gain,uint32_t width,uint32_t height,uint32_t stride,const SensorCharacteristics & chars)1735 void EmulatedSensor::CaptureDepth(uint8_t* img, uint32_t gain, uint32_t width,
1736                                   uint32_t height, uint32_t stride,
1737                                   const SensorCharacteristics& chars) {
1738   ATRACE_CALL();
1739   float total_gain = gain / 100.0 * GetBaseGainFactor(chars.max_raw_value);
1740   // In fixed-point math, calculate scaling factor to 13bpp millimeters
1741   int scale64x = 64 * total_gain * 8191 / chars.max_raw_value;
1742   uint32_t inc_h = ceil((float)chars.full_res_width / width);
1743   uint32_t inc_v = ceil((float)chars.full_res_height / height);
1744 
1745   for (unsigned int y = 0, out_y = 0; y < chars.full_res_height;
1746        y += inc_v, out_y++) {
1747     scene_->SetReadoutPixel(0, y);
1748     uint16_t* px = (uint16_t*)(img + (out_y * stride));
1749     for (unsigned int x = 0; x < chars.full_res_width; x += inc_h) {
1750       uint32_t depth_count;
1751       // TODO: Make up real depth scene instead of using green channel
1752       // as depth
1753       const uint32_t* pixel = scene_->GetPixelElectrons();
1754       depth_count = pixel[EmulatedScene::Gr] * scale64x;
1755 
1756       *px++ = depth_count < 8191 * 64 ? depth_count / 64 : 0;
1757       for (unsigned int j = 1; j < inc_h; j++) scene_->GetPixelElectrons();
1758     }
1759     // TODO: Handle this better
1760     // simulatedTime += mRowReadoutTime;
1761   }
1762   ALOGVV("Depth sensor image captured");
1763 }
1764 
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)1765 status_t EmulatedSensor::ProcessYUV420(const YUV420Frame& input,
1766                                        const YUV420Frame& output, uint32_t gain,
1767                                        ProcessType process_type,
1768                                        float zoom_ratio, bool rotate_and_crop,
1769                                        int32_t color_space,
1770                                        const SensorCharacteristics& chars) {
1771   ATRACE_CALL();
1772   size_t input_width, input_height;
1773   YCbCrPlanes input_planes, output_planes;
1774   std::vector<uint8_t> temp_yuv, temp_output_uv, temp_input_uv;
1775 
1776   // Overwrite HIGH_QUALITY to REGULAR for Emulator if property
1777   // ro.boot.qemu.camera_hq_edge_processing is false;
1778   if (process_type == HIGH_QUALITY &&
1779       !property_get_bool("ro.boot.qemu.camera_hq_edge_processing", true)) {
1780     process_type = REGULAR;
1781   }
1782 
1783   size_t bytes_per_pixel = output.planes.bytesPerPixel;
1784   switch (process_type) {
1785     case HIGH_QUALITY:
1786       CaptureYUV420(output.planes, output.width, output.height, gain,
1787                     zoom_ratio, rotate_and_crop, color_space, chars);
1788       return OK;
1789     case REPROCESS:
1790       input_width = input.width;
1791       input_height = input.height;
1792       input_planes = input.planes;
1793 
1794       // libyuv only supports planar YUV420 during scaling.
1795       // Split the input U/V plane in separate planes if needed.
1796       if (input_planes.cbcr_step == 2) {
1797         temp_input_uv.resize(input_width * input_height / 2);
1798         auto temp_uv_buffer = temp_input_uv.data();
1799         input_planes.img_cb = temp_uv_buffer;
1800         input_planes.img_cr = temp_uv_buffer + (input_width * input_height) / 4;
1801         input_planes.cbcr_stride = input_width / 2;
1802         if (input.planes.img_cb < input.planes.img_cr) {
1803           libyuv::SplitUVPlane(input.planes.img_cb, input.planes.cbcr_stride,
1804                                input_planes.img_cb, input_planes.cbcr_stride,
1805                                input_planes.img_cr, input_planes.cbcr_stride,
1806                                input_width / 2, input_height / 2);
1807         } else {
1808           libyuv::SplitUVPlane(input.planes.img_cr, input.planes.cbcr_stride,
1809                                input_planes.img_cr, input_planes.cbcr_stride,
1810                                input_planes.img_cb, input_planes.cbcr_stride,
1811                                input_width / 2, input_height / 2);
1812         }
1813       }
1814       break;
1815     case REGULAR:
1816     default:
1817       // Generate the smallest possible frame with the expected AR and
1818       // then scale using libyuv.
1819       float aspect_ratio = static_cast<float>(output.width) / output.height;
1820       zoom_ratio = std::max(1.f, zoom_ratio);
1821       input_width = EmulatedScene::kSceneWidth * aspect_ratio;
1822       input_height = EmulatedScene::kSceneHeight;
1823       temp_yuv.reserve((input_width * input_height * 3 * bytes_per_pixel) / 2);
1824       auto temp_yuv_buffer = temp_yuv.data();
1825       input_planes = {
1826           .img_y = temp_yuv_buffer,
1827           .img_cb =
1828               temp_yuv_buffer + input_width * input_height * bytes_per_pixel,
1829           .img_cr = temp_yuv_buffer +
1830                     (input_width * input_height * bytes_per_pixel * 5) / 4,
1831           .y_stride = static_cast<uint32_t>(input_width * bytes_per_pixel),
1832           .cbcr_stride =
1833               static_cast<uint32_t>(input_width * bytes_per_pixel) / 2,
1834           .cbcr_step = 1,
1835           .bytesPerPixel = bytes_per_pixel};
1836       CaptureYUV420(input_planes, input_width, input_height, gain, zoom_ratio,
1837                     rotate_and_crop, color_space, chars);
1838   }
1839 
1840   output_planes = output.planes;
1841   // libyuv only supports planar YUV420 during scaling.
1842   // Treat the output UV space as planar first and then
1843   // interleave in the second step.
1844   if (output_planes.cbcr_step == 2) {
1845     temp_output_uv.resize(output.width * output.height * bytes_per_pixel / 2);
1846     auto temp_uv_buffer = temp_output_uv.data();
1847     output_planes.img_cb = temp_uv_buffer;
1848     output_planes.img_cr =
1849         temp_uv_buffer + output.width * output.height * bytes_per_pixel / 4;
1850     output_planes.cbcr_stride = output.width * bytes_per_pixel / 2;
1851   }
1852 
1853   // NOTE: libyuv takes strides in pixels, not bytes.
1854   int ret = 0;
1855   if (bytes_per_pixel == 2) {
1856     ret = I420Scale_16((const uint16_t*)input_planes.img_y,
1857                        input_planes.y_stride / bytes_per_pixel,
1858                        (const uint16_t*)input_planes.img_cb,
1859                        input_planes.cbcr_stride / bytes_per_pixel,
1860                        (const uint16_t*)input_planes.img_cr,
1861                        input_planes.cbcr_stride / bytes_per_pixel, input_width,
1862                        input_height, (uint16_t*)output_planes.img_y,
1863                        output_planes.y_stride / bytes_per_pixel,
1864                        (uint16_t*)output_planes.img_cb,
1865                        output_planes.cbcr_stride / bytes_per_pixel,
1866                        (uint16_t*)output_planes.img_cr,
1867                        output_planes.cbcr_stride / bytes_per_pixel,
1868                        output.width, output.height, libyuv::kFilterNone);
1869   } else {
1870     ret = I420Scale(input_planes.img_y, input_planes.y_stride,
1871                     input_planes.img_cb, input_planes.cbcr_stride,
1872                     input_planes.img_cr, input_planes.cbcr_stride, input_width,
1873                     input_height, output_planes.img_y, output_planes.y_stride,
1874                     output_planes.img_cb, output_planes.cbcr_stride,
1875                     output_planes.img_cr, output_planes.cbcr_stride,
1876                     output.width, output.height, libyuv::kFilterNone);
1877   }
1878   if (ret != 0) {
1879     ALOGE("%s: Failed during YUV scaling: %d", __FUNCTION__, ret);
1880     return ret;
1881   }
1882 
1883   // Merge U/V Planes for the interleaved case
1884   if (output_planes.cbcr_step == 2) {
1885     if (output.planes.img_cb < output.planes.img_cr) {
1886       if (bytes_per_pixel == 2) {
1887         libyuv::MergeUVPlane_16((const uint16_t*)output_planes.img_cb,
1888                                 output_planes.cbcr_stride / bytes_per_pixel,
1889                                 (const uint16_t*)output_planes.img_cr,
1890                                 output_planes.cbcr_stride / bytes_per_pixel,
1891                                 (uint16_t*)output.planes.img_cb,
1892                                 output.planes.cbcr_stride / bytes_per_pixel,
1893                                 output.width / 2, output.height / 2,
1894                                 /*depth*/ 16);
1895       } else {
1896         libyuv::MergeUVPlane(output_planes.img_cb, output_planes.cbcr_stride,
1897                              output_planes.img_cr, output_planes.cbcr_stride,
1898                              output.planes.img_cb, output.planes.cbcr_stride,
1899                              output.width / 2, output.height / 2);
1900       }
1901     } else {
1902       if (bytes_per_pixel == 2) {
1903         libyuv::MergeUVPlane_16((const uint16_t*)output_planes.img_cr,
1904                                 output_planes.cbcr_stride / bytes_per_pixel,
1905                                 (const uint16_t*)output_planes.img_cb,
1906                                 output_planes.cbcr_stride / bytes_per_pixel,
1907                                 (uint16_t*)output.planes.img_cr,
1908                                 output.planes.cbcr_stride / bytes_per_pixel,
1909                                 output.width / 2, output.height / 2,
1910                                 /*depth*/ 16);
1911       } else {
1912         libyuv::MergeUVPlane(output_planes.img_cr, output_planes.cbcr_stride,
1913                              output_planes.img_cb, output_planes.cbcr_stride,
1914                              output.planes.img_cr, output.planes.cbcr_stride,
1915                              output.width / 2, output.height / 2);
1916       }
1917     }
1918   }
1919 
1920   return ret;
1921 }
1922 
ApplysRGBGamma(int32_t value,int32_t saturation)1923 int32_t EmulatedSensor::ApplysRGBGamma(int32_t value, int32_t saturation) {
1924   float n_value = (static_cast<float>(value) / saturation);
1925   n_value = (n_value <= 0.0031308f)
1926                 ? n_value * 12.92f
1927                 : 1.055f * pow(n_value, 0.4166667f) - 0.055f;
1928   return n_value * saturation;
1929 }
1930 
ApplySMPTE170MGamma(int32_t value,int32_t saturation)1931 int32_t EmulatedSensor::ApplySMPTE170MGamma(int32_t value, int32_t saturation) {
1932   float n_value = (static_cast<float>(value) / saturation);
1933   n_value = (n_value <= 0.018f) ? n_value * 4.5f
1934                                 : 1.099f * pow(n_value, 0.45f) - 0.099f;
1935   return n_value * saturation;
1936 }
1937 
ApplyST2084Gamma(int32_t value,int32_t saturation)1938 int32_t EmulatedSensor::ApplyST2084Gamma(int32_t value, int32_t saturation) {
1939   float n_value = (static_cast<float>(value) / saturation);
1940   float c2 = 32.f * 2413.f / 4096.f;
1941   float c3 = 32.f * 2392.f / 4096.f;
1942   float c1 = c3 - c2 + 1.f;
1943   float m = 128.f * 2523.f / 4096.f;
1944   float n = 0.25f * 2610.f / 4096.f;
1945   n_value = pow((c1 + c2 * pow(n_value, n)) / (1 + c3 * pow(n_value, n)), m);
1946   return n_value * saturation;
1947 }
1948 
ApplyHLGGamma(int32_t value,int32_t saturation)1949 int32_t EmulatedSensor::ApplyHLGGamma(int32_t value, int32_t saturation) {
1950   float n_value = (static_cast<float>(value) / saturation);
1951   // The full HLG gamma curve has additional parameters for n_value > 1, but n_value
1952   // in the emulated camera is always <= 1 due to lack of HDR display features.
1953   n_value = 0.5f * pow(n_value, 0.5f);
1954   return n_value * saturation;
1955 }
1956 
GammaTable(int32_t value,int32_t color_space)1957 int32_t EmulatedSensor::GammaTable(int32_t value, int32_t color_space) {
1958   switch (color_space) {
1959     case ColorSpaceNamed::BT709:
1960       return gamma_table_smpte170m_[value];
1961     case ColorSpaceNamed::BT2020:
1962       return gamma_table_hlg_[value];  // Assume HLG
1963     case ColorSpaceNamed::DISPLAY_P3:
1964     case ColorSpaceNamed::SRGB:
1965     default:
1966       return gamma_table_sRGB_[value];
1967   }
1968 
1969   return 0;
1970 }
1971 
RgbToRgb(uint32_t * r_count,uint32_t * g_count,uint32_t * b_count)1972 void EmulatedSensor::RgbToRgb(uint32_t* r_count, uint32_t* g_count,
1973                               uint32_t* b_count) {
1974   uint32_t r = *r_count;
1975   uint32_t g = *g_count;
1976   uint32_t b = *b_count;
1977   *r_count = (uint32_t)std::max(
1978       r * rgb_rgb_matrix_.rR + g * rgb_rgb_matrix_.gR + b * rgb_rgb_matrix_.bR,
1979       0.0f);
1980   *g_count = (uint32_t)std::max(
1981       r * rgb_rgb_matrix_.rG + g * rgb_rgb_matrix_.gG + b * rgb_rgb_matrix_.bG,
1982       0.0f);
1983   *b_count = (uint32_t)std::max(
1984       r * rgb_rgb_matrix_.rB + g * rgb_rgb_matrix_.gB + b * rgb_rgb_matrix_.bB,
1985       0.0f);
1986 }
1987 
CalculateRgbRgbMatrix(int32_t color_space,const SensorCharacteristics & chars)1988 void EmulatedSensor::CalculateRgbRgbMatrix(int32_t color_space,
1989                                            const SensorCharacteristics& chars) {
1990   const XyzMatrix* xyzMatrix;
1991   switch (color_space) {
1992     case ColorSpaceNamed::DISPLAY_P3:
1993       xyzMatrix = &kDisplayP3Matrix;
1994       break;
1995     case ColorSpaceNamed::BT709:
1996       xyzMatrix = &kBt709Matrix;
1997       break;
1998     case ColorSpaceNamed::BT2020:
1999       xyzMatrix = &kBt2020Matrix;
2000       break;
2001     case ColorSpaceNamed::SRGB:
2002     default:
2003       xyzMatrix = &kSrgbXyzMatrix;
2004       break;
2005   }
2006 
2007   rgb_rgb_matrix_.rR = xyzMatrix->xR * chars.forward_matrix.rX +
2008                        xyzMatrix->yR * chars.forward_matrix.rY +
2009                        xyzMatrix->zR * chars.forward_matrix.rZ;
2010   rgb_rgb_matrix_.gR = xyzMatrix->xR * chars.forward_matrix.gX +
2011                        xyzMatrix->yR * chars.forward_matrix.gY +
2012                        xyzMatrix->zR * chars.forward_matrix.gZ;
2013   rgb_rgb_matrix_.bR = xyzMatrix->xR * chars.forward_matrix.bX +
2014                        xyzMatrix->yR * chars.forward_matrix.bY +
2015                        xyzMatrix->zR * chars.forward_matrix.bZ;
2016   rgb_rgb_matrix_.rG = xyzMatrix->xG * chars.forward_matrix.rX +
2017                        xyzMatrix->yG * chars.forward_matrix.rY +
2018                        xyzMatrix->zG * chars.forward_matrix.rZ;
2019   rgb_rgb_matrix_.gG = xyzMatrix->xG * chars.forward_matrix.gX +
2020                        xyzMatrix->yG * chars.forward_matrix.gY +
2021                        xyzMatrix->zG * chars.forward_matrix.gZ;
2022   rgb_rgb_matrix_.bG = xyzMatrix->xG * chars.forward_matrix.bX +
2023                        xyzMatrix->yG * chars.forward_matrix.bY +
2024                        xyzMatrix->zG * chars.forward_matrix.bZ;
2025   rgb_rgb_matrix_.rB = xyzMatrix->xB * chars.forward_matrix.rX +
2026                        xyzMatrix->yB * chars.forward_matrix.rY +
2027                        xyzMatrix->zB * chars.forward_matrix.rZ;
2028   rgb_rgb_matrix_.gB = xyzMatrix->xB * chars.forward_matrix.gX +
2029                        xyzMatrix->yB * chars.forward_matrix.gY +
2030                        xyzMatrix->zB * chars.forward_matrix.gZ;
2031   rgb_rgb_matrix_.bB = xyzMatrix->xB * chars.forward_matrix.bX +
2032                        xyzMatrix->yB * chars.forward_matrix.bY +
2033                        xyzMatrix->zB * chars.forward_matrix.bZ;
2034 }
2035 
2036 }  // namespace android
2037