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
15import its.image
16import its.caps
17import its.device
18import its.objects
19import os.path
20from matplotlib import pylab
21import matplotlib
22import matplotlib.pyplot
23
24def main():
25    """Measure jitter in camera timestamps.
26    """
27    NAME = os.path.basename(__file__).split(".")[0]
28
29    # Pass/fail thresholds
30    MIN_AVG_FRAME_DELTA = 30 # at least 30ms delta between frames
31    MAX_VAR_FRAME_DELTA = 0.01 # variance of frame deltas
32    MAX_FRAME_DELTA_JITTER = 0.3 # max ms gap from the average frame delta
33
34    with its.device.ItsSession() as cam:
35        props = cam.get_camera_properties()
36        its.caps.skip_unless(its.caps.manual_sensor(props) and
37                             its.caps.sensor_fusion(props))
38
39        req, fmt = its.objects.get_fastest_manual_capture_settings(props)
40        caps = cam.do_capture([req]*50, [fmt])
41
42        # Print out the millisecond delta between the start of each exposure
43        tstamps = [c['metadata']['android.sensor.timestamp'] for c in caps]
44        deltas = [tstamps[i]-tstamps[i-1] for i in range(1,len(tstamps))]
45        deltas_ms = [d/1000000.0 for d in deltas]
46        avg = sum(deltas_ms) / len(deltas_ms)
47        var = sum([d*d for d in deltas_ms]) / len(deltas_ms) - avg * avg
48        range0 = min(deltas_ms) - avg
49        range1 = max(deltas_ms) - avg
50        print "Average:", avg
51        print "Variance:", var
52        print "Jitter range:", range0, "to", range1
53
54        # Draw a plot.
55        pylab.plot(range(len(deltas_ms)), deltas_ms)
56        matplotlib.pyplot.savefig("%s_deltas.png" % (NAME))
57
58        # Test for pass/fail.
59        assert(avg > MIN_AVG_FRAME_DELTA)
60        assert(var < MAX_VAR_FRAME_DELTA)
61        assert(abs(range0) < MAX_FRAME_DELTA_JITTER)
62        assert(abs(range1) < MAX_FRAME_DELTA_JITTER)
63
64if __name__ == '__main__':
65    main()
66
67