1# Copyright 2013 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"""Verifies android.flash.mode parameters is applied when set."""
15
16
17import logging
18import os.path
19from mobly import test_runner
20
21import its_base_test
22import camera_properties_utils
23import capture_request_utils
24import image_processing_utils
25import its_session_utils
26import target_exposure_utils
27
28CHART_DISTANCE_NO_SCALING = 100  # 1 meter to disable scaling
29FLASH_MODES = {'OFF': 0, 'SINGLE': 1, 'TORCH': 2}
30FLASH_STATES = {'UNAVAIL': 0, 'CHARGING': 1, 'READY': 2, 'FIRED': 3,
31                'PARTIAL': 4}
32NAME = os.path.splitext(os.path.basename(__file__))[0]
33PATCH_H = 0.25  # center 25%
34PATCH_W = 0.25
35PATCH_X = 0.5 - PATCH_W/2
36PATCH_Y = 0.5 - PATCH_H/2
37GRADIENT_DELTA = 0.1  # used for tablet setups (tablet screen aborbs energy)
38Y_RELATIVE_DELTA_FLASH = 0.1  # 10%  # used for reflective chart setups
39Y_RELATIVE_DELTA_TORCH = 0.05  # 5%  # used for reflective chart setups
40
41
42class ParamFlashModeTest(its_base_test.ItsBaseTest):
43  """Test that the android.flash.mode parameter is applied."""
44
45  def test_param_flash_mode(self):
46    logging.debug('Starting %s', NAME)
47    logging.debug('FLASH_MODES[OFF]: %d, [SINGLE]: %d, [TORCH]: %d',
48                  FLASH_MODES['OFF'], FLASH_MODES['SINGLE'],
49                  FLASH_MODES['TORCH'])
50    logging.debug(('FLASH_STATES[UNAVAIL]: %d, [CHARGING]: %d, [READY]: %d,'
51                   '[FIRED] %d, [PARTIAL]: %d'), FLASH_STATES['UNAVAIL'],
52                  FLASH_STATES['CHARGING'], FLASH_STATES['READY'],
53                  FLASH_STATES['FIRED'], FLASH_STATES['PARTIAL'])
54
55    with its_session_utils.ItsSession(
56        device_id=self.dut.serial,
57        camera_id=self.camera_id,
58        hidden_physical_id=self.hidden_physical_id) as cam:
59      props = cam.get_camera_properties()
60      props = cam.override_with_hidden_physical_camera_props(props)
61      log_path = self.log_path
62
63      # check SKIP conditions
64      camera_properties_utils.skip_unless(
65          camera_properties_utils.compute_target_exposure(props) and
66          camera_properties_utils.flash(props))
67
68      # Load chart for scene
69      its_session_utils.load_scene(
70          cam, props, self.scene, self.tablet, CHART_DISTANCE_NO_SCALING)
71
72      modes = []
73      states = []
74      means = []
75      grads = []
76
77      # Manually set the exposure to be a little on the dark side, so that
78      # it should be obvious whether the flash fired or not, and use a
79      # linear tonemap.
80      largest_yuv = capture_request_utils.get_largest_yuv_format(props)
81      match_ar = (largest_yuv['width'], largest_yuv['height'])
82      fmt = capture_request_utils.get_smallest_yuv_format(
83          props, match_ar=match_ar)
84      sync_latency = camera_properties_utils.sync_latency(props)
85
86      e, s = target_exposure_utils.get_target_exposure_combos(
87          log_path, cam)['midExposureTime']
88      e /= 2  # darken image slightly
89      req = capture_request_utils.manual_capture_request(s, e, 0.0, True, props)
90
91      for f in FLASH_MODES.values():
92        req['android.flash.mode'] = f
93        cap = its_session_utils.do_capture_with_latency(
94            cam, req, sync_latency, fmt)
95        modes.append(cap['metadata']['android.flash.mode'])
96        states.append(cap['metadata']['android.flash.state'])
97        y, _, _ = image_processing_utils.convert_capture_to_planes(cap, props)
98        image_processing_utils.write_image(
99            y, '%s_%d.jpg' % (os.path.join(log_path, NAME), f))
100        patch = image_processing_utils.get_image_patch(
101            y, PATCH_X, PATCH_Y, PATCH_W, PATCH_H)
102        image_processing_utils.write_image(
103            patch, '%s_%d_patch.jpg' % (os.path.join(log_path, NAME), f))
104        means.append(image_processing_utils.compute_image_means(patch)[0])
105        grads.append(image_processing_utils.compute_image_max_gradients(
106            patch)[0])
107
108      # Assert state behavior
109      logging.debug('Reported modes: %s', str(modes))
110      logging.debug('Reported states: %s', str(states))
111      assert modes == list(FLASH_MODES.values()), str(modes)
112
113      e_msg = 'flash state reported[OFF]: %d' % states[FLASH_MODES['OFF']]
114      assert states[FLASH_MODES['OFF']] not in [
115          FLASH_STATES['FIRED'], FLASH_STATES['PARTIAL']], e_msg
116
117      e_msg = 'flash state reported[SINGLE]: %d' % states[FLASH_MODES['SINGLE']]
118      assert states[FLASH_MODES['SINGLE']] in [
119          FLASH_STATES['FIRED'], FLASH_STATES['PARTIAL']], e_msg
120
121      e_msg = 'flash state reported[TORCH]: %d' % states[FLASH_MODES['TORCH']]
122      assert states[FLASH_MODES['TORCH']] in [
123          FLASH_STATES['FIRED'], FLASH_STATES['PARTIAL']], e_msg
124
125      # Assert image behavior: change between OFF & SINGLE
126      logging.debug('Brightness means: %s', str(means))
127      logging.debug('Max gradients: %s', str(grads))
128      grad_delta = grads[FLASH_MODES['SINGLE']] - grads[FLASH_MODES['OFF']]
129      mean_delta = ((means[FLASH_MODES['SINGLE']] - means[FLASH_MODES['OFF']]) /
130                    means[FLASH_MODES['OFF']])
131      e_msg = 'gradient SINGLE-OFF: %.3f, ATOL: %.3f' % (
132          grad_delta, GRADIENT_DELTA)
133      e_msg += ' mean SINGLE:OFF %.3f, ATOL: %.3f' % (
134          mean_delta, Y_RELATIVE_DELTA_FLASH)
135      assert (grad_delta > GRADIENT_DELTA or
136              mean_delta > Y_RELATIVE_DELTA_FLASH), e_msg
137
138      # Assert image behavior: change between OFF & TORCH
139      grad_delta = grads[FLASH_MODES['TORCH']] - grads[FLASH_MODES['OFF']]
140      mean_delta = ((means[FLASH_MODES['TORCH']] - means[FLASH_MODES['OFF']]) /
141                    means[FLASH_MODES['OFF']])
142      e_msg = 'gradient TORCH-OFF: %.3f, ATOL: %.3f' % (
143          grad_delta, GRADIENT_DELTA)
144      e_msg += ' mean TORCH:OFF %.3f, ATOL: %.3f' % (
145          mean_delta, Y_RELATIVE_DELTA_TORCH)
146      assert (grad_delta > GRADIENT_DELTA or
147              mean_delta > Y_RELATIVE_DELTA_TORCH), e_msg
148
149if __name__ == '__main__':
150  test_runner.main()
151
152