aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/MediaCodecInfoBuilder.java
blob: 95c079190c25896957c829e0210d1e744487c467 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.Q;
import static java.util.Arrays.asList;

import android.media.MediaCodecInfo;
import android.media.MediaCodecInfo.AudioCapabilities;
import android.media.MediaCodecInfo.CodecCapabilities;
import android.media.MediaCodecInfo.CodecProfileLevel;
import android.media.MediaCodecInfo.EncoderCapabilities;
import android.media.MediaCodecInfo.VideoCapabilities;
import android.media.MediaFormat;
import android.util.Range;
import com.google.common.base.Preconditions;
import java.util.HashSet;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.ReflectionHelpers.ClassParameter;
import org.robolectric.util.reflector.Accessor;
import org.robolectric.util.reflector.ForType;
import org.robolectric.util.reflector.Reflector;
import org.robolectric.util.reflector.Static;

/** Builder for {@link MediaCodecInfo}. */
public class MediaCodecInfoBuilder {

  private String name;
  private boolean isEncoder;
  private boolean isVendor;
  private boolean isSoftwareOnly;
  private boolean isHardwareAccelerated;
  private CodecCapabilities[] capabilities = new CodecCapabilities[0];

  private MediaCodecInfoBuilder() {}

  /** Create a new {@link MediaCodecInfoBuilder}. */
  public static MediaCodecInfoBuilder newBuilder() {
    return new MediaCodecInfoBuilder();
  }

  /**
   * Sets the codec name.
   *
   * @param name codec name.
   * @throws NullPointerException if name is null.
   */
  public MediaCodecInfoBuilder setName(String name) {
    this.name = Preconditions.checkNotNull(name);
    return this;
  }

  /**
   * Sets the codec role.
   *
   * @param isEncoder a boolean to indicate whether the codec is an encoder {@code true} or a
   *     decoder {@code false}. Default value is {@code false}.
   */
  public MediaCodecInfoBuilder setIsEncoder(boolean isEncoder) {
    this.isEncoder = isEncoder;
    return this;
  }

  /**
   * Sets the codec provider.
   *
   * @param isVendor a boolean to indicate whether the codec is provided by the device manufacturer
   *     {@code true} or by the Android platform {@code false}. Default value is {@code false}.
   */
  public MediaCodecInfoBuilder setIsVendor(boolean isVendor) {
    this.isVendor = isVendor;
    return this;
  }

  /**
   * Sets whether the codec is softwrare only or not.
   *
   * @param isSoftwareOnly a boolean to indicate whether the codec is software only {@code true} or
   *     not {@code false}. Default value is {@code false}.
   */
  public MediaCodecInfoBuilder setIsSoftwareOnly(boolean isSoftwareOnly) {
    this.isSoftwareOnly = isSoftwareOnly;
    return this;
  }

  /**
   * Sets whether the codec is hardware accelerated or not.
   *
   * @param isHardwareAccelerated a boolean to indicate whether the codec is hardware accelerated
   *     {@code true} or not {@code false}. Default value is {@code false}.
   */
  public MediaCodecInfoBuilder setIsHardwareAccelerated(boolean isHardwareAccelerated) {
    this.isHardwareAccelerated = isHardwareAccelerated;
    return this;
  }

  /**
   * Sets codec capabilities.
   *
   * <p>Use {@link CodecCapabilitiesBuilder} can be to create an instance of {@link
   * CodecCapabilities}.
   *
   * @param capabilities one or multiple {@link CodecCapabilities}.
   * @throws NullPointerException if capabilities is null.
   */
  public MediaCodecInfoBuilder setCapabilities(CodecCapabilities... capabilities) {
    this.capabilities = capabilities;
    return this;
  }

  public MediaCodecInfo build() {
    Preconditions.checkNotNull(name, "Codec name is not set.");

    if (RuntimeEnvironment.getApiLevel() >= Q) {
      int flags = getCodecFlags();
      return ReflectionHelpers.callConstructor(
          MediaCodecInfo.class,
          ClassParameter.from(String.class, name),
          ClassParameter.from(String.class, name), // canonicalName
          ClassParameter.from(int.class, flags),
          ClassParameter.from(CodecCapabilities[].class, capabilities));
    } else if (RuntimeEnvironment.getApiLevel() >= LOLLIPOP) {
      return ReflectionHelpers.callConstructor(
          MediaCodecInfo.class,
          ClassParameter.from(String.class, name),
          ClassParameter.from(boolean.class, isEncoder),
          ClassParameter.from(CodecCapabilities[].class, capabilities));
    } else {
      throw new UnsupportedOperationException("Unable to create MediaCodecInfo");
    }
  }

  /** Accessor interface for {@link MediaCodecInfo}'s internals. */
  @ForType(MediaCodecInfo.class)
  interface MediaCodecInfoReflector {

    @Static
    @Accessor("FLAG_IS_ENCODER")
    int getIsEncoderFlagValue();

    @Static
    @Accessor("FLAG_IS_VENDOR")
    int getIsVendorFlagValue();

    @Static
    @Accessor("FLAG_IS_SOFTWARE_ONLY")
    int getIsSoftwareOnlyFlagValue();

    @Static
    @Accessor("FLAG_IS_HARDWARE_ACCELERATED")
    int getIsHardwareAcceleratedFlagValue();
  }

  /** Convert the boolean flags describing codec to values recognized by {@link MediaCodecInfo}. */
  private int getCodecFlags() {
    MediaCodecInfoReflector mediaCodecInfoReflector =
        Reflector.reflector(MediaCodecInfoReflector.class);

    int flags = 0;

    if (isEncoder) {
      flags |= mediaCodecInfoReflector.getIsEncoderFlagValue();
    }
    if (isVendor) {
      flags |= mediaCodecInfoReflector.getIsVendorFlagValue();
    }
    if (isSoftwareOnly) {
      flags |= mediaCodecInfoReflector.getIsSoftwareOnlyFlagValue();
    }
    if (isHardwareAccelerated) {
      flags |= mediaCodecInfoReflector.getIsHardwareAcceleratedFlagValue();
    }

    return flags;
  }

  /** Builder for {@link CodecCapabilities}. */
  public static class CodecCapabilitiesBuilder {
    private MediaFormat mediaFormat;
    private boolean isEncoder;
    private CodecProfileLevel[] profileLevels = new CodecProfileLevel[0];
    private int[] colorFormats;
    private String[] requiredFeatures = new String[0];

    private CodecCapabilitiesBuilder() {}

    /** Creates a new {@link CodecCapabilitiesBuilder}. */
    public static CodecCapabilitiesBuilder newBuilder() {
      return new CodecCapabilitiesBuilder();
    }

    /**
     * Sets media format.
     *
     * @param mediaFormat a {@link MediaFormat} supported by the codec. It is a requirement for
     *     mediaFormat to have {@link MediaFormat.KEY_MIME} set. Other keys are optional. Setting
     *     {@link MediaFormat.KEY_WIDTH}, {@link MediaFormat.KEY_MAX_WIDTH} and {@link
     *     MediaFormat.KEY_HEIGHT}, {@link MediaFormat.KEY_MAX_HEIGHT} will set the minimum and
     *     maximum width, height respectively. For backwards compatibility, setting only {@link
     *     MediaFormat.KEY_WIDTH}, {@link MediaFormat.KEY_HEIGHT} will only set the maximum width,
     *     height respectively.
     * @throws {@link NullPointerException} if mediaFormat is null.
     * @throws {@link IllegalArgumentException} if mediaFormat does not have {@link
     *     MediaFormat.KEY_MIME}.
     */
    public CodecCapabilitiesBuilder setMediaFormat(MediaFormat mediaFormat) {
      Preconditions.checkNotNull(mediaFormat);
      Preconditions.checkArgument(
          mediaFormat.getString(MediaFormat.KEY_MIME) != null,
          "MIME type of the format is not set.");
      this.mediaFormat = mediaFormat;
      return this;
    }

    /**
     * Sets required features.
     *
     * @param requiredFeatures An array of {@link CodecCapabilities} FEATURE strings.
     */
    public CodecCapabilitiesBuilder setRequiredFeatures(String[] requiredFeatures) {
      this.requiredFeatures = requiredFeatures;
      return this;
    }

    /**
     * Sets codec role.
     *
     * @param isEncoder a boolean to indicate whether the codec is an encoder or a decoder. Default
     *     value is false.
     */
    public CodecCapabilitiesBuilder setIsEncoder(boolean isEncoder) {
      this.isEncoder = isEncoder;
      return this;
    }

    /**
     * Sets profiles and levels.
     *
     * @param profileLevels an array of {@link MediaCodecInfo.CodecProfileLevel} supported by the
     *     codec.
     * @throws NullPointerException if profileLevels is null.
     */
    public CodecCapabilitiesBuilder setProfileLevels(CodecProfileLevel[] profileLevels) {
      this.profileLevels = Preconditions.checkNotNull(profileLevels);
      return this;
    }

    /**
     * Sets color formats.
     *
     * @param colorFormats an array of color formats supported by the video codec. Refer to {@link
     *     CodecCapabilities} for possible values.
     */
    public CodecCapabilitiesBuilder setColorFormats(int[] colorFormats) {
      this.colorFormats = colorFormats;
      return this;
    }

    /** Accessor interface for {@link CodecCapabilities}'s internals. */
    @ForType(CodecCapabilities.class)
    interface CodecCapabilitiesReflector {

      @Accessor("mMime")
      void setMime(String mime);

      @Accessor("mMaxSupportedInstances")
      void setMaxSupportedInstances(int maxSupportedInstances);

      @Accessor("mDefaultFormat")
      void setDefaultFormat(MediaFormat mediaFormat);

      @Accessor("mCapabilitiesInfo")
      void setCapabilitiesInfo(MediaFormat mediaFormat);

      @Accessor("mVideoCaps")
      void setVideoCaps(VideoCapabilities videoCaps);

      @Accessor("mAudioCaps")
      void setAudioCaps(AudioCapabilities audioCaps);

      @Accessor("mEncoderCaps")
      void setEncoderCaps(EncoderCapabilities encoderCaps);

      @Accessor("mFlagsSupported")
      void setFlagsSupported(int flagsSupported);

      @Accessor("mFlagsRequired")
      void setFlagsRequired(int flagsRequired);
    }

    /** Accessor interface for {@link VideoCapabilities}'s internals. */
    @ForType(VideoCapabilities.class)
    interface VideoCapabilitiesReflector {

      @Accessor("mWidthRange")
      void setWidthRange(Range<Integer> range);

      @Accessor("mHeightRange")
      void setHeightRange(Range<Integer> range);
    }

    public CodecCapabilities build() {
      Preconditions.checkNotNull(mediaFormat, "mediaFormat is not set.");
      Preconditions.checkNotNull(profileLevels, "profileLevels is not set.");

      final String mime = mediaFormat.getString(MediaFormat.KEY_MIME);
      final boolean isVideoCodec = mime.startsWith("video/");

      CodecCapabilities caps = new CodecCapabilities();
      CodecCapabilitiesReflector capsReflector =
          Reflector.reflector(CodecCapabilitiesReflector.class, caps);

      caps.profileLevels = profileLevels;
      if (isVideoCodec) {
        Preconditions.checkNotNull(colorFormats, "colorFormats should not be null for video codec");
        caps.colorFormats = colorFormats;
      } else {
        Preconditions.checkArgument(
            colorFormats == null || colorFormats.length == 0,
            "colorFormats should not be set for audio codec");
        caps.colorFormats = new int[0]; // To prevet crash in CodecCapabilities.dup().
      }

      capsReflector.setMime(mime);
      if (RuntimeEnvironment.getApiLevel() >= Q) {
        capsReflector.setMaxSupportedInstances(32);
      }

      capsReflector.setDefaultFormat(mediaFormat);
      capsReflector.setCapabilitiesInfo(mediaFormat);

      if (isVideoCodec) {
        VideoCapabilities videoCaps = createDefaultVideoCapabilities(caps, mediaFormat);
        VideoCapabilitiesReflector videoCapsReflector =
            Reflector.reflector(VideoCapabilitiesReflector.class, videoCaps);
        if (mediaFormat.containsKey(MediaFormat.KEY_MAX_WIDTH)
            && mediaFormat.containsKey(MediaFormat.KEY_WIDTH)) {
          videoCapsReflector.setWidthRange(
              new Range<>(
                  mediaFormat.getInteger(MediaFormat.KEY_WIDTH),
                  mediaFormat.getInteger(MediaFormat.KEY_MAX_WIDTH)));
        } else if (mediaFormat.containsKey(MediaFormat.KEY_WIDTH)) {
          videoCapsReflector.setWidthRange(
              new Range<>(1, mediaFormat.getInteger(MediaFormat.KEY_WIDTH)));
        }
        if (mediaFormat.containsKey(MediaFormat.KEY_MAX_HEIGHT)
            && mediaFormat.containsKey(MediaFormat.KEY_HEIGHT)) {
          videoCapsReflector.setHeightRange(
              new Range<>(
                  mediaFormat.getInteger(MediaFormat.KEY_HEIGHT),
                  mediaFormat.getInteger(MediaFormat.KEY_MAX_HEIGHT)));
        } else if (mediaFormat.containsKey(MediaFormat.KEY_HEIGHT)) {
          videoCapsReflector.setHeightRange(
              new Range<>(1, mediaFormat.getInteger(MediaFormat.KEY_HEIGHT)));
        }

        capsReflector.setVideoCaps(videoCaps);
      } else {
        AudioCapabilities audioCaps = createDefaultAudioCapabilities(caps, mediaFormat);
        capsReflector.setAudioCaps(audioCaps);
      }

      if (isEncoder) {
        EncoderCapabilities encoderCaps = createDefaultEncoderCapabilities(caps, mediaFormat);
        capsReflector.setEncoderCaps(encoderCaps);
      }

      if (RuntimeEnvironment.getApiLevel() >= Q) {
        int flagsSupported = getSupportedFeatures(caps, mediaFormat);
        capsReflector.setFlagsSupported(flagsSupported);

        int flagsRequired = getRequiredFeatures(caps, requiredFeatures);
        capsReflector.setFlagsRequired(flagsRequired);
      }

      return caps;
    }

    /** Create a default {@link AudioCapabilities} for a given {@link MediaFormat}. */
    private static AudioCapabilities createDefaultAudioCapabilities(
        CodecCapabilities parent, MediaFormat mediaFormat) {
      return ReflectionHelpers.callStaticMethod(
          AudioCapabilities.class,
          "create",
          ClassParameter.from(MediaFormat.class, mediaFormat),
          ClassParameter.from(CodecCapabilities.class, parent));
    }

    /** Create a default {@link VideoCapabilities} for a given {@link MediaFormat}. */
    private static VideoCapabilities createDefaultVideoCapabilities(
        CodecCapabilities parent, MediaFormat mediaFormat) {
      return ReflectionHelpers.callStaticMethod(
          VideoCapabilities.class,
          "create",
          ClassParameter.from(MediaFormat.class, mediaFormat),
          ClassParameter.from(CodecCapabilities.class, parent));
    }

    /** Create a default {@link EncoderCapabilities} for a given {@link MediaFormat}. */
    private static EncoderCapabilities createDefaultEncoderCapabilities(
        CodecCapabilities parent, MediaFormat mediaFormat) {
      return ReflectionHelpers.callStaticMethod(
          EncoderCapabilities.class,
          "create",
          ClassParameter.from(MediaFormat.class, mediaFormat),
          ClassParameter.from(CodecCapabilities.class, parent));
    }

    /**
     * Read codec features from a given {@link MediaFormat} and convert them to values recognized by
     * {@link CodecCapabilities}.
     */
    private static int getSupportedFeatures(CodecCapabilities parent, MediaFormat mediaFormat) {
      int flagsSupported = 0;
      Object[] validFeatures = ReflectionHelpers.callInstanceMethod(parent, "getValidFeatures");
      for (Object validFeature : validFeatures) {
        String featureName = (String) ReflectionHelpers.getField(validFeature, "mName");
        int featureValue = (int) ReflectionHelpers.getField(validFeature, "mValue");
        if (mediaFormat.containsFeature(featureName)
            && mediaFormat.getFeatureEnabled(featureName)) {
          flagsSupported |= featureValue;
        }
      }
      return flagsSupported;
    }

    /**
     * Read codec features from a given array of feature strings and convert them to values
     * recognized by {@link CodecCapabilities}.
     */
    private static int getRequiredFeatures(CodecCapabilities parent, String[] requiredFeatures) {
      int flagsRequired = 0;
      Object[] validFeatures = ReflectionHelpers.callInstanceMethod(parent, "getValidFeatures");
      HashSet<String> requiredFeaturesSet = new HashSet<>(asList(requiredFeatures));
      for (Object validFeature : validFeatures) {
        String featureName = (String) ReflectionHelpers.getField(validFeature, "mName");
        int featureValue = (int) ReflectionHelpers.getField(validFeature, "mValue");
        if (requiredFeaturesSet.contains(featureName)) {
          flagsRequired |= featureValue;
        }
      }
      return flagsRequired;
    }
  }
}