1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "EmulatedRequestState"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 
20 #include "EmulatedRequestState.h"
21 
22 #include <inttypes.h>
23 #include <log/log.h>
24 #include <utils/HWLUtils.h>
25 
26 #include "EmulatedRequestProcessor.h"
27 
28 namespace android {
29 
30 using google_camera_hal::HwlPipelineResult;
31 
32 const std::set<uint8_t> EmulatedRequestState::kSupportedCapabilites = {
33     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE,
34     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR,
35     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MANUAL_POST_PROCESSING,
36     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_RAW,
37     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_READ_SENSOR_SETTINGS,
38     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE,
39     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_DEPTH_OUTPUT,
40     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING,
41     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING,
42     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA,
43     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_REMOSAIC_REPROCESSING,
44     ANDROID_REQUEST_AVAILABLE_CAPABILITIES_ULTRA_HIGH_RESOLUTION_SENSOR};
45 
46 const std::set<uint8_t> EmulatedRequestState::kSupportedHWLevels = {
47     ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED,
48     ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_FULL,
49     ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_3,
50 };
51 
52 template <typename T>
GetClosestValue(T val,T min,T max)53 T GetClosestValue(T val, T min, T max) {
54   if ((min > max) || ((val >= min) && (val <= max))) {
55     return val;
56   } else if (val > max) {
57     return max;
58   } else {
59     return min;
60   }
61 }
62 
Update3AMeteringRegion(uint32_t tag,const HalCameraMetadata & settings,int32_t * region)63 status_t EmulatedRequestState::Update3AMeteringRegion(
64     uint32_t tag, const HalCameraMetadata& settings, int32_t* region /*out*/) {
65   if ((region == nullptr) || ((tag != ANDROID_CONTROL_AE_REGIONS) &&
66                               (tag != ANDROID_CONTROL_AF_REGIONS) &&
67                               (tag != ANDROID_CONTROL_AWB_REGIONS))) {
68     return BAD_VALUE;
69   }
70 
71   camera_metadata_ro_entry_t entry;
72   auto ret = settings.Get(ANDROID_SCALER_CROP_REGION, &entry);
73   if ((ret == OK) && (entry.count > 0)) {
74     int32_t crop_region[4];
75     crop_region[0] = entry.data.i32[0];
76     crop_region[1] = entry.data.i32[1];
77     crop_region[2] = entry.data.i32[2] + crop_region[0];
78     crop_region[3] = entry.data.i32[3] + crop_region[1];
79     ret = settings.Get(tag, &entry);
80     if ((ret == OK) && (entry.count > 0)) {
81       const int32_t* a_region = entry.data.i32;
82       // calculate the intersection of 3A and CROP regions
83       if (a_region[0] < crop_region[2] && crop_region[0] < a_region[2] &&
84           a_region[1] < crop_region[3] && crop_region[1] < a_region[3]) {
85         region[0] = std::max(a_region[0], crop_region[0]);
86         region[1] = std::max(a_region[1], crop_region[1]);
87         region[2] = std::min(a_region[2], crop_region[2]);
88         region[3] = std::min(a_region[3], crop_region[3]);
89         region[4] = entry.data.i32[4];
90       }
91     }
92   }
93 
94   return OK;
95 }
96 
CompensateAE()97 status_t EmulatedRequestState::CompensateAE() {
98   if (!exposure_compensation_supported_) {
99     sensor_exposure_time_ = current_exposure_time_;
100     return OK;
101   }
102 
103   camera_metadata_ro_entry_t entry;
104   auto ret =
105       request_settings_->Get(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION, &entry);
106   if ((ret == OK) && (entry.count == 1)) {
107     exposure_compensation_ = entry.data.i32[0];
108   } else {
109     ALOGW("%s: AE compensation absent from request,  re-using previous value!",
110           __FUNCTION__);
111   }
112 
113   float ae_compensation = ::powf(
114       2, exposure_compensation_ *
115              ((static_cast<float>(exposure_compensation_step_.numerator) /
116                exposure_compensation_step_.denominator)));
117 
118   sensor_exposure_time_ = GetClosestValue(
119       static_cast<nsecs_t>(ae_compensation * current_exposure_time_),
120       sensor_exposure_time_range_.first, sensor_exposure_time_range_.second);
121 
122   return OK;
123 }
124 
DoFakeAE()125 status_t EmulatedRequestState::DoFakeAE() {
126   camera_metadata_ro_entry_t entry;
127   auto ret = request_settings_->Get(ANDROID_CONTROL_AE_LOCK, &entry);
128   if ((ret == OK) && (entry.count == 1)) {
129     ae_lock_ = entry.data.u8[0];
130   } else {
131     ae_lock_ = ANDROID_CONTROL_AE_LOCK_OFF;
132   }
133 
134   if (ae_lock_ == ANDROID_CONTROL_AE_LOCK_ON) {
135     ae_state_ = ANDROID_CONTROL_AE_STATE_LOCKED;
136     return OK;
137   }
138 
139   FPSRange fps_range;
140   ret = request_settings_->Get(ANDROID_CONTROL_AE_TARGET_FPS_RANGE, &entry);
141   if ((ret == OK) && (entry.count == 2)) {
142     for (const auto& it : available_fps_ranges_) {
143       if ((it.min_fps == entry.data.i32[0]) &&
144           (it.max_fps == entry.data.i32[1])) {
145         fps_range = {entry.data.i32[0], entry.data.i32[1]};
146         break;
147       }
148     }
149     if (fps_range.max_fps == 0) {
150       ALOGE("%s: Unsupported framerate range [%d, %d]", __FUNCTION__,
151             entry.data.i32[0], entry.data.i32[1]);
152       return BAD_VALUE;
153     }
154   } else {
155     fps_range = *available_fps_ranges_.begin();
156   }
157 
158   ret = request_settings_->Get(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &entry);
159   if ((ret == OK) && (entry.count == 1)) {
160     ae_trigger_ = entry.data.u8[0];
161   } else {
162     ae_trigger_ = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
163   }
164 
165   nsecs_t min_frame_duration =
166       GetClosestValue(ms2ns(1000 / fps_range.max_fps),
167                       EmulatedSensor::kSupportedFrameDurationRange[0],
168                       sensor_max_frame_duration_);
169   nsecs_t max_frame_duration =
170       GetClosestValue(ms2ns(1000 / fps_range.min_fps),
171                       EmulatedSensor::kSupportedFrameDurationRange[0],
172                       sensor_max_frame_duration_);
173   sensor_frame_duration_ = (max_frame_duration + min_frame_duration) / 2;
174 
175   // Face priority mode usually changes the AE algorithm behavior by
176   // using the regions of interest associated with detected faces.
177   // Try to emulate this behavior by slightly increasing the target exposure
178   // time compared to normal operation.
179   if (exposure_compensation_supported_) {
180     float max_ae_compensation = ::powf(
181         2, exposure_compensation_range_[1] *
182                ((static_cast<float>(exposure_compensation_step_.numerator) /
183                  exposure_compensation_step_.denominator)));
184     ae_target_exposure_time_ = GetClosestValue(
185         static_cast<nsecs_t>(sensor_frame_duration_ / max_ae_compensation),
186         sensor_exposure_time_range_.first, sensor_exposure_time_range_.second);
187   } else if (scene_mode_ == ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY) {
188     ae_target_exposure_time_ = GetClosestValue(
189         sensor_frame_duration_ / 4, sensor_exposure_time_range_.first,
190         sensor_exposure_time_range_.second);
191   } else {
192     ae_target_exposure_time_ = GetClosestValue(
193         sensor_frame_duration_ / 5, sensor_exposure_time_range_.first,
194         sensor_exposure_time_range_.second);
195   }
196 
197   if ((ae_trigger_ == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START) ||
198       (ae_state_ == ANDROID_CONTROL_AE_STATE_PRECAPTURE)) {
199     if (ae_state_ != ANDROID_CONTROL_AE_STATE_PRECAPTURE) {
200       ae_frame_counter_ = 0;
201     }
202 
203     if (ae_trigger_ == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) {
204       // Done with precapture
205       ae_frame_counter_ = 0;
206       ae_state_ = ANDROID_CONTROL_AE_STATE_CONVERGED;
207       ae_trigger_ = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL;
208     } else if ((ae_frame_counter_ > kAEPrecaptureMinFrames) &&
209                (abs(ae_target_exposure_time_ - current_exposure_time_) <
210                 ae_target_exposure_time_ / kAETargetThreshold)) {
211       // Done with precapture
212       ae_frame_counter_ = 0;
213       ae_state_ = ANDROID_CONTROL_AE_STATE_CONVERGED;
214       ae_trigger_ = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
215     } else {
216       // Converge some more
217       current_exposure_time_ +=
218           (ae_target_exposure_time_ - current_exposure_time_) *
219           kExposureTrackRate;
220       ae_frame_counter_++;
221       ae_state_ = ANDROID_CONTROL_AE_STATE_PRECAPTURE;
222     }
223   } else {
224     switch (ae_state_) {
225       case ANDROID_CONTROL_AE_STATE_INACTIVE:
226         ae_state_ = ANDROID_CONTROL_AE_STATE_SEARCHING;
227         break;
228       case ANDROID_CONTROL_AE_STATE_CONVERGED:
229         ae_frame_counter_++;
230         if (ae_frame_counter_ > kStableAeMaxFrames) {
231           float exposure_step = ((double)rand_r(&rand_seed_) / RAND_MAX) *
232                                     (kExposureWanderMax - kExposureWanderMin) +
233                                 kExposureWanderMin;
234           ae_target_exposure_time_ =
235               GetClosestValue(static_cast<nsecs_t>(ae_target_exposure_time_ *
236                                                    std::pow(2, exposure_step)),
237                               sensor_exposure_time_range_.first,
238                               sensor_exposure_time_range_.second);
239           ae_state_ = ANDROID_CONTROL_AE_STATE_SEARCHING;
240         }
241         break;
242       case ANDROID_CONTROL_AE_STATE_SEARCHING:
243         current_exposure_time_ +=
244             (ae_target_exposure_time_ - current_exposure_time_) *
245             kExposureTrackRate;
246         if (abs(ae_target_exposure_time_ - current_exposure_time_) <
247             ae_target_exposure_time_ / kAETargetThreshold) {
248           // Close enough
249           ae_state_ = ANDROID_CONTROL_AE_STATE_CONVERGED;
250           ae_frame_counter_ = 0;
251         }
252         break;
253       case ANDROID_CONTROL_AE_STATE_LOCKED:
254         ae_state_ = ANDROID_CONTROL_AE_STATE_CONVERGED;
255         ae_frame_counter_ = 0;
256         break;
257       default:
258         ALOGE("%s: Unexpected AE state %d!", __FUNCTION__, ae_state_);
259         return INVALID_OPERATION;
260     }
261   }
262 
263   return OK;
264 }
265 
ProcessAWB()266 status_t EmulatedRequestState::ProcessAWB() {
267   if (max_awb_regions_ > 0) {
268     auto ret = Update3AMeteringRegion(ANDROID_CONTROL_AWB_REGIONS,
269                                       *request_settings_, awb_metering_region_);
270     if (ret != OK) {
271       return ret;
272     }
273   }
274   if (((awb_mode_ == ANDROID_CONTROL_AWB_MODE_OFF) ||
275        (control_mode_ == ANDROID_CONTROL_MODE_OFF)) &&
276       supports_manual_post_processing_) {
277     // TODO: Add actual manual support
278   } else if (is_backward_compatible_) {
279     camera_metadata_ro_entry_t entry;
280     auto ret = request_settings_->Get(ANDROID_CONTROL_AWB_LOCK, &entry);
281     if ((ret == OK) && (entry.count == 1)) {
282       awb_lock_ = entry.data.u8[0];
283     } else {
284       awb_lock_ = ANDROID_CONTROL_AWB_LOCK_OFF;
285     }
286 
287     if (awb_lock_ == ANDROID_CONTROL_AWB_LOCK_ON) {
288       awb_state_ = ANDROID_CONTROL_AWB_STATE_LOCKED;
289     } else {
290       awb_state_ = ANDROID_CONTROL_AWB_STATE_CONVERGED;
291     }
292   } else {
293     // No color output support no need for AWB
294   }
295 
296   return OK;
297 }
298 
ProcessAF()299 status_t EmulatedRequestState::ProcessAF() {
300   camera_metadata_ro_entry entry;
301 
302   if (max_af_regions_ > 0) {
303     auto ret = Update3AMeteringRegion(ANDROID_CONTROL_AF_REGIONS,
304                                       *request_settings_, af_metering_region_);
305     if (ret != OK) {
306       return ret;
307     }
308   }
309   if (af_mode_ == ANDROID_CONTROL_AF_MODE_OFF) {
310     camera_metadata_ro_entry_t entry;
311     auto ret = request_settings_->Get(ANDROID_LENS_FOCUS_DISTANCE, &entry);
312     if ((ret == OK) && (entry.count == 1)) {
313       if ((entry.data.f[0] >= 0.f) &&
314           (entry.data.f[0] <= minimum_focus_distance_)) {
315         focus_distance_ = entry.data.f[0];
316       } else {
317         ALOGE(
318             "%s: Unsupported focus distance, It should be within "
319             "[%5.2f, %5.2f]",
320             __FUNCTION__, 0.f, minimum_focus_distance_);
321       }
322     }
323 
324     af_state_ = ANDROID_CONTROL_AF_STATE_INACTIVE;
325     return OK;
326   }
327 
328   auto ret = request_settings_->Get(ANDROID_CONTROL_AF_TRIGGER, &entry);
329   if ((ret == OK) && (entry.count == 1)) {
330     af_trigger_ = entry.data.u8[0];
331   } else {
332     af_trigger_ = ANDROID_CONTROL_AF_TRIGGER_IDLE;
333   }
334 
335   /**
336    * Simulate AF triggers. Transition at most 1 state per frame.
337    * - Focusing always succeeds (goes into locked, or PASSIVE_SCAN).
338    */
339 
340   bool af_trigger_start = false;
341   switch (af_trigger_) {
342     case ANDROID_CONTROL_AF_TRIGGER_IDLE:
343       break;
344     case ANDROID_CONTROL_AF_TRIGGER_START:
345       af_trigger_start = true;
346       break;
347     case ANDROID_CONTROL_AF_TRIGGER_CANCEL:
348       // Cancel trigger always transitions into INACTIVE
349       af_state_ = ANDROID_CONTROL_AF_STATE_INACTIVE;
350 
351       // Stay in 'inactive' until at least next frame
352       return OK;
353     default:
354       ALOGE("%s: Unknown AF trigger value", __FUNCTION__);
355       return BAD_VALUE;
356   }
357 
358   // If we get down here, we're either in ANDROID_CONTROL_AF_MODE_AUTO,
359   // ANDROID_CONTROL_AF_MODE_MACRO, ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO,
360   // ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE and no other modes like
361   // ANDROID_CONTROL_AF_MODE_OFF or ANDROID_CONTROL_AF_MODE_EDOF
362   switch (af_state_) {
363     case ANDROID_CONTROL_AF_STATE_INACTIVE:
364       if (af_trigger_start) {
365         switch (af_mode_) {
366           case ANDROID_CONTROL_AF_MODE_AUTO:
367             // fall-through
368           case ANDROID_CONTROL_AF_MODE_MACRO:
369             af_state_ = ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN;
370             break;
371           case ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO:
372             // fall-through
373           case ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE:
374             af_state_ = ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED;
375             break;
376         }
377       } else {
378         // At least one frame stays in INACTIVE
379         if (!af_mode_changed_) {
380           switch (af_mode_) {
381             case ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO:
382               // fall-through
383             case ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE:
384               af_state_ = ANDROID_CONTROL_AF_STATE_PASSIVE_SCAN;
385               break;
386           }
387         }
388       }
389       break;
390     case ANDROID_CONTROL_AF_STATE_PASSIVE_SCAN:
391       /**
392        * When the AF trigger is activated, the algorithm should finish
393        * its PASSIVE_SCAN if active, and then transition into AF_FOCUSED
394        * or AF_NOT_FOCUSED as appropriate
395        */
396       if (af_trigger_start) {
397         // Randomly transition to focused or not focused
398         if (rand_r(&rand_seed_) % 3) {
399           af_state_ = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
400         } else {
401           af_state_ = ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED;
402         }
403       }
404       /**
405        * When the AF trigger is not involved, the AF algorithm should
406        * start in INACTIVE state, and then transition into PASSIVE_SCAN
407        * and PASSIVE_FOCUSED states
408        */
409       else {
410         // Randomly transition to passive focus
411         if (rand_r(&rand_seed_) % 3 == 0) {
412           af_state_ = ANDROID_CONTROL_AF_STATE_PASSIVE_FOCUSED;
413         }
414       }
415 
416       break;
417     case ANDROID_CONTROL_AF_STATE_PASSIVE_FOCUSED:
418       if (af_trigger_start) {
419         // Randomly transition to focused or not focused
420         if (rand_r(&rand_seed_) % 3) {
421           af_state_ = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
422         } else {
423           af_state_ = ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED;
424         }
425       }
426       // TODO: initiate passive scan (PASSIVE_SCAN)
427       break;
428     case ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN:
429       // Simulate AF sweep completing instantaneously
430 
431       // Randomly transition to focused or not focused
432       if (rand_r(&rand_seed_) % 3) {
433         af_state_ = ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED;
434       } else {
435         af_state_ = ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED;
436       }
437       break;
438     case ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED:
439       if (af_trigger_start) {
440         switch (af_mode_) {
441           case ANDROID_CONTROL_AF_MODE_AUTO:
442             // fall-through
443           case ANDROID_CONTROL_AF_MODE_MACRO:
444             af_state_ = ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN;
445             break;
446           case ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO:
447             // fall-through
448           case ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE:
449             // continuous autofocus => trigger start has no effect
450             break;
451         }
452       }
453       break;
454     case ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED:
455       if (af_trigger_start) {
456         switch (af_mode_) {
457           case ANDROID_CONTROL_AF_MODE_AUTO:
458             // fall-through
459           case ANDROID_CONTROL_AF_MODE_MACRO:
460             af_state_ = ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN;
461             break;
462           case ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO:
463             // fall-through
464           case ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE:
465             // continuous autofocus => trigger start has no effect
466             break;
467         }
468       }
469       break;
470     default:
471       ALOGE("%s: Bad af state %d", __FUNCTION__, af_state_);
472   }
473 
474   return OK;
475 }
476 
ProcessAE()477 status_t EmulatedRequestState::ProcessAE() {
478   if (max_ae_regions_ > 0) {
479     auto ret = Update3AMeteringRegion(ANDROID_CONTROL_AE_REGIONS,
480                                       *request_settings_, ae_metering_region_);
481     if (ret != OK) {
482       ALOGE("%s: Failed updating the 3A metering regions: %d, (%s)",
483             __FUNCTION__, ret, strerror(-ret));
484     }
485   }
486 
487   camera_metadata_ro_entry_t entry;
488   bool auto_ae_mode = false;
489   bool auto_ae_flash_mode = false;
490   switch (ae_mode_) {
491     case ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH:
492     case ANDROID_CONTROL_AE_MODE_ON_ALWAYS_FLASH:
493     case ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE:
494       auto_ae_flash_mode = true;
495       [[fallthrough]];
496     case ANDROID_CONTROL_AE_MODE_ON:
497       auto_ae_mode = true;
498   };
499   if (((ae_mode_ == ANDROID_CONTROL_AE_MODE_OFF) ||
500        (control_mode_ == ANDROID_CONTROL_MODE_OFF)) &&
501       supports_manual_sensor_) {
502     auto ret = request_settings_->Get(ANDROID_SENSOR_EXPOSURE_TIME, &entry);
503     if ((ret == OK) && (entry.count == 1)) {
504       if ((entry.data.i64[0] >= sensor_exposure_time_range_.first) &&
505           (entry.data.i64[0] <= sensor_exposure_time_range_.second)) {
506         sensor_exposure_time_ = entry.data.i64[0];
507       } else {
508         ALOGE(
509             "%s: Sensor exposure time %" PRId64
510             " not within supported range[%" PRId64 ", %" PRId64 "]",
511             __FUNCTION__,
512             entry.data.i64[0],
513             sensor_exposure_time_range_.first,
514             sensor_exposure_time_range_.second);
515         // Use last valid value
516       }
517     }
518 
519     ret = request_settings_->Get(ANDROID_SENSOR_FRAME_DURATION, &entry);
520     if ((ret == OK) && (entry.count == 1)) {
521       if ((entry.data.i64[0] >=
522            EmulatedSensor::kSupportedFrameDurationRange[0]) &&
523           (entry.data.i64[0] <= sensor_max_frame_duration_)) {
524         sensor_frame_duration_ = entry.data.i64[0];
525       } else {
526         ALOGE(
527             "%s: Sensor frame duration %" PRId64
528             " not within supported range[%" PRId64 ", %" PRId64 "]",
529             __FUNCTION__, entry.data.i64[0],
530             EmulatedSensor::kSupportedFrameDurationRange[0],
531             sensor_max_frame_duration_);
532         // Use last valid value
533       }
534     }
535 
536     if (sensor_frame_duration_ < sensor_exposure_time_) {
537       sensor_frame_duration_ = sensor_exposure_time_;
538     }
539 
540     ret = request_settings_->Get(ANDROID_SENSOR_SENSITIVITY, &entry);
541     if ((ret == OK) && (entry.count == 1)) {
542       if ((entry.data.i32[0] >= sensor_sensitivity_range_.first) &&
543           (entry.data.i32[0] <= sensor_sensitivity_range_.second)) {
544         sensor_sensitivity_ = entry.data.i32[0];
545       } else {
546         ALOGE("%s: Sensor sensitivity %d not within supported range[%d, %d]",
547               __FUNCTION__, entry.data.i32[0],
548               sensor_sensitivity_range_.first,
549               sensor_sensitivity_range_.second);
550         // Use last valid value
551       }
552     }
553     ae_state_ = ANDROID_CONTROL_AE_STATE_INACTIVE;
554   } else if (is_backward_compatible_ && auto_ae_mode) {
555     auto ret = DoFakeAE();
556     if (ret != OK) {
557       ALOGE("%s: Failed fake AE: %d, (%s)", __FUNCTION__, ret, strerror(-ret));
558     }
559 
560     // Do AE compensation on the results of the AE
561     ret = CompensateAE();
562     if (ret != OK) {
563       ALOGE("%s: Failed during AE compensation: %d, (%s)", __FUNCTION__, ret,
564             strerror(-ret));
565     }
566   } else {
567     ALOGI(
568         "%s: No emulation for current AE mode using previous sensor settings!",
569         __FUNCTION__);
570   }
571 
572   if (is_flash_supported_) {
573     flash_state_ = ANDROID_FLASH_STATE_READY;
574     // Flash fires only if the request manually enables it (SINGLE/TORCH)
575     // and the appropriate AE mode is set or during still capture with auto
576     // flash AE modes.
577     bool manual_flash_mode = false;
578     auto ret = request_settings_->Get(ANDROID_FLASH_MODE, &entry);
579     if ((ret == OK) && (entry.count == 1)) {
580       if ((entry.data.u8[0] == ANDROID_FLASH_MODE_SINGLE) ||
581           (entry.data.u8[0] == ANDROID_FLASH_MODE_TORCH)) {
582         manual_flash_mode = true;
583       }
584     }
585     if (manual_flash_mode && !auto_ae_flash_mode) {
586       flash_state_ = ANDROID_FLASH_STATE_FIRED;
587     } else {
588       bool is_still_capture = false;
589       ret = request_settings_->Get(ANDROID_CONTROL_CAPTURE_INTENT, &entry);
590       if ((ret == OK) && (entry.count == 1)) {
591         if (entry.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE) {
592           is_still_capture = true;
593         }
594       }
595       if (is_still_capture && auto_ae_flash_mode) {
596         flash_state_ = ANDROID_FLASH_STATE_FIRED;
597       }
598     }
599   } else {
600     flash_state_ = ANDROID_FLASH_STATE_UNAVAILABLE;
601   }
602 
603   return OK;
604 }
605 
InitializeSensorSettings(std::unique_ptr<HalCameraMetadata> request_settings,EmulatedSensor::SensorSettings * sensor_settings)606 status_t EmulatedRequestState::InitializeSensorSettings(
607     std::unique_ptr<HalCameraMetadata> request_settings,
608     EmulatedSensor::SensorSettings* sensor_settings /*out*/) {
609   if ((sensor_settings == nullptr) || (request_settings.get() == nullptr)) {
610     return BAD_VALUE;
611   }
612 
613   std::lock_guard<std::mutex> lock(request_state_mutex_);
614   request_settings_ = std::move(request_settings);
615   camera_metadata_ro_entry_t entry;
616   auto ret = request_settings_->Get(ANDROID_CONTROL_MODE, &entry);
617   if ((ret == OK) && (entry.count == 1)) {
618     if (available_control_modes_.find(entry.data.u8[0]) !=
619         available_control_modes_.end()) {
620       control_mode_ = entry.data.u8[0];
621     } else {
622       ALOGE("%s: Unsupported control mode!", __FUNCTION__);
623       return BAD_VALUE;
624     }
625   }
626 
627   ret = request_settings_->Get(ANDROID_SENSOR_PIXEL_MODE, &entry);
628   if ((ret == OK) && (entry.count == 1)) {
629     if (available_sensor_pixel_modes_.find(entry.data.u8[0]) !=
630         available_sensor_pixel_modes_.end()) {
631       sensor_pixel_mode_ = entry.data.u8[0];
632     } else {
633       ALOGE("%s: Unsupported control sensor pixel  mode!", __FUNCTION__);
634       return BAD_VALUE;
635     }
636   }
637 
638   ret = request_settings_->Get(ANDROID_CONTROL_SCENE_MODE, &entry);
639   if ((ret == OK) && (entry.count == 1)) {
640     // Disabled scene is not expected to be among the available scene list
641     if ((entry.data.u8[0] == ANDROID_CONTROL_SCENE_MODE_DISABLED) ||
642         (available_scenes_.find(entry.data.u8[0]) != available_scenes_.end())) {
643       scene_mode_ = entry.data.u8[0];
644     } else {
645       ALOGE("%s: Unsupported scene mode!", __FUNCTION__);
646       return BAD_VALUE;
647     }
648   }
649 
650   float min_zoom = min_zoom_, max_zoom = max_zoom_;
651   ret = request_settings_->Get(ANDROID_CONTROL_EXTENDED_SCENE_MODE, &entry);
652   if ((ret == OK) && (entry.count == 1)) {
653     bool extended_scene_mode_valid = false;
654     for (const auto& cap : available_extended_scene_mode_caps_) {
655       if (cap.mode == entry.data.u8[0]) {
656         extended_scene_mode_ = entry.data.u8[0];
657         min_zoom = cap.min_zoom;
658         max_zoom = cap.max_zoom;
659         extended_scene_mode_valid = true;
660         break;
661       }
662     }
663     if (!extended_scene_mode_valid) {
664       ALOGE("%s: Unsupported extended scene mode %d!", __FUNCTION__,
665             entry.data.u8[0]);
666       return BAD_VALUE;
667     }
668     if (extended_scene_mode_ != ANDROID_CONTROL_EXTENDED_SCENE_MODE_DISABLED) {
669       scene_mode_ = ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY;
670     }
671   }
672 
673   // Check zoom ratio range and override to supported range
674   ret = request_settings_->Get(ANDROID_CONTROL_ZOOM_RATIO, &entry);
675   if ((ret == OK) && (entry.count == 1)) {
676     zoom_ratio_ = std::min(std::max(entry.data.f[0], min_zoom), max_zoom);
677   }
678 
679   // Check rotate_and_crop setting
680   ret = request_settings_->Get(ANDROID_SCALER_ROTATE_AND_CROP, &entry);
681   if ((ret == OK) && (entry.count == 1)) {
682     if (available_rotate_crop_modes_.find(entry.data.u8[0]) !=
683         available_rotate_crop_modes_.end()) {
684       rotate_and_crop_ = entry.data.u8[0];
685     } else {
686       ALOGE("%s: Unsupported rotate and crop mode: %u", __FUNCTION__, entry.data.u8[0]);
687       return BAD_VALUE;
688     }
689   }
690 
691   // Check video stabilization parameter
692   uint8_t vstab_mode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
693   ret = request_settings_->Get(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, &entry);
694   if ((ret == OK) && (entry.count == 1)) {
695     if (available_vstab_modes_.find(entry.data.u8[0]) !=
696       available_vstab_modes_.end()) {
697       vstab_mode = entry.data.u8[0];
698     } else {
699       ALOGE("%s: Unsupported video stabilization mode: %u! Video stabilization will be disabled!",
700             __FUNCTION__, entry.data.u8[0]);
701     }
702   }
703 
704   // Check video stabilization parameter
705   uint8_t edge_mode = ANDROID_EDGE_MODE_OFF;
706   ret = request_settings_->Get(ANDROID_EDGE_MODE, &entry);
707   if ((ret == OK) && (entry.count == 1)) {
708     if (available_edge_modes_.find(entry.data.u8[0]) !=
709       available_edge_modes_.end()) {
710       edge_mode = entry.data.u8[0];
711     } else {
712       ALOGE("%s: Unsupported edge mode: %u", __FUNCTION__, entry.data.u8[0]);
713       return BAD_VALUE;
714     }
715   }
716 
717   // Check test pattern parameter
718   uint8_t test_pattern_mode = ANDROID_SENSOR_TEST_PATTERN_MODE_OFF;
719   ret = request_settings_->Get(ANDROID_SENSOR_TEST_PATTERN_MODE, &entry);
720   if ((ret == OK) && (entry.count == 1)) {
721     if (available_test_pattern_modes_.find(entry.data.u8[0]) !=
722         available_test_pattern_modes_.end()) {
723       test_pattern_mode = entry.data.u8[0];
724     } else {
725       ALOGE("%s: Unsupported test pattern mode: %u", __FUNCTION__,
726             entry.data.u8[0]);
727       return BAD_VALUE;
728     }
729   }
730   uint32_t test_pattern_data[4] = {0, 0, 0, 0};
731   if (test_pattern_mode == ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR) {
732     ret = request_settings_->Get(ANDROID_SENSOR_TEST_PATTERN_DATA, &entry);
733     if ((ret == OK) && (entry.count == 4)) {
734       // 'Convert' from i32 to u32 here
735       memcpy(test_pattern_data, entry.data.i32, sizeof(test_pattern_data));
736     }
737   }
738   // BLACK is just SOLID_COLOR with all-zero data
739   if (test_pattern_mode == ANDROID_SENSOR_TEST_PATTERN_MODE_BLACK) {
740     test_pattern_mode = ANDROID_SENSOR_TEST_PATTERN_MODE_SOLID_COLOR;
741   }
742 
743   // 3A modes are active in case the scene is disabled or set to face priority
744   // or the control mode is not using scenes
745   if ((scene_mode_ == ANDROID_CONTROL_SCENE_MODE_DISABLED) ||
746       (scene_mode_ == ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY) ||
747       (control_mode_ != ANDROID_CONTROL_MODE_USE_SCENE_MODE)) {
748     ret = request_settings_->Get(ANDROID_CONTROL_AE_MODE, &entry);
749     if ((ret == OK) && (entry.count == 1)) {
750       if (available_ae_modes_.find(entry.data.u8[0]) !=
751           available_ae_modes_.end()) {
752         ae_mode_ = entry.data.u8[0];
753       } else {
754         ALOGE("%s: Unsupported AE mode! Using last valid mode!", __FUNCTION__);
755       }
756     }
757 
758     ret = request_settings_->Get(ANDROID_CONTROL_AWB_MODE, &entry);
759     if ((ret == OK) && (entry.count == 1)) {
760       if (available_awb_modes_.find(entry.data.u8[0]) !=
761           available_awb_modes_.end()) {
762         awb_mode_ = entry.data.u8[0];
763       } else {
764         ALOGE("%s: Unsupported AWB mode! Using last valid mode!", __FUNCTION__);
765       }
766     }
767 
768     ret = request_settings_->Get(ANDROID_CONTROL_AF_MODE, &entry);
769     if ((ret == OK) && (entry.count == 1)) {
770       if (available_af_modes_.find(entry.data.u8[0]) !=
771           available_af_modes_.end()) {
772         af_mode_changed_ = af_mode_ != entry.data.u8[0];
773         af_mode_ = entry.data.u8[0];
774       } else {
775         ALOGE("%s: Unsupported AF mode! Using last valid mode!", __FUNCTION__);
776       }
777     }
778   } else {
779     auto it = scene_overrides_.find(scene_mode_);
780     if (it != scene_overrides_.end()) {
781       ae_mode_ = it->second.ae_mode;
782       awb_mode_ = it->second.awb_mode;
783       af_mode_changed_ = af_mode_ != entry.data.u8[0];
784       af_mode_ = it->second.af_mode;
785     } else {
786       ALOGW(
787           "%s: Current scene has no overrides! Using the currently active 3A "
788           "modes!",
789           __FUNCTION__);
790     }
791   }
792 
793   ret = ProcessAE();
794   if (ret != OK) {
795     return ret;
796   }
797 
798   ret = ProcessAWB();
799   if (ret != OK) {
800     return ret;
801   }
802 
803   ret = ProcessAF();
804   if (ret != OK) {
805     return ret;
806   }
807 
808   ret = request_settings_->Get(ANDROID_STATISTICS_LENS_SHADING_MAP_MODE, &entry);
809   if ((ret == OK) && (entry.count == 1)) {
810     if (available_lens_shading_map_modes_.find(entry.data.u8[0]) !=
811         available_lens_shading_map_modes_.end()) {
812       sensor_settings->lens_shading_map_mode = entry.data.u8[0];
813     } else {
814       ALOGE("%s: Unsupported lens shading map mode!", __FUNCTION__);
815     }
816   }
817 
818   sensor_settings->exposure_time = sensor_exposure_time_;
819   sensor_settings->frame_duration = sensor_frame_duration_;
820   sensor_settings->gain = sensor_sensitivity_;
821   sensor_settings->report_neutral_color_point = report_neutral_color_point_;
822   sensor_settings->report_green_split = report_green_split_;
823   sensor_settings->report_noise_profile = report_noise_profile_;
824   sensor_settings->zoom_ratio = zoom_ratio_;
825   sensor_settings->report_rotate_and_crop = report_rotate_and_crop_;
826   sensor_settings->rotate_and_crop = rotate_and_crop_;
827   sensor_settings->report_video_stab = !available_vstab_modes_.empty();
828   sensor_settings->video_stab = vstab_mode;
829   sensor_settings->report_edge_mode = report_edge_mode_;
830   sensor_settings->edge_mode = edge_mode;
831   sensor_settings->sensor_pixel_mode = sensor_pixel_mode_;
832   sensor_settings->test_pattern_mode = test_pattern_mode;
833   memcpy(sensor_settings->test_pattern_data, test_pattern_data,
834          sizeof(sensor_settings->test_pattern_data));
835 
836   return OK;
837 }
838 
InitializeResult(uint32_t pipeline_id,uint32_t frame_number)839 std::unique_ptr<HwlPipelineResult> EmulatedRequestState::InitializeResult(
840     uint32_t pipeline_id, uint32_t frame_number) {
841   std::lock_guard<std::mutex> lock(request_state_mutex_);
842   auto result = std::make_unique<HwlPipelineResult>();
843   result->camera_id = camera_id_;
844   result->pipeline_id = pipeline_id;
845   result->frame_number = frame_number;
846   result->result_metadata = HalCameraMetadata::Clone(request_settings_.get());
847   result->partial_result = partial_result_count_;
848 
849   // Results supported on all emulated devices
850   result->result_metadata->Set(ANDROID_REQUEST_PIPELINE_DEPTH,
851                                &max_pipeline_depth_, 1);
852   result->result_metadata->Set(ANDROID_CONTROL_MODE, &control_mode_, 1);
853   result->result_metadata->Set(ANDROID_SENSOR_PIXEL_MODE, &sensor_pixel_mode_,
854                                1);
855 
856   result->result_metadata->Set(ANDROID_CONTROL_AF_MODE, &af_mode_, 1);
857   result->result_metadata->Set(ANDROID_CONTROL_AF_STATE, &af_state_, 1);
858   result->result_metadata->Set(ANDROID_CONTROL_AWB_MODE, &awb_mode_, 1);
859   result->result_metadata->Set(ANDROID_CONTROL_AWB_STATE, &awb_state_, 1);
860   result->result_metadata->Set(ANDROID_CONTROL_AE_MODE, &ae_mode_, 1);
861   result->result_metadata->Set(ANDROID_CONTROL_AE_STATE, &ae_state_, 1);
862   int32_t fps_range[] = {ae_target_fps_.min_fps, ae_target_fps_.max_fps};
863   result->result_metadata->Set(ANDROID_CONTROL_AE_TARGET_FPS_RANGE, fps_range,
864                                ARRAY_SIZE(fps_range));
865   result->result_metadata->Set(ANDROID_FLASH_STATE, &flash_state_, 1);
866   result->result_metadata->Set(ANDROID_LENS_STATE, &lens_state_, 1);
867 
868   // Results depending on device capability and features
869   if (is_backward_compatible_) {
870     result->result_metadata->Set(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
871                                  &ae_trigger_, 1);
872     result->result_metadata->Set(ANDROID_CONTROL_AF_TRIGGER, &af_trigger_, 1);
873     uint8_t vstab_mode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
874     result->result_metadata->Set(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE,
875                                  &vstab_mode, 1);
876     if (exposure_compensation_supported_) {
877       result->result_metadata->Set(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION,
878                                    &exposure_compensation_, 1);
879     }
880   }
881   if (ae_lock_available_ && report_ae_lock_) {
882     result->result_metadata->Set(ANDROID_CONTROL_AE_LOCK, &ae_lock_, 1);
883   }
884   if (awb_lock_available_ && report_awb_lock_) {
885     result->result_metadata->Set(ANDROID_CONTROL_AWB_LOCK, &awb_lock_, 1);
886   }
887   if (scenes_supported_) {
888     result->result_metadata->Set(ANDROID_CONTROL_SCENE_MODE, &scene_mode_, 1);
889   }
890   if (max_ae_regions_ > 0) {
891     result->result_metadata->Set(ANDROID_CONTROL_AE_REGIONS, ae_metering_region_,
892                                  ARRAY_SIZE(ae_metering_region_));
893   }
894   if (max_awb_regions_ > 0) {
895     result->result_metadata->Set(ANDROID_CONTROL_AWB_REGIONS,
896                                  awb_metering_region_,
897                                  ARRAY_SIZE(awb_metering_region_));
898   }
899   if (max_af_regions_ > 0) {
900     result->result_metadata->Set(ANDROID_CONTROL_AF_REGIONS, af_metering_region_,
901                                  ARRAY_SIZE(af_metering_region_));
902   }
903   if (report_exposure_time_) {
904     result->result_metadata->Set(ANDROID_SENSOR_EXPOSURE_TIME,
905                                  &sensor_exposure_time_, 1);
906   }
907   if (report_frame_duration_) {
908     result->result_metadata->Set(ANDROID_SENSOR_FRAME_DURATION,
909                                  &sensor_frame_duration_, 1);
910   }
911   if (report_sensitivity_) {
912     result->result_metadata->Set(ANDROID_SENSOR_SENSITIVITY,
913                                  &sensor_sensitivity_, 1);
914   }
915   if (report_rolling_shutter_skew_) {
916     result->result_metadata->Set(
917         ANDROID_SENSOR_ROLLING_SHUTTER_SKEW,
918         &EmulatedSensor::kSupportedFrameDurationRange[0], 1);
919   }
920   if (report_post_raw_boost_) {
921     result->result_metadata->Set(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
922                                  &post_raw_boost_, 1);
923   }
924   if (report_focus_distance_) {
925     result->result_metadata->Set(ANDROID_LENS_FOCUS_DISTANCE, &focus_distance_,
926                                  1);
927   }
928   if (report_focus_range_) {
929     float focus_range[2] = {0.f};
930     if (minimum_focus_distance_ > .0f) {
931       focus_range[0] = 1 / minimum_focus_distance_;
932     }
933     result->result_metadata->Set(ANDROID_LENS_FOCUS_RANGE, focus_range,
934                                  ARRAY_SIZE(focus_range));
935   }
936   if (report_filter_density_) {
937     result->result_metadata->Set(ANDROID_LENS_FILTER_DENSITY, &filter_density_,
938                                  1);
939   }
940   if (report_ois_mode_) {
941     result->result_metadata->Set(ANDROID_LENS_OPTICAL_STABILIZATION_MODE,
942                                  &ois_mode_, 1);
943   }
944   if (report_pose_rotation_) {
945     result->result_metadata->Set(ANDROID_LENS_POSE_ROTATION, pose_rotation_,
946                                  ARRAY_SIZE(pose_rotation_));
947   }
948   if (report_pose_translation_) {
949     result->result_metadata->Set(ANDROID_LENS_POSE_TRANSLATION,
950                                  pose_translation_,
951                                  ARRAY_SIZE(pose_translation_));
952   }
953   if (report_intrinsic_calibration_) {
954     result->result_metadata->Set(ANDROID_LENS_INTRINSIC_CALIBRATION,
955                                  intrinsic_calibration_,
956                                  ARRAY_SIZE(intrinsic_calibration_));
957   }
958   if (report_distortion_) {
959     result->result_metadata->Set(ANDROID_LENS_DISTORTION, distortion_,
960                                  ARRAY_SIZE(distortion_));
961   }
962   if (report_black_level_lock_) {
963     result->result_metadata->Set(ANDROID_BLACK_LEVEL_LOCK, &black_level_lock_,
964                                  1);
965   }
966   if (report_scene_flicker_) {
967     result->result_metadata->Set(ANDROID_STATISTICS_SCENE_FLICKER,
968                                  &current_scene_flicker_, 1);
969   }
970   if (zoom_ratio_supported_) {
971     result->result_metadata->Set(ANDROID_CONTROL_ZOOM_RATIO, &zoom_ratio_, 1);
972     int32_t* chosen_crop_region = scaler_crop_region_default_;
973     if (sensor_pixel_mode_ == ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION) {
974       chosen_crop_region = scaler_crop_region_max_resolution_;
975     }
976     result->result_metadata->Set(ANDROID_SCALER_CROP_REGION, chosen_crop_region,
977                                  ARRAY_SIZE(scaler_crop_region_default_));
978   }
979   if (report_extended_scene_mode_) {
980     result->result_metadata->Set(ANDROID_CONTROL_EXTENDED_SCENE_MODE,
981                                  &extended_scene_mode_, 1);
982   }
983   return result;
984 }
985 
SupportsCapability(uint8_t cap)986 bool EmulatedRequestState::SupportsCapability(uint8_t cap) {
987   return available_capabilities_.find(cap) != available_capabilities_.end();
988 }
989 
InitializeSensorDefaults()990 status_t EmulatedRequestState::InitializeSensorDefaults() {
991   camera_metadata_ro_entry_t entry;
992   auto ret =
993       static_metadata_->Get(ANDROID_SENSOR_INFO_SENSITIVITY_RANGE, &entry);
994   if ((ret == OK) && (entry.count == 2)) {
995     sensor_sensitivity_range_ =
996         std::make_pair(entry.data.i32[0], entry.data.i32[1]);
997   } else if (!supports_manual_sensor_) {
998     sensor_sensitivity_range_ =
999         std::make_pair(EmulatedSensor::kSupportedSensitivityRange[0],
1000                        EmulatedSensor::kSupportedSensitivityRange[1]);
1001   } else {
1002     ALOGE("%s: Manual sensor devices must advertise sensor sensitivity range!",
1003           __FUNCTION__);
1004     return BAD_VALUE;
1005   }
1006 
1007   ret = static_metadata_->Get(ANDROID_SENSOR_INFO_EXPOSURE_TIME_RANGE, &entry);
1008   if ((ret == OK) && (entry.count == 2)) {
1009     sensor_exposure_time_range_ =
1010         std::make_pair(entry.data.i64[0], entry.data.i64[1]);
1011   } else if (!supports_manual_sensor_) {
1012     sensor_exposure_time_range_ =
1013         std::make_pair(EmulatedSensor::kSupportedExposureTimeRange[0],
1014                        EmulatedSensor::kSupportedExposureTimeRange[1]);
1015   } else {
1016     ALOGE(
1017         "%s: Manual sensor devices must advertise sensor exposure time range!",
1018         __FUNCTION__);
1019     return BAD_VALUE;
1020   }
1021 
1022   ret = static_metadata_->Get(ANDROID_SENSOR_INFO_MAX_FRAME_DURATION, &entry);
1023   if ((ret == OK) && (entry.count == 1)) {
1024     sensor_max_frame_duration_ = entry.data.i64[0];
1025   } else if (!supports_manual_sensor_) {
1026     sensor_max_frame_duration_ = EmulatedSensor::kSupportedFrameDurationRange[1];
1027   } else {
1028     ALOGE("%s: Manual sensor devices must advertise sensor max frame duration!",
1029           __FUNCTION__);
1030     return BAD_VALUE;
1031   }
1032 
1033   if (supports_manual_sensor_) {
1034     if (available_requests_.find(ANDROID_SENSOR_SENSITIVITY) ==
1035         available_requests_.end()) {
1036       ALOGE(
1037           "%s: Sensor sensitivity must be configurable on manual sensor "
1038           "devices!",
1039           __FUNCTION__);
1040       return BAD_VALUE;
1041     }
1042 
1043     if (available_requests_.find(ANDROID_SENSOR_EXPOSURE_TIME) ==
1044         available_requests_.end()) {
1045       ALOGE(
1046           "%s: Sensor exposure time must be configurable on manual sensor "
1047           "devices!",
1048           __FUNCTION__);
1049       return BAD_VALUE;
1050     }
1051 
1052     if (available_requests_.find(ANDROID_SENSOR_FRAME_DURATION) ==
1053         available_requests_.end()) {
1054       ALOGE(
1055           "%s: Sensor frame duration must be configurable on manual sensor "
1056           "devices!",
1057           __FUNCTION__);
1058       return BAD_VALUE;
1059     }
1060   }
1061 
1062   report_rolling_shutter_skew_ =
1063       available_results_.find(ANDROID_SENSOR_ROLLING_SHUTTER_SKEW) !=
1064       available_results_.end();
1065   report_sensitivity_ = available_results_.find(ANDROID_SENSOR_SENSITIVITY) !=
1066                         available_results_.end();
1067   report_exposure_time_ =
1068       available_results_.find(ANDROID_SENSOR_EXPOSURE_TIME) !=
1069       available_results_.end();
1070   report_frame_duration_ =
1071       available_results_.find(ANDROID_SENSOR_FRAME_DURATION) !=
1072       available_results_.end();
1073   report_neutral_color_point_ =
1074       available_results_.find(ANDROID_SENSOR_NEUTRAL_COLOR_POINT) !=
1075       available_results_.end();
1076   report_green_split_ = available_results_.find(ANDROID_SENSOR_GREEN_SPLIT) !=
1077                         available_results_.end();
1078   report_noise_profile_ =
1079       available_results_.find(ANDROID_SENSOR_NOISE_PROFILE) !=
1080       available_results_.end();
1081 
1082   if (is_raw_capable_ && !report_green_split_) {
1083     ALOGE("%s: RAW capable devices must be able to report the noise profile!",
1084           __FUNCTION__);
1085     return BAD_VALUE;
1086   }
1087 
1088   if (is_raw_capable_ && !report_neutral_color_point_) {
1089     ALOGE(
1090         "%s: RAW capable devices must be able to report the neutral color "
1091         "point!",
1092         __FUNCTION__);
1093     return BAD_VALUE;
1094   }
1095 
1096   if (is_raw_capable_ && !report_green_split_) {
1097     ALOGE("%s: RAW capable devices must be able to report the green split!",
1098           __FUNCTION__);
1099     return BAD_VALUE;
1100   }
1101   if (available_results_.find(ANDROID_SENSOR_TIMESTAMP) ==
1102       available_results_.end()) {
1103     ALOGE("%s: Sensor timestamp must always be part of the results!",
1104           __FUNCTION__);
1105     return BAD_VALUE;
1106   }
1107 
1108   ret = static_metadata_->Get(ANDROID_SENSOR_AVAILABLE_TEST_PATTERN_MODES,
1109                               &entry);
1110   if (ret == OK) {
1111     available_test_pattern_modes_.insert(entry.data.i32,
1112                                          entry.data.i32 + entry.count);
1113   } else {
1114     ALOGE("%s: No available test pattern modes!", __FUNCTION__);
1115     return BAD_VALUE;
1116   }
1117 
1118   sensor_exposure_time_ = GetClosestValue(EmulatedSensor::kDefaultExposureTime,
1119                                           sensor_exposure_time_range_.first,
1120                                           sensor_exposure_time_range_.second);
1121   sensor_frame_duration_ =
1122       GetClosestValue(EmulatedSensor::kDefaultFrameDuration,
1123                       EmulatedSensor::kSupportedFrameDurationRange[0],
1124                       sensor_max_frame_duration_);
1125   sensor_sensitivity_ = GetClosestValue(EmulatedSensor::kDefaultSensitivity,
1126                                         sensor_sensitivity_range_.first,
1127                                         sensor_sensitivity_range_.second);
1128 
1129   bool off_test_pattern_mode_supported =
1130       available_test_pattern_modes_.find(ANDROID_SENSOR_TEST_PATTERN_MODE_OFF) !=
1131       available_test_pattern_modes_.end();
1132   int32_t test_pattern_mode = (off_test_pattern_mode_supported)
1133                                   ? ANDROID_SENSOR_TEST_PATTERN_MODE_OFF
1134                                   : *available_test_pattern_modes_.begin();
1135   int32_t test_pattern_data[4] = {0, 0, 0, 0};
1136 
1137   for (size_t idx = 0; idx < kTemplateCount; idx++) {
1138     if (default_requests_[idx].get() == nullptr) {
1139       continue;
1140     }
1141 
1142     default_requests_[idx]->Set(ANDROID_SENSOR_EXPOSURE_TIME,
1143                                 &sensor_exposure_time_, 1);
1144     default_requests_[idx]->Set(ANDROID_SENSOR_FRAME_DURATION,
1145                                 &sensor_frame_duration_, 1);
1146     default_requests_[idx]->Set(ANDROID_SENSOR_SENSITIVITY,
1147                                 &sensor_sensitivity_, 1);
1148     default_requests_[idx]->Set(ANDROID_SENSOR_TEST_PATTERN_MODE,
1149                                 &test_pattern_mode, 1);
1150     default_requests_[idx]->Set(ANDROID_SENSOR_TEST_PATTERN_DATA,
1151                                 test_pattern_data, 4);
1152   }
1153 
1154   return OK;
1155 }
1156 
InitializeStatisticsDefaults()1157 status_t EmulatedRequestState::InitializeStatisticsDefaults() {
1158   camera_metadata_ro_entry_t entry;
1159   auto ret = static_metadata_->Get(
1160       ANDROID_STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES, &entry);
1161   if (ret == OK) {
1162     available_face_detect_modes_.insert(entry.data.u8,
1163                                         entry.data.u8 + entry.count);
1164   } else {
1165     ALOGE("%s: No available face detect modes!", __FUNCTION__);
1166     return BAD_VALUE;
1167   }
1168 
1169   ret = static_metadata_->Get(
1170       ANDROID_STATISTICS_INFO_AVAILABLE_LENS_SHADING_MAP_MODES, &entry);
1171   if (ret == OK) {
1172     available_lens_shading_map_modes_.insert(entry.data.u8,
1173                                              entry.data.u8 + entry.count);
1174   } else {
1175     ALOGE("%s: No available lens shading modes!", __FUNCTION__);
1176     return BAD_VALUE;
1177   }
1178 
1179   ret = static_metadata_->Get(
1180       ANDROID_STATISTICS_INFO_AVAILABLE_HOT_PIXEL_MAP_MODES, &entry);
1181   if (ret == OK) {
1182     available_hot_pixel_map_modes_.insert(entry.data.u8,
1183                                           entry.data.u8 + entry.count);
1184   } else if (is_raw_capable_) {
1185     ALOGE("%s: RAW capable device must support hot pixel map modes!",
1186           __FUNCTION__);
1187     return BAD_VALUE;
1188   } else {
1189     available_hot_pixel_map_modes_.emplace(
1190         ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF);
1191   }
1192 
1193   bool hot_pixel_mode_off_supported =
1194       available_hot_pixel_map_modes_.find(
1195           ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF) !=
1196       available_hot_pixel_map_modes_.end();
1197   bool face_detect_mode_off_supported =
1198       available_face_detect_modes_.find(
1199           ANDROID_STATISTICS_FACE_DETECT_MODE_OFF) !=
1200       available_face_detect_modes_.end();
1201   bool lens_shading_map_mode_off_supported =
1202       available_lens_shading_map_modes_.find(
1203           ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_ON) !=
1204       available_lens_shading_map_modes_.end();
1205   bool lens_shading_map_mode_on_supported =
1206       available_lens_shading_map_modes_.find(
1207           ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_ON) !=
1208       available_lens_shading_map_modes_.end();
1209   if (is_raw_capable_ && !lens_shading_map_mode_on_supported) {
1210     ALOGE("%s: RAW capable device must support lens shading map reporting!",
1211           __FUNCTION__);
1212     return BAD_VALUE;
1213   }
1214 
1215   if (lens_shading_map_mode_on_supported &&
1216       (available_results_.find(ANDROID_STATISTICS_LENS_SHADING_MAP) ==
1217        available_results_.end())) {
1218     ALOGE(
1219         "%s: Lens shading map reporting available but corresponding result key "
1220         "is absent!",
1221         __FUNCTION__);
1222     return BAD_VALUE;
1223   }
1224 
1225   if (lens_shading_map_mode_on_supported &&
1226       ((shading_map_size_[0] == 0) || (shading_map_size_[1] == 0))) {
1227     ALOGE(
1228         "%s: Lens shading map reporting available but without valid shading "
1229         "map size!",
1230         __FUNCTION__);
1231     return BAD_VALUE;
1232   }
1233 
1234   report_scene_flicker_ =
1235       available_results_.find(ANDROID_STATISTICS_SCENE_FLICKER) !=
1236       available_results_.end();
1237 
1238   uint8_t face_detect_mode = face_detect_mode_off_supported
1239                                  ? ANDROID_STATISTICS_FACE_DETECT_MODE_OFF
1240                                  : *available_face_detect_modes_.begin();
1241   uint8_t hot_pixel_map_mode = hot_pixel_mode_off_supported
1242                                    ? ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE_OFF
1243                                    : *available_hot_pixel_map_modes_.begin();
1244   uint8_t lens_shading_map_mode =
1245       lens_shading_map_mode_off_supported
1246           ? ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_OFF
1247           : *available_lens_shading_map_modes_.begin();
1248   for (size_t idx = 0; idx < kTemplateCount; idx++) {
1249     if (default_requests_[idx].get() == nullptr) {
1250       continue;
1251     }
1252 
1253     if ((static_cast<RequestTemplate>(idx) == RequestTemplate::kStillCapture) &&
1254         is_raw_capable_ && lens_shading_map_mode_on_supported) {
1255       uint8_t lens_shading_map_on = ANDROID_STATISTICS_LENS_SHADING_MAP_MODE_ON;
1256       default_requests_[idx]->Set(ANDROID_STATISTICS_LENS_SHADING_MAP_MODE,
1257                                   &lens_shading_map_on, 1);
1258     } else {
1259       default_requests_[idx]->Set(ANDROID_STATISTICS_LENS_SHADING_MAP_MODE,
1260                                   &lens_shading_map_mode, 1);
1261     }
1262 
1263     default_requests_[idx]->Set(ANDROID_STATISTICS_FACE_DETECT_MODE,
1264                                 &face_detect_mode, 1);
1265     default_requests_[idx]->Set(ANDROID_STATISTICS_HOT_PIXEL_MAP_MODE,
1266                                 &hot_pixel_map_mode, 1);
1267   }
1268 
1269   return InitializeBlackLevelDefaults();
1270 }
1271 
InitializeControlSceneDefaults()1272 status_t EmulatedRequestState::InitializeControlSceneDefaults() {
1273   camera_metadata_ro_entry_t entry;
1274   auto ret =
1275       static_metadata_->Get(ANDROID_CONTROL_AVAILABLE_SCENE_MODES, &entry);
1276   if (ret == OK) {
1277     available_scenes_.insert(entry.data.u8, entry.data.u8 + entry.count);
1278   } else {
1279     ALOGE("%s: No available scene modes!", __FUNCTION__);
1280     return BAD_VALUE;
1281   }
1282 
1283   if ((entry.count == 1) &&
1284       (entry.data.u8[0] == ANDROID_CONTROL_SCENE_MODE_DISABLED)) {
1285     scenes_supported_ = false;
1286     return OK;
1287   } else {
1288     scenes_supported_ = true;
1289   }
1290 
1291   if (available_requests_.find(ANDROID_CONTROL_SCENE_MODE) ==
1292       available_requests_.end()) {
1293     ALOGE("%s: Scene mode cannot be set!", __FUNCTION__);
1294     return BAD_VALUE;
1295   }
1296 
1297   if (available_results_.find(ANDROID_CONTROL_SCENE_MODE) ==
1298       available_results_.end()) {
1299     ALOGE("%s: Scene mode cannot be reported!", __FUNCTION__);
1300     return BAD_VALUE;
1301   }
1302 
1303   camera_metadata_ro_entry_t overrides_entry;
1304   ret = static_metadata_->Get(ANDROID_CONTROL_SCENE_MODE_OVERRIDES,
1305                               &overrides_entry);
1306   if ((ret == OK) && ((overrides_entry.count / 3) == available_scenes_.size()) &&
1307       ((overrides_entry.count % 3) == 0)) {
1308     for (size_t i = 0; i < entry.count; i++) {
1309       SceneOverride scene(overrides_entry.data.u8[i*3],
1310                           overrides_entry.data.u8[i*3 + 1],
1311                           overrides_entry.data.u8[i*3 + 2]);
1312       if (available_ae_modes_.find(scene.ae_mode) == available_ae_modes_.end()) {
1313         ALOGE("%s: AE scene mode override: %d not supported!", __FUNCTION__,
1314               scene.ae_mode);
1315         return BAD_VALUE;
1316       }
1317       if (available_awb_modes_.find(scene.awb_mode) ==
1318           available_awb_modes_.end()) {
1319         ALOGE("%s: AWB scene mode override: %d not supported!", __FUNCTION__,
1320               scene.awb_mode);
1321         return BAD_VALUE;
1322       }
1323       if (available_af_modes_.find(scene.af_mode) == available_af_modes_.end()) {
1324         ALOGE("%s: AF scene mode override: %d not supported!", __FUNCTION__,
1325               scene.af_mode);
1326         return BAD_VALUE;
1327       }
1328       scene_overrides_.emplace(entry.data.u8[i], scene);
1329     }
1330   } else {
1331     ALOGE("%s: No available scene overrides!", __FUNCTION__);
1332     return BAD_VALUE;
1333   }
1334 
1335   return OK;
1336 }
1337 
InitializeControlAFDefaults()1338 status_t EmulatedRequestState::InitializeControlAFDefaults() {
1339   camera_metadata_ro_entry_t entry;
1340   auto ret = static_metadata_->Get(ANDROID_CONTROL_AF_AVAILABLE_MODES, &entry);
1341   if (ret == OK) {
1342     available_af_modes_.insert(entry.data.u8, entry.data.u8 + entry.count);
1343   } else {
1344     ALOGE("%s: No available AF modes!", __FUNCTION__);
1345     return BAD_VALUE;
1346   }
1347   // Off mode must always be present
1348   if (available_af_modes_.find(ANDROID_CONTROL_AF_MODE_OFF) ==
1349       available_af_modes_.end()) {
1350     ALOGE("%s: AF off control mode must always be present!", __FUNCTION__);
1351     return BAD_VALUE;
1352   }
1353 
1354   if (available_requests_.find(ANDROID_CONTROL_AF_MODE) ==
1355       available_requests_.end()) {
1356     ALOGE("%s: Clients must be able to set AF mode!", __FUNCTION__);
1357     return BAD_VALUE;
1358   }
1359 
1360   if (available_requests_.find(ANDROID_CONTROL_AF_TRIGGER) ==
1361       available_requests_.end()) {
1362     ALOGE("%s: Clients must be able to set AF trigger!", __FUNCTION__);
1363     return BAD_VALUE;
1364   }
1365   if (available_results_.find(ANDROID_CONTROL_AF_TRIGGER) ==
1366       available_results_.end()) {
1367     ALOGE("%s: AF trigger must be reported!", __FUNCTION__);
1368     return BAD_VALUE;
1369   }
1370 
1371   if (available_results_.find(ANDROID_CONTROL_AF_MODE) ==
1372       available_results_.end()) {
1373     ALOGE("%s: AF mode must be reported!", __FUNCTION__);
1374     return BAD_VALUE;
1375   }
1376 
1377   if (available_results_.find(ANDROID_CONTROL_AF_STATE) ==
1378       available_results_.end()) {
1379     ALOGE("%s: AF state must be reported!", __FUNCTION__);
1380     return BAD_VALUE;
1381   }
1382 
1383   bool auto_mode_present =
1384       available_af_modes_.find(ANDROID_CONTROL_AF_MODE_AUTO) !=
1385       available_af_modes_.end();
1386   bool picture_caf_mode_present =
1387       available_af_modes_.find(ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE) !=
1388       available_af_modes_.end();
1389   bool video_caf_mode_present =
1390       available_af_modes_.find(ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO) !=
1391       available_af_modes_.end();
1392   af_supported_ = auto_mode_present && (minimum_focus_distance_ > .0f);
1393   picture_caf_supported_ =
1394       picture_caf_mode_present && (minimum_focus_distance_ > .0f);
1395   video_caf_supported_ =
1396       video_caf_mode_present && (minimum_focus_distance_ > .0f);
1397 
1398   return OK;
1399 }
1400 
InitializeControlAWBDefaults()1401 status_t EmulatedRequestState::InitializeControlAWBDefaults() {
1402   camera_metadata_ro_entry_t entry;
1403   auto ret = static_metadata_->Get(ANDROID_CONTROL_AWB_AVAILABLE_MODES, &entry);
1404   if (ret == OK) {
1405     available_awb_modes_.insert(entry.data.u8, entry.data.u8 + entry.count);
1406   } else {
1407     ALOGE("%s: No available AWB modes!", __FUNCTION__);
1408     return BAD_VALUE;
1409   }
1410   // Auto mode must always be present
1411   if (available_awb_modes_.find(ANDROID_CONTROL_AWB_MODE_AUTO) ==
1412       available_awb_modes_.end()) {
1413     ALOGE("%s: AWB auto control mode must always be present!", __FUNCTION__);
1414     return BAD_VALUE;
1415   }
1416 
1417   if (available_results_.find(ANDROID_CONTROL_AWB_MODE) ==
1418       available_results_.end()) {
1419     ALOGE("%s: AWB mode must be reported!", __FUNCTION__);
1420     return BAD_VALUE;
1421   }
1422 
1423   if (available_results_.find(ANDROID_CONTROL_AWB_STATE) ==
1424       available_results_.end()) {
1425     ALOGE("%s: AWB state must be reported!", __FUNCTION__);
1426     return BAD_VALUE;
1427   }
1428 
1429   ret = static_metadata_->Get(ANDROID_CONTROL_AWB_LOCK_AVAILABLE, &entry);
1430   if ((ret == OK) && (entry.count == 1)) {
1431     awb_lock_available_ =
1432         entry.data.u8[0] == ANDROID_CONTROL_AWB_LOCK_AVAILABLE_TRUE;
1433   } else {
1434     ALOGV("%s: No available AWB lock!", __FUNCTION__);
1435     awb_lock_available_ = false;
1436   }
1437   report_awb_lock_ = available_results_.find(ANDROID_CONTROL_AWB_LOCK) !=
1438                      available_results_.end();
1439 
1440   return OK;
1441 }
1442 
InitializeBlackLevelDefaults()1443 status_t EmulatedRequestState::InitializeBlackLevelDefaults() {
1444   if (is_level_full_or_higher_) {
1445     if (available_requests_.find(ANDROID_BLACK_LEVEL_LOCK) ==
1446         available_requests_.end()) {
1447       ALOGE(
1448           "%s: Full or above capable devices must be able to set the black "
1449           "level lock!",
1450           __FUNCTION__);
1451       return BAD_VALUE;
1452     }
1453 
1454     if (available_results_.find(ANDROID_BLACK_LEVEL_LOCK) ==
1455         available_results_.end()) {
1456       ALOGE(
1457           "%s: Full or above capable devices must be able to report the black "
1458           "level lock!",
1459           __FUNCTION__);
1460       return BAD_VALUE;
1461     }
1462 
1463     report_black_level_lock_ = true;
1464     uint8_t blackLevelLock = ANDROID_BLACK_LEVEL_LOCK_OFF;
1465     for (size_t idx = 0; idx < kTemplateCount; idx++) {
1466       if (default_requests_[idx].get() == nullptr) {
1467         continue;
1468       }
1469 
1470       default_requests_[idx]->Set(ANDROID_BLACK_LEVEL_LOCK, &blackLevelLock, 1);
1471     }
1472   }
1473 
1474   return InitializeEdgeDefaults();
1475 }
1476 
InitializeControlAEDefaults()1477 status_t EmulatedRequestState::InitializeControlAEDefaults() {
1478   camera_metadata_ro_entry_t entry;
1479   auto ret = static_metadata_->Get(ANDROID_CONTROL_AE_AVAILABLE_MODES, &entry);
1480   if (ret == OK) {
1481     available_ae_modes_.insert(entry.data.u8, entry.data.u8 + entry.count);
1482   } else {
1483     ALOGE("%s: No available AE modes!", __FUNCTION__);
1484     return BAD_VALUE;
1485   }
1486   // On mode must always be present
1487   if (available_ae_modes_.find(ANDROID_CONTROL_AE_MODE_ON) ==
1488       available_ae_modes_.end()) {
1489     ALOGE("%s: AE on control mode must always be present!", __FUNCTION__);
1490     return BAD_VALUE;
1491   }
1492 
1493   if (available_results_.find(ANDROID_CONTROL_AE_MODE) ==
1494       available_results_.end()) {
1495     ALOGE("%s: AE mode must be reported!", __FUNCTION__);
1496     return BAD_VALUE;
1497   }
1498 
1499   if (available_results_.find(ANDROID_CONTROL_AE_STATE) ==
1500       available_results_.end()) {
1501     ALOGE("%s: AE state must be reported!", __FUNCTION__);
1502     return BAD_VALUE;
1503   }
1504 
1505   ret = static_metadata_->Get(ANDROID_CONTROL_AE_LOCK_AVAILABLE, &entry);
1506   if ((ret == OK) && (entry.count == 1)) {
1507     ae_lock_available_ =
1508         entry.data.u8[0] == ANDROID_CONTROL_AE_LOCK_AVAILABLE_TRUE;
1509   } else {
1510     ALOGV("%s: No available AE lock!", __FUNCTION__);
1511     ae_lock_available_ = false;
1512   }
1513   report_ae_lock_ = available_results_.find(ANDROID_CONTROL_AE_LOCK) !=
1514                     available_results_.end();
1515 
1516   if (supports_manual_sensor_) {
1517     if (!ae_lock_available_) {
1518       ALOGE("%s: AE lock must always be available for manual sensors!",
1519             __FUNCTION__);
1520       return BAD_VALUE;
1521     }
1522     auto off_mode = available_control_modes_.find(ANDROID_CONTROL_MODE_OFF);
1523     if (off_mode == available_control_modes_.end()) {
1524       ALOGE("%s: Off control mode must always be present for manual sensors!",
1525             __FUNCTION__);
1526       return BAD_VALUE;
1527     }
1528 
1529     off_mode = available_ae_modes_.find(ANDROID_CONTROL_AE_MODE_OFF);
1530     if (off_mode == available_ae_modes_.end()) {
1531       ALOGE(
1532           "%s: AE off control mode must always be present for manual sensors!",
1533           __FUNCTION__);
1534       return BAD_VALUE;
1535     }
1536   }
1537 
1538   if (available_requests_.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER) ==
1539       available_requests_.end()) {
1540     ALOGE("%s: Clients must be able to set AE pre-capture trigger!",
1541           __FUNCTION__);
1542     return BAD_VALUE;
1543   }
1544 
1545   if (available_results_.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER) ==
1546       available_results_.end()) {
1547     ALOGE("%s: AE pre-capture trigger must be reported!", __FUNCTION__);
1548     return BAD_VALUE;
1549   }
1550 
1551   ret = static_metadata_->Get(ANDROID_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES,
1552                               &entry);
1553   if (ret == OK) {
1554     available_antibanding_modes_.insert(entry.data.u8,
1555                                         entry.data.u8 + entry.count);
1556   } else {
1557     ALOGE("%s: No available antibanding modes!", __FUNCTION__);
1558     return BAD_VALUE;
1559   }
1560 
1561   ret = static_metadata_->Get(ANDROID_CONTROL_AE_COMPENSATION_RANGE, &entry);
1562   if ((ret == OK) && (entry.count == 2)) {
1563     exposure_compensation_range_[0] = entry.data.i32[0];
1564     exposure_compensation_range_[1] = entry.data.i32[1];
1565   } else {
1566     ALOGE("%s: No available exposure compensation range!", __FUNCTION__);
1567     return BAD_VALUE;
1568   }
1569 
1570   ret = static_metadata_->Get(ANDROID_CONTROL_AE_COMPENSATION_STEP, &entry);
1571   if ((ret == OK) && (entry.count == 1)) {
1572     exposure_compensation_step_ = entry.data.r[0];
1573   } else {
1574     ALOGE("%s: No available exposure compensation step!", __FUNCTION__);
1575     return BAD_VALUE;
1576   }
1577 
1578   bool ae_comp_requests =
1579       available_requests_.find(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION) !=
1580       available_requests_.end();
1581   bool ae_comp_results =
1582       available_results_.find(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION) !=
1583       available_results_.end();
1584   exposure_compensation_supported_ =
1585       ((exposure_compensation_range_[0] < 0) &&
1586        (exposure_compensation_range_[1] > 0) &&
1587        (exposure_compensation_step_.denominator > 0) &&
1588        (exposure_compensation_step_.numerator > 0)) &&
1589       ae_comp_results && ae_comp_requests;
1590 
1591   return OK;
1592 }
1593 
InitializeMeteringRegionDefault(uint32_t tag,int32_t * region)1594 status_t EmulatedRequestState::InitializeMeteringRegionDefault(
1595     uint32_t tag, int32_t* region /*out*/) {
1596   if (region == nullptr) {
1597     return BAD_VALUE;
1598   }
1599   if (available_requests_.find(tag) == available_requests_.end()) {
1600     ALOGE("%s: %d metering region configuration must be supported!",
1601           __FUNCTION__, tag);
1602     return BAD_VALUE;
1603   }
1604   if (available_results_.find(tag) == available_results_.end()) {
1605     ALOGE("%s: %d metering region must be reported!", __FUNCTION__, tag);
1606     return BAD_VALUE;
1607   }
1608 
1609   region[0] = scaler_crop_region_default_[0];
1610   region[1] = scaler_crop_region_default_[1];
1611   region[2] = scaler_crop_region_default_[2];
1612   region[3] = scaler_crop_region_default_[3];
1613   region[4] = 0;
1614 
1615   return OK;
1616 }
1617 
InitializeControlDefaults()1618 status_t EmulatedRequestState::InitializeControlDefaults() {
1619   camera_metadata_ro_entry_t entry;
1620   int32_t metering_area[5] = {0};  // (top, left, width, height, wight)
1621   auto ret = static_metadata_->Get(ANDROID_CONTROL_AVAILABLE_MODES, &entry);
1622   if (ret == OK) {
1623     available_control_modes_.insert(entry.data.u8, entry.data.u8 + entry.count);
1624   } else {
1625     ALOGE("%s: No available control modes!", __FUNCTION__);
1626     return BAD_VALUE;
1627   }
1628 
1629   available_sensor_pixel_modes_.insert(ANDROID_SENSOR_PIXEL_MODE_DEFAULT);
1630 
1631   if (SupportsCapability(
1632           ANDROID_REQUEST_AVAILABLE_CAPABILITIES_ULTRA_HIGH_RESOLUTION_SENSOR)) {
1633     available_sensor_pixel_modes_.insert(
1634         ANDROID_SENSOR_PIXEL_MODE_MAXIMUM_RESOLUTION);
1635   }
1636 
1637   // Auto mode must always be present
1638   if (available_control_modes_.find(ANDROID_CONTROL_MODE_AUTO) ==
1639       available_control_modes_.end()) {
1640     ALOGE("%s: Auto control modes must always be present!", __FUNCTION__);
1641     return BAD_VALUE;
1642   }
1643 
1644   // Capture intent must always be user configurable
1645   if (available_requests_.find(ANDROID_CONTROL_CAPTURE_INTENT) ==
1646       available_requests_.end()) {
1647     ALOGE("%s: Clients must be able to set the capture intent!", __FUNCTION__);
1648     return BAD_VALUE;
1649   }
1650 
1651   ret = static_metadata_->Get(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES,
1652                               &entry);
1653   if ((ret == OK) && ((entry.count % 2) == 0)) {
1654     available_fps_ranges_.reserve(entry.count / 2);
1655     for (size_t i = 0; i < entry.count; i += 2) {
1656       FPSRange range(entry.data.i32[i], entry.data.i32[i + 1]);
1657       if (range.min_fps > range.max_fps) {
1658         ALOGE("%s: Mininum framerate: %d bigger than maximum framerate: %d",
1659               __FUNCTION__, range.min_fps, range.max_fps);
1660         return BAD_VALUE;
1661       }
1662       if ((range.max_fps >= kMinimumStreamingFPS) &&
1663           (range.max_fps == range.min_fps) && (ae_target_fps_.max_fps == 0)) {
1664         ae_target_fps_ = range;
1665       }
1666       available_fps_ranges_.push_back(range);
1667     }
1668   } else {
1669     ALOGE("%s: No available framerate ranges!", __FUNCTION__);
1670     return BAD_VALUE;
1671   }
1672 
1673   if (ae_target_fps_.max_fps == 0) {
1674     ALOGE("%s: No minimum streaming capable framerate range available!",
1675           __FUNCTION__);
1676     return BAD_VALUE;
1677   }
1678 
1679   if (available_requests_.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE) ==
1680       available_requests_.end()) {
1681     ALOGE("%s: Clients must be able to set the target framerate range!",
1682           __FUNCTION__);
1683     return BAD_VALUE;
1684   }
1685 
1686   if (available_results_.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE) ==
1687       available_results_.end()) {
1688     ALOGE("%s: Target framerate must be reported!", __FUNCTION__);
1689     return BAD_VALUE;
1690   }
1691 
1692   report_extended_scene_mode_ =
1693       available_results_.find(ANDROID_CONTROL_EXTENDED_SCENE_MODE) !=
1694       available_results_.end();
1695 
1696   if (is_backward_compatible_) {
1697     ret = static_metadata_->Get(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
1698                                 &entry);
1699     if (ret == OK) {
1700       post_raw_boost_ = entry.data.i32[0];
1701     } else {
1702       ALOGW("%s: No available post RAW boost! Setting default!", __FUNCTION__);
1703       post_raw_boost_ = 100;
1704     }
1705     report_post_raw_boost_ =
1706         available_results_.find(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST) !=
1707         available_results_.end();
1708 
1709     ret = static_metadata_->Get(ANDROID_CONTROL_AVAILABLE_EFFECTS, &entry);
1710     if ((ret == OK) && (entry.count > 0)) {
1711       available_effects_.insert(entry.data.u8, entry.data.u8 + entry.count);
1712       if (available_effects_.find(ANDROID_CONTROL_EFFECT_MODE_OFF) ==
1713           available_effects_.end()) {
1714         ALOGE("%s: Off color effect mode not supported!", __FUNCTION__);
1715         return BAD_VALUE;
1716       }
1717     } else {
1718       ALOGE("%s: No available effects!", __FUNCTION__);
1719       return BAD_VALUE;
1720     }
1721 
1722     ret = static_metadata_->Get(
1723         ANDROID_CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES, &entry);
1724     if ((ret == OK) && (entry.count > 0)) {
1725       available_vstab_modes_.insert(entry.data.u8, entry.data.u8 + entry.count);
1726       if (available_vstab_modes_.find(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF) ==
1727         available_vstab_modes_.end()) {
1728         ALOGE("%s: Off video stabilization mode not supported!", __FUNCTION__);
1729         return BAD_VALUE;
1730       }
1731       if (available_vstab_modes_.find(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_ON) !=
1732         available_vstab_modes_.end()) {
1733         vstab_available_ = true;
1734       }
1735     } else {
1736       ALOGE("%s: No available video stabilization modes!", __FUNCTION__);
1737       return BAD_VALUE;
1738     }
1739 
1740     ret = static_metadata_->Get(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM,
1741                                 &entry);
1742     if ((ret == OK) && (entry.count > 0)) {
1743       if (entry.count != 1) {
1744         ALOGE("%s: Invalid max digital zoom capability!", __FUNCTION__);
1745         return BAD_VALUE;
1746       }
1747       max_zoom_ = entry.data.f[0];
1748     } else {
1749       ALOGE("%s: No available max digital zoom", __FUNCTION__);
1750       return BAD_VALUE;
1751     }
1752 
1753     ret = static_metadata_->Get(ANDROID_CONTROL_ZOOM_RATIO_RANGE, &entry);
1754     if ((ret == OK) && (entry.count > 0)) {
1755       if (entry.count != 2) {
1756         ALOGE("%s: Invalid zoom ratio range capability!", __FUNCTION__);
1757         return BAD_VALUE;
1758       }
1759 
1760       if (entry.data.f[1] != max_zoom_) {
1761         ALOGE("%s: Max zoom ratio must be equal to max digital zoom",
1762               __FUNCTION__);
1763         return BAD_VALUE;
1764       }
1765 
1766       if (entry.data.f[1] < entry.data.f[0]) {
1767         ALOGE("%s: Max zoom ratio must be larger than min zoom ratio",
1768               __FUNCTION__);
1769         return BAD_VALUE;
1770       }
1771 
1772       // Sanity check request and result keys
1773       if (available_requests_.find(ANDROID_CONTROL_ZOOM_RATIO) ==
1774           available_requests_.end()) {
1775         ALOGE("%s: Zoom ratio tag must be available in available request keys",
1776               __FUNCTION__);
1777         return BAD_VALUE;
1778       }
1779       if (available_results_.find(ANDROID_CONTROL_ZOOM_RATIO) ==
1780           available_results_.end()) {
1781         ALOGE("%s: Zoom ratio tag must be available in available result keys",
1782               __FUNCTION__);
1783         return BAD_VALUE;
1784       }
1785 
1786       zoom_ratio_supported_ = true;
1787       min_zoom_ = entry.data.f[0];
1788     }
1789 
1790     ret = static_metadata_->Get(
1791         ANDROID_CONTROL_AVAILABLE_EXTENDED_SCENE_MODE_MAX_SIZES, &entry);
1792     if ((ret == OK) && (entry.count > 0)) {
1793       if (entry.count % 3 != 0) {
1794         ALOGE("%s: Invalid bokeh capabilities!", __FUNCTION__);
1795         return BAD_VALUE;
1796       }
1797 
1798       camera_metadata_ro_entry_t zoom_ratio_ranges_entry;
1799       ret = static_metadata_->Get(
1800           ANDROID_CONTROL_AVAILABLE_EXTENDED_SCENE_MODE_ZOOM_RATIO_RANGES,
1801           &zoom_ratio_ranges_entry);
1802       if (ret != OK ||
1803           zoom_ratio_ranges_entry.count / 2 != entry.count / 3 - 1) {
1804         ALOGE("%s: Invalid bokeh mode zoom ratio ranges.", __FUNCTION__);
1805         return BAD_VALUE;
1806       }
1807 
1808       // Sanity check request and characteristics keys
1809       if (available_requests_.find(ANDROID_CONTROL_EXTENDED_SCENE_MODE) ==
1810           available_requests_.end()) {
1811         ALOGE("%s: Extended scene mode must be configurable for this device",
1812               __FUNCTION__);
1813         return BAD_VALUE;
1814       }
1815       if (available_characteristics_.find(
1816               ANDROID_CONTROL_AVAILABLE_EXTENDED_SCENE_MODE_MAX_SIZES) ==
1817               available_characteristics_.end() ||
1818           available_characteristics_.find(
1819               ANDROID_CONTROL_AVAILABLE_EXTENDED_SCENE_MODE_ZOOM_RATIO_RANGES) ==
1820               available_characteristics_.end()) {
1821         ALOGE(
1822             "%s: ExtendedSceneMode maxSizes and zoomRatioRanges "
1823             "characteristics keys must "
1824             "be available",
1825             __FUNCTION__);
1826         return BAD_VALUE;
1827       }
1828 
1829       // Derive available bokeh caps.
1830       StreamConfigurationMap stream_configuration_map(*static_metadata_);
1831       std::set<StreamSize> yuv_sizes = stream_configuration_map.GetOutputSizes(
1832           HAL_PIXEL_FORMAT_YCBCR_420_888);
1833       bool has_extended_scene_mode_off = false;
1834       for (size_t i = 0, j = 0; i < entry.count; i += 3) {
1835         int32_t mode = entry.data.i32[i];
1836         int32_t max_width = entry.data.i32[i + 1];
1837         int32_t max_height = entry.data.i32[i + 2];
1838         float min_zoom_ratio, max_zoom_ratio;
1839 
1840         if (mode < ANDROID_CONTROL_EXTENDED_SCENE_MODE_DISABLED ||
1841             (mode > ANDROID_CONTROL_EXTENDED_SCENE_MODE_BOKEH_CONTINUOUS &&
1842              mode < ANDROID_CONTROL_EXTENDED_SCENE_MODE_VENDOR_START)) {
1843           ALOGE("%s: Invalid extended scene mode %d", __FUNCTION__, mode);
1844           return BAD_VALUE;
1845         }
1846 
1847         if (mode == ANDROID_CONTROL_EXTENDED_SCENE_MODE_DISABLED) {
1848           has_extended_scene_mode_off = true;
1849           if (max_width != 0 || max_height != 0) {
1850             ALOGE(
1851                 "%s: Invalid max width or height for "
1852                 "EXTENDED_SCENE_MODE_DISABLED",
1853                 __FUNCTION__);
1854             return BAD_VALUE;
1855           }
1856           min_zoom_ratio = min_zoom_;
1857           max_zoom_ratio = max_zoom_;
1858         } else if (yuv_sizes.find({max_width, max_height}) == yuv_sizes.end()) {
1859           ALOGE("%s: Invalid max width or height for extended scene mode %d",
1860                 __FUNCTION__, mode);
1861           return BAD_VALUE;
1862         } else {
1863           min_zoom_ratio = zoom_ratio_ranges_entry.data.f[j];
1864           max_zoom_ratio = zoom_ratio_ranges_entry.data.f[j + 1];
1865           j += 2;
1866         }
1867 
1868         ExtendedSceneModeCapability cap(mode, max_width, max_height,
1869                                         min_zoom_ratio, max_zoom_ratio);
1870         available_extended_scene_mode_caps_.push_back(cap);
1871       }
1872       if (!has_extended_scene_mode_off) {
1873         ALOGE("%s: Off extended scene mode not supported!", __FUNCTION__);
1874         return BAD_VALUE;
1875       }
1876     }
1877 
1878     ret = static_metadata_->Get(ANDROID_CONTROL_MAX_REGIONS, &entry);
1879     if ((ret == OK) && (entry.count == 3)) {
1880       max_ae_regions_ = entry.data.i32[0];
1881       max_awb_regions_ = entry.data.i32[1];
1882       max_af_regions_ = entry.data.i32[2];
1883     } else {
1884       ALOGE(
1885           "%s: Metering regions must be available for backward compatible "
1886           "devices!",
1887           __FUNCTION__);
1888       return BAD_VALUE;
1889     }
1890 
1891     if ((is_level_full_or_higher_) &&
1892         ((max_ae_regions_ == 0) || (max_af_regions_ == 0))) {
1893       ALOGE(
1894           "%s: Full and higher level cameras must support at AF and AE "
1895           "metering regions",
1896           __FUNCTION__);
1897       return BAD_VALUE;
1898     }
1899 
1900     if (max_ae_regions_ > 0) {
1901       ret = InitializeMeteringRegionDefault(ANDROID_CONTROL_AE_REGIONS,
1902                                             ae_metering_region_);
1903       if (ret != OK) {
1904         return ret;
1905       }
1906     }
1907 
1908     if (max_awb_regions_ > 0) {
1909       ret = InitializeMeteringRegionDefault(ANDROID_CONTROL_AWB_REGIONS,
1910                                             awb_metering_region_);
1911       if (ret != OK) {
1912         return ret;
1913       }
1914     }
1915 
1916     if (max_af_regions_ > 0) {
1917       ret = InitializeMeteringRegionDefault(ANDROID_CONTROL_AF_REGIONS,
1918                                             af_metering_region_);
1919       if (ret != OK) {
1920         return ret;
1921       }
1922     }
1923 
1924     ret = InitializeControlAEDefaults();
1925     if (ret != OK) {
1926       return ret;
1927     }
1928 
1929     ret = InitializeControlAWBDefaults();
1930     if (ret != OK) {
1931       return ret;
1932     }
1933 
1934     ret = InitializeControlAFDefaults();
1935     if (ret != OK) {
1936       return ret;
1937     }
1938 
1939     ret = InitializeControlSceneDefaults();
1940     if (ret != OK) {
1941       return ret;
1942     }
1943   }
1944 
1945   for (size_t idx = 0; idx < kTemplateCount; idx++) {
1946     auto template_idx = static_cast<RequestTemplate>(idx);
1947     if (default_requests_[idx].get() == nullptr) {
1948       continue;
1949     }
1950 
1951     uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_CUSTOM;
1952     uint8_t control_mode, ae_mode, awb_mode, af_mode, scene_mode, vstab_mode;
1953     control_mode = ANDROID_CONTROL_MODE_AUTO;
1954     ae_mode = ANDROID_CONTROL_AE_MODE_ON;
1955     awb_mode = ANDROID_CONTROL_AWB_MODE_AUTO;
1956     af_mode = af_supported_ ? ANDROID_CONTROL_AF_MODE_AUTO
1957                             : ANDROID_CONTROL_AF_MODE_OFF;
1958     scene_mode = ANDROID_CONTROL_SCENE_MODE_DISABLED;
1959     vstab_mode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF;
1960     uint8_t effect_mode = ANDROID_CONTROL_EFFECT_MODE_OFF;
1961     uint8_t ae_lock = ANDROID_CONTROL_AE_LOCK_OFF;
1962     uint8_t awb_lock = ANDROID_CONTROL_AWB_LOCK_OFF;
1963     int32_t ae_target_fps[] = {ae_target_fps_.min_fps, ae_target_fps_.max_fps};
1964     float zoom_ratio = 1.0f;
1965     switch (template_idx) {
1966       case RequestTemplate::kManual:
1967         intent = ANDROID_CONTROL_CAPTURE_INTENT_MANUAL;
1968         control_mode = ANDROID_CONTROL_MODE_OFF;
1969         ae_mode = ANDROID_CONTROL_AE_MODE_OFF;
1970         awb_mode = ANDROID_CONTROL_AWB_MODE_OFF;
1971         af_mode = ANDROID_CONTROL_AF_MODE_OFF;
1972         break;
1973       case RequestTemplate::kZeroShutterLag:
1974         intent = ANDROID_CONTROL_CAPTURE_INTENT_ZERO_SHUTTER_LAG;
1975         if (picture_caf_supported_) {
1976           af_mode = ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE;
1977         }
1978         break;
1979       case RequestTemplate::kPreview:
1980         intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
1981         if (picture_caf_supported_) {
1982           af_mode = ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE;
1983         }
1984         break;
1985       case RequestTemplate::kStillCapture:
1986         intent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
1987         if (picture_caf_supported_) {
1988           af_mode = ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE;
1989         }
1990         break;
1991       case RequestTemplate::kVideoRecord:
1992         intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
1993         if (video_caf_supported_) {
1994           af_mode = ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO;
1995         }
1996         if (vstab_available_) {
1997           vstab_mode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_ON;
1998         }
1999         break;
2000       case RequestTemplate::kVideoSnapshot:
2001         intent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2002         if (video_caf_supported_) {
2003           af_mode = ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO;
2004         }
2005         if (vstab_available_) {
2006           vstab_mode = ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_ON;
2007         }
2008         break;
2009       default:
2010         // Noop
2011         break;
2012     }
2013 
2014     if (intent != ANDROID_CONTROL_CAPTURE_INTENT_CUSTOM) {
2015       default_requests_[idx]->Set(ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1);
2016       default_requests_[idx]->Set(ANDROID_CONTROL_MODE, &control_mode, 1);
2017       default_requests_[idx]->Set(ANDROID_CONTROL_AE_MODE, &ae_mode, 1);
2018       default_requests_[idx]->Set(ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
2019                                   ae_target_fps, ARRAY_SIZE(ae_target_fps));
2020       default_requests_[idx]->Set(ANDROID_CONTROL_AWB_MODE, &awb_mode, 1);
2021       default_requests_[idx]->Set(ANDROID_CONTROL_AF_MODE, &af_mode, 1);
2022       if (is_backward_compatible_) {
2023         default_requests_[idx]->Set(ANDROID_CONTROL_POST_RAW_SENSITIVITY_BOOST,
2024                                     &post_raw_boost_, 1);
2025         if (vstab_available_) {
2026           default_requests_[idx]->Set(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE,
2027                                       &vstab_mode, 1);
2028         }
2029         if (ae_lock_available_) {
2030           default_requests_[idx]->Set(ANDROID_CONTROL_AE_LOCK, &ae_lock, 1);
2031         }
2032         if (awb_lock_available_) {
2033           default_requests_[idx]->Set(ANDROID_CONTROL_AWB_LOCK, &awb_lock, 1);
2034         }
2035         if (scenes_supported_) {
2036           default_requests_[idx]->Set(ANDROID_CONTROL_SCENE_MODE, &scene_mode,
2037                                       1);
2038         }
2039         if (max_ae_regions_ > 0) {
2040           default_requests_[idx]->Set(ANDROID_CONTROL_AE_REGIONS, metering_area,
2041                                       ARRAY_SIZE(metering_area));
2042         }
2043         if (max_awb_regions_ > 0) {
2044           default_requests_[idx]->Set(ANDROID_CONTROL_AWB_REGIONS,
2045                                       metering_area, ARRAY_SIZE(metering_area));
2046         }
2047         if (max_af_regions_ > 0) {
2048           default_requests_[idx]->Set(ANDROID_CONTROL_AF_REGIONS, metering_area,
2049                                       ARRAY_SIZE(metering_area));
2050         }
2051         if (exposure_compensation_supported_) {
2052           default_requests_[idx]->Set(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION,
2053                                       &exposure_compensation_, 1);
2054         }
2055         if (zoom_ratio_supported_) {
2056           default_requests_[idx]->Set(ANDROID_CONTROL_ZOOM_RATIO, &zoom_ratio,
2057                                       1);
2058         }
2059         bool is_auto_antbanding_supported =
2060             available_antibanding_modes_.find(
2061                 ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO) !=
2062             available_antibanding_modes_.end();
2063         uint8_t antibanding_mode = is_auto_antbanding_supported
2064                                        ? ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO
2065                                        : *available_antibanding_modes_.begin();
2066         default_requests_[idx]->Set(ANDROID_CONTROL_AE_ANTIBANDING_MODE,
2067                                     &antibanding_mode, 1);
2068         default_requests_[idx]->Set(ANDROID_CONTROL_EFFECT_MODE, &effect_mode,
2069                                     1);
2070         uint8_t ae_trigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE;
2071         default_requests_[idx]->Set(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2072                                     &ae_trigger, 1);
2073         uint8_t af_trigger = ANDROID_CONTROL_AF_TRIGGER_IDLE;
2074         default_requests_[idx]->Set(ANDROID_CONTROL_AF_TRIGGER, &af_trigger, 1);
2075       }
2076     }
2077   }
2078 
2079   return InitializeHotPixelDefaults();
2080 }
2081 
InitializeTonemapDefaults()2082 status_t EmulatedRequestState::InitializeTonemapDefaults() {
2083   if (is_backward_compatible_) {
2084     camera_metadata_ro_entry_t entry;
2085     auto ret =
2086         static_metadata_->Get(ANDROID_TONEMAP_AVAILABLE_TONE_MAP_MODES, &entry);
2087     if (ret == OK) {
2088       available_tonemap_modes_.insert(entry.data.u8,
2089                                       entry.data.u8 + entry.count);
2090     } else {
2091       ALOGE("%s: No available tonemap modes!", __FUNCTION__);
2092       return BAD_VALUE;
2093     }
2094 
2095     if ((is_level_full_or_higher_) && (available_tonemap_modes_.size() < 3)) {
2096       ALOGE(
2097           "%s: Full and higher level cameras must support at least three or "
2098           "more tonemap modes",
2099           __FUNCTION__);
2100       return BAD_VALUE;
2101     }
2102 
2103     bool fast_mode_supported =
2104         available_tonemap_modes_.find(ANDROID_TONEMAP_MODE_FAST) !=
2105         available_tonemap_modes_.end();
2106     bool hq_mode_supported =
2107         available_tonemap_modes_.find(ANDROID_TONEMAP_MODE_HIGH_QUALITY) !=
2108         available_tonemap_modes_.end();
2109     uint8_t tonemap_mode = *available_tonemap_modes_.begin();
2110     for (size_t idx = 0; idx < kTemplateCount; idx++) {
2111       if (default_requests_[idx].get() == nullptr) {
2112         continue;
2113       }
2114 
2115       switch (static_cast<RequestTemplate>(idx)) {
2116         case RequestTemplate::kVideoRecord:  // Pass-through
2117         case RequestTemplate::kPreview:
2118           if (fast_mode_supported) {
2119             tonemap_mode = ANDROID_TONEMAP_MODE_FAST;
2120           }
2121           break;
2122         case RequestTemplate::kVideoSnapshot:  // Pass-through
2123         case RequestTemplate::kStillCapture:
2124           if (hq_mode_supported) {
2125             tonemap_mode = ANDROID_TONEMAP_MODE_HIGH_QUALITY;
2126           }
2127           break;
2128         default:
2129           // Noop
2130           break;
2131       }
2132 
2133       default_requests_[idx]->Set(ANDROID_TONEMAP_MODE, &tonemap_mode, 1);
2134       default_requests_[idx]->Set(
2135           ANDROID_TONEMAP_CURVE_RED, EmulatedSensor::kDefaultToneMapCurveRed,
2136           ARRAY_SIZE(EmulatedSensor::kDefaultToneMapCurveRed));
2137       default_requests_[idx]->Set(
2138           ANDROID_TONEMAP_CURVE_GREEN, EmulatedSensor::kDefaultToneMapCurveGreen,
2139           ARRAY_SIZE(EmulatedSensor::kDefaultToneMapCurveGreen));
2140       default_requests_[idx]->Set(
2141           ANDROID_TONEMAP_CURVE_BLUE, EmulatedSensor::kDefaultToneMapCurveBlue,
2142           ARRAY_SIZE(EmulatedSensor::kDefaultToneMapCurveBlue));
2143     }
2144   }
2145 
2146   return InitializeStatisticsDefaults();
2147 }
2148 
InitializeEdgeDefaults()2149 status_t EmulatedRequestState::InitializeEdgeDefaults() {
2150   if (is_backward_compatible_) {
2151     camera_metadata_ro_entry_t entry;
2152     auto ret = static_metadata_->Get(ANDROID_EDGE_AVAILABLE_EDGE_MODES, &entry);
2153     if (ret == OK) {
2154       available_edge_modes_.insert(entry.data.u8, entry.data.u8 + entry.count);
2155     } else {
2156       ALOGE("%s: No available edge modes!", __FUNCTION__);
2157       return BAD_VALUE;
2158     }
2159 
2160     report_edge_mode_ = available_results_.find(ANDROID_EDGE_MODE) != available_results_.end();
2161     bool is_fast_mode_supported =
2162         available_edge_modes_.find(ANDROID_EDGE_MODE_FAST) !=
2163         available_edge_modes_.end();
2164     bool is_hq_mode_supported =
2165         available_edge_modes_.find(ANDROID_EDGE_MODE_HIGH_QUALITY) !=
2166         available_edge_modes_.end();
2167     bool is_zsl_mode_supported =
2168         available_edge_modes_.find(ANDROID_EDGE_MODE_ZERO_SHUTTER_LAG) !=
2169         available_edge_modes_.end();
2170     uint8_t edge_mode = *available_ae_modes_.begin();
2171     for (size_t idx = 0; idx < kTemplateCount; idx++) {
2172       if (default_requests_[idx].get() == nullptr) {
2173         continue;
2174       }
2175 
2176       switch (static_cast<RequestTemplate>(idx)) {
2177         case RequestTemplate::kVideoRecord:  // Pass-through
2178         case RequestTemplate::kPreview:
2179           if (is_fast_mode_supported) {
2180             edge_mode = ANDROID_EDGE_MODE_FAST;
2181           }
2182           break;
2183         case RequestTemplate::kVideoSnapshot:  // Pass-through
2184         case RequestTemplate::kStillCapture:
2185           if (is_hq_mode_supported) {
2186             edge_mode = ANDROID_EDGE_MODE_HIGH_QUALITY;
2187           }
2188           break;
2189         case RequestTemplate::kZeroShutterLag:
2190           if (is_zsl_mode_supported) {
2191             edge_mode = ANDROID_EDGE_MODE_ZERO_SHUTTER_LAG;
2192           }
2193           break;
2194         default:
2195           // Noop
2196           break;
2197       }
2198 
2199       default_requests_[idx]->Set(ANDROID_EDGE_MODE, &edge_mode, 1);
2200     }
2201   }
2202 
2203   return InitializeShadingDefaults();
2204 }
2205 
InitializeColorCorrectionDefaults()2206 status_t EmulatedRequestState::InitializeColorCorrectionDefaults() {
2207   camera_metadata_ro_entry_t entry;
2208   auto ret = static_metadata_->Get(
2209       ANDROID_COLOR_CORRECTION_AVAILABLE_ABERRATION_MODES, &entry);
2210   if (ret == OK) {
2211     available_color_aberration_modes_.insert(entry.data.u8,
2212                                              entry.data.u8 + entry.count);
2213   } else if (supports_manual_post_processing_) {
2214     ALOGE(
2215         "%s: Devices capable of manual post-processing must support color "
2216         "abberation!",
2217         __FUNCTION__);
2218     return BAD_VALUE;
2219   }
2220 
2221   if (!available_color_aberration_modes_.empty()) {
2222     bool is_fast_mode_supported =
2223         available_color_aberration_modes_.find(
2224             ANDROID_COLOR_CORRECTION_ABERRATION_MODE_FAST) !=
2225         available_color_aberration_modes_.end();
2226     bool is_hq_mode_supported =
2227         available_color_aberration_modes_.find(
2228             ANDROID_COLOR_CORRECTION_ABERRATION_MODE_HIGH_QUALITY) !=
2229         available_color_aberration_modes_.end();
2230     uint8_t color_aberration = *available_color_aberration_modes_.begin();
2231     uint8_t color_correction_mode = ANDROID_COLOR_CORRECTION_MODE_FAST;
2232     for (size_t idx = 0; idx < kTemplateCount; idx++) {
2233       if (default_requests_[idx].get() == nullptr) {
2234         continue;
2235       }
2236 
2237       switch (static_cast<RequestTemplate>(idx)) {
2238         case RequestTemplate::kVideoRecord:  // Pass-through
2239         case RequestTemplate::kPreview:
2240           if (is_fast_mode_supported) {
2241             color_aberration = ANDROID_COLOR_CORRECTION_ABERRATION_MODE_FAST;
2242           }
2243           break;
2244         case RequestTemplate::kVideoSnapshot:  // Pass-through
2245         case RequestTemplate::kStillCapture:
2246           if (is_hq_mode_supported) {
2247             color_aberration =
2248                 ANDROID_COLOR_CORRECTION_ABERRATION_MODE_HIGH_QUALITY;
2249           }
2250           break;
2251         default:
2252           // Noop
2253           break;
2254       }
2255 
2256       default_requests_[idx]->Set(ANDROID_COLOR_CORRECTION_ABERRATION_MODE,
2257                                   &color_aberration, 1);
2258       if (is_backward_compatible_) {
2259         default_requests_[idx]->Set(ANDROID_COLOR_CORRECTION_MODE,
2260                                     &color_correction_mode, 1);
2261         default_requests_[idx]->Set(
2262             ANDROID_COLOR_CORRECTION_TRANSFORM,
2263             EmulatedSensor::kDefaultColorTransform,
2264             ARRAY_SIZE(EmulatedSensor::kDefaultColorTransform));
2265         default_requests_[idx]->Set(
2266             ANDROID_COLOR_CORRECTION_GAINS,
2267             EmulatedSensor::kDefaultColorCorrectionGains,
2268             ARRAY_SIZE(EmulatedSensor::kDefaultColorCorrectionGains));
2269       }
2270     }
2271   }
2272 
2273   return InitializeSensorDefaults();
2274 }
2275 
InitializeScalerDefaults()2276 status_t EmulatedRequestState::InitializeScalerDefaults() {
2277   if (is_backward_compatible_) {
2278     camera_metadata_ro_entry_t entry;
2279     auto ret =
2280         static_metadata_->Get(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE, &entry);
2281     if ((ret == OK) && (entry.count == 4)) {
2282       scaler_crop_region_default_[0] = entry.data.i32[0];
2283       scaler_crop_region_default_[1] = entry.data.i32[1];
2284       scaler_crop_region_default_[2] = entry.data.i32[2];
2285       scaler_crop_region_default_[3] = entry.data.i32[3];
2286     } else {
2287       ALOGE("%s: Sensor pixel array size is not available!", __FUNCTION__);
2288       return BAD_VALUE;
2289     }
2290 
2291     if (SupportsCapability(
2292             ANDROID_REQUEST_AVAILABLE_CAPABILITIES_ULTRA_HIGH_RESOLUTION_SENSOR)) {
2293       ret = static_metadata_->Get(
2294           ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE_MAXIMUM_RESOLUTION, &entry);
2295       if ((ret == OK) && (entry.count == 4)) {
2296         scaler_crop_region_max_resolution_[0] = entry.data.i32[0];
2297         scaler_crop_region_max_resolution_[1] = entry.data.i32[1];
2298         scaler_crop_region_max_resolution_[2] = entry.data.i32[2];
2299         scaler_crop_region_max_resolution_[3] = entry.data.i32[3];
2300       } else {
2301         ALOGE(
2302             "%s: Sensor pixel array size maximum resolution is not available!",
2303             __FUNCTION__);
2304         return BAD_VALUE;
2305       }
2306     }
2307 
2308     if (available_requests_.find(ANDROID_SCALER_CROP_REGION) ==
2309         available_requests_.end()) {
2310       ALOGE(
2311           "%s: Backward compatible devices must support scaler crop "
2312           "configuration!",
2313           __FUNCTION__);
2314       return BAD_VALUE;
2315     }
2316     if (available_results_.find(ANDROID_SCALER_CROP_REGION) ==
2317         available_results_.end()) {
2318       ALOGE("%s: Scaler crop must reported on backward compatible devices!",
2319             __FUNCTION__);
2320       return BAD_VALUE;
2321     }
2322     ret = static_metadata_->Get(ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES,
2323                                 &entry);
2324     if ((ret == OK) && (entry.count > 0)) {
2325       // Listing rotate and crop, so need to make sure it's consistently reported
2326       if (available_requests_.find(ANDROID_SCALER_ROTATE_AND_CROP) ==
2327           available_requests_.end()) {
2328         ALOGE(
2329             "%s: Rotate and crop must be listed in request keys if supported!",
2330             __FUNCTION__);
2331         return BAD_VALUE;
2332       }
2333       if (available_results_.find(ANDROID_SCALER_ROTATE_AND_CROP) ==
2334           available_results_.end()) {
2335         ALOGE("%s: Rotate and crop must be listed in result keys if supported!",
2336               __FUNCTION__);
2337         return BAD_VALUE;
2338       }
2339       if (available_characteristics_.find(
2340               ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES) ==
2341           available_characteristics_.end()) {
2342         ALOGE(
2343             "%s: Rotate and crop must be listed in characteristics keys if "
2344             "supported!",
2345             __FUNCTION__);
2346         return BAD_VALUE;
2347       }
2348       report_rotate_and_crop_ = true;
2349       for (size_t i = 0; i < entry.count; i++) {
2350         if (entry.data.u8[i] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2351           rotate_and_crop_ = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2352         }
2353         available_rotate_crop_modes_.insert(entry.data.u8[i]);
2354       }
2355     }
2356 
2357     for (size_t idx = 0; idx < kTemplateCount; idx++) {
2358       if (default_requests_[idx].get() == nullptr) {
2359         continue;
2360       }
2361 
2362       default_requests_[idx]->Set(ANDROID_SCALER_CROP_REGION,
2363                                   scaler_crop_region_default_,
2364                                   ARRAY_SIZE(scaler_crop_region_default_));
2365       if (report_rotate_and_crop_) {
2366         default_requests_[idx]->Set(ANDROID_SCALER_ROTATE_AND_CROP,
2367                                     &rotate_and_crop_, 1);
2368       }
2369     }
2370   }
2371 
2372   return InitializeControlDefaults();
2373 }
2374 
InitializeShadingDefaults()2375 status_t EmulatedRequestState::InitializeShadingDefaults() {
2376   camera_metadata_ro_entry_t entry;
2377   auto ret = static_metadata_->Get(ANDROID_SHADING_AVAILABLE_MODES, &entry);
2378   if (ret == OK) {
2379     available_shading_modes_.insert(entry.data.u8, entry.data.u8 + entry.count);
2380   } else {
2381     ALOGE("%s: No available lens shading modes!", __FUNCTION__);
2382     return BAD_VALUE;
2383   }
2384 
2385   if (supports_manual_post_processing_ &&
2386       (available_shading_modes_.size() < 2)) {
2387     ALOGE(
2388         "%s: Devices capable of manual post-processing need to support at "
2389         "least "
2390         "two"
2391         " lens shading modes!",
2392         __FUNCTION__);
2393     return BAD_VALUE;
2394   }
2395 
2396   bool is_fast_mode_supported =
2397       available_shading_modes_.find(ANDROID_SHADING_MODE_FAST) !=
2398       available_shading_modes_.end();
2399   bool is_hq_mode_supported =
2400       available_shading_modes_.find(ANDROID_SHADING_MODE_HIGH_QUALITY) !=
2401       available_shading_modes_.end();
2402   uint8_t shading_mode = *available_shading_modes_.begin();
2403   for (size_t idx = 0; idx < kTemplateCount; idx++) {
2404     if (default_requests_[idx].get() == nullptr) {
2405       continue;
2406     }
2407 
2408     switch (static_cast<RequestTemplate>(idx)) {
2409       case RequestTemplate::kVideoRecord:  // Pass-through
2410       case RequestTemplate::kPreview:
2411         if (is_fast_mode_supported) {
2412           shading_mode = ANDROID_SHADING_MODE_FAST;
2413         }
2414         break;
2415       case RequestTemplate::kVideoSnapshot:  // Pass-through
2416       case RequestTemplate::kStillCapture:
2417         if (is_hq_mode_supported) {
2418           shading_mode = ANDROID_SHADING_MODE_HIGH_QUALITY;
2419         }
2420         break;
2421       default:
2422         // Noop
2423         break;
2424     }
2425 
2426     default_requests_[idx]->Set(ANDROID_SHADING_MODE, &shading_mode, 1);
2427   }
2428 
2429   return InitializeNoiseReductionDefaults();
2430 }
2431 
InitializeNoiseReductionDefaults()2432 status_t EmulatedRequestState::InitializeNoiseReductionDefaults() {
2433   camera_metadata_ro_entry_t entry;
2434   auto ret = static_metadata_->Get(
2435       ANDROID_NOISE_REDUCTION_AVAILABLE_NOISE_REDUCTION_MODES, &entry);
2436   if (ret == OK) {
2437     available_noise_reduction_modes_.insert(entry.data.u8,
2438                                             entry.data.u8 + entry.count);
2439   } else {
2440     ALOGE("%s: No available noise reduction modes!", __FUNCTION__);
2441     return BAD_VALUE;
2442   }
2443 
2444   if ((is_level_full_or_higher_) &&
2445       (available_noise_reduction_modes_.size() < 2)) {
2446     ALOGE(
2447         "%s: Full and above device must support at least two noise reduction "
2448         "modes!",
2449         __FUNCTION__);
2450     return BAD_VALUE;
2451   }
2452 
2453   bool is_fast_mode_supported =
2454       available_noise_reduction_modes_.find(ANDROID_NOISE_REDUCTION_MODE_FAST) !=
2455       available_noise_reduction_modes_.end();
2456   bool is_hq_mode_supported = available_noise_reduction_modes_.find(
2457                                   ANDROID_NOISE_REDUCTION_MODE_HIGH_QUALITY) !=
2458                               available_noise_reduction_modes_.end();
2459   bool is_zsl_mode_supported =
2460       available_noise_reduction_modes_.find(
2461           ANDROID_NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG) !=
2462       available_noise_reduction_modes_.end();
2463   uint8_t noise_reduction_mode = *available_noise_reduction_modes_.begin();
2464   for (size_t idx = 0; idx < kTemplateCount; idx++) {
2465     if (default_requests_[idx].get() == nullptr) {
2466       continue;
2467     }
2468 
2469     switch (static_cast<RequestTemplate>(idx)) {
2470       case RequestTemplate::kVideoRecord:  // Pass-through
2471       case RequestTemplate::kVideoSnapshot:  // Pass-through
2472       case RequestTemplate::kPreview:
2473         if (is_fast_mode_supported) {
2474           noise_reduction_mode = ANDROID_NOISE_REDUCTION_MODE_FAST;
2475         }
2476         break;
2477       case RequestTemplate::kStillCapture:
2478         if (is_hq_mode_supported) {
2479           noise_reduction_mode = ANDROID_NOISE_REDUCTION_MODE_HIGH_QUALITY;
2480         }
2481         break;
2482       case RequestTemplate::kZeroShutterLag:
2483         if (is_zsl_mode_supported) {
2484           noise_reduction_mode = ANDROID_NOISE_REDUCTION_MODE_ZERO_SHUTTER_LAG;
2485         }
2486         break;
2487       default:
2488         // Noop
2489         break;
2490     }
2491 
2492     default_requests_[idx]->Set(ANDROID_NOISE_REDUCTION_MODE,
2493                                 &noise_reduction_mode, 1);
2494   }
2495 
2496   return InitializeColorCorrectionDefaults();
2497 }
2498 
InitializeHotPixelDefaults()2499 status_t EmulatedRequestState::InitializeHotPixelDefaults() {
2500   camera_metadata_ro_entry_t entry;
2501   auto ret = static_metadata_->Get(ANDROID_HOT_PIXEL_AVAILABLE_HOT_PIXEL_MODES,
2502                                    &entry);
2503   if (ret == OK) {
2504     available_hot_pixel_modes_.insert(entry.data.u8,
2505                                       entry.data.u8 + entry.count);
2506   } else {
2507     ALOGE("%s: No available hotpixel modes!", __FUNCTION__);
2508     return BAD_VALUE;
2509   }
2510 
2511   if ((is_level_full_or_higher_) && (available_hot_pixel_modes_.size() < 2)) {
2512     ALOGE(
2513         "%s: Full and higher level cameras must support at least fast and hq "
2514         "hotpixel modes",
2515         __FUNCTION__);
2516     return BAD_VALUE;
2517   }
2518 
2519   bool fast_mode_supported =
2520       available_hot_pixel_modes_.find(ANDROID_HOT_PIXEL_MODE_FAST) !=
2521       available_hot_pixel_modes_.end();
2522   bool hq_mode_supported =
2523       available_hot_pixel_modes_.find(ANDROID_HOT_PIXEL_MODE_HIGH_QUALITY) !=
2524       available_hot_pixel_modes_.end();
2525   uint8_t hotpixel_mode = *available_hot_pixel_modes_.begin();
2526   for (size_t idx = 0; idx < kTemplateCount; idx++) {
2527     if (default_requests_[idx].get() == nullptr) {
2528       continue;
2529     }
2530 
2531     switch (static_cast<RequestTemplate>(idx)) {
2532       case RequestTemplate::kVideoRecord:  // Pass-through
2533       case RequestTemplate::kPreview:
2534         if (fast_mode_supported) {
2535           hotpixel_mode = ANDROID_HOT_PIXEL_MODE_FAST;
2536         }
2537         break;
2538       case RequestTemplate::kVideoSnapshot:  // Pass-through
2539       case RequestTemplate::kStillCapture:
2540         if (hq_mode_supported) {
2541           hotpixel_mode = ANDROID_HOT_PIXEL_MODE_HIGH_QUALITY;
2542         }
2543         break;
2544       default:
2545         // Noop
2546         break;
2547     }
2548 
2549     default_requests_[idx]->Set(ANDROID_HOT_PIXEL_MODE, &hotpixel_mode, 1);
2550   }
2551 
2552   return InitializeTonemapDefaults();
2553 }
2554 
InitializeFlashDefaults()2555 status_t EmulatedRequestState::InitializeFlashDefaults() {
2556   camera_metadata_ro_entry_t entry;
2557   auto ret = static_metadata_->Get(ANDROID_FLASH_INFO_AVAILABLE, &entry);
2558   if ((ret == OK) && (entry.count == 1)) {
2559     is_flash_supported_ = entry.data.u8[0];
2560   } else {
2561     ALOGE("%s: No available flash info!", __FUNCTION__);
2562     return BAD_VALUE;
2563   }
2564 
2565   if (is_flash_supported_) {
2566     flash_state_ = ANDROID_FLASH_STATE_READY;
2567   } else {
2568     flash_state_ = ANDROID_FLASH_STATE_UNAVAILABLE;
2569   }
2570 
2571   uint8_t flash_mode = ANDROID_FLASH_MODE_OFF;
2572   for (size_t idx = 0; idx < kTemplateCount; idx++) {
2573     if (default_requests_[idx].get() == nullptr) {
2574       continue;
2575     }
2576 
2577     default_requests_[idx]->Set(ANDROID_FLASH_MODE, &flash_mode, 1);
2578   }
2579 
2580   return InitializeScalerDefaults();
2581 }
2582 
InitializeLensDefaults()2583 status_t EmulatedRequestState::InitializeLensDefaults() {
2584   camera_metadata_ro_entry_t entry;
2585   auto ret =
2586       static_metadata_->Get(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE, &entry);
2587   if ((ret == OK) && (entry.count == 1)) {
2588     minimum_focus_distance_ = entry.data.f[0];
2589   } else {
2590     ALOGW("%s: No available minimum focus distance assuming fixed focus!",
2591           __FUNCTION__);
2592     minimum_focus_distance_ = .0f;
2593   }
2594 
2595   ret = static_metadata_->Get(ANDROID_LENS_INFO_AVAILABLE_APERTURES, &entry);
2596   if ((ret == OK) && (entry.count > 0)) {
2597     // TODO: add support for multiple apertures
2598     aperture_ = entry.data.f[0];
2599   } else {
2600     ALOGE("%s: No available aperture!", __FUNCTION__);
2601     return BAD_VALUE;
2602   }
2603 
2604   ret = static_metadata_->Get(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS, &entry);
2605   if ((ret == OK) && (entry.count > 0)) {
2606     focal_length_ = entry.data.f[0];
2607   } else {
2608     ALOGE("%s: No available focal length!", __FUNCTION__);
2609     return BAD_VALUE;
2610   }
2611 
2612   ret = static_metadata_->Get(ANDROID_LENS_INFO_SHADING_MAP_SIZE, &entry);
2613   if ((ret == OK) && (entry.count == 2)) {
2614     shading_map_size_[0] = entry.data.i32[0];
2615     shading_map_size_[1] = entry.data.i32[1];
2616   } else if (is_raw_capable_) {
2617     ALOGE("%s: No available shading map size!", __FUNCTION__);
2618     return BAD_VALUE;
2619   }
2620 
2621   ret = static_metadata_->Get(ANDROID_LENS_INFO_AVAILABLE_FILTER_DENSITIES,
2622                               &entry);
2623   if ((ret == OK) && (entry.count > 0)) {
2624     // TODO: add support for multiple filter densities
2625     filter_density_ = entry.data.f[0];
2626   } else {
2627     ALOGE("%s: No available filter density!", __FUNCTION__);
2628     return BAD_VALUE;
2629   }
2630 
2631   ret = static_metadata_->Get(ANDROID_LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION,
2632                               &entry);
2633   if ((ret == OK) && (entry.count > 0)) {
2634     // TODO: add support for multiple OIS modes
2635     available_ois_modes_.insert(entry.data.u8, entry.data.u8 + entry.count);
2636     if (available_ois_modes_.find(ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF) ==
2637         available_ois_modes_.end()) {
2638       ALOGE("%s: OIS off mode not supported!", __FUNCTION__);
2639       return BAD_VALUE;
2640     }
2641   } else {
2642     ALOGE("%s: No available OIS modes!", __FUNCTION__);
2643     return BAD_VALUE;
2644   }
2645 
2646   ret = static_metadata_->Get(ANDROID_LENS_POSE_ROTATION, &entry);
2647   if ((ret == OK) && (entry.count == ARRAY_SIZE(pose_rotation_))) {
2648     memcpy(pose_rotation_, entry.data.f, sizeof(pose_rotation_));
2649   }
2650   ret = static_metadata_->Get(ANDROID_LENS_POSE_TRANSLATION, &entry);
2651   if ((ret == OK) && (entry.count == ARRAY_SIZE(pose_translation_))) {
2652     memcpy(pose_translation_, entry.data.f, sizeof(pose_translation_));
2653   }
2654   ret = static_metadata_->Get(ANDROID_LENS_INTRINSIC_CALIBRATION, &entry);
2655   if ((ret == OK) && (entry.count == ARRAY_SIZE(intrinsic_calibration_))) {
2656     memcpy(intrinsic_calibration_, entry.data.f, sizeof(intrinsic_calibration_));
2657   }
2658 
2659   ret = static_metadata_->Get(ANDROID_LENS_DISTORTION, &entry);
2660   if ((ret == OK) && (entry.count == ARRAY_SIZE(distortion_))) {
2661     memcpy(distortion_, entry.data.f, sizeof(distortion_));
2662   }
2663 
2664   report_focus_distance_ =
2665       available_results_.find(ANDROID_LENS_FOCUS_DISTANCE) !=
2666       available_results_.end();
2667   report_focus_range_ = available_results_.find(ANDROID_LENS_FOCUS_RANGE) !=
2668                         available_results_.end();
2669   report_filter_density_ =
2670       available_results_.find(ANDROID_LENS_FILTER_DENSITY) !=
2671       available_results_.end();
2672   report_ois_mode_ =
2673       available_results_.find(ANDROID_LENS_OPTICAL_STABILIZATION_MODE) !=
2674       available_results_.end();
2675   report_pose_rotation_ = available_results_.find(ANDROID_LENS_POSE_ROTATION) !=
2676                           available_results_.end();
2677   report_pose_translation_ =
2678       available_results_.find(ANDROID_LENS_POSE_TRANSLATION) !=
2679       available_results_.end();
2680   report_intrinsic_calibration_ =
2681       available_results_.find(ANDROID_LENS_INTRINSIC_CALIBRATION) !=
2682       available_results_.end();
2683   report_distortion_ = available_results_.find(ANDROID_LENS_DISTORTION) !=
2684                        available_results_.end();
2685 
2686   focus_distance_ = minimum_focus_distance_;
2687   for (size_t idx = 0; idx < kTemplateCount; idx++) {
2688     if (default_requests_[idx].get() == nullptr) {
2689       continue;
2690     }
2691 
2692     default_requests_[idx]->Set(ANDROID_LENS_APERTURE, &aperture_, 1);
2693     default_requests_[idx]->Set(ANDROID_LENS_FOCAL_LENGTH, &focal_length_, 1);
2694     default_requests_[idx]->Set(ANDROID_LENS_FOCUS_DISTANCE, &focus_distance_,
2695                                 1);
2696     default_requests_[idx]->Set(ANDROID_LENS_OPTICAL_STABILIZATION_MODE,
2697                                 &ois_mode_, 1);
2698   }
2699 
2700   return InitializeFlashDefaults();
2701 }
2702 
InitializeInfoDefaults()2703 status_t EmulatedRequestState::InitializeInfoDefaults() {
2704   camera_metadata_ro_entry_t entry;
2705   auto ret =
2706       static_metadata_->Get(ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL, &entry);
2707   if ((ret == OK) && (entry.count == 1)) {
2708     if (kSupportedHWLevels.find(entry.data.u8[0]) ==
2709         kSupportedCapabilites.end()) {
2710       ALOGE("%s: HW Level: %u not supported", __FUNCTION__, entry.data.u8[0]);
2711       return BAD_VALUE;
2712     }
2713   } else {
2714     ALOGE("%s: No available hardware level!", __FUNCTION__);
2715     return BAD_VALUE;
2716   }
2717 
2718   supported_hw_level_ = entry.data.u8[0];
2719   is_level_full_or_higher_ =
2720       (supported_hw_level_ == ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_FULL) ||
2721       (supported_hw_level_ == ANDROID_INFO_SUPPORTED_HARDWARE_LEVEL_3);
2722 
2723   return InitializeReprocessDefaults();
2724 }
2725 
InitializeReprocessDefaults()2726 status_t EmulatedRequestState::InitializeReprocessDefaults() {
2727   if (supports_private_reprocessing_ || supports_yuv_reprocessing_ ||
2728       supports_remosaic_reprocessing_) {
2729     StreamConfigurationMap config_map(*static_metadata_);
2730     if (!config_map.SupportsReprocessing()) {
2731       ALOGE(
2732           "%s: Reprocess capability present but InputOutput format map is "
2733           "absent!",
2734           __FUNCTION__);
2735       return BAD_VALUE;
2736     }
2737 
2738     auto input_formats = config_map.GetInputFormats();
2739     for (const auto& input_format : input_formats) {
2740       auto output_formats =
2741           config_map.GetValidOutputFormatsForInput(input_format);
2742       for (const auto& output_format : output_formats) {
2743         if (!EmulatedSensor::IsReprocessPathSupported(
2744                 EmulatedSensor::OverrideFormat(input_format),
2745                 EmulatedSensor::OverrideFormat(output_format))) {
2746           ALOGE(
2747               "%s: Input format: 0x%x to output format: 0x%x reprocess is"
2748               " currently not supported!",
2749               __FUNCTION__, input_format, output_format);
2750           return BAD_VALUE;
2751         }
2752       }
2753     }
2754   }
2755 
2756   return InitializeLensDefaults();
2757 }
2758 
InitializeRequestDefaults()2759 status_t EmulatedRequestState::InitializeRequestDefaults() {
2760   camera_metadata_ro_entry_t entry;
2761   auto ret =
2762       static_metadata_->Get(ANDROID_REQUEST_AVAILABLE_CAPABILITIES, &entry);
2763   if ((ret == OK) && (entry.count > 0)) {
2764     for (size_t i = 0; i < entry.count; i++) {
2765       if (kSupportedCapabilites.find(entry.data.u8[i]) ==
2766           kSupportedCapabilites.end()) {
2767         ALOGE("%s: Capability: %u not supported", __FUNCTION__,
2768               entry.data.u8[i]);
2769         return BAD_VALUE;
2770       }
2771     }
2772   } else {
2773     ALOGE("%s: No available capabilities!", __FUNCTION__);
2774     return BAD_VALUE;
2775   }
2776   available_capabilities_.insert(entry.data.u8, entry.data.u8 + entry.count);
2777 
2778   ret = static_metadata_->Get(ANDROID_REQUEST_PIPELINE_MAX_DEPTH, &entry);
2779   if ((ret == OK) && (entry.count == 1)) {
2780     if (entry.data.u8[0] == 0) {
2781       ALOGE("%s: Maximum request pipeline depth must have a non zero value!",
2782             __FUNCTION__);
2783       return BAD_VALUE;
2784     }
2785   } else {
2786     ALOGE("%s: Maximum request pipeline depth absent!", __FUNCTION__);
2787     return BAD_VALUE;
2788   }
2789   max_pipeline_depth_ = entry.data.u8[0];
2790 
2791   ret = static_metadata_->Get(ANDROID_REQUEST_PARTIAL_RESULT_COUNT, &entry);
2792   if ((ret == OK) && (entry.count == 1)) {
2793     if (entry.data.i32[0] != 1) {
2794       ALOGW("%s: Partial results not supported!", __FUNCTION__);
2795     }
2796   }
2797 
2798   ret = static_metadata_->Get(ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS,
2799                               &entry);
2800   if ((ret != OK) || (entry.count == 0)) {
2801     ALOGE("%s: No available characteristic keys!", __FUNCTION__);
2802     return BAD_VALUE;
2803   }
2804   available_characteristics_.insert(entry.data.i32,
2805                                     entry.data.i32 + entry.count);
2806 
2807   ret = static_metadata_->Get(ANDROID_REQUEST_AVAILABLE_RESULT_KEYS, &entry);
2808   if ((ret != OK) || (entry.count == 0)) {
2809     ALOGE("%s: No available result keys!", __FUNCTION__);
2810     return BAD_VALUE;
2811   }
2812   available_results_.insert(entry.data.i32, entry.data.i32 + entry.count);
2813 
2814   ret = static_metadata_->Get(ANDROID_REQUEST_AVAILABLE_REQUEST_KEYS, &entry);
2815   if ((ret != OK) || (entry.count == 0)) {
2816     ALOGE("%s: No available request keys!", __FUNCTION__);
2817     return BAD_VALUE;
2818   }
2819   available_requests_.insert(entry.data.i32, entry.data.i32 + entry.count);
2820 
2821   supports_manual_sensor_ =
2822       SupportsCapability(ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR);
2823   supports_manual_post_processing_ = SupportsCapability(
2824       ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MANUAL_POST_PROCESSING);
2825   supports_private_reprocessing_ = SupportsCapability(
2826       ANDROID_REQUEST_AVAILABLE_CAPABILITIES_PRIVATE_REPROCESSING);
2827   supports_yuv_reprocessing_ = SupportsCapability(
2828       ANDROID_REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING);
2829   supports_remosaic_reprocessing_ = SupportsCapability(
2830       ANDROID_REQUEST_AVAILABLE_CAPABILITIES_REMOSAIC_REPROCESSING);
2831   is_backward_compatible_ = SupportsCapability(
2832       ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE);
2833   is_raw_capable_ =
2834       SupportsCapability(ANDROID_REQUEST_AVAILABLE_CAPABILITIES_RAW);
2835 
2836   if (supports_manual_sensor_) {
2837     auto templateIdx = static_cast<size_t>(RequestTemplate::kManual);
2838     default_requests_[templateIdx] = HalCameraMetadata::Create(1, 10);
2839   }
2840 
2841   for (size_t templateIdx = 0; templateIdx < kTemplateCount; templateIdx++) {
2842     switch (static_cast<RequestTemplate>(templateIdx)) {
2843       case RequestTemplate::kPreview:
2844       case RequestTemplate::kStillCapture:
2845       case RequestTemplate::kVideoRecord:
2846       case RequestTemplate::kVideoSnapshot:
2847         default_requests_[templateIdx] = HalCameraMetadata::Create(1, 10);
2848         break;
2849       default:
2850         // Noop
2851         break;
2852     }
2853   }
2854 
2855   if (supports_yuv_reprocessing_ || supports_private_reprocessing_) {
2856     auto templateIdx = static_cast<size_t>(RequestTemplate::kZeroShutterLag);
2857     default_requests_[templateIdx] = HalCameraMetadata::Create(1, 10);
2858   }
2859 
2860   return InitializeInfoDefaults();
2861 }
2862 
Initialize(std::unique_ptr<HalCameraMetadata> staticMeta)2863 status_t EmulatedRequestState::Initialize(
2864     std::unique_ptr<HalCameraMetadata> staticMeta) {
2865   std::lock_guard<std::mutex> lock(request_state_mutex_);
2866   static_metadata_ = std::move(staticMeta);
2867 
2868   return InitializeRequestDefaults();
2869 }
2870 
GetDefaultRequest(RequestTemplate type,std::unique_ptr<HalCameraMetadata> * default_settings)2871 status_t EmulatedRequestState::GetDefaultRequest(
2872     RequestTemplate type, std::unique_ptr<HalCameraMetadata>* default_settings) {
2873   if (default_settings == nullptr) {
2874     ALOGE("%s default_settings is nullptr", __FUNCTION__);
2875     return BAD_VALUE;
2876   }
2877 
2878   std::lock_guard<std::mutex> lock(request_state_mutex_);
2879   auto idx = static_cast<size_t>(type);
2880   if (idx >= kTemplateCount) {
2881     ALOGE("%s: Unexpected request type: %d", __FUNCTION__, type);
2882     return BAD_VALUE;
2883   }
2884 
2885   if (default_requests_[idx].get() == nullptr) {
2886     ALOGE("%s: Unsupported request type: %d", __FUNCTION__, type);
2887     return BAD_VALUE;
2888   }
2889 
2890   *default_settings =
2891       HalCameraMetadata::Clone(default_requests_[idx]->GetRawCameraMetadata());
2892 
2893   return OK;
2894 }
2895 
2896 }  // namespace android
2897