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