1# Copyright 2014 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"""CameraITS test to verify metadata entries."""
15
16import logging
17import math
18
19from mobly import test_runner
20
21import its_base_test
22import camera_properties_utils
23import capture_request_utils
24import its_session_utils
25
26_HYPERFOCAL_MIN = 0.02
27
28
29class MetadataTest(its_base_test.ItsBaseTest):
30  """Test the validity of some metadata entries.
31
32  Looks at the capture results and at the camera characteristics objects.
33  """
34
35  def test_metadata(self):
36    with its_session_utils.ItsSession(
37        device_id=self.dut.serial,
38        camera_id=self.camera_id,
39        hidden_physical_id=self.hidden_physical_id) as cam:
40      # Arbitrary capture request exposure values; image content is not
41      # important for this test, only the metadata.
42      props = cam.get_camera_properties()
43      props = cam.override_with_hidden_physical_camera_props(props)
44      camera_properties_utils.skip_unless(
45          camera_properties_utils.backward_compatible(props))
46      auto_req = capture_request_utils.auto_capture_request()
47      cap = cam.do_capture(auto_req)
48      md = cap['metadata']
49      self.failed = False
50      logging.debug('Hardware level')
51      logging.debug('Legacy: %s', camera_properties_utils.legacy(props))
52
53      logging.debug('Limited: %s', camera_properties_utils.limited(props))
54      logging.debug('Full or better: %s',
55                    camera_properties_utils.full_or_better(props))
56      logging.debug('Level 3: %s', camera_properties_utils.level3(props))
57      logging.debug('Capabilities')
58      logging.debug('Manual sensor: %s',
59                    camera_properties_utils.manual_sensor(props))
60      logging.debug('Manual post-proc: %s',
61                    camera_properties_utils.manual_post_proc(props))
62      logging.debug('Raw: %s', camera_properties_utils.raw(props))
63      logging.debug('Sensor fusion: %s',
64                    camera_properties_utils.sensor_fusion(props))
65
66      check(self, 'android.info.supportedHardwareLevel' in props,
67            'android.info.supportedHardwareLevel in props')
68      check(self, props['android.info.supportedHardwareLevel'] is not None,
69            'props[android.info.supportedHardwareLevel] is not None')
70      check(self, props['android.info.supportedHardwareLevel'] in [0, 1, 2, 3],
71            'props[android.info.supportedHardwareLevel] in [0, 1, 2, 3]')
72      manual_sensor = camera_properties_utils.manual_sensor(props)
73      # Test: rollingShutterSkew, and frameDuration tags must all be present,
74      # and rollingShutterSkew must be greater than zero and smaller than all
75      # of the possible frame durations.
76      if manual_sensor:
77        check(self, 'android.sensor.frameDuration' in md,
78              'md.has_key("android.sensor.frameDuration")')
79        check(self, md['android.sensor.frameDuration'] is not None,
80              'md["android.sensor.frameDuration"] is not None')
81        check(self, md['android.sensor.rollingShutterSkew'] > 0,
82              'md["android.sensor.rollingShutterSkew"] > 0')
83        check(self, md['android.sensor.frameDuration'] > 0,
84              'md["android.sensor.frameDuration"] > 0')
85        check(
86            self, md['android.sensor.rollingShutterSkew'] <=
87            md['android.sensor.frameDuration'],
88            ('md["android.sensor.rollingShutterSkew"] <= '
89             'md["android.sensor.frameDuration"]'))
90        logging.debug('frameDuration: %d ns',
91                      md['android.sensor.frameDuration'])
92
93      check(self, 'android.sensor.rollingShutterSkew' in md,
94            'md.has_key("android.sensor.rollingShutterSkew")')
95      check(self, md['android.sensor.rollingShutterSkew'] is not None,
96            'md["android.sensor.rollingShutterSkew"] is not None')
97      logging.debug('rollingShutterSkew: %d ns',
98                    md['android.sensor.rollingShutterSkew'])
99
100      # Test: timestampSource must be a valid value.
101      check(self, 'android.sensor.info.timestampSource' in props,
102            'props.has_key("android.sensor.info.timestampSource")')
103      check(self, props['android.sensor.info.timestampSource'] is not None,
104            'props["android.sensor.info.timestampSource"] is not None')
105      check(self, props['android.sensor.info.timestampSource'] in [0, 1],
106            'props["android.sensor.info.timestampSource"] in [0,1]')
107
108      # Test: croppingType must be a valid value, and for full devices, it
109      # must be FREEFORM=1.
110      check(self, 'android.scaler.croppingType' in props,
111            'props.has_key("android.scaler.croppingType")')
112      check(self, props['android.scaler.croppingType'] is not None,
113            'props["android.scaler.croppingType"] is not None')
114      check(self, props['android.scaler.croppingType'] in [0, 1],
115            'props["android.scaler.croppingType"] in [0,1]')
116
117      # Test: android.sensor.blackLevelPattern exists for RAW and is not None
118      if camera_properties_utils.raw(props):
119        check(self, 'android.sensor.blackLevelPattern' in props,
120              'props.has_key("android.sensor.blackLevelPattern")')
121        check(self, props['android.sensor.blackLevelPattern'] is not None,
122              'props["android.sensor.blackLevelPattern"] is not None')
123
124      if self.failed:
125        raise AssertionError('props failure. Check test_log.DEBUG.')
126
127      if not camera_properties_utils.legacy(props):
128        # Test: pixel_pitch, FOV, and hyperfocal distance are reasonable
129        fmts = props['android.scaler.streamConfigurationMap'][
130            'availableStreamConfigurations']
131        fmts = sorted(
132            fmts, key=lambda k: k['width'] * k['height'], reverse=True)
133        sensor_size = props['android.sensor.info.physicalSize']
134        pixel_pitch_h = (sensor_size['height'] / fmts[0]['height'] * 1E3)
135        pixel_pitch_w = (sensor_size['width'] / fmts[0]['width'] * 1E3)
136        logging.debug('Assert pixel_pitch WxH: %.2f um, %.2f um', pixel_pitch_w,
137                      pixel_pitch_h)
138        if (not 0.5 <= pixel_pitch_w <= 10 or
139            not 0.5 <= pixel_pitch_h <= 10 or
140            not 0.333 <= pixel_pitch_w/pixel_pitch_h <= 3.0):
141          raise AssertionError(
142              f'Pixel pitch error! w: {pixel_pitch_w}, h: {pixel_pitch_h}')
143
144        diag = math.sqrt(sensor_size['height']**2 + sensor_size['width']**2)
145        fl = md['android.lens.focalLength']
146        logging.debug('Focal length: %.3f', fl)
147        fov = 2 * math.degrees(math.atan(diag / (2 * fl)))
148        logging.debug('Assert field of view: %.1f degrees', fov)
149        if not 10 <= fov <= 130:
150          raise AssertionError(f'FoV error: {fov:.1f}')
151
152        if camera_properties_utils.lens_approx_calibrated(props):
153          diopter_hyperfocal = props['android.lens.info.hyperfocalDistance']
154          if diopter_hyperfocal != 0.0:
155            hyperfocal = 1.0 / diopter_hyperfocal
156            if _HYPERFOCAL_MIN > hyperfocal:
157              raise AssertionError('hyperfocal distance error: '
158                                   f'{hyperfocal:.2f}, MIN: {_HYPERFOCAL_MIN}')
159
160        logging.debug('Minimum focus distance: %3.f',
161                      props['android.lens.info.minimumFocusDistance'])
162
163
164def check(self, expr, msg):
165  if expr:
166    logging.debug('Passed>>%s', msg)
167  else:
168    logging.debug('Failed>>%s', msg)
169    self.failed = True
170
171
172if __name__ == '__main__':
173  test_runner.main()
174