1# Copyright 2024 The Android Open Source Project 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Verify manual flash strength control (SINGLE capture mode) works correctly.""" 15 16import logging 17import os.path 18 19from mobly import test_runner 20import camera_properties_utils 21import capture_request_utils 22import image_processing_utils 23import its_base_test 24import its_session_utils 25import lighting_control_utils 26 27_TESTING_AE_MODES = (0, 1, 2) 28_AE_MODE_FLASH_CONTROL = (0, 1) 29_AE_MODES = {0: 'OFF', 1: 'ON', 2: 'ON_AUTO_FLASH', 3: 'ON_ALWAYS_FLASH', 30 4: 'ON_AUTO_FLASH_REDEYE', 5: 'ON_EXTERNAL_FLASH'} 31_AE_STATES = {0: 'INACTIVE', 1: 'SEARCHING', 2: 'CONVERGED', 3: 'LOCKED', 32 4: 'FLASH_REQUIRED', 5: 'PRECAPTURE'} 33_FLASH_STATES = {0: 'FLASH_STATE_UNAVAILABLE', 1: 'FLASH_STATE_CHARGING', 34 2: 'FLASH_STATE_READY', 3: 'FLASH_STATE_FIRED', 35 4: 'FLASH_STATE_PARTIAL'} 36_FORMAT_NAME = 'yuv' 37_IMG_SIZE = (640, 480) 38_PATCH_H = 0.25 # center 25% 39_PATCH_W = 0.25 40_PATCH_X = 0.5-_PATCH_W/2 41_PATCH_Y = 0.5-_PATCH_H/2 42_TEST_NAME = os.path.splitext(os.path.basename(__file__))[0] 43_CAPTURE_INTENT_STILL_CAPTURE = 2 44_MAX_FLASH_STRENGTH = 'android.flash.singleStrengthMaxLevel' 45_MAX_TORCH_STRENGTH = 'android.flash.torchStrengthMaxLevel' 46_BRIGHTNESS_MEAN_ATOL = 5 # Tolerance for brightness mean 47_STRENGTH_STEPS = 3 # Steps of flash strengths to be tested 48 49 50def _take_captures(out_surfaces, cam, img_name, ae_mode, strength=0): 51 """Takes captures and returns the captured image. 52 53 Args: 54 out_surfaces: list; valid output surfaces for caps. 55 cam: ItsSession util object. 56 img_name: image name to be saved. 57 ae_mode: AE mode to be tested with. 58 strength: Flash strength that flash should be fired with. 59 Note that 0 is for baseline capture. 60 61 Returns: 62 cap: captured image object as defined by 63 ItsSessionUtils.do_capture(). 64 """ 65 cam.do_3a(do_af=False) 66 # Take base image without flash 67 if strength == 0: 68 cap_req = capture_request_utils.auto_capture_request() 69 cap_req[ 70 'android.control.captureIntent'] = _CAPTURE_INTENT_STILL_CAPTURE 71 cap_req['android.control.aeMode'] = 0 72 cap = cam.do_capture(cap_req, out_surfaces) 73 # Take capture with flash strength 74 else: 75 cap = capture_request_utils.take_captures_with_flash_strength( 76 cam, out_surfaces, ae_mode, strength) 77 78 img = image_processing_utils.convert_capture_to_rgb_image(cap) 79 # Save captured image 80 image_processing_utils.write_image(img, img_name) 81 return cap 82 83 84def _get_mean(cap, props): 85 """Evaluate captured image by extracting means in the center patch. 86 87 Args: 88 cap: captured image object as defined by 89 ItsSessionUtils.do_capture(). 90 props: Camera properties object. 91 92 Returns: 93 mean: (float64) calculated mean of image center patch. 94 """ 95 metadata = cap['metadata'] 96 exp = int(metadata['android.sensor.exposureTime']) 97 iso = int(metadata['android.sensor.sensitivity']) 98 flash_exp_x_iso = [] 99 logging.debug('cap ISO: %d, exp: %d ns', iso, exp) 100 logging.debug('AE_MODE (cap): %s', 101 _AE_MODES[metadata['android.control.aeMode']]) 102 ae_state = _AE_STATES[metadata['android.control.aeState']] 103 logging.debug('AE_STATE (cap): %s', ae_state) 104 flash_state = _FLASH_STATES[metadata['android.flash.state']] 105 logging.debug('FLASH_STATE: %s', flash_state) 106 107 flash_exp_x_iso = exp*iso 108 y, _, _ = image_processing_utils.convert_capture_to_planes( 109 cap, props) 110 patch = image_processing_utils.get_image_patch( 111 y, _PATCH_X, _PATCH_Y, _PATCH_W, _PATCH_H) 112 flash_mean = image_processing_utils.compute_image_means( 113 patch)[0]*255 114 flash_grad = image_processing_utils.compute_image_max_gradients( 115 patch)[0]*255 116 117 # log results 118 logging.debug('Flash exposure X ISO %d', flash_exp_x_iso) 119 logging.debug('Flash frames Y grad: %.4f', flash_grad) 120 logging.debug('Flash frames Y mean: %.4f', flash_mean) 121 return flash_mean 122 123 124def _compare_means(formats_means, ae_mode, flash_strengths): 125 """Analyzes test results and generates failure messages. 126 127 If AE_MODE is ON/OFF, capture should show mean differences 128 in flash strengths. If AE_MODE is ON_AUTO_FLASH, flash 129 strength should be overwritten hence no mean difference in captures. 130 131 Args: 132 formats_means: list of calculated means of image center patches. 133 ae_mode: requested AE mode during testing. 134 flash_strengths: list of flash strength values requested during testing. 135 136 Returns: 137 failure_messages: (list of string) list of error messages. 138 """ 139 failure_messages = [] 140 if ae_mode in _AE_MODE_FLASH_CONTROL: 141 for mean in range(1, len(formats_means)-1): 142 if formats_means[mean] >= formats_means[mean+1]: 143 msg = ( 144 f'Capture with AE_CONTROL_MODE OFF/ON. ' 145 f'{flash_strengths[mean]} mean: {formats_means[mean]}, ' 146 f'{flash_strengths[mean+1]} mean: ' 147 f'{formats_means[mean+1]}. ' 148 f'{flash_strengths[mean+1]} should be brighter than ' 149 f'{flash_strengths[mean]}. ' 150 ) 151 failure_messages.append(msg) 152 else: 153 for mean in range(1, len(formats_means)-1): 154 diff = abs(formats_means[mean] - formats_means[mean+1]) 155 if diff > _BRIGHTNESS_MEAN_ATOL: 156 msg = ( 157 f'Capture with AE_CONTROL_MODE ON_AUTO_FLASH. ' 158 f'{flash_strengths[mean]} mean: {formats_means[mean]}, ' 159 f'{flash_strengths[mean+1]} mean: ' 160 f'{formats_means[mean+1]}. ' 161 f'Diff: {diff}; ATOL: {_BRIGHTNESS_MEAN_ATOL}. ' 162 ) 163 failure_messages.append(msg) 164 return failure_messages 165 166 167class FlashStrengthTest(its_base_test.ItsBaseTest): 168 """Test if flash strength control (SINGLE capture mode) feature works as intended.""" 169 170 def test_flash_strength(self): 171 name_with_path = os.path.join(self.log_path, _TEST_NAME) 172 173 with its_session_utils.ItsSession( 174 device_id=self.dut.serial, 175 camera_id=self.camera_id, 176 hidden_physical_id=self.hidden_physical_id) as cam: 177 props = cam.get_camera_properties() 178 props = cam.override_with_hidden_physical_camera_props(props) 179 180 # check SKIP conditions 181 max_flash_strength = props[_MAX_FLASH_STRENGTH] 182 max_torch_strength = props[_MAX_TORCH_STRENGTH] 183 camera_properties_utils.skip_unless( 184 camera_properties_utils.flash(props) and 185 max_flash_strength > 1 and max_torch_strength > 1) 186 # establish connection with lighting controller 187 arduino_serial_port = lighting_control_utils.lighting_control( 188 self.lighting_cntl, self.lighting_ch) 189 190 # turn OFF lights to darken scene 191 lighting_control_utils.set_lighting_state( 192 arduino_serial_port, self.lighting_ch, 'OFF') 193 194 failure_messages = [] 195 # list with no flash (baseline), linear strength steps, max strength 196 flash_strengths = [max_flash_strength*i/_STRENGTH_STEPS for i in 197 range(_STRENGTH_STEPS)] 198 flash_strengths.append(max_flash_strength) 199 logging.debug('Testing flash strengths: %s', flash_strengths) 200 # loop through ae modes to be tested 201 for ae_mode in _TESTING_AE_MODES: 202 formats_means = [] 203 # loop through flash strengths 204 for strength in flash_strengths: 205 if 0 < strength <= 1: 206 logging.debug('Flash strength value <=1, test case ignored') 207 else: 208 # naming images to be captured 209 img_name = f'{name_with_path}_ae_mode={ae_mode}_flash_strength={strength}.jpg' 210 # defining out_surfaces 211 width, height = _IMG_SIZE 212 out_surfaces = {'format': _FORMAT_NAME, 213 'width': width, 'height': height} 214 # take capture and evaluate 215 cap = _take_captures(out_surfaces, cam, img_name, ae_mode, strength) 216 formats_means.append(_get_mean(cap, props)) 217 218 # Compare means and assert PASS/FAIL 219 failure_messages += _compare_means(formats_means, 220 ae_mode, flash_strengths) 221 222 # turn the lights back on 223 lighting_control_utils.set_lighting_state( 224 arduino_serial_port, self.lighting_ch, 'ON') 225 if failure_messages: 226 raise AssertionError('\n'.join(failure_messages)) 227 228if __name__ == '__main__': 229 test_runner.main() 230