1 /*
2  * Copyright (C) 2014 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 package android.hardware.camera2.params;
18 
19 import static com.android.internal.util.Preconditions.checkArrayElementsNotNull;
20 import static com.android.internal.util.Preconditions.checkNotNull;
21 
22 import android.graphics.ImageFormat;
23 import android.graphics.PixelFormat;
24 import android.hardware.camera2.CameraCharacteristics;
25 import android.hardware.camera2.CameraDevice;
26 import android.hardware.camera2.CameraMetadata;
27 import android.hardware.camera2.CaptureRequest;
28 import android.hardware.camera2.legacy.LegacyCameraDevice;
29 import android.hardware.camera2.utils.HashCodeHelpers;
30 import android.hardware.camera2.utils.SurfaceUtils;
31 import android.util.Range;
32 import android.util.Size;
33 import android.util.SparseIntArray;
34 import android.view.Surface;
35 
36 import java.util.Arrays;
37 import java.util.HashMap;
38 import java.util.Objects;
39 import java.util.Set;
40 
41 /**
42  * Immutable class to store the available stream
43  * {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP configurations} to set up
44  * {@link android.view.Surface Surfaces} for creating a
45  * {@link android.hardware.camera2.CameraCaptureSession capture session} with
46  * {@link android.hardware.camera2.CameraDevice#createCaptureSession}.
47  * <!-- TODO: link to input stream configuration -->
48  *
49  * <p>This is the authoritative list for all <!-- input/ -->output formats (and sizes respectively
50  * for that format) that are supported by a camera device.</p>
51  *
52  * <p>This also contains the minimum frame durations and stall durations for each format/size
53  * combination that can be used to calculate effective frame rate when submitting multiple captures.
54  * </p>
55  *
56  * <p>An instance of this object is available from {@link CameraCharacteristics} using
57  * the {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP} key and the
58  * {@link CameraCharacteristics#get} method.</p>
59  *
60  * <pre><code>{@code
61  * CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
62  * StreamConfigurationMap configs = characteristics.get(
63  *         CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
64  * }</code></pre>
65  *
66  * @see CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP
67  * @see CameraDevice#createCaptureSession
68  */
69 public final class StreamConfigurationMap {
70 
71     private static final String TAG = "StreamConfigurationMap";
72 
73     /**
74      * Create a new {@link StreamConfigurationMap}.
75      *
76      * <p>The array parameters ownership is passed to this object after creation; do not
77      * write to them after this constructor is invoked.</p>
78      *
79      * @param configurations a non-{@code null} array of {@link StreamConfiguration}
80      * @param minFrameDurations a non-{@code null} array of {@link StreamConfigurationDuration}
81      * @param stallDurations a non-{@code null} array of {@link StreamConfigurationDuration}
82      * @param depthConfigurations a non-{@code null} array of depth {@link StreamConfiguration}
83      * @param depthMinFrameDurations a non-{@code null} array of depth
84      *        {@link StreamConfigurationDuration}
85      * @param depthStallDurations a non-{@code null} array of depth
86      *        {@link StreamConfigurationDuration}
87      * @param dynamicDepthConfigurations a non-{@code null} array of dynamic depth
88      *        {@link StreamConfiguration}
89      * @param dynamicDepthMinFrameDurations a non-{@code null} array of dynamic depth
90      *        {@link StreamConfigurationDuration}
91      * @param dynamicDepthStallDurations a non-{@code null} array of dynamic depth
92      *        {@link StreamConfigurationDuration}
93      * @param heicConfigurations a non-{@code null} array of heic {@link StreamConfiguration}
94      * @param heicMinFrameDurations a non-{@code null} array of heic
95      *        {@link StreamConfigurationDuration}
96      * @param heicStallDurations a non-{@code null} array of heic
97      *        {@link StreamConfigurationDuration}
98      * @param highSpeedVideoConfigurations an array of {@link HighSpeedVideoConfiguration}, null if
99      *        camera device does not support high speed video recording
100      * @param listHighResolution a flag indicating whether the device supports BURST_CAPTURE
101      *        and thus needs a separate list of slow high-resolution output sizes
102      * @throws NullPointerException if any of the arguments except highSpeedVideoConfigurations
103      *         were {@code null} or any subelements were {@code null}
104      *
105      * @hide
106      */
StreamConfigurationMap( StreamConfiguration[] configurations, StreamConfigurationDuration[] minFrameDurations, StreamConfigurationDuration[] stallDurations, StreamConfiguration[] depthConfigurations, StreamConfigurationDuration[] depthMinFrameDurations, StreamConfigurationDuration[] depthStallDurations, StreamConfiguration[] dynamicDepthConfigurations, StreamConfigurationDuration[] dynamicDepthMinFrameDurations, StreamConfigurationDuration[] dynamicDepthStallDurations, StreamConfiguration[] heicConfigurations, StreamConfigurationDuration[] heicMinFrameDurations, StreamConfigurationDuration[] heicStallDurations, HighSpeedVideoConfiguration[] highSpeedVideoConfigurations, ReprocessFormatsMap inputOutputFormatsMap, boolean listHighResolution)107     public StreamConfigurationMap(
108             StreamConfiguration[] configurations,
109             StreamConfigurationDuration[] minFrameDurations,
110             StreamConfigurationDuration[] stallDurations,
111             StreamConfiguration[] depthConfigurations,
112             StreamConfigurationDuration[] depthMinFrameDurations,
113             StreamConfigurationDuration[] depthStallDurations,
114             StreamConfiguration[] dynamicDepthConfigurations,
115             StreamConfigurationDuration[] dynamicDepthMinFrameDurations,
116             StreamConfigurationDuration[] dynamicDepthStallDurations,
117             StreamConfiguration[] heicConfigurations,
118             StreamConfigurationDuration[] heicMinFrameDurations,
119             StreamConfigurationDuration[] heicStallDurations,
120             HighSpeedVideoConfiguration[] highSpeedVideoConfigurations,
121             ReprocessFormatsMap inputOutputFormatsMap,
122             boolean listHighResolution) {
123         this(configurations, minFrameDurations, stallDurations,
124                     depthConfigurations, depthMinFrameDurations, depthStallDurations,
125                     dynamicDepthConfigurations, dynamicDepthMinFrameDurations,
126                     dynamicDepthStallDurations,
127                     heicConfigurations, heicMinFrameDurations, heicStallDurations,
128                     highSpeedVideoConfigurations, inputOutputFormatsMap, listHighResolution,
129                     /*enforceImplementationDefined*/ true);
130     }
131 
132     /**
133      * Create a new {@link StreamConfigurationMap}.
134      *
135      * <p>The array parameters ownership is passed to this object after creation; do not
136      * write to them after this constructor is invoked.</p>
137      *
138      * @param configurations a non-{@code null} array of {@link StreamConfiguration}
139      * @param minFrameDurations a non-{@code null} array of {@link StreamConfigurationDuration}
140      * @param stallDurations a non-{@code null} array of {@link StreamConfigurationDuration}
141      * @param depthConfigurations a non-{@code null} array of depth {@link StreamConfiguration}
142      * @param depthMinFrameDurations a non-{@code null} array of depth
143      *        {@link StreamConfigurationDuration}
144      * @param depthStallDurations a non-{@code null} array of depth
145      *        {@link StreamConfigurationDuration}
146      * @param dynamicDepthConfigurations a non-{@code null} array of dynamic depth
147      *        {@link StreamConfiguration}
148      * @param dynamicDepthMinFrameDurations a non-{@code null} array of dynamic depth
149      *        {@link StreamConfigurationDuration}
150      * @param dynamicDepthStallDurations a non-{@code null} array of dynamic depth
151      *        {@link StreamConfigurationDuration}
152      * @param heicConfigurations a non-{@code null} array of heic {@link StreamConfiguration}
153      * @param heicMinFrameDurations a non-{@code null} array of heic
154      *        {@link StreamConfigurationDuration}
155      * @param heicStallDurations a non-{@code null} array of heic
156      *        {@link StreamConfigurationDuration}
157      * @param highSpeedVideoConfigurations an array of {@link HighSpeedVideoConfiguration}, null if
158      *        camera device does not support high speed video recording
159      * @param listHighResolution a flag indicating whether the device supports BURST_CAPTURE
160      *        and thus needs a separate list of slow high-resolution output sizes
161      * @param enforceImplementationDefined a flag indicating whether
162      *        IMPLEMENTATION_DEFINED format configuration must be present
163      * @throws NullPointerException if any of the arguments except highSpeedVideoConfigurations
164      *         were {@code null} or any subelements were {@code null}
165      *
166      * @hide
167      */
StreamConfigurationMap( StreamConfiguration[] configurations, StreamConfigurationDuration[] minFrameDurations, StreamConfigurationDuration[] stallDurations, StreamConfiguration[] depthConfigurations, StreamConfigurationDuration[] depthMinFrameDurations, StreamConfigurationDuration[] depthStallDurations, StreamConfiguration[] dynamicDepthConfigurations, StreamConfigurationDuration[] dynamicDepthMinFrameDurations, StreamConfigurationDuration[] dynamicDepthStallDurations, StreamConfiguration[] heicConfigurations, StreamConfigurationDuration[] heicMinFrameDurations, StreamConfigurationDuration[] heicStallDurations, HighSpeedVideoConfiguration[] highSpeedVideoConfigurations, ReprocessFormatsMap inputOutputFormatsMap, boolean listHighResolution, boolean enforceImplementationDefined)168     public StreamConfigurationMap(
169             StreamConfiguration[] configurations,
170             StreamConfigurationDuration[] minFrameDurations,
171             StreamConfigurationDuration[] stallDurations,
172             StreamConfiguration[] depthConfigurations,
173             StreamConfigurationDuration[] depthMinFrameDurations,
174             StreamConfigurationDuration[] depthStallDurations,
175             StreamConfiguration[] dynamicDepthConfigurations,
176             StreamConfigurationDuration[] dynamicDepthMinFrameDurations,
177             StreamConfigurationDuration[] dynamicDepthStallDurations,
178             StreamConfiguration[] heicConfigurations,
179             StreamConfigurationDuration[] heicMinFrameDurations,
180             StreamConfigurationDuration[] heicStallDurations,
181             HighSpeedVideoConfiguration[] highSpeedVideoConfigurations,
182             ReprocessFormatsMap inputOutputFormatsMap,
183             boolean listHighResolution,
184             boolean enforceImplementationDefined) {
185 
186         if (configurations == null &&
187                 depthConfigurations == null &&
188                 heicConfigurations == null) {
189             throw new NullPointerException("At least one of color/depth/heic configurations " +
190                     "must not be null");
191         }
192 
193         if (configurations == null) {
194             // If no color configurations exist, ensure depth ones do
195             mConfigurations = new StreamConfiguration[0];
196             mMinFrameDurations = new StreamConfigurationDuration[0];
197             mStallDurations = new StreamConfigurationDuration[0];
198         } else {
199             mConfigurations = checkArrayElementsNotNull(configurations, "configurations");
200             mMinFrameDurations = checkArrayElementsNotNull(minFrameDurations, "minFrameDurations");
201             mStallDurations = checkArrayElementsNotNull(stallDurations, "stallDurations");
202         }
203 
204         mListHighResolution = listHighResolution;
205 
206         if (depthConfigurations == null) {
207             mDepthConfigurations = new StreamConfiguration[0];
208             mDepthMinFrameDurations = new StreamConfigurationDuration[0];
209             mDepthStallDurations = new StreamConfigurationDuration[0];
210         } else {
211             mDepthConfigurations = checkArrayElementsNotNull(depthConfigurations,
212                     "depthConfigurations");
213             mDepthMinFrameDurations = checkArrayElementsNotNull(depthMinFrameDurations,
214                     "depthMinFrameDurations");
215             mDepthStallDurations = checkArrayElementsNotNull(depthStallDurations,
216                     "depthStallDurations");
217         }
218 
219         if (dynamicDepthConfigurations == null) {
220             mDynamicDepthConfigurations = new StreamConfiguration[0];
221             mDynamicDepthMinFrameDurations = new StreamConfigurationDuration[0];
222             mDynamicDepthStallDurations = new StreamConfigurationDuration[0];
223         } else {
224             mDynamicDepthConfigurations = checkArrayElementsNotNull(dynamicDepthConfigurations,
225                     "dynamicDepthConfigurations");
226             mDynamicDepthMinFrameDurations = checkArrayElementsNotNull(
227                     dynamicDepthMinFrameDurations, "dynamicDepthMinFrameDurations");
228             mDynamicDepthStallDurations = checkArrayElementsNotNull(dynamicDepthStallDurations,
229                     "dynamicDepthStallDurations");
230         }
231 
232         if (heicConfigurations == null) {
233             mHeicConfigurations = new StreamConfiguration[0];
234             mHeicMinFrameDurations = new StreamConfigurationDuration[0];
235             mHeicStallDurations = new StreamConfigurationDuration[0];
236         } else {
237             mHeicConfigurations = checkArrayElementsNotNull(heicConfigurations,
238                     "heicConfigurations");
239             mHeicMinFrameDurations = checkArrayElementsNotNull(heicMinFrameDurations,
240                     "heicMinFrameDurations");
241             mHeicStallDurations = checkArrayElementsNotNull(heicStallDurations,
242                     "heicStallDurations");
243         }
244 
245         if (highSpeedVideoConfigurations == null) {
246             mHighSpeedVideoConfigurations = new HighSpeedVideoConfiguration[0];
247         } else {
248             mHighSpeedVideoConfigurations = checkArrayElementsNotNull(
249                     highSpeedVideoConfigurations, "highSpeedVideoConfigurations");
250         }
251 
252         // For each format, track how many sizes there are available to configure
253         for (StreamConfiguration config : mConfigurations) {
254             int fmt = config.getFormat();
255             SparseIntArray map = null;
256             if (config.isOutput()) {
257                 mAllOutputFormats.put(fmt, mAllOutputFormats.get(fmt) + 1);
258                 long duration = 0;
259                 if (mListHighResolution) {
260                     for (StreamConfigurationDuration configurationDuration : mMinFrameDurations) {
261                         if (configurationDuration.getFormat() == fmt &&
262                                 configurationDuration.getWidth() == config.getSize().getWidth() &&
263                                 configurationDuration.getHeight() == config.getSize().getHeight()) {
264                             duration = configurationDuration.getDuration();
265                             break;
266                         }
267                     }
268                 }
269                 map = duration <= DURATION_20FPS_NS ?
270                         mOutputFormats : mHighResOutputFormats;
271             } else {
272                 map = mInputFormats;
273             }
274             map.put(fmt, map.get(fmt) + 1);
275         }
276 
277         // For each depth format, track how many sizes there are available to configure
278         for (StreamConfiguration config : mDepthConfigurations) {
279             if (!config.isOutput()) {
280                 // Ignoring input depth configs
281                 continue;
282             }
283 
284             mDepthOutputFormats.put(config.getFormat(),
285                     mDepthOutputFormats.get(config.getFormat()) + 1);
286         }
287         for (StreamConfiguration config : mDynamicDepthConfigurations) {
288             if (!config.isOutput()) {
289                 // Ignoring input configs
290                 continue;
291             }
292 
293             mDynamicDepthOutputFormats.put(config.getFormat(),
294                     mDynamicDepthOutputFormats.get(config.getFormat()) + 1);
295         }
296 
297         // For each heic format, track how many sizes there are available to configure
298         for (StreamConfiguration config : mHeicConfigurations) {
299             if (!config.isOutput()) {
300                 // Ignoring input depth configs
301                 continue;
302             }
303 
304             mHeicOutputFormats.put(config.getFormat(),
305                     mHeicOutputFormats.get(config.getFormat()) + 1);
306         }
307 
308         if (configurations != null && enforceImplementationDefined &&
309                 mOutputFormats.indexOfKey(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) < 0) {
310             throw new AssertionError(
311                     "At least one stream configuration for IMPLEMENTATION_DEFINED must exist");
312         }
313 
314         // For each Size/FPS range, track how many FPS range/Size there are available
315         for (HighSpeedVideoConfiguration config : mHighSpeedVideoConfigurations) {
316             Size size = config.getSize();
317             Range<Integer> fpsRange = config.getFpsRange();
318             Integer fpsRangeCount = mHighSpeedVideoSizeMap.get(size);
319             if (fpsRangeCount == null) {
320                 fpsRangeCount = 0;
321             }
322             mHighSpeedVideoSizeMap.put(size, fpsRangeCount + 1);
323             Integer sizeCount = mHighSpeedVideoFpsRangeMap.get(fpsRange);
324             if (sizeCount == null) {
325                 sizeCount = 0;
326             }
327             mHighSpeedVideoFpsRangeMap.put(fpsRange, sizeCount + 1);
328         }
329 
330         mInputOutputFormatsMap = inputOutputFormatsMap;
331     }
332 
333     /**
334      * Get the image {@code format} output formats in this stream configuration.
335      *
336      * <p>All image formats returned by this function will be defined in either {@link ImageFormat}
337      * or in {@link PixelFormat} (and there is no possibility of collision).</p>
338      *
339      * <p>Formats listed in this array are guaranteed to return true if queried with
340      * {@link #isOutputSupportedFor(int)}.</p>
341      *
342      * @return an array of integer format
343      *
344      * @see ImageFormat
345      * @see PixelFormat
346      */
getOutputFormats()347     public int[] getOutputFormats() {
348         return getPublicFormats(/*output*/true);
349     }
350 
351     /**
352      * Get the image {@code format} output formats for a reprocessing input format.
353      *
354      * <p>When submitting a {@link CaptureRequest} with an input Surface of a given format,
355      * the only allowed target outputs of the {@link CaptureRequest} are the ones with a format
356      * listed in the return value of this method. Including any other output Surface as a target
357      * will throw an IllegalArgumentException. If no output format is supported given the input
358      * format, an empty int[] will be returned.</p>
359      *
360      * <p>All image formats returned by this function will be defined in either {@link ImageFormat}
361      * or in {@link PixelFormat} (and there is no possibility of collision).</p>
362      *
363      * <p>Formats listed in this array are guaranteed to return true if queried with
364      * {@link #isOutputSupportedFor(int)}.</p>
365      *
366      * @return an array of integer format
367      *
368      * @see ImageFormat
369      * @see PixelFormat
370      */
getValidOutputFormatsForInput(int inputFormat)371     public int[] getValidOutputFormatsForInput(int inputFormat) {
372         if (mInputOutputFormatsMap == null) {
373             return new int[0];
374         }
375 
376         int[] outputs = mInputOutputFormatsMap.getOutputs(inputFormat);
377         if (mHeicOutputFormats.size() > 0) {
378             // All reprocessing formats map contain JPEG.
379             int[] outputsWithHeic = Arrays.copyOf(outputs, outputs.length+1);
380             outputsWithHeic[outputs.length] = ImageFormat.HEIC;
381             return outputsWithHeic;
382         } else {
383             return outputs;
384         }
385     }
386 
387     /**
388      * Get the image {@code format} input formats in this stream configuration.
389      *
390      * <p>All image formats returned by this function will be defined in either {@link ImageFormat}
391      * or in {@link PixelFormat} (and there is no possibility of collision).</p>
392      *
393      * @return an array of integer format
394      *
395      * @see ImageFormat
396      * @see PixelFormat
397      */
getInputFormats()398     public int[] getInputFormats() {
399         return getPublicFormats(/*output*/false);
400     }
401 
402     /**
403      * Get the supported input sizes for this input format.
404      *
405      * <p>The format must have come from {@link #getInputFormats}; otherwise
406      * {@code null} is returned.</p>
407      *
408      * @param format a format from {@link #getInputFormats}
409      * @return a non-empty array of sizes, or {@code null} if the format was not available.
410      */
getInputSizes(final int format)411     public Size[] getInputSizes(final int format) {
412         return getPublicFormatSizes(format, /*output*/false, /*highRes*/false);
413     }
414 
415     /**
416      * Determine whether or not output surfaces with a particular user-defined format can be passed
417      * {@link CameraDevice#createCaptureSession createCaptureSession}.
418      *
419      * <p>This method determines that the output {@code format} is supported by the camera device;
420      * each output {@code surface} target may or may not itself support that {@code format}.
421      * Refer to the class which provides the surface for additional documentation.</p>
422      *
423      * <p>Formats for which this returns {@code true} are guaranteed to exist in the result
424      * returned by {@link #getOutputSizes}.</p>
425      *
426      * @param format an image format from either {@link ImageFormat} or {@link PixelFormat}
427      * @return
428      *          {@code true} iff using a {@code surface} with this {@code format} will be
429      *          supported with {@link CameraDevice#createCaptureSession}
430      *
431      * @throws IllegalArgumentException
432      *          if the image format was not a defined named constant
433      *          from either {@link ImageFormat} or {@link PixelFormat}
434      *
435      * @see ImageFormat
436      * @see PixelFormat
437      * @see CameraDevice#createCaptureSession
438      */
isOutputSupportedFor(int format)439     public boolean isOutputSupportedFor(int format) {
440         checkArgumentFormat(format);
441 
442         int internalFormat = imageFormatToInternal(format);
443         int dataspace = imageFormatToDataspace(format);
444         if (dataspace == HAL_DATASPACE_DEPTH) {
445             return mDepthOutputFormats.indexOfKey(internalFormat) >= 0;
446         } else if (dataspace == HAL_DATASPACE_DYNAMIC_DEPTH) {
447             return mDynamicDepthOutputFormats.indexOfKey(internalFormat) >= 0;
448         } else if (dataspace == HAL_DATASPACE_HEIF) {
449             return mHeicOutputFormats.indexOfKey(internalFormat) >= 0;
450         } else {
451             return getFormatsMap(/*output*/true).indexOfKey(internalFormat) >= 0;
452         }
453     }
454 
455     /**
456      * Determine whether or not output streams can be configured with a particular class
457      * as a consumer.
458      *
459      * <p>The following list is generally usable for outputs:
460      * <ul>
461      * <li>{@link android.media.ImageReader} -
462      * Recommended for image processing or streaming to external resources (such as a file or
463      * network)
464      * <li>{@link android.media.MediaRecorder} -
465      * Recommended for recording video (simple to use)
466      * <li>{@link android.media.MediaCodec} -
467      * Recommended for recording video (more complicated to use, with more flexibility)
468      * <li>{@link android.renderscript.Allocation} -
469      * Recommended for image processing with {@link android.renderscript RenderScript}
470      * <li>{@link android.view.SurfaceHolder} -
471      * Recommended for low-power camera preview with {@link android.view.SurfaceView}
472      * <li>{@link android.graphics.SurfaceTexture} -
473      * Recommended for OpenGL-accelerated preview processing or compositing with
474      * {@link android.view.TextureView}
475      * </ul>
476      * </p>
477      *
478      * <p>Generally speaking this means that creating a {@link Surface} from that class <i>may</i>
479      * provide a producer endpoint that is suitable to be used with
480      * {@link CameraDevice#createCaptureSession}.</p>
481      *
482      * <p>Since not all of the above classes support output of all format and size combinations,
483      * the particular combination should be queried with {@link #isOutputSupportedFor(Surface)}.</p>
484      *
485      * @param klass a non-{@code null} {@link Class} object reference
486      * @return {@code true} if this class is supported as an output, {@code false} otherwise
487      *
488      * @throws NullPointerException if {@code klass} was {@code null}
489      *
490      * @see CameraDevice#createCaptureSession
491      * @see #isOutputSupportedFor(Surface)
492      */
isOutputSupportedFor(Class<T> klass)493     public static <T> boolean isOutputSupportedFor(Class<T> klass) {
494         checkNotNull(klass, "klass must not be null");
495 
496         if (klass == android.media.ImageReader.class) {
497             return true;
498         } else if (klass == android.media.MediaRecorder.class) {
499             return true;
500         } else if (klass == android.media.MediaCodec.class) {
501             return true;
502         } else if (klass == android.renderscript.Allocation.class) {
503             return true;
504         } else if (klass == android.view.SurfaceHolder.class) {
505             return true;
506         } else if (klass == android.graphics.SurfaceTexture.class) {
507             return true;
508         }
509 
510         return false;
511     }
512 
513     /**
514      * Determine whether or not the {@code surface} in its current state is suitable to be included
515      * in a {@link CameraDevice#createCaptureSession capture session} as an output.
516      *
517      * <p>Not all surfaces are usable with the {@link CameraDevice}, and not all configurations
518      * of that {@code surface} are compatible. Some classes that provide the {@code surface} are
519      * compatible with the {@link CameraDevice} in general
520      * (see {@link #isOutputSupportedFor(Class)}, but it is the caller's responsibility to put the
521      * {@code surface} into a state that will be compatible with the {@link CameraDevice}.</p>
522      *
523      * <p>Reasons for a {@code surface} being specifically incompatible might be:
524      * <ul>
525      * <li>Using a format that's not listed by {@link #getOutputFormats}
526      * <li>Using a format/size combination that's not listed by {@link #getOutputSizes}
527      * <li>The {@code surface} itself is not in a state where it can service a new producer.</p>
528      * </li>
529      * </ul>
530      *
531      * <p>Surfaces from flexible sources will return true even if the exact size of the Surface does
532      * not match a camera-supported size, as long as the format (or class) is supported and the
533      * camera device supports a size that is equal to or less than 1080p in that format. If such as
534      * Surface is used to create a capture session, it will have its size rounded to the nearest
535      * supported size, below or equal to 1080p. Flexible sources include SurfaceView, SurfaceTexture,
536      * and ImageReader.</p>
537      *
538      * <p>This is not an exhaustive list; see the particular class's documentation for further
539      * possible reasons of incompatibility.</p>
540      *
541      * @param surface a non-{@code null} {@link Surface} object reference
542      * @return {@code true} if this is supported, {@code false} otherwise
543      *
544      * @throws NullPointerException if {@code surface} was {@code null}
545      * @throws IllegalArgumentException if the Surface endpoint is no longer valid
546      *
547      * @see CameraDevice#createCaptureSession
548      * @see #isOutputSupportedFor(Class)
549      */
isOutputSupportedFor(Surface surface)550     public boolean isOutputSupportedFor(Surface surface) {
551         checkNotNull(surface, "surface must not be null");
552 
553         Size surfaceSize = SurfaceUtils.getSurfaceSize(surface);
554         int surfaceFormat = SurfaceUtils.getSurfaceFormat(surface);
555         int surfaceDataspace = SurfaceUtils.getSurfaceDataspace(surface);
556 
557         // See if consumer is flexible.
558         boolean isFlexible = SurfaceUtils.isFlexibleConsumer(surface);
559 
560         StreamConfiguration[] configs =
561                 surfaceDataspace == HAL_DATASPACE_DEPTH ? mDepthConfigurations :
562                 surfaceDataspace == HAL_DATASPACE_DYNAMIC_DEPTH ? mDynamicDepthConfigurations :
563                 surfaceDataspace == HAL_DATASPACE_HEIF ? mHeicConfigurations :
564                 mConfigurations;
565         for (StreamConfiguration config : configs) {
566             if (config.getFormat() == surfaceFormat && config.isOutput()) {
567                 // Matching format, either need exact size match, or a flexible consumer
568                 // and a size no bigger than MAX_DIMEN_FOR_ROUNDING
569                 if (config.getSize().equals(surfaceSize)) {
570                     return true;
571                 } else if (isFlexible &&
572                         (config.getSize().getWidth() <= LegacyCameraDevice.MAX_DIMEN_FOR_ROUNDING)) {
573                     return true;
574                 }
575             }
576         }
577         return false;
578     }
579 
580     /**
581      * Determine whether or not the particular stream configuration is suitable to be included
582      * in a {@link CameraDevice#createCaptureSession capture session} as an output.
583      *
584      * @param size stream configuration size
585      * @param format stream configuration format
586      * @return {@code true} if this is supported, {@code false} otherwise
587      *
588      * @see CameraDevice#createCaptureSession
589      * @see #isOutputSupportedFor(Class)
590      * @hide
591      */
isOutputSupportedFor(Size size, int format)592     public boolean isOutputSupportedFor(Size size, int format) {
593         int internalFormat = imageFormatToInternal(format);
594         int dataspace = imageFormatToDataspace(format);
595 
596         StreamConfiguration[] configs =
597                 dataspace == HAL_DATASPACE_DEPTH ? mDepthConfigurations :
598                 dataspace == HAL_DATASPACE_DYNAMIC_DEPTH ? mDynamicDepthConfigurations :
599                 dataspace == HAL_DATASPACE_HEIF ? mHeicConfigurations :
600                 mConfigurations;
601         for (StreamConfiguration config : configs) {
602             if ((config.getFormat() == internalFormat) && config.isOutput() &&
603                     config.getSize().equals(size)) {
604                 return true;
605             }
606         }
607 
608         return false;
609     }
610 
611     /**
612      * Get a list of sizes compatible with {@code klass} to use as an output.
613      *
614      * <p>Some of the supported classes may support additional formats beyond
615      * {@link ImageFormat#PRIVATE}; this function only returns
616      * sizes for {@link ImageFormat#PRIVATE}. For example, {@link android.media.ImageReader}
617      * supports {@link ImageFormat#YUV_420_888} and {@link ImageFormat#PRIVATE}, this method will
618      * only return the sizes for {@link ImageFormat#PRIVATE} for {@link android.media.ImageReader}
619      * class.</p>
620      *
621      * <p>If a well-defined format such as {@code NV21} is required, use
622      * {@link #getOutputSizes(int)} instead.</p>
623      *
624      * <p>The {@code klass} should be a supported output, that querying
625      * {@code #isOutputSupportedFor(Class)} should return {@code true}.</p>
626      *
627      * @param klass
628      *          a non-{@code null} {@link Class} object reference
629      * @return
630      *          an array of supported sizes for {@link ImageFormat#PRIVATE} format,
631      *          or {@code null} iff the {@code klass} is not a supported output.
632      *
633      *
634      * @throws NullPointerException if {@code klass} was {@code null}
635      *
636      * @see #isOutputSupportedFor(Class)
637      */
getOutputSizes(Class<T> klass)638     public <T> Size[] getOutputSizes(Class<T> klass) {
639         if (isOutputSupportedFor(klass) == false) {
640             return null;
641         }
642 
643         return getInternalFormatSizes(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,
644                 HAL_DATASPACE_UNKNOWN,/*output*/true, /*highRes*/false);
645     }
646 
647     /**
648      * Get a list of sizes compatible with the requested image {@code format}.
649      *
650      * <p>The {@code format} should be a supported format (one of the formats returned by
651      * {@link #getOutputFormats}).</p>
652      *
653      * As of API level 23, the {@link #getHighResolutionOutputSizes} method can be used on devices
654      * that support the
655      * {@link android.hardware.camera2.CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE BURST_CAPTURE}
656      * capability to get a list of high-resolution output sizes that cannot operate at the preferred
657      * 20fps rate. This means that for some supported formats, this method will return an empty
658      * list, if all the supported resolutions operate at below 20fps.  For devices that do not
659      * support the BURST_CAPTURE capability, all output resolutions are listed through this method.
660      *
661      * @param format an image format from {@link ImageFormat} or {@link PixelFormat}
662      * @return
663      *          an array of supported sizes,
664      *          or {@code null} if the {@code format} is not a supported output
665      *
666      * @see ImageFormat
667      * @see PixelFormat
668      * @see #getOutputFormats
669      */
getOutputSizes(int format)670     public Size[] getOutputSizes(int format) {
671         return getPublicFormatSizes(format, /*output*/true, /*highRes*/ false);
672     }
673 
674     /**
675      * Get a list of supported high speed video recording sizes.
676      * <p>
677      * When {@link CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO} is
678      * supported in {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES}, this method will
679      * list the supported high speed video size configurations. All the sizes listed will be a
680      * subset of the sizes reported by {@link #getOutputSizes} for processed non-stalling formats
681      * (typically {@link ImageFormat#PRIVATE} {@link ImageFormat#YUV_420_888}, etc.)
682      * </p>
683      * <p>
684      * To enable high speed video recording, application must create a constrained create high speed
685      * capture session via {@link CameraDevice#createConstrainedHighSpeedCaptureSession}, and submit
686      * a CaptureRequest list created by
687      * {@link android.hardware.camera2.CameraConstrainedHighSpeedCaptureSession#createHighSpeedRequestList}
688      * to this session. The application must select the video size from this method and
689      * {@link CaptureRequest#CONTROL_AE_TARGET_FPS_RANGE FPS range} from
690      * {@link #getHighSpeedVideoFpsRangesFor} to configure the constrained high speed session and
691      * generate the high speed request list. For example, if the application intends to do high
692      * speed recording, it can select the maximum size reported by this method to create high speed
693      * capture session. Note that for the use case of multiple output streams, application must
694      * select one unique size from this method to use (e.g., preview and recording streams must have
695      * the same size). Otherwise, the high speed session creation will fail. Once the size is
696      * selected, application can get the supported FPS ranges by
697      * {@link #getHighSpeedVideoFpsRangesFor}, and use these FPS ranges to setup the recording
698      * request lists via
699      * {@link android.hardware.camera2.CameraConstrainedHighSpeedCaptureSession#createHighSpeedRequestList}.
700      * </p>
701      *
702      * @return an array of supported high speed video recording sizes
703      * @see #getHighSpeedVideoFpsRangesFor(Size)
704      * @see CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO
705      * @see CameraDevice#createConstrainedHighSpeedCaptureSession
706      * @see android.hardware.camera2.CameraConstrainedHighSpeedCaptureSession#createHighSpeedRequestList
707      */
getHighSpeedVideoSizes()708     public Size[] getHighSpeedVideoSizes() {
709         Set<Size> keySet = mHighSpeedVideoSizeMap.keySet();
710         return keySet.toArray(new Size[keySet.size()]);
711     }
712 
713     /**
714      * Get the frame per second ranges (fpsMin, fpsMax) for input high speed video size.
715      * <p>
716      * See {@link #getHighSpeedVideoFpsRanges} for how to enable high speed recording.
717      * </p>
718      * <p>
719      * The {@link CaptureRequest#CONTROL_AE_TARGET_FPS_RANGE FPS ranges} reported in this method
720      * must not be used to setup capture requests that are submitted to unconstrained capture
721      * sessions, or it will result in {@link IllegalArgumentException IllegalArgumentExceptions}.
722      * </p>
723      * <p>
724      * See {@link #getHighSpeedVideoFpsRanges} for the characteristics of the returned FPS ranges.
725      * </p>
726      *
727      * @param size one of the sizes returned by {@link #getHighSpeedVideoSizes()}
728      * @return an array of supported high speed video recording FPS ranges The upper bound of
729      *         returned ranges is guaranteed to be greater than or equal to 120.
730      * @throws IllegalArgumentException if input size does not exist in the return value of
731      *             getHighSpeedVideoSizes
732      * @see #getHighSpeedVideoSizes()
733      * @see #getHighSpeedVideoFpsRanges()
734      */
getHighSpeedVideoFpsRangesFor(Size size)735     public Range<Integer>[] getHighSpeedVideoFpsRangesFor(Size size) {
736         Integer fpsRangeCount = mHighSpeedVideoSizeMap.get(size);
737         if (fpsRangeCount == null || fpsRangeCount == 0) {
738             throw new IllegalArgumentException(String.format(
739                     "Size %s does not support high speed video recording", size));
740         }
741 
742         @SuppressWarnings("unchecked")
743         Range<Integer>[] fpsRanges = new Range[fpsRangeCount];
744         int i = 0;
745         for (HighSpeedVideoConfiguration config : mHighSpeedVideoConfigurations) {
746             if (size.equals(config.getSize())) {
747                 fpsRanges[i++] = config.getFpsRange();
748             }
749         }
750         return fpsRanges;
751     }
752 
753     /**
754      * Get a list of supported high speed video recording FPS ranges.
755      * <p>
756      * When {@link CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO} is
757      * supported in {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES}, this method will
758      * list the supported high speed video FPS range configurations. Application can then use
759      * {@link #getHighSpeedVideoSizesFor} to query available sizes for one of returned FPS range.
760      * </p>
761      * <p>
762      * To enable high speed video recording, application must create a constrained create high speed
763      * capture session via {@link CameraDevice#createConstrainedHighSpeedCaptureSession}, and submit
764      * a CaptureRequest list created by
765      * {@link android.hardware.camera2.CameraConstrainedHighSpeedCaptureSession#createHighSpeedRequestList}
766      * to this session. The application must select the video size from this method and
767      * {@link CaptureRequest#CONTROL_AE_TARGET_FPS_RANGE FPS range} from
768      * {@link #getHighSpeedVideoFpsRangesFor} to configure the constrained high speed session and
769      * generate the high speed request list. For example, if the application intends to do high
770      * speed recording, it can select one FPS range reported by this method, query the video sizes
771      * corresponding to this FPS range by {@link #getHighSpeedVideoSizesFor} and use one of reported
772      * sizes to create a high speed capture session. Note that for the use case of multiple output
773      * streams, application must select one unique size from this method to use (e.g., preview and
774      * recording streams must have the same size). Otherwise, the high speed session creation will
775      * fail. Once the high speed capture session is created, the application can set the FPS range
776      * in the recording request lists via
777      * {@link android.hardware.camera2.CameraConstrainedHighSpeedCaptureSession#createHighSpeedRequestList}.
778      * </p>
779      * <p>
780      * The FPS ranges reported by this method will have below characteristics:
781      * <li>The fpsMin and fpsMax will be a multiple 30fps.</li>
782      * <li>The fpsMin will be no less than 30fps, the fpsMax will be no less than 120fps.</li>
783      * <li>At least one range will be a fixed FPS range where fpsMin == fpsMax.</li>
784      * <li>For each fixed FPS range, there will be one corresponding variable FPS range [30,
785      * fps_max]. These kinds of FPS ranges are suitable for preview-only use cases where the
786      * application doesn't want the camera device always produce higher frame rate than the display
787      * refresh rate.</li>
788      * </p>
789      *
790      * @return an array of supported high speed video recording FPS ranges The upper bound of
791      *         returned ranges is guaranteed to be larger or equal to 120.
792      * @see #getHighSpeedVideoSizesFor
793      * @see CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO
794      * @see CameraDevice#createConstrainedHighSpeedCaptureSession
795      * @see android.hardware.camera2.CameraConstrainedHighSpeedCaptureSession#createHighSpeedRequestList
796      */
797     @SuppressWarnings("unchecked")
getHighSpeedVideoFpsRanges()798     public Range<Integer>[] getHighSpeedVideoFpsRanges() {
799         Set<Range<Integer>> keySet = mHighSpeedVideoFpsRangeMap.keySet();
800         return keySet.toArray(new Range[keySet.size()]);
801     }
802 
803     /**
804      * Get the supported video sizes for an input high speed FPS range.
805      *
806      * <p> See {@link #getHighSpeedVideoSizes} for how to enable high speed recording.</p>
807      *
808      * @param fpsRange one of the FPS range returned by {@link #getHighSpeedVideoFpsRanges()}
809      * @return An array of video sizes to create high speed capture sessions for high speed streaming
810      *         use cases.
811      *
812      * @throws IllegalArgumentException if input FPS range does not exist in the return value of
813      *         getHighSpeedVideoFpsRanges
814      * @see #getHighSpeedVideoFpsRanges()
815      */
getHighSpeedVideoSizesFor(Range<Integer> fpsRange)816     public Size[] getHighSpeedVideoSizesFor(Range<Integer> fpsRange) {
817         Integer sizeCount = mHighSpeedVideoFpsRangeMap.get(fpsRange);
818         if (sizeCount == null || sizeCount == 0) {
819             throw new IllegalArgumentException(String.format(
820                     "FpsRange %s does not support high speed video recording", fpsRange));
821         }
822 
823         Size[] sizes = new Size[sizeCount];
824         int i = 0;
825         for (HighSpeedVideoConfiguration config : mHighSpeedVideoConfigurations) {
826             if (fpsRange.equals(config.getFpsRange())) {
827                 sizes[i++] = config.getSize();
828             }
829         }
830         return sizes;
831     }
832 
833     /**
834      * Get a list of supported high resolution sizes, which cannot operate at full BURST_CAPTURE
835      * rate.
836      *
837      * <p>This includes all output sizes that cannot meet the 20 fps frame rate requirements for the
838      * {@link android.hardware.camera2.CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE BURST_CAPTURE}
839      * capability.  This does not include the stall duration, so for example, a JPEG or RAW16 output
840      * resolution with a large stall duration but a minimum frame duration that's above 20 fps will
841      * still be listed in the regular {@link #getOutputSizes} list. All the sizes on this list that
842      * are less than 24 megapixels are still guaranteed to operate at a rate of at least 10 fps,
843      * not including stall duration. Sizes on this list that are at least 24 megapixels are allowed
844      * to operate at less than 10 fps.</p>
845      *
846      * <p>For a device that does not support the BURST_CAPTURE capability, this list will be
847      * {@code null}, since resolutions in the {@link #getOutputSizes} list are already not
848      * guaranteed to meet &gt;= 20 fps rate requirements. For a device that does support the
849      * BURST_CAPTURE capability, this list may be empty, if all supported resolutions meet the 20
850      * fps requirement.</p>
851      *
852      * @return an array of supported slower high-resolution sizes, or {@code null} if the
853      *         BURST_CAPTURE capability is not supported
854      */
getHighResolutionOutputSizes(int format)855     public Size[] getHighResolutionOutputSizes(int format) {
856         if (!mListHighResolution) return null;
857 
858         return getPublicFormatSizes(format, /*output*/true, /*highRes*/ true);
859     }
860 
861     /**
862      * Get the minimum {@link CaptureRequest#SENSOR_FRAME_DURATION frame duration}
863      * for the format/size combination (in nanoseconds).
864      *
865      * <p>{@code format} should be one of the ones returned by {@link #getOutputFormats()}.</p>
866      * <p>{@code size} should be one of the ones returned by
867      * {@link #getOutputSizes(int)}.</p>
868      *
869      * <p>This should correspond to the frame duration when only that stream is active, with all
870      * processing (typically in {@code android.*.mode}) set to either {@code OFF} or {@code FAST}.
871      * </p>
872      *
873      * <p>When multiple streams are used in a request, the minimum frame duration will be
874      * {@code max(individual stream min durations)}.</p>
875      *
876      * <p>For devices that do not support manual sensor control
877      * ({@link android.hardware.camera2.CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR}),
878      * this function may return 0.</p>
879      *
880      * <!--
881      * TODO: uncomment after adding input stream support
882      * <p>The minimum frame duration of a stream (of a particular format, size) is the same
883      * regardless of whether the stream is input or output.</p>
884      * -->
885      *
886      * @param format an image format from {@link ImageFormat} or {@link PixelFormat}
887      * @param size an output-compatible size
888      * @return a minimum frame duration {@code >} 0 in nanoseconds, or
889      *          0 if the minimum frame duration is not available.
890      *
891      * @throws IllegalArgumentException if {@code format} or {@code size} was not supported
892      * @throws NullPointerException if {@code size} was {@code null}
893      *
894      * @see CaptureRequest#SENSOR_FRAME_DURATION
895      * @see #getOutputStallDuration(int, Size)
896      * @see ImageFormat
897      * @see PixelFormat
898      */
getOutputMinFrameDuration(int format, Size size)899     public long getOutputMinFrameDuration(int format, Size size) {
900         checkNotNull(size, "size must not be null");
901         checkArgumentFormatSupported(format, /*output*/true);
902 
903         return getInternalFormatDuration(imageFormatToInternal(format),
904                 imageFormatToDataspace(format),
905                 size,
906                 DURATION_MIN_FRAME);
907     }
908 
909     /**
910      * Get the minimum {@link CaptureRequest#SENSOR_FRAME_DURATION frame duration}
911      * for the class/size combination (in nanoseconds).
912      *
913      * <p>This assumes that the {@code klass} is set up to use {@link ImageFormat#PRIVATE}.
914      * For user-defined formats, use {@link #getOutputMinFrameDuration(int, Size)}.</p>
915      *
916      * <p>{@code klass} should be one of the ones which is supported by
917      * {@link #isOutputSupportedFor(Class)}.</p>
918      *
919      * <p>{@code size} should be one of the ones returned by
920      * {@link #getOutputSizes(int)}.</p>
921      *
922      * <p>This should correspond to the frame duration when only that stream is active, with all
923      * processing (typically in {@code android.*.mode}) set to either {@code OFF} or {@code FAST}.
924      * </p>
925      *
926      * <p>When multiple streams are used in a request, the minimum frame duration will be
927      * {@code max(individual stream min durations)}.</p>
928      *
929      * <p>For devices that do not support manual sensor control
930      * ({@link android.hardware.camera2.CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR}),
931      * this function may return 0.</p>
932      *
933      * <!--
934      * TODO: uncomment after adding input stream support
935      * <p>The minimum frame duration of a stream (of a particular format, size) is the same
936      * regardless of whether the stream is input or output.</p>
937      * -->
938      *
939      * @param klass
940      *          a class which is supported by {@link #isOutputSupportedFor(Class)} and has a
941      *          non-empty array returned by {@link #getOutputSizes(Class)}
942      * @param size an output-compatible size
943      * @return a minimum frame duration {@code >} 0 in nanoseconds, or
944      *          0 if the minimum frame duration is not available.
945      *
946      * @throws IllegalArgumentException if {@code klass} or {@code size} was not supported
947      * @throws NullPointerException if {@code size} or {@code klass} was {@code null}
948      *
949      * @see CaptureRequest#SENSOR_FRAME_DURATION
950      * @see ImageFormat
951      * @see PixelFormat
952      */
getOutputMinFrameDuration(final Class<T> klass, final Size size)953     public <T> long getOutputMinFrameDuration(final Class<T> klass, final Size size) {
954         if (!isOutputSupportedFor(klass)) {
955             throw new IllegalArgumentException("klass was not supported");
956         }
957 
958         return getInternalFormatDuration(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,
959                 HAL_DATASPACE_UNKNOWN,
960                 size, DURATION_MIN_FRAME);
961     }
962 
963     /**
964      * Get the stall duration for the format/size combination (in nanoseconds).
965      *
966      * <p>{@code format} should be one of the ones returned by {@link #getOutputFormats()}.</p>
967      * <p>{@code size} should be one of the ones returned by
968      * {@link #getOutputSizes(int)}.</p>
969      *
970      * <p>
971      * A stall duration is how much extra time would get added to the normal minimum frame duration
972      * for a repeating request that has streams with non-zero stall.
973      *
974      * <p>For example, consider JPEG captures which have the following characteristics:
975      *
976      * <ul>
977      * <li>JPEG streams act like processed YUV streams in requests for which they are not included;
978      * in requests in which they are directly referenced, they act as JPEG streams.
979      * This is because supporting a JPEG stream requires the underlying YUV data to always be ready
980      * for use by a JPEG encoder, but the encoder will only be used (and impact frame duration) on
981      * requests that actually reference a JPEG stream.
982      * <li>The JPEG processor can run concurrently to the rest of the camera pipeline, but cannot
983      * process more than 1 capture at a time.
984      * </ul>
985      *
986      * <p>In other words, using a repeating YUV request would result in a steady frame rate
987      * (let's say it's 30 FPS). If a single JPEG request is submitted periodically,
988      * the frame rate will stay at 30 FPS (as long as we wait for the previous JPEG to return each
989      * time). If we try to submit a repeating YUV + JPEG request, then the frame rate will drop from
990      * 30 FPS.</p>
991      *
992      * <p>In general, submitting a new request with a non-0 stall time stream will <em>not</em> cause a
993      * frame rate drop unless there are still outstanding buffers for that stream from previous
994      * requests.</p>
995      *
996      * <p>Submitting a repeating request with streams (call this {@code S}) is the same as setting
997      * the minimum frame duration from the normal minimum frame duration corresponding to {@code S},
998      * added with the maximum stall duration for {@code S}.</p>
999      *
1000      * <p>If interleaving requests with and without a stall duration, a request will stall by the
1001      * maximum of the remaining times for each can-stall stream with outstanding buffers.</p>
1002      *
1003      * <p>This means that a stalling request will not have an exposure start until the stall has
1004      * completed.</p>
1005      *
1006      * <p>This should correspond to the stall duration when only that stream is active, with all
1007      * processing (typically in {@code android.*.mode}) set to {@code FAST} or {@code OFF}.
1008      * Setting any of the processing modes to {@code HIGH_QUALITY} effectively results in an
1009      * indeterminate stall duration for all streams in a request (the regular stall calculation
1010      * rules are ignored).</p>
1011      *
1012      * <p>The following formats may always have a stall duration:
1013      * <ul>
1014      * <li>{@link ImageFormat#JPEG JPEG}
1015      * <li>{@link ImageFormat#RAW_SENSOR RAW16}
1016      * <li>{@link ImageFormat#RAW_PRIVATE RAW_PRIVATE}
1017      * </ul>
1018      * </p>
1019      *
1020      * <p>The following formats will never have a stall duration:
1021      * <ul>
1022      * <li>{@link ImageFormat#YUV_420_888 YUV_420_888}
1023      * <li>{@link #isOutputSupportedFor(Class) Implementation-Defined}
1024      * </ul></p>
1025      *
1026      * <p>
1027      * All other formats may or may not have an allowed stall duration on a per-capability basis;
1028      * refer to {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
1029      * android.request.availableCapabilities} for more details.</p>
1030      * </p>
1031      *
1032      * <p>See {@link CaptureRequest#SENSOR_FRAME_DURATION android.sensor.frameDuration}
1033      * for more information about calculating the max frame rate (absent stalls).</p>
1034      *
1035      * @param format an image format from {@link ImageFormat} or {@link PixelFormat}
1036      * @param size an output-compatible size
1037      * @return a stall duration {@code >=} 0 in nanoseconds
1038      *
1039      * @throws IllegalArgumentException if {@code format} or {@code size} was not supported
1040      * @throws NullPointerException if {@code size} was {@code null}
1041      *
1042      * @see CaptureRequest#SENSOR_FRAME_DURATION
1043      * @see ImageFormat
1044      * @see PixelFormat
1045      */
getOutputStallDuration(int format, Size size)1046     public long getOutputStallDuration(int format, Size size) {
1047         checkArgumentFormatSupported(format, /*output*/true);
1048 
1049         return getInternalFormatDuration(imageFormatToInternal(format),
1050                 imageFormatToDataspace(format),
1051                 size,
1052                 DURATION_STALL);
1053     }
1054 
1055     /**
1056      * Get the stall duration for the class/size combination (in nanoseconds).
1057      *
1058      * <p>This assumes that the {@code klass} is set up to use {@link ImageFormat#PRIVATE}.
1059      * For user-defined formats, use {@link #getOutputMinFrameDuration(int, Size)}.</p>
1060      *
1061      * <p>{@code klass} should be one of the ones with a non-empty array returned by
1062      * {@link #getOutputSizes(Class)}.</p>
1063      *
1064      * <p>{@code size} should be one of the ones returned by
1065      * {@link #getOutputSizes(Class)}.</p>
1066      *
1067      * <p>See {@link #getOutputStallDuration(int, Size)} for a definition of a
1068      * <em>stall duration</em>.</p>
1069      *
1070      * @param klass
1071      *          a class which is supported by {@link #isOutputSupportedFor(Class)} and has a
1072      *          non-empty array returned by {@link #getOutputSizes(Class)}
1073      * @param size an output-compatible size
1074      * @return a minimum frame duration {@code >=} 0 in nanoseconds
1075      *
1076      * @throws IllegalArgumentException if {@code klass} or {@code size} was not supported
1077      * @throws NullPointerException if {@code size} or {@code klass} was {@code null}
1078      *
1079      * @see CaptureRequest#SENSOR_FRAME_DURATION
1080      * @see ImageFormat
1081      * @see PixelFormat
1082      */
getOutputStallDuration(final Class<T> klass, final Size size)1083     public <T> long getOutputStallDuration(final Class<T> klass, final Size size) {
1084         if (!isOutputSupportedFor(klass)) {
1085             throw new IllegalArgumentException("klass was not supported");
1086         }
1087 
1088         return getInternalFormatDuration(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,
1089                 HAL_DATASPACE_UNKNOWN, size, DURATION_STALL);
1090     }
1091 
1092     /**
1093      * Check if this {@link StreamConfigurationMap} is equal to another
1094      * {@link StreamConfigurationMap}.
1095      *
1096      * <p>Two vectors are only equal if and only if each of the respective elements is equal.</p>
1097      *
1098      * @return {@code true} if the objects were equal, {@code false} otherwise
1099      */
1100     @Override
equals(final Object obj)1101     public boolean equals(final Object obj) {
1102         if (obj == null) {
1103             return false;
1104         }
1105         if (this == obj) {
1106             return true;
1107         }
1108         if (obj instanceof StreamConfigurationMap) {
1109             final StreamConfigurationMap other = (StreamConfigurationMap) obj;
1110             // XX: do we care about order?
1111             return Arrays.equals(mConfigurations, other.mConfigurations) &&
1112                     Arrays.equals(mMinFrameDurations, other.mMinFrameDurations) &&
1113                     Arrays.equals(mStallDurations, other.mStallDurations) &&
1114                     Arrays.equals(mDepthConfigurations, other.mDepthConfigurations) &&
1115                     Arrays.equals(mDepthMinFrameDurations, other.mDepthMinFrameDurations) &&
1116                     Arrays.equals(mDepthStallDurations, other.mDepthStallDurations) &&
1117                     Arrays.equals(mDynamicDepthConfigurations, other.mDynamicDepthConfigurations) &&
1118                     Arrays.equals(mDynamicDepthMinFrameDurations,
1119                             other.mDynamicDepthMinFrameDurations) &&
1120                     Arrays.equals(mDynamicDepthStallDurations, other.mDynamicDepthStallDurations) &&
1121                     Arrays.equals(mHeicConfigurations, other.mHeicConfigurations) &&
1122                     Arrays.equals(mHeicMinFrameDurations, other.mHeicMinFrameDurations) &&
1123                     Arrays.equals(mHeicStallDurations, other.mHeicStallDurations) &&
1124                     Arrays.equals(mHighSpeedVideoConfigurations,
1125                             other.mHighSpeedVideoConfigurations);
1126         }
1127         return false;
1128     }
1129 
1130     /**
1131      * {@inheritDoc}
1132      */
1133     @Override
hashCode()1134     public int hashCode() {
1135         // XX: do we care about order?
1136         return HashCodeHelpers.hashCodeGeneric(
1137                 mConfigurations, mMinFrameDurations, mStallDurations,
1138                 mDepthConfigurations, mDepthMinFrameDurations, mDepthStallDurations,
1139                 mDynamicDepthConfigurations, mDynamicDepthMinFrameDurations,
1140                 mDynamicDepthStallDurations, mHeicConfigurations,
1141                 mHeicMinFrameDurations, mHeicStallDurations,
1142                 mHighSpeedVideoConfigurations);
1143     }
1144 
1145     // Check that the argument is supported by #getOutputFormats or #getInputFormats
checkArgumentFormatSupported(int format, boolean output)1146     private int checkArgumentFormatSupported(int format, boolean output) {
1147         checkArgumentFormat(format);
1148 
1149         int internalFormat = imageFormatToInternal(format);
1150         int internalDataspace = imageFormatToDataspace(format);
1151 
1152         if (output) {
1153             if (internalDataspace == HAL_DATASPACE_DEPTH) {
1154                 if (mDepthOutputFormats.indexOfKey(internalFormat) >= 0) {
1155                     return format;
1156                 }
1157             } else if (internalDataspace == HAL_DATASPACE_DYNAMIC_DEPTH) {
1158                 if (mDynamicDepthOutputFormats.indexOfKey(internalFormat) >= 0) {
1159                     return format;
1160                 }
1161             } else if (internalDataspace == HAL_DATASPACE_HEIF) {
1162                 if (mHeicOutputFormats.indexOfKey(internalFormat) >= 0) {
1163                     return format;
1164                 }
1165             } else {
1166                 if (mAllOutputFormats.indexOfKey(internalFormat) >= 0) {
1167                     return format;
1168                 }
1169             }
1170         } else {
1171             if (mInputFormats.indexOfKey(internalFormat) >= 0) {
1172                 return format;
1173             }
1174         }
1175 
1176         throw new IllegalArgumentException(String.format(
1177                 "format %x is not supported by this stream configuration map", format));
1178     }
1179 
1180     /**
1181      * Ensures that the format is either user-defined or implementation defined.
1182      *
1183      * <p>If a format has a different internal representation than the public representation,
1184      * passing in the public representation here will fail.</p>
1185      *
1186      * <p>For example if trying to use {@link ImageFormat#JPEG}:
1187      * it has a different public representation than the internal representation
1188      * {@code HAL_PIXEL_FORMAT_BLOB}, this check will fail.</p>
1189      *
1190      * <p>Any invalid/undefined formats will raise an exception.</p>
1191      *
1192      * @param format image format
1193      * @return the format
1194      *
1195      * @throws IllegalArgumentException if the format was invalid
1196      */
checkArgumentFormatInternal(int format)1197     static int checkArgumentFormatInternal(int format) {
1198         switch (format) {
1199             case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
1200             case HAL_PIXEL_FORMAT_BLOB:
1201             case HAL_PIXEL_FORMAT_RAW_OPAQUE:
1202             case HAL_PIXEL_FORMAT_Y16:
1203                 return format;
1204             case ImageFormat.JPEG:
1205             case ImageFormat.HEIC:
1206                 throw new IllegalArgumentException(
1207                         "An unknown internal format: " + format);
1208             default:
1209                 return checkArgumentFormat(format);
1210         }
1211     }
1212 
1213     /**
1214      * Ensures that the format is publicly user-defined in either ImageFormat or PixelFormat.
1215      *
1216      * <p>If a format has a different public representation than the internal representation,
1217      * passing in the internal representation here will fail.</p>
1218      *
1219      * <p>For example if trying to use {@code HAL_PIXEL_FORMAT_BLOB}:
1220      * it has a different internal representation than the public representation
1221      * {@link ImageFormat#JPEG}, this check will fail.</p>
1222      *
1223      * <p>Any invalid/undefined formats will raise an exception, including implementation-defined.
1224      * </p>
1225      *
1226      * <p>Note that {@code @hide} and deprecated formats will not pass this check.</p>
1227      *
1228      * @param format image format
1229      * @return the format
1230      *
1231      * @throws IllegalArgumentException if the format was not user-defined
1232      */
checkArgumentFormat(int format)1233     static int checkArgumentFormat(int format) {
1234         if (!ImageFormat.isPublicFormat(format) && !PixelFormat.isPublicFormat(format)) {
1235             throw new IllegalArgumentException(String.format(
1236                     "format 0x%x was not defined in either ImageFormat or PixelFormat", format));
1237         }
1238 
1239         return format;
1240     }
1241 
1242     /**
1243      * Convert an internal format compatible with {@code graphics.h} into public-visible
1244      * {@code ImageFormat}. This assumes the dataspace of the format is not HAL_DATASPACE_DEPTH.
1245      *
1246      * <p>In particular these formats are converted:
1247      * <ul>
1248      * <li>HAL_PIXEL_FORMAT_BLOB => ImageFormat.JPEG</li>
1249      * </ul>
1250      * </p>
1251      *
1252      * <p>Passing in a format which has no public equivalent will fail;
1253      * as will passing in a public format which has a different internal format equivalent.
1254      * See {@link #checkArgumentFormat} for more details about a legal public format.</p>
1255      *
1256      * <p>All other formats are returned as-is, no further invalid check is performed.</p>
1257      *
1258      * <p>This function is the dual of {@link #imageFormatToInternal} for dataspaces other than
1259      * HAL_DATASPACE_DEPTH.</p>
1260      *
1261      * @param format image format from {@link ImageFormat} or {@link PixelFormat}
1262      * @return the converted image formats
1263      *
1264      * @throws IllegalArgumentException
1265      *          if {@code format} is {@code HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED} or
1266      *          {@link ImageFormat#JPEG}
1267      *
1268      * @see ImageFormat
1269      * @see PixelFormat
1270      * @see #checkArgumentFormat
1271      * @hide
1272      */
imageFormatToPublic(int format)1273     public static int imageFormatToPublic(int format) {
1274         switch (format) {
1275             case HAL_PIXEL_FORMAT_BLOB:
1276                 return ImageFormat.JPEG;
1277             case ImageFormat.JPEG:
1278                 throw new IllegalArgumentException(
1279                         "ImageFormat.JPEG is an unknown internal format");
1280             default:
1281                 return format;
1282         }
1283     }
1284 
1285     /**
1286      * Convert an internal format compatible with {@code graphics.h} into public-visible
1287      * {@code ImageFormat}. This assumes the dataspace of the format is HAL_DATASPACE_DEPTH.
1288      *
1289      * <p>In particular these formats are converted:
1290      * <ul>
1291      * <li>HAL_PIXEL_FORMAT_BLOB => ImageFormat.DEPTH_POINT_CLOUD
1292      * <li>HAL_PIXEL_FORMAT_Y16 => ImageFormat.DEPTH16
1293      * </ul>
1294      * </p>
1295      *
1296      * <p>Passing in an implementation-defined format which has no public equivalent will fail;
1297      * as will passing in a public format which has a different internal format equivalent.
1298      * See {@link #checkArgumentFormat} for more details about a legal public format.</p>
1299      *
1300      * <p>All other formats are returned as-is, no further invalid check is performed.</p>
1301      *
1302      * <p>This function is the dual of {@link #imageFormatToInternal} for formats associated with
1303      * HAL_DATASPACE_DEPTH.</p>
1304      *
1305      * @param format image format from {@link ImageFormat} or {@link PixelFormat}
1306      * @return the converted image formats
1307      *
1308      * @throws IllegalArgumentException
1309      *          if {@code format} is {@code HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED} or
1310      *          {@link ImageFormat#JPEG}
1311      *
1312      * @see ImageFormat
1313      * @see PixelFormat
1314      * @see #checkArgumentFormat
1315      * @hide
1316      */
depthFormatToPublic(int format)1317     public static int depthFormatToPublic(int format) {
1318         switch (format) {
1319             case HAL_PIXEL_FORMAT_BLOB:
1320                 return ImageFormat.DEPTH_POINT_CLOUD;
1321             case HAL_PIXEL_FORMAT_Y16:
1322                 return ImageFormat.DEPTH16;
1323             case HAL_PIXEL_FORMAT_RAW16:
1324                 return ImageFormat.RAW_DEPTH;
1325             case ImageFormat.JPEG:
1326                 throw new IllegalArgumentException(
1327                         "ImageFormat.JPEG is an unknown internal format");
1328             case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
1329                 throw new IllegalArgumentException(
1330                         "IMPLEMENTATION_DEFINED must not leak to public API");
1331             default:
1332                 throw new IllegalArgumentException(
1333                         "Unknown DATASPACE_DEPTH format " + format);
1334         }
1335     }
1336 
1337     /**
1338      * Convert image formats from internal to public formats (in-place).
1339      *
1340      * @param formats an array of image formats
1341      * @return {@code formats}
1342      *
1343      * @see #imageFormatToPublic
1344      */
imageFormatToPublic(int[] formats)1345     static int[] imageFormatToPublic(int[] formats) {
1346         if (formats == null) {
1347             return null;
1348         }
1349 
1350         for (int i = 0; i < formats.length; ++i) {
1351             formats[i] = imageFormatToPublic(formats[i]);
1352         }
1353 
1354         return formats;
1355     }
1356 
1357     /**
1358      * Convert a public format compatible with {@code ImageFormat} to an internal format
1359      * from {@code graphics.h}.
1360      *
1361      * <p>In particular these formats are converted:
1362      * <ul>
1363      * <li>ImageFormat.JPEG => HAL_PIXEL_FORMAT_BLOB
1364      * <li>ImageFormat.DEPTH_POINT_CLOUD => HAL_PIXEL_FORMAT_BLOB
1365      * <li>ImageFormat.DEPTH_JPEG => HAL_PIXEL_FORMAT_BLOB
1366      * <li>ImageFormat.HEIC => HAL_PIXEL_FORMAT_BLOB
1367      * <li>ImageFormat.DEPTH16 => HAL_PIXEL_FORMAT_Y16
1368      * </ul>
1369      * </p>
1370      *
1371      * <p>Passing in an internal format which has a different public format equivalent will fail.
1372      * See {@link #checkArgumentFormat} for more details about a legal public format.</p>
1373      *
1374      * <p>All other formats are returned as-is, no invalid check is performed.</p>
1375      *
1376      * <p>This function is the dual of {@link #imageFormatToPublic}.</p>
1377      *
1378      * @param format public image format from {@link ImageFormat} or {@link PixelFormat}
1379      * @return the converted image formats
1380      *
1381      * @see ImageFormat
1382      * @see PixelFormat
1383      *
1384      * @throws IllegalArgumentException
1385      *              if {@code format} was {@code HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED}
1386      */
imageFormatToInternal(int format)1387     static int imageFormatToInternal(int format) {
1388         switch (format) {
1389             case ImageFormat.JPEG:
1390             case ImageFormat.DEPTH_POINT_CLOUD:
1391             case ImageFormat.DEPTH_JPEG:
1392             case ImageFormat.HEIC:
1393                 return HAL_PIXEL_FORMAT_BLOB;
1394             case ImageFormat.DEPTH16:
1395                 return HAL_PIXEL_FORMAT_Y16;
1396             case ImageFormat.RAW_DEPTH:
1397                 return HAL_PIXEL_FORMAT_RAW16;
1398             default:
1399                 return format;
1400         }
1401     }
1402 
1403     /**
1404      * Convert a public format compatible with {@code ImageFormat} to an internal dataspace
1405      * from {@code graphics.h}.
1406      *
1407      * <p>In particular these formats are converted:
1408      * <ul>
1409      * <li>ImageFormat.JPEG => HAL_DATASPACE_V0_JFIF
1410      * <li>ImageFormat.DEPTH_POINT_CLOUD => HAL_DATASPACE_DEPTH
1411      * <li>ImageFormat.DEPTH16 => HAL_DATASPACE_DEPTH
1412      * <li>ImageFormat.DEPTH_JPEG => HAL_DATASPACE_DYNAMIC_DEPTH
1413      * <li>ImageFormat.HEIC => HAL_DATASPACE_HEIF
1414      * <li>others => HAL_DATASPACE_UNKNOWN
1415      * </ul>
1416      * </p>
1417      *
1418      * <p>Passing in an implementation-defined format here will fail (it's not a public format);
1419      * as will passing in an internal format which has a different public format equivalent.
1420      * See {@link #checkArgumentFormat} for more details about a legal public format.</p>
1421      *
1422      * <p>All other formats are returned as-is, no invalid check is performed.</p>
1423      *
1424      * <p>This function is the dual of {@link #imageFormatToPublic}.</p>
1425      *
1426      * @param format public image format from {@link ImageFormat} or {@link PixelFormat}
1427      * @return the converted image formats
1428      *
1429      * @see ImageFormat
1430      * @see PixelFormat
1431      *
1432      * @throws IllegalArgumentException
1433      *              if {@code format} was {@code HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED}
1434      */
imageFormatToDataspace(int format)1435     static int imageFormatToDataspace(int format) {
1436         switch (format) {
1437             case ImageFormat.JPEG:
1438                 return HAL_DATASPACE_V0_JFIF;
1439             case ImageFormat.DEPTH_POINT_CLOUD:
1440             case ImageFormat.DEPTH16:
1441             case ImageFormat.RAW_DEPTH:
1442                 return HAL_DATASPACE_DEPTH;
1443             case ImageFormat.DEPTH_JPEG:
1444                 return HAL_DATASPACE_DYNAMIC_DEPTH;
1445             case ImageFormat.HEIC:
1446                 return HAL_DATASPACE_HEIF;
1447             default:
1448                 return HAL_DATASPACE_UNKNOWN;
1449         }
1450     }
1451 
1452     /**
1453      * Convert image formats from public to internal formats (in-place).
1454      *
1455      * @param formats an array of image formats
1456      * @return {@code formats}
1457      *
1458      * @see #imageFormatToInternal
1459      *
1460      * @hide
1461      */
imageFormatToInternal(int[] formats)1462     public static int[] imageFormatToInternal(int[] formats) {
1463         if (formats == null) {
1464             return null;
1465         }
1466 
1467         for (int i = 0; i < formats.length; ++i) {
1468             formats[i] = imageFormatToInternal(formats[i]);
1469         }
1470 
1471         return formats;
1472     }
1473 
getPublicFormatSizes(int format, boolean output, boolean highRes)1474     private Size[] getPublicFormatSizes(int format, boolean output, boolean highRes) {
1475         try {
1476             checkArgumentFormatSupported(format, output);
1477         } catch (IllegalArgumentException e) {
1478             return null;
1479         }
1480 
1481         int internalFormat = imageFormatToInternal(format);
1482         int dataspace = imageFormatToDataspace(format);
1483 
1484         return getInternalFormatSizes(internalFormat, dataspace, output, highRes);
1485     }
1486 
getInternalFormatSizes(int format, int dataspace, boolean output, boolean highRes)1487     private Size[] getInternalFormatSizes(int format, int dataspace,
1488             boolean output, boolean highRes) {
1489         // All depth formats are non-high-res.
1490         if (dataspace == HAL_DATASPACE_DEPTH && highRes) {
1491             return new Size[0];
1492         }
1493 
1494         SparseIntArray formatsMap =
1495                 !output ? mInputFormats :
1496                 dataspace == HAL_DATASPACE_DEPTH ? mDepthOutputFormats :
1497                 dataspace == HAL_DATASPACE_DYNAMIC_DEPTH ? mDynamicDepthOutputFormats :
1498                 dataspace == HAL_DATASPACE_HEIF ? mHeicOutputFormats :
1499                 highRes ? mHighResOutputFormats :
1500                 mOutputFormats;
1501 
1502         int sizesCount = formatsMap.get(format);
1503         if ( ((!output || (dataspace == HAL_DATASPACE_DEPTH ||
1504                             dataspace == HAL_DATASPACE_DYNAMIC_DEPTH ||
1505                             dataspace == HAL_DATASPACE_HEIF)) && sizesCount == 0) ||
1506                 (output && (dataspace != HAL_DATASPACE_DEPTH &&
1507                             dataspace != HAL_DATASPACE_DYNAMIC_DEPTH &&
1508                             dataspace != HAL_DATASPACE_HEIF) &&
1509                  mAllOutputFormats.get(format) == 0)) {
1510             return null;
1511         }
1512 
1513         Size[] sizes = new Size[sizesCount];
1514         int sizeIndex = 0;
1515 
1516         StreamConfiguration[] configurations =
1517                 (dataspace == HAL_DATASPACE_DEPTH) ? mDepthConfigurations :
1518                 (dataspace == HAL_DATASPACE_DYNAMIC_DEPTH) ? mDynamicDepthConfigurations :
1519                 (dataspace == HAL_DATASPACE_HEIF) ? mHeicConfigurations :
1520                 mConfigurations;
1521         StreamConfigurationDuration[] minFrameDurations =
1522                 (dataspace == HAL_DATASPACE_DEPTH) ? mDepthMinFrameDurations :
1523                 (dataspace == HAL_DATASPACE_DYNAMIC_DEPTH) ? mDynamicDepthMinFrameDurations :
1524                 (dataspace == HAL_DATASPACE_HEIF) ? mHeicMinFrameDurations :
1525                 mMinFrameDurations;
1526 
1527         for (StreamConfiguration config : configurations) {
1528             int fmt = config.getFormat();
1529             if (fmt == format && config.isOutput() == output) {
1530                 if (output && mListHighResolution) {
1531                     // Filter slow high-res output formats; include for
1532                     // highRes, remove for !highRes
1533                     long duration = 0;
1534                     for (int i = 0; i < minFrameDurations.length; i++) {
1535                         StreamConfigurationDuration d = minFrameDurations[i];
1536                         if (d.getFormat() == fmt &&
1537                                 d.getWidth() == config.getSize().getWidth() &&
1538                                 d.getHeight() == config.getSize().getHeight()) {
1539                             duration = d.getDuration();
1540                             break;
1541                         }
1542                     }
1543                     if (dataspace != HAL_DATASPACE_DEPTH &&
1544                             highRes != (duration > DURATION_20FPS_NS)) {
1545                         continue;
1546                     }
1547                 }
1548                 sizes[sizeIndex++] = config.getSize();
1549             }
1550         }
1551 
1552         // Dynamic depth streams can have both fast and also high res modes.
1553         if ((sizeIndex != sizesCount) && (dataspace == HAL_DATASPACE_DYNAMIC_DEPTH ||
1554                 dataspace == HAL_DATASPACE_HEIF)) {
1555 
1556             if (sizeIndex > sizesCount) {
1557                 throw new AssertionError(
1558                         "Too many dynamic depth sizes (expected " + sizesCount + ", actual " +
1559                         sizeIndex + ")");
1560             }
1561 
1562             if (sizeIndex <= 0) {
1563                 sizes = new Size[0];
1564             } else {
1565                 sizes = Arrays.copyOf(sizes, sizeIndex);
1566             }
1567         } else if (sizeIndex != sizesCount) {
1568             throw new AssertionError(
1569                     "Too few sizes (expected " + sizesCount + ", actual " + sizeIndex + ")");
1570         }
1571 
1572         return sizes;
1573     }
1574 
1575     /** Get the list of publically visible output formats; does not include IMPL_DEFINED */
getPublicFormats(boolean output)1576     private int[] getPublicFormats(boolean output) {
1577         int[] formats = new int[getPublicFormatCount(output)];
1578 
1579         int i = 0;
1580 
1581         SparseIntArray map = getFormatsMap(output);
1582         for (int j = 0; j < map.size(); j++) {
1583             int format = map.keyAt(j);
1584             formats[i++] = imageFormatToPublic(format);
1585         }
1586         if (output) {
1587             for (int j = 0; j < mDepthOutputFormats.size(); j++) {
1588                 formats[i++] = depthFormatToPublic(mDepthOutputFormats.keyAt(j));
1589             }
1590             if (mDynamicDepthOutputFormats.size() > 0) {
1591                 // Only one publicly dynamic depth format is available.
1592                 formats[i++] = ImageFormat.DEPTH_JPEG;
1593             }
1594             if (mHeicOutputFormats.size() > 0) {
1595                 formats[i++] = ImageFormat.HEIC;
1596             }
1597         }
1598         if (formats.length != i) {
1599             throw new AssertionError("Too few formats " + i + ", expected " + formats.length);
1600         }
1601 
1602         return formats;
1603     }
1604 
1605     /** Get the format -> size count map for either output or input formats */
getFormatsMap(boolean output)1606     private SparseIntArray getFormatsMap(boolean output) {
1607         return output ? mAllOutputFormats : mInputFormats;
1608     }
1609 
getInternalFormatDuration(int format, int dataspace, Size size, int duration)1610     private long getInternalFormatDuration(int format, int dataspace, Size size, int duration) {
1611         // assume format is already checked, since its internal
1612 
1613         if (!isSupportedInternalConfiguration(format, dataspace, size)) {
1614             throw new IllegalArgumentException("size was not supported");
1615         }
1616 
1617         StreamConfigurationDuration[] durations = getDurations(duration, dataspace);
1618 
1619         for (StreamConfigurationDuration configurationDuration : durations) {
1620             if (configurationDuration.getFormat() == format &&
1621                     configurationDuration.getWidth() == size.getWidth() &&
1622                     configurationDuration.getHeight() == size.getHeight()) {
1623                 return configurationDuration.getDuration();
1624             }
1625         }
1626         // Default duration is '0' (unsupported/no extra stall)
1627         return 0;
1628     }
1629 
1630     /**
1631      * Get the durations array for the kind of duration
1632      *
1633      * @see #DURATION_MIN_FRAME
1634      * @see #DURATION_STALL
1635      * */
getDurations(int duration, int dataspace)1636     private StreamConfigurationDuration[] getDurations(int duration, int dataspace) {
1637         switch (duration) {
1638             case DURATION_MIN_FRAME:
1639                 return (dataspace == HAL_DATASPACE_DEPTH) ? mDepthMinFrameDurations :
1640                         (dataspace == HAL_DATASPACE_DYNAMIC_DEPTH) ?
1641                         mDynamicDepthMinFrameDurations :
1642                         (dataspace == HAL_DATASPACE_HEIF) ? mHeicMinFrameDurations :
1643                         mMinFrameDurations;
1644 
1645             case DURATION_STALL:
1646                 return (dataspace == HAL_DATASPACE_DEPTH) ? mDepthStallDurations :
1647                         (dataspace == HAL_DATASPACE_DYNAMIC_DEPTH) ? mDynamicDepthStallDurations :
1648                         (dataspace == HAL_DATASPACE_HEIF) ? mHeicStallDurations :
1649                         mStallDurations;
1650             default:
1651                 throw new IllegalArgumentException("duration was invalid");
1652         }
1653     }
1654 
1655     /** Count the number of publicly-visible output formats */
getPublicFormatCount(boolean output)1656     private int getPublicFormatCount(boolean output) {
1657         SparseIntArray formatsMap = getFormatsMap(output);
1658         int size = formatsMap.size();
1659         if (output) {
1660             size += mDepthOutputFormats.size();
1661             size += mDynamicDepthOutputFormats.size();
1662             size += mHeicOutputFormats.size();
1663         }
1664 
1665         return size;
1666     }
1667 
arrayContains(T[] array, T element)1668     private static <T> boolean arrayContains(T[] array, T element) {
1669         if (array == null) {
1670             return false;
1671         }
1672 
1673         for (T el : array) {
1674             if (Objects.equals(el, element)) {
1675                 return true;
1676             }
1677         }
1678 
1679         return false;
1680     }
1681 
isSupportedInternalConfiguration(int format, int dataspace, Size size)1682     private boolean isSupportedInternalConfiguration(int format, int dataspace, Size size) {
1683         StreamConfiguration[] configurations =
1684                 (dataspace == HAL_DATASPACE_DEPTH) ? mDepthConfigurations :
1685                 (dataspace == HAL_DATASPACE_DYNAMIC_DEPTH) ? mDynamicDepthConfigurations :
1686                 (dataspace == HAL_DATASPACE_HEIF) ? mHeicConfigurations :
1687                 mConfigurations;
1688 
1689         for (int i = 0; i < configurations.length; i++) {
1690             if (configurations[i].getFormat() == format &&
1691                     configurations[i].getSize().equals(size)) {
1692                 return true;
1693             }
1694         }
1695 
1696         return false;
1697     }
1698 
1699     /**
1700      * Return this {@link StreamConfigurationMap} as a string representation.
1701      *
1702      * <p>{@code "StreamConfigurationMap(Outputs([w:%d, h:%d, format:%s(%d), min_duration:%d,
1703      * stall:%d], ... [w:%d, h:%d, format:%s(%d), min_duration:%d, stall:%d]), Inputs([w:%d, h:%d,
1704      * format:%s(%d)], ... [w:%d, h:%d, format:%s(%d)]), ValidOutputFormatsForInput(
1705      * [in:%d, out:%d, ... %d], ... [in:%d, out:%d, ... %d]), HighSpeedVideoConfigurations(
1706      * [w:%d, h:%d, min_fps:%d, max_fps:%d], ... [w:%d, h:%d, min_fps:%d, max_fps:%d]))"}.</p>
1707      *
1708      * <p>{@code Outputs([w:%d, h:%d, format:%s(%d), min_duration:%d, stall:%d], ...
1709      * [w:%d, h:%d, format:%s(%d), min_duration:%d, stall:%d])}, where
1710      * {@code [w:%d, h:%d, format:%s(%d), min_duration:%d, stall:%d]} represents an output
1711      * configuration's width, height, format, minimal frame duration in nanoseconds, and stall
1712      * duration in nanoseconds.</p>
1713      *
1714      * <p>{@code Inputs([w:%d, h:%d, format:%s(%d)], ... [w:%d, h:%d, format:%s(%d)])}, where
1715      * {@code [w:%d, h:%d, format:%s(%d)]} represents an input configuration's width, height, and
1716      * format.</p>
1717      *
1718      * <p>{@code ValidOutputFormatsForInput([in:%s(%d), out:%s(%d), ... %s(%d)],
1719      * ... [in:%s(%d), out:%s(%d), ... %s(%d)])}, where {@code [in:%s(%d), out:%s(%d), ... %s(%d)]}
1720      * represents an input fomat and its valid output formats.</p>
1721      *
1722      * <p>{@code HighSpeedVideoConfigurations([w:%d, h:%d, min_fps:%d, max_fps:%d],
1723      * ... [w:%d, h:%d, min_fps:%d, max_fps:%d])}, where
1724      * {@code [w:%d, h:%d, min_fps:%d, max_fps:%d]} represents a high speed video output
1725      * configuration's width, height, minimal frame rate, and maximal frame rate.</p>
1726      *
1727      * @return string representation of {@link StreamConfigurationMap}
1728      */
1729     @Override
toString()1730     public String toString() {
1731         StringBuilder sb = new StringBuilder("StreamConfiguration(");
1732         appendOutputsString(sb);
1733         sb.append(", ");
1734         appendHighResOutputsString(sb);
1735         sb.append(", ");
1736         appendInputsString(sb);
1737         sb.append(", ");
1738         appendValidOutputFormatsForInputString(sb);
1739         sb.append(", ");
1740         appendHighSpeedVideoConfigurationsString(sb);
1741         sb.append(")");
1742 
1743         return sb.toString();
1744     }
1745 
appendOutputsString(StringBuilder sb)1746     private void appendOutputsString(StringBuilder sb) {
1747         sb.append("Outputs(");
1748         int[] formats = getOutputFormats();
1749         for (int format : formats) {
1750             Size[] sizes = getOutputSizes(format);
1751             for (Size size : sizes) {
1752                 long minFrameDuration = getOutputMinFrameDuration(format, size);
1753                 long stallDuration = getOutputStallDuration(format, size);
1754                 sb.append(String.format("[w:%d, h:%d, format:%s(%d), min_duration:%d, " +
1755                         "stall:%d], ", size.getWidth(), size.getHeight(), formatToString(format),
1756                         format, minFrameDuration, stallDuration));
1757             }
1758         }
1759         // Remove the pending ", "
1760         if (sb.charAt(sb.length() - 1) == ' ') {
1761             sb.delete(sb.length() - 2, sb.length());
1762         }
1763         sb.append(")");
1764     }
1765 
appendHighResOutputsString(StringBuilder sb)1766     private void appendHighResOutputsString(StringBuilder sb) {
1767         sb.append("HighResolutionOutputs(");
1768         int[] formats = getOutputFormats();
1769         for (int format : formats) {
1770             Size[] sizes = getHighResolutionOutputSizes(format);
1771             if (sizes == null) continue;
1772             for (Size size : sizes) {
1773                 long minFrameDuration = getOutputMinFrameDuration(format, size);
1774                 long stallDuration = getOutputStallDuration(format, size);
1775                 sb.append(String.format("[w:%d, h:%d, format:%s(%d), min_duration:%d, " +
1776                         "stall:%d], ", size.getWidth(), size.getHeight(), formatToString(format),
1777                         format, minFrameDuration, stallDuration));
1778             }
1779         }
1780         // Remove the pending ", "
1781         if (sb.charAt(sb.length() - 1) == ' ') {
1782             sb.delete(sb.length() - 2, sb.length());
1783         }
1784         sb.append(")");
1785     }
1786 
appendInputsString(StringBuilder sb)1787     private void appendInputsString(StringBuilder sb) {
1788         sb.append("Inputs(");
1789         int[] formats = getInputFormats();
1790         for (int format : formats) {
1791             Size[] sizes = getInputSizes(format);
1792             for (Size size : sizes) {
1793                 sb.append(String.format("[w:%d, h:%d, format:%s(%d)], ", size.getWidth(),
1794                         size.getHeight(), formatToString(format), format));
1795             }
1796         }
1797         // Remove the pending ", "
1798         if (sb.charAt(sb.length() - 1) == ' ') {
1799             sb.delete(sb.length() - 2, sb.length());
1800         }
1801         sb.append(")");
1802     }
1803 
appendValidOutputFormatsForInputString(StringBuilder sb)1804     private void appendValidOutputFormatsForInputString(StringBuilder sb) {
1805         sb.append("ValidOutputFormatsForInput(");
1806         int[] inputFormats = getInputFormats();
1807         for (int inputFormat : inputFormats) {
1808             sb.append(String.format("[in:%s(%d), out:", formatToString(inputFormat), inputFormat));
1809             int[] outputFormats = getValidOutputFormatsForInput(inputFormat);
1810             for (int i = 0; i < outputFormats.length; i++) {
1811                 sb.append(String.format("%s(%d)", formatToString(outputFormats[i]),
1812                         outputFormats[i]));
1813                 if (i < outputFormats.length - 1) {
1814                     sb.append(", ");
1815                 }
1816             }
1817             sb.append("], ");
1818         }
1819         // Remove the pending ", "
1820         if (sb.charAt(sb.length() - 1) == ' ') {
1821             sb.delete(sb.length() - 2, sb.length());
1822         }
1823         sb.append(")");
1824     }
1825 
appendHighSpeedVideoConfigurationsString(StringBuilder sb)1826     private void appendHighSpeedVideoConfigurationsString(StringBuilder sb) {
1827         sb.append("HighSpeedVideoConfigurations(");
1828         Size[] sizes = getHighSpeedVideoSizes();
1829         for (Size size : sizes) {
1830             Range<Integer>[] ranges = getHighSpeedVideoFpsRangesFor(size);
1831             for (Range<Integer> range : ranges) {
1832                 sb.append(String.format("[w:%d, h:%d, min_fps:%d, max_fps:%d], ", size.getWidth(),
1833                         size.getHeight(), range.getLower(), range.getUpper()));
1834             }
1835         }
1836         // Remove the pending ", "
1837         if (sb.charAt(sb.length() - 1) == ' ') {
1838             sb.delete(sb.length() - 2, sb.length());
1839         }
1840         sb.append(")");
1841     }
1842 
formatToString(int format)1843     private String formatToString(int format) {
1844         switch (format) {
1845             case ImageFormat.YV12:
1846                 return "YV12";
1847             case ImageFormat.YUV_420_888:
1848                 return "YUV_420_888";
1849             case ImageFormat.NV21:
1850                 return "NV21";
1851             case ImageFormat.NV16:
1852                 return "NV16";
1853             case PixelFormat.RGB_565:
1854                 return "RGB_565";
1855             case PixelFormat.RGBA_8888:
1856                 return "RGBA_8888";
1857             case PixelFormat.RGBX_8888:
1858                 return "RGBX_8888";
1859             case PixelFormat.RGB_888:
1860                 return "RGB_888";
1861             case ImageFormat.JPEG:
1862                 return "JPEG";
1863             case ImageFormat.YUY2:
1864                 return "YUY2";
1865             case ImageFormat.Y8:
1866                 return "Y8";
1867             case ImageFormat.Y16:
1868                 return "Y16";
1869             case ImageFormat.RAW_SENSOR:
1870                 return "RAW_SENSOR";
1871             case ImageFormat.RAW_PRIVATE:
1872                 return "RAW_PRIVATE";
1873             case ImageFormat.RAW10:
1874                 return "RAW10";
1875             case ImageFormat.DEPTH16:
1876                 return "DEPTH16";
1877             case ImageFormat.DEPTH_POINT_CLOUD:
1878                 return "DEPTH_POINT_CLOUD";
1879             case ImageFormat.DEPTH_JPEG:
1880                 return "DEPTH_JPEG";
1881             case ImageFormat.RAW_DEPTH:
1882                 return "RAW_DEPTH";
1883             case ImageFormat.PRIVATE:
1884                 return "PRIVATE";
1885             case ImageFormat.HEIC:
1886                 return "HEIC";
1887             default:
1888                 return "UNKNOWN";
1889         }
1890     }
1891 
1892     // from system/core/include/system/graphics.h
1893     private static final int HAL_PIXEL_FORMAT_RAW16 = 0x20;
1894     private static final int HAL_PIXEL_FORMAT_BLOB = 0x21;
1895     private static final int HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED = 0x22;
1896     private static final int HAL_PIXEL_FORMAT_YCbCr_420_888 = 0x23;
1897     private static final int HAL_PIXEL_FORMAT_RAW_OPAQUE = 0x24;
1898     private static final int HAL_PIXEL_FORMAT_RAW10 = 0x25;
1899     private static final int HAL_PIXEL_FORMAT_RAW12 = 0x26;
1900     private static final int HAL_PIXEL_FORMAT_Y16 = 0x20363159;
1901 
1902 
1903     private static final int HAL_DATASPACE_STANDARD_SHIFT = 16;
1904     private static final int HAL_DATASPACE_TRANSFER_SHIFT = 22;
1905     private static final int HAL_DATASPACE_RANGE_SHIFT = 27;
1906 
1907     private static final int HAL_DATASPACE_UNKNOWN = 0x0;
1908     private static final int HAL_DATASPACE_V0_JFIF =
1909             (2 << HAL_DATASPACE_STANDARD_SHIFT) |
1910             (3 << HAL_DATASPACE_TRANSFER_SHIFT) |
1911             (1 << HAL_DATASPACE_RANGE_SHIFT);
1912 
1913     private static final int HAL_DATASPACE_DEPTH = 0x1000;
1914     private static final int HAL_DATASPACE_DYNAMIC_DEPTH = 0x1002;
1915     private static final int HAL_DATASPACE_HEIF = 0x1003;
1916     private static final long DURATION_20FPS_NS = 50000000L;
1917     /**
1918      * @see #getDurations(int, int)
1919      */
1920     private static final int DURATION_MIN_FRAME = 0;
1921     private static final int DURATION_STALL = 1;
1922 
1923     private final StreamConfiguration[] mConfigurations;
1924     private final StreamConfigurationDuration[] mMinFrameDurations;
1925     private final StreamConfigurationDuration[] mStallDurations;
1926 
1927     private final StreamConfiguration[] mDepthConfigurations;
1928     private final StreamConfigurationDuration[] mDepthMinFrameDurations;
1929     private final StreamConfigurationDuration[] mDepthStallDurations;
1930 
1931     private final StreamConfiguration[] mDynamicDepthConfigurations;
1932     private final StreamConfigurationDuration[] mDynamicDepthMinFrameDurations;
1933     private final StreamConfigurationDuration[] mDynamicDepthStallDurations;
1934 
1935     private final StreamConfiguration[] mHeicConfigurations;
1936     private final StreamConfigurationDuration[] mHeicMinFrameDurations;
1937     private final StreamConfigurationDuration[] mHeicStallDurations;
1938 
1939     private final HighSpeedVideoConfiguration[] mHighSpeedVideoConfigurations;
1940     private final ReprocessFormatsMap mInputOutputFormatsMap;
1941 
1942     private final boolean mListHighResolution;
1943 
1944     /** internal format -> num output sizes mapping, not including slow high-res sizes, for
1945      * non-depth dataspaces */
1946     private final SparseIntArray mOutputFormats = new SparseIntArray();
1947     /** internal format -> num output sizes mapping for slow high-res sizes, for non-depth
1948      * dataspaces */
1949     private final SparseIntArray mHighResOutputFormats = new SparseIntArray();
1950     /** internal format -> num output sizes mapping for all non-depth dataspaces */
1951     private final SparseIntArray mAllOutputFormats = new SparseIntArray();
1952     /** internal format -> num input sizes mapping, for input reprocessing formats */
1953     private final SparseIntArray mInputFormats = new SparseIntArray();
1954     /** internal format -> num depth output sizes mapping, for HAL_DATASPACE_DEPTH */
1955     private final SparseIntArray mDepthOutputFormats = new SparseIntArray();
1956     /** internal format -> num dynamic depth output sizes mapping, for HAL_DATASPACE_DYNAMIC_DEPTH */
1957     private final SparseIntArray mDynamicDepthOutputFormats = new SparseIntArray();
1958     /** internal format -> num heic output sizes mapping, for HAL_DATASPACE_HEIF */
1959     private final SparseIntArray mHeicOutputFormats = new SparseIntArray();
1960 
1961     /** High speed video Size -> FPS range count mapping*/
1962     private final HashMap</*HighSpeedVideoSize*/Size, /*Count*/Integer> mHighSpeedVideoSizeMap =
1963             new HashMap<Size, Integer>();
1964     /** High speed video FPS range -> Size count mapping*/
1965     private final HashMap</*HighSpeedVideoFpsRange*/Range<Integer>, /*Count*/Integer>
1966             mHighSpeedVideoFpsRangeMap = new HashMap<Range<Integer>, Integer>();
1967 
1968 }
1969