Class Util


  • public final class Util
    extends Object
    Miscellaneous utility methods.
    • Field Detail

      • SDK_INT

        public static final int SDK_INT
        Like Build.VERSION.SDK_INT, but in a place where it can be conveniently overridden for local testing.
      • DEVICE

        public static final String DEVICE
        Like Build.DEVICE, but in a place where it can be conveniently overridden for local testing.
      • MANUFACTURER

        public static final String MANUFACTURER
        Like Build.MANUFACTURER, but in a place where it can be conveniently overridden for local testing.
      • MODEL

        public static final String MODEL
        Like Build.MODEL, but in a place where it can be conveniently overridden for local testing.
      • DEVICE_DEBUG_INFO

        public static final String DEVICE_DEBUG_INFO
        A concise description of the device that it can be useful to log for debugging purposes.
      • EMPTY_BYTE_ARRAY

        public static final byte[] EMPTY_BYTE_ARRAY
        An empty byte array.
    • Method Detail

      • toByteArray

        public static byte[] toByteArray​(InputStream inputStream)
                                  throws IOException
        Converts the entirety of an InputStream to a byte array.
        Parameters:
        inputStream - the InputStream to be read. The input stream is not closed by this method.
        Returns:
        a byte array containing all of the inputStream's bytes.
        Throws:
        IOException - if an error occurs reading from the stream.
      • maybeRequestReadExternalStoragePermission

        public static boolean maybeRequestReadExternalStoragePermission​(Activity activity,
                                                                        Uri... uris)
        Checks whether it's necessary to request the Manifest.permission.READ_EXTERNAL_STORAGE permission read the specified Uris, requesting the permission if necessary.
        Parameters:
        activity - The host activity for checking and requesting the permission.
        uris - Uris that may require Manifest.permission.READ_EXTERNAL_STORAGE to read.
        Returns:
        Whether a permission request was made.
      • checkCleartextTrafficPermitted

        public static boolean checkCleartextTrafficPermitted​(MediaItem... mediaItems)
        Returns whether it may be possible to load the URIs of the given media items based on the network security policy's cleartext traffic permissions.
        Parameters:
        mediaItems - A list of media items.
        Returns:
        Whether it may be possible to load the URIs of the given media items.
      • isLocalFileUri

        public static boolean isLocalFileUri​(Uri uri)
        Returns true if the URI is a path to a local file or a reference to a local file.
        Parameters:
        uri - The uri to test.
      • areEqual

        public static boolean areEqual​(@Nullable
                                       Object o1,
                                       @Nullable
                                       Object o2)
        Tests two objects for Object.equals(Object) equality, handling the case where one or both may be null.
        Parameters:
        o1 - The first object.
        o2 - The second object.
        Returns:
        o1 == null ? o2 == null : o1.equals(o2).
      • contains

        public static boolean contains​(@NullableType Object[] items,
                                       @Nullable
                                       Object item)
        Tests whether an items array contains an object equal to item, according to Object.equals(Object).

        If item is null then true is returned if and only if items contains null.

        Parameters:
        items - The array of items to search.
        item - The item to search for.
        Returns:
        True if the array contains an object equal to the item being searched for.
      • removeRange

        public static <T> void removeRange​(List<T> list,
                                           int fromIndex,
                                           int toIndex)
        Removes an indexed range from a List.

        Does nothing if the provided range is valid and fromIndex == toIndex.

        Parameters:
        list - The List to remove the range from.
        fromIndex - The first index to be removed (inclusive).
        toIndex - The last index to be removed (exclusive).
        Throws:
        IllegalArgumentException - If fromIndex < 0, toIndex > list.size(), or fromIndex > toIndex.
      • castNonNull

        @EnsuresNonNull("#1")
        public static <T> T castNonNull​(@Nullable
                                        T value)
        Casts a nullable variable to a non-null variable without runtime null check.

        Use Assertions.checkNotNull(Object) to throw if the value is null.

      • castNonNullTypeArray

        @EnsuresNonNull("#1")
        public static <T> T[] castNonNullTypeArray​(@NullableType T[] value)
        Casts a nullable type array to a non-null type array without runtime null check.
      • nullSafeArrayCopy

        public static <T> T[] nullSafeArrayCopy​(T[] input,
                                                int length)
        Copies and optionally truncates an array. Prevents null array elements created by Arrays.copyOf(Object[], int) by ensuring the new length does not exceed the current length.
        Parameters:
        input - The input array.
        length - The output array length. Must be less or equal to the length of the input array.
        Returns:
        The copied array.
      • nullSafeArrayCopyOfRange

        public static <T> T[] nullSafeArrayCopyOfRange​(T[] input,
                                                       int from,
                                                       int to)
        Copies a subset of an array.
        Parameters:
        input - The input array.
        from - The start the range to be copied, inclusive
        to - The end of the range to be copied, exclusive.
        Returns:
        The copied array.
      • nullSafeArrayAppend

        public static <T> T[] nullSafeArrayAppend​(T[] original,
                                                  T newElement)
        Creates a new array containing original with newElement appended.
        Parameters:
        original - The input array.
        newElement - The element to append.
        Returns:
        The new array.
      • nullSafeArrayConcatenation

        public static <T> T[] nullSafeArrayConcatenation​(T[] first,
                                                         T[] second)
        Creates a new array containing the concatenation of two non-null type arrays.
        Parameters:
        first - The first array.
        second - The second array.
        Returns:
        The concatenated result.
      • nullSafeListToArray

        public static <T> void nullSafeListToArray​(List<T> list,
                                                   T[] array)
        Copies the contents of list into array.

        list.size() must be the same as array.length to ensure the contents can be copied into array without leaving any nulls at the end.

        Parameters:
        list - The list to copy items from.
        array - The array to copy items to.
      • createHandlerForCurrentLooper

        public static Handler createHandlerForCurrentLooper​(@Nullable
                                                            @UnknownInitialization Handler.Callback callback)
        Creates a Handler with the specified Handler.Callback on the current Looper thread.

        The method accepts partially initialized objects as callback under the assumption that the Handler won't be used to send messages until the callback is fully initialized.

        Parameters:
        callback - A Handler.Callback. May be a partially initialized class, or null if no callback is required.
        Returns:
        A Handler with the specified callback on the current Looper thread.
        Throws:
        IllegalStateException - If the current thread doesn't have a Looper.
      • createHandlerForCurrentOrMainLooper

        public static Handler createHandlerForCurrentOrMainLooper()
        Creates a Handler on the current Looper thread.

        If the current thread doesn't have a Looper, the application's main thread Looper is used.

      • createHandlerForCurrentOrMainLooper

        public static Handler createHandlerForCurrentOrMainLooper​(@Nullable
                                                                  @UnknownInitialization Handler.Callback callback)
        Creates a Handler with the specified Handler.Callback on the current Looper thread.

        The method accepts partially initialized objects as callback under the assumption that the Handler won't be used to send messages until the callback is fully initialized.

        If the current thread doesn't have a Looper, the application's main thread Looper is used.

        Parameters:
        callback - A Handler.Callback. May be a partially initialized class, or null if no callback is required.
        Returns:
        A Handler with the specified callback on the current Looper thread.
      • createHandler

        public static Handler createHandler​(Looper looper,
                                            @Nullable
                                            @UnknownInitialization Handler.Callback callback)
        Creates a Handler with the specified Handler.Callback on the specified Looper thread.

        The method accepts partially initialized objects as callback under the assumption that the Handler won't be used to send messages until the callback is fully initialized.

        Parameters:
        looper - A Looper to run the callback on.
        callback - A Handler.Callback. May be a partially initialized class, or null if no callback is required.
        Returns:
        A Handler with the specified callback on the current Looper thread.
      • postOrRun

        public static boolean postOrRun​(Handler handler,
                                        Runnable runnable)
        Posts the Runnable if the calling thread differs with the Looper of the Handler. Otherwise, runs the Runnable directly.
        Parameters:
        handler - The handler to which the Runnable will be posted.
        runnable - The runnable to either post or run.
        Returns:
        true if the Runnable was successfully posted to the Handler or run. false otherwise.
      • getCurrentOrMainLooper

        public static Looper getCurrentOrMainLooper()
        Returns the Looper associated with the current thread, or the Looper of the application's main thread if the current thread doesn't have a Looper.
      • newSingleThreadExecutor

        public static ExecutorService newSingleThreadExecutor​(String threadName)
        Instantiates a new single threaded executor whose thread has the specified name.
        Parameters:
        threadName - The name of the thread.
        Returns:
        The executor.
      • readBoolean

        public static boolean readBoolean​(Parcel parcel)
        Reads an integer from a Parcel and interprets it as a boolean, with 0 mapping to false and all other values mapping to true.
        Parameters:
        parcel - The Parcel to read from.
        Returns:
        The read value.
      • writeBoolean

        public static void writeBoolean​(Parcel parcel,
                                        boolean value)
        Writes a boolean to a Parcel. The boolean is written as an integer with value 1 (true) or 0 (false).
        Parameters:
        parcel - The Parcel to write to.
        value - The value to write.
      • getLocaleLanguageTag

        public static String getLocaleLanguageTag​(Locale locale)
        Returns the language tag for a Locale.

        For API levels ≥ 21, this tag is IETF BCP 47 compliant. Use normalizeLanguageCode(String) to retrieve a normalized IETF BCP 47 language tag for all API levels if needed.

        Parameters:
        locale - A Locale.
        Returns:
        The language tag.
      • normalizeLanguageCode

        public static @PolyNull String normalizeLanguageCode​(@PolyNull String language)
        Returns a normalized IETF BCP 47 language tag for language.
        Parameters:
        language - A case-insensitive language code supported by Locale.forLanguageTag(String).
        Returns:
        The all-lowercase normalized code, or null if the input was null, or language.toLowerCase() if the language could not be normalized.
      • fromUtf8Bytes

        public static String fromUtf8Bytes​(byte[] bytes)
        Returns a new String constructed by decoding UTF-8 encoded bytes.
        Parameters:
        bytes - The UTF-8 encoded bytes to decode.
        Returns:
        The string.
      • fromUtf8Bytes

        public static String fromUtf8Bytes​(byte[] bytes,
                                           int offset,
                                           int length)
        Returns a new String constructed by decoding UTF-8 encoded bytes in a subarray.
        Parameters:
        bytes - The UTF-8 encoded bytes to decode.
        offset - The index of the first byte to decode.
        length - The number of bytes to decode.
        Returns:
        The string.
      • getUtf8Bytes

        public static byte[] getUtf8Bytes​(String value)
        Returns a new byte array containing the code points of a String encoded using UTF-8.
        Parameters:
        value - The String whose bytes should be obtained.
        Returns:
        The code points encoding using UTF-8.
      • split

        public static String[] split​(String value,
                                     String regex)
        Splits a string using value.split(regex, -1). Note: this is is similar to String.split(String) but empty matches at the end of the string will not be omitted from the returned array.
        Parameters:
        value - The string to split.
        regex - A delimiting regular expression.
        Returns:
        The array of strings resulting from splitting the string.
      • splitAtFirst

        public static String[] splitAtFirst​(String value,
                                            String regex)
        Splits the string at the first occurrence of the delimiter regex. If the delimiter does not match, returns an array with one element which is the input string. If the delimiter does match, returns an array with the portion of the string before the delimiter and the rest of the string.
        Parameters:
        value - The string.
        regex - A delimiting regular expression.
        Returns:
        The string split by the first occurrence of the delimiter.
      • isLinebreak

        public static boolean isLinebreak​(int c)
        Returns whether the given character is a carriage return ('\r') or a line feed ('\n').
        Parameters:
        c - The character.
        Returns:
        Whether the given character is a linebreak.
      • ceilDivide

        public static int ceilDivide​(int numerator,
                                     int denominator)
        Divides a numerator by a denominator, returning the ceiled result.
        Parameters:
        numerator - The numerator to divide.
        denominator - The denominator to divide by.
        Returns:
        The ceiled result of the division.
      • ceilDivide

        public static long ceilDivide​(long numerator,
                                      long denominator)
        Divides a numerator by a denominator, returning the ceiled result.
        Parameters:
        numerator - The numerator to divide.
        denominator - The denominator to divide by.
        Returns:
        The ceiled result of the division.
      • constrainValue

        public static int constrainValue​(int value,
                                         int min,
                                         int max)
        Constrains a value to the specified bounds.
        Parameters:
        value - The value to constrain.
        min - The lower bound.
        max - The upper bound.
        Returns:
        The constrained value Math.max(min, Math.min(value, max)).
      • constrainValue

        public static long constrainValue​(long value,
                                          long min,
                                          long max)
        Constrains a value to the specified bounds.
        Parameters:
        value - The value to constrain.
        min - The lower bound.
        max - The upper bound.
        Returns:
        The constrained value Math.max(min, Math.min(value, max)).
      • constrainValue

        public static float constrainValue​(float value,
                                           float min,
                                           float max)
        Constrains a value to the specified bounds.
        Parameters:
        value - The value to constrain.
        min - The lower bound.
        max - The upper bound.
        Returns:
        The constrained value Math.max(min, Math.min(value, max)).
      • addWithOverflowDefault

        public static long addWithOverflowDefault​(long x,
                                                  long y,
                                                  long overflowResult)
        Returns the sum of two arguments, or a third argument if the result overflows.
        Parameters:
        x - The first value.
        y - The second value.
        overflowResult - The return value if x + y overflows.
        Returns:
        x + y, or overflowResult if the result overflows.
      • subtractWithOverflowDefault

        public static long subtractWithOverflowDefault​(long x,
                                                       long y,
                                                       long overflowResult)
        Returns the difference between two arguments, or a third argument if the result overflows.
        Parameters:
        x - The first value.
        y - The second value.
        overflowResult - The return value if x - y overflows.
        Returns:
        x - y, or overflowResult if the result overflows.
      • linearSearch

        public static int linearSearch​(int[] array,
                                       int value)
        Returns the index of the first occurrence of value in array, or C.INDEX_UNSET if value is not contained in array.
        Parameters:
        array - The array to search.
        value - The value to search for.
        Returns:
        The index of the first occurrence of value in array, or C.INDEX_UNSET if value is not contained in array.
      • linearSearch

        public static int linearSearch​(long[] array,
                                       long value)
        Returns the index of the first occurrence of value in array, or C.INDEX_UNSET if value is not contained in array.
        Parameters:
        array - The array to search.
        value - The value to search for.
        Returns:
        The index of the first occurrence of value in array, or C.INDEX_UNSET if value is not contained in array.
      • binarySearchFloor

        public static int binarySearchFloor​(int[] array,
                                            int value,
                                            boolean inclusive,
                                            boolean stayInBounds)
        Returns the index of the largest element in array that is less than (or optionally equal to) a specified value.

        The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to value and inclusive is true, the index of the first one will be returned.

        Parameters:
        array - The array to search.
        value - The value being searched for.
        inclusive - If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the largest element strictly less than the value.
        stayInBounds - If true, then 0 will be returned in the case that the value is smaller than the smallest element in the array. If false then -1 will be returned.
        Returns:
        The index of the largest element in array that is less than (or optionally equal to) value.
      • binarySearchFloor

        public static int binarySearchFloor​(long[] array,
                                            long value,
                                            boolean inclusive,
                                            boolean stayInBounds)
        Returns the index of the largest element in array that is less than (or optionally equal to) a specified value.

        The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to value and inclusive is true, the index of the first one will be returned.

        Parameters:
        array - The array to search.
        value - The value being searched for.
        inclusive - If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the largest element strictly less than the value.
        stayInBounds - If true, then 0 will be returned in the case that the value is smaller than the smallest element in the array. If false then -1 will be returned.
        Returns:
        The index of the largest element in array that is less than (or optionally equal to) value.
      • binarySearchFloor

        public static <T extends Comparable<? super T>> int binarySearchFloor​(List<? extends Comparable<? super T>> list,
                                                                              T value,
                                                                              boolean inclusive,
                                                                              boolean stayInBounds)
        Returns the index of the largest element in list that is less than (or optionally equal to) a specified value.

        The search is performed using a binary search algorithm, so the list must be sorted. If the list contains multiple elements equal to value and inclusive is true, the index of the first one will be returned.

        Type Parameters:
        T - The type of values being searched.
        Parameters:
        list - The list to search.
        value - The value being searched for.
        inclusive - If the value is present in the list, whether to return the corresponding index. If false then the returned index corresponds to the largest element strictly less than the value.
        stayInBounds - If true, then 0 will be returned in the case that the value is smaller than the smallest element in the list. If false then -1 will be returned.
        Returns:
        The index of the largest element in list that is less than (or optionally equal to) value.
      • binarySearchFloor

        public static int binarySearchFloor​(LongArray longArray,
                                            long value,
                                            boolean inclusive,
                                            boolean stayInBounds)
        Returns the index of the largest element in longArray that is less than (or optionally equal to) a specified value.

        The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to value and inclusive is true, the index of the first one will be returned.

        Parameters:
        longArray - The array to search.
        value - The value being searched for.
        inclusive - If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the largest element strictly less than the value.
        stayInBounds - If true, then 0 will be returned in the case that the value is smaller than the smallest element in the array. If false then -1 will be returned.
        Returns:
        The index of the largest element in array that is less than (or optionally equal to) value.
      • binarySearchCeil

        public static int binarySearchCeil​(int[] array,
                                           int value,
                                           boolean inclusive,
                                           boolean stayInBounds)
        Returns the index of the smallest element in array that is greater than (or optionally equal to) a specified value.

        The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to value and inclusive is true, the index of the last one will be returned.

        Parameters:
        array - The array to search.
        value - The value being searched for.
        inclusive - If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the smallest element strictly greater than the value.
        stayInBounds - If true, then (a.length - 1) will be returned in the case that the value is greater than the largest element in the array. If false then a.length will be returned.
        Returns:
        The index of the smallest element in array that is greater than (or optionally equal to) value.
      • binarySearchCeil

        public static int binarySearchCeil​(long[] array,
                                           long value,
                                           boolean inclusive,
                                           boolean stayInBounds)
        Returns the index of the smallest element in array that is greater than (or optionally equal to) a specified value.

        The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to value and inclusive is true, the index of the last one will be returned.

        Parameters:
        array - The array to search.
        value - The value being searched for.
        inclusive - If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the smallest element strictly greater than the value.
        stayInBounds - If true, then (a.length - 1) will be returned in the case that the value is greater than the largest element in the array. If false then a.length will be returned.
        Returns:
        The index of the smallest element in array that is greater than (or optionally equal to) value.
      • binarySearchCeil

        public static <T extends Comparable<? super T>> int binarySearchCeil​(List<? extends Comparable<? super T>> list,
                                                                             T value,
                                                                             boolean inclusive,
                                                                             boolean stayInBounds)
        Returns the index of the smallest element in list that is greater than (or optionally equal to) a specified value.

        The search is performed using a binary search algorithm, so the list must be sorted. If the list contains multiple elements equal to value and inclusive is true, the index of the last one will be returned.

        Type Parameters:
        T - The type of values being searched.
        Parameters:
        list - The list to search.
        value - The value being searched for.
        inclusive - If the value is present in the list, whether to return the corresponding index. If false then the returned index corresponds to the smallest element strictly greater than the value.
        stayInBounds - If true, then (list.size() - 1) will be returned in the case that the value is greater than the largest element in the list. If false then list.size() will be returned.
        Returns:
        The index of the smallest element in list that is greater than (or optionally equal to) value.
      • compareLong

        public static int compareLong​(long left,
                                      long right)
        Compares two long values and returns the same value as Long.compare(long, long).
        Parameters:
        left - The left operand.
        right - The right operand.
        Returns:
        0, if left == right, a negative value if left < right, or a positive value if left > right.
      • usToMs

        public static long usToMs​(long timeUs)
        Converts a time in microseconds to the corresponding time in milliseconds, preserving C.TIME_UNSET and C.TIME_END_OF_SOURCE values.
        Parameters:
        timeUs - The time in microseconds.
        Returns:
        The corresponding time in milliseconds.
      • msToUs

        public static long msToUs​(long timeMs)
        Converts a time in milliseconds to the corresponding time in microseconds, preserving C.TIME_UNSET values and C.TIME_END_OF_SOURCE values.
        Parameters:
        timeMs - The time in milliseconds.
        Returns:
        The corresponding time in microseconds.
      • parseXsDuration

        public static long parseXsDuration​(String value)
        Parses an xs:duration attribute value, returning the parsed duration in milliseconds.
        Parameters:
        value - The attribute value to decode.
        Returns:
        The parsed duration in milliseconds.
      • parseXsDateTime

        public static long parseXsDateTime​(String value)
                                    throws ParserException
        Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the epoch.
        Parameters:
        value - The attribute value to decode.
        Returns:
        The parsed timestamp in milliseconds since the epoch.
        Throws:
        ParserException - if an error occurs parsing the dateTime attribute value.
      • scaleLargeTimestamp

        public static long scaleLargeTimestamp​(long timestamp,
                                               long multiplier,
                                               long divisor)
        Scales a large timestamp.

        Logically, scaling consists of a multiplication followed by a division. The actual operations performed are designed to minimize the probability of overflow.

        Parameters:
        timestamp - The timestamp to scale.
        multiplier - The multiplier.
        divisor - The divisor.
        Returns:
        The scaled timestamp.
      • scaleLargeTimestamps

        public static long[] scaleLargeTimestamps​(List<Long> timestamps,
                                                  long multiplier,
                                                  long divisor)
        Applies scaleLargeTimestamp(long, long, long) to a list of unscaled timestamps.
        Parameters:
        timestamps - The timestamps to scale.
        multiplier - The multiplier.
        divisor - The divisor.
        Returns:
        The scaled timestamps.
      • scaleLargeTimestampsInPlace

        public static void scaleLargeTimestampsInPlace​(long[] timestamps,
                                                       long multiplier,
                                                       long divisor)
        Applies scaleLargeTimestamp(long, long, long) to an array of unscaled timestamps.
        Parameters:
        timestamps - The timestamps to scale.
        multiplier - The multiplier.
        divisor - The divisor.
      • getMediaDurationForPlayoutDuration

        public static long getMediaDurationForPlayoutDuration​(long playoutDuration,
                                                              float speed)
        Returns the duration of media that will elapse in playoutDuration.
        Parameters:
        playoutDuration - The duration to scale.
        speed - The factor by which playback is sped up.
        Returns:
        The scaled duration, in the same units as playoutDuration.
      • getPlayoutDurationForMediaDuration

        public static long getPlayoutDurationForMediaDuration​(long mediaDuration,
                                                              float speed)
        Returns the playout duration of mediaDuration of media.
        Parameters:
        mediaDuration - The duration to scale.
        Returns:
        The scaled duration, in the same units as mediaDuration.
      • getIntegerCodeForString

        public static int getIntegerCodeForString​(String string)
        Returns the integer equal to the big-endian concatenation of the characters in string as bytes. The string must be no more than four characters long.
        Parameters:
        string - A string no more than four characters long.
      • toUnsignedLong

        public static long toUnsignedLong​(int x)
        Converts an integer to a long by unsigned conversion.

        This method is equivalent to Integer.toUnsignedLong(int) for API 26+.

      • toLong

        public static long toLong​(int mostSignificantBits,
                                  int leastSignificantBits)
        Returns the long that is composed of the bits of the 2 specified integers.
        Parameters:
        mostSignificantBits - The 32 most significant bits of the long to return.
        leastSignificantBits - The 32 least significant bits of the long to return.
        Returns:
        a long where its 32 most significant bits are mostSignificantBits bits and its 32 least significant bits are leastSignificantBits.
      • truncateAscii

        public static CharSequence truncateAscii​(CharSequence sequence,
                                                 int maxLength)
        Truncates a sequence of ASCII characters to a maximum length.

        This preserves span styling in the CharSequence. If that's not important, use Ascii.truncate(CharSequence, int, String).

        Note: This is not safe to use in general on Unicode text because it may separate characters from combining characters or split up surrogate pairs.

        Parameters:
        sequence - The character sequence to truncate.
        maxLength - The max length to truncate to.
        Returns:
        sequence directly if sequence.length() <= maxLength, otherwise sequence.subsequence(0, maxLength.
      • getBytesFromHexString

        public static byte[] getBytesFromHexString​(String hexString)
        Returns a byte array containing values parsed from the hex string provided.
        Parameters:
        hexString - The hex string to convert to bytes.
        Returns:
        A byte array containing values parsed from the hex string provided.
      • toHexString

        public static String toHexString​(byte[] bytes)
        Returns a string containing a lower-case hex representation of the bytes provided.
        Parameters:
        bytes - The byte data to convert to hex.
        Returns:
        A String containing the hex representation of bytes.
      • getCommaDelimitedSimpleClassNames

        public static String getCommaDelimitedSimpleClassNames​(Object[] objects)
        Returns a string with comma delimited simple names of each object's class.
        Parameters:
        objects - The objects whose simple class names should be comma delimited and returned.
        Returns:
        A string with comma delimited simple names of each object's class.
      • getUserAgent

        public static String getUserAgent​(Context context,
                                          String applicationName)
        Returns a user agent string based on the given application name and the library version.
        Parameters:
        context - A valid context of the calling application.
        applicationName - String that will be prefix'ed to the generated user agent.
        Returns:
        A user agent string generated using the applicationName and the library version.
      • getCodecCountOfType

        public static int getCodecCountOfType​(@Nullable
                                              String codecs,
                                              @com.google.android.exoplayer2.C.TrackType int trackType)
        Returns the number of codec strings in codecs whose type matches trackType.
      • getCodecsOfType

        @Nullable
        public static String getCodecsOfType​(@Nullable
                                             String codecs,
                                             @com.google.android.exoplayer2.C.TrackType int trackType)
        Returns a copy of codecs without the codecs whose track type doesn't match trackType.
        Parameters:
        codecs - A codec sequence string, as defined in RFC 6381.
        trackType - The track type.
        Returns:
        A copy of codecs without the codecs whose track type doesn't match trackType. If this ends up empty, or codecs is null, returns null.
      • splitCodecs

        public static String[] splitCodecs​(@Nullable
                                           String codecs)
        Splits a codecs sequence string, as defined in RFC 6381, into individual codec strings.
        Parameters:
        codecs - A codec sequence string, as defined in RFC 6381.
        Returns:
        The split codecs, or an array of length zero if the input was empty or null.
      • getPcmFormat

        public static Format getPcmFormat​(@PcmEncoding
                                          int pcmEncoding,
                                          int channels,
                                          int sampleRate)
        Gets a PCM Format with the specified parameters.
        Parameters:
        pcmEncoding - The C.PcmEncoding.
        channels - The number of channels, or Format.NO_VALUE if unknown.
        sampleRate - The sample rate in Hz, or Format.NO_VALUE if unknown.
        Returns:
        The PCM format.
      • isEncodingLinearPcm

        public static boolean isEncodingLinearPcm​(@Encoding
                                                  int encoding)
        Returns whether encoding is one of the linear PCM encodings.
        Parameters:
        encoding - The encoding of the audio data.
        Returns:
        Whether the encoding is one of the PCM encodings.
      • isEncodingHighResolutionPcm

        public static boolean isEncodingHighResolutionPcm​(@PcmEncoding
                                                          int encoding)
        Returns whether encoding is high resolution (> 16-bit) PCM.
        Parameters:
        encoding - The encoding of the audio data.
        Returns:
        Whether the encoding is high resolution PCM.
      • getAudioTrackChannelConfig

        public static int getAudioTrackChannelConfig​(int channelCount)
        Returns the audio track channel configuration for the given channel count, or AudioFormat.CHANNEL_INVALID if output is not possible.
        Parameters:
        channelCount - The number of channels in the input audio.
        Returns:
        The channel configuration or AudioFormat.CHANNEL_INVALID if output is not possible.
      • getPcmFrameSize

        public static int getPcmFrameSize​(@PcmEncoding
                                          int pcmEncoding,
                                          int channelCount)
        Returns the frame size for audio with channelCount channels in the specified encoding.
        Parameters:
        pcmEncoding - The encoding of the audio data.
        channelCount - The channel count.
        Returns:
        The size of one audio frame in bytes.
      • getAudioUsageForStreamType

        @AudioUsage
        public static @com.google.android.exoplayer2.C.AudioUsage int getAudioUsageForStreamType​(@StreamType
                                                                                                 int streamType)
        Returns the C.AudioUsage corresponding to the specified C.StreamType.
      • getDrmUuid

        @Nullable
        public static UUID getDrmUuid​(String drmScheme)
        Derives a DRM UUID from drmScheme.
        Parameters:
        drmScheme - A UUID string, or "widevine", "playready" or "clearkey".
        Returns:
        The derived UUID, or null if one could not be derived.
      • inferContentType

        @ContentType
        public static int inferContentType​(Uri uri,
                                           @Nullable
                                           String overrideExtension)
        Makes a best guess to infer the C.ContentType from a Uri.
        Parameters:
        uri - The Uri.
        overrideExtension - If not null, used to infer the type.
        Returns:
        The content type.
      • inferContentType

        @ContentType
        public static int inferContentType​(Uri uri)
        Makes a best guess to infer the C.ContentType from a Uri.
        Parameters:
        uri - The Uri.
        Returns:
        The content type.
      • inferContentType

        @ContentType
        public static int inferContentType​(String fileName)
        Makes a best guess to infer the C.ContentType from a file name.
        Parameters:
        fileName - Name of the file. It can include the path of the file.
        Returns:
        The content type.
      • inferContentTypeForUriAndMimeType

        @ContentType
        public static int inferContentTypeForUriAndMimeType​(Uri uri,
                                                            @Nullable
                                                            String mimeType)
        Makes a best guess to infer the C.ContentType from a Uri and optional MIME type.
        Parameters:
        uri - The Uri.
        mimeType - If MIME type, or null.
        Returns:
        The content type.
      • getAdaptiveMimeTypeForContentType

        @Nullable
        public static String getAdaptiveMimeTypeForContentType​(int contentType)
        Returns the MIME type corresponding to the given adaptive C.ContentType, or null if the content type is C.TYPE_OTHER.
      • fixSmoothStreamingIsmManifestUri

        public static Uri fixSmoothStreamingIsmManifestUri​(Uri uri)
        If the provided URI is an ISM Presentation URI, returns the URI with "Manifest" appended to its path (i.e., the corresponding default manifest URI). Else returns the provided URI without modification. See [MS-SSTR] v20180912, section 2.2.1.
        Parameters:
        uri - The original URI.
        Returns:
        The fixed URI.
      • getStringForTime

        public static String getStringForTime​(StringBuilder builder,
                                              Formatter formatter,
                                              long timeMs)
        Returns the specified millisecond time formatted as a string.
        Parameters:
        builder - The builder that formatter will write to.
        formatter - The formatter.
        timeMs - The time to format as a string, in milliseconds.
        Returns:
        The time formatted as a string.
      • escapeFileName

        public static String escapeFileName​(String fileName)
        Escapes a string so that it's safe for use as a file or directory name on at least FAT32 filesystems. FAT32 is the most restrictive of all filesystems still commonly used today.

        For simplicity, this only handles common characters known to be illegal on FAT32: <, >, :, ", /, \, |, ?, and *. % is also escaped since it is used as the escape character. Escaping is performed in a consistent way so that no collisions occur and unescapeFileName(String) can be used to retrieve the original file name.

        Parameters:
        fileName - File name to be escaped.
        Returns:
        An escaped file name which will be safe for use on at least FAT32 filesystems.
      • unescapeFileName

        @Nullable
        public static String unescapeFileName​(String fileName)
        Unescapes an escaped file or directory name back to its original value.

        See escapeFileName(String) for more information.

        Parameters:
        fileName - File name to be unescaped.
        Returns:
        The original value of the file name before it was escaped, or null if the escaped fileName seems invalid.
      • getDataUriForString

        public static Uri getDataUriForString​(String mimeType,
                                              String data)
        Returns a data URI with the specified MIME type and data.
      • sneakyThrow

        public static void sneakyThrow​(Throwable t)
        A hacky method that always throws t even if t is a checked exception, and is not declared to be thrown.
      • recursiveDelete

        public static void recursiveDelete​(File fileOrDirectory)
        Recursively deletes a directory and its content.
      • crc32

        public static int crc32​(byte[] bytes,
                                int start,
                                int end,
                                int initialValue)
        Returns the result of updating a CRC-32 with the specified bytes in a "most significant bit first" order.
        Parameters:
        bytes - Array containing the bytes to update the crc value with.
        start - The index to the first byte in the byte range to update the crc with.
        end - The index after the last byte in the byte range to update the crc with.
        initialValue - The initial value for the crc calculation.
        Returns:
        The result of updating the initial value with the specified bytes.
      • crc8

        public static int crc8​(byte[] bytes,
                               int start,
                               int end,
                               int initialValue)
        Returns the result of updating a CRC-8 with the specified bytes in a "most significant bit first" order.
        Parameters:
        bytes - Array containing the bytes to update the crc value with.
        start - The index to the first byte in the byte range to update the crc with.
        end - The index after the last byte in the byte range to update the crc with.
        initialValue - The initial value for the crc calculation.
        Returns:
        The result of updating the initial value with the specified bytes.
      • gzip

        public static byte[] gzip​(byte[] input)
        Compresses input using gzip and returns the result in a newly allocated byte array.
      • getBigEndianInt

        public static int getBigEndianInt​(ByteBuffer buffer,
                                          int index)
        Absolute get method for reading an int value in ByteOrder.BIG_ENDIAN in a ByteBuffer. Same as ByteBuffer.getInt(int) except the buffer's order as returned by ByteBuffer.order() is ignored and ByteOrder.BIG_ENDIAN is used instead.
        Parameters:
        buffer - The buffer from which to read an int in big endian.
        index - The index from which the bytes will be read.
        Returns:
        The int value at the given index with the buffer bytes ordered most significant to least significant.
      • getCountryCode

        public static String getCountryCode​(@Nullable
                                            Context context)
        Returns the upper-case ISO 3166-1 alpha-2 country code of the current registered operator's MCC (Mobile Country Code), or the country code of the default Locale if not available.
        Parameters:
        context - A context to access the telephony service. If null, only the Locale can be used.
        Returns:
        The upper-case ISO 3166-1 alpha-2 country code, or an empty String if unavailable.
      • getSystemLanguageCodes

        public static String[] getSystemLanguageCodes()
        Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages ordered by preference.
      • getDefaultDisplayLocale

        public static Locale getDefaultDisplayLocale()
        Returns the default DISPLAY Locale.
      • inflate

        public static boolean inflate​(ParsableByteArray input,
                                      ParsableByteArray output,
                                      @Nullable
                                      Inflater inflater)
        Uncompresses the data in input.
        Parameters:
        input - Wraps the compressed input data.
        output - Wraps an output buffer to be used to store the uncompressed data. If output.data isn't big enough to hold the uncompressed data, a new array is created. If true is returned then the output's position will be set to 0 and its limit will be set to the length of the uncompressed data.
        inflater - If not null, used to uncompressed the input. Otherwise a new Inflater is created.
        Returns:
        Whether the input is uncompressed successfully.
      • isTv

        public static boolean isTv​(Context context)
        Returns whether the app is running on a TV device.
        Parameters:
        context - Any context.
        Returns:
        Whether the app is running on a TV device.
      • isAutomotive

        public static boolean isAutomotive​(Context context)
        Returns whether the app is running on an automotive device.
        Parameters:
        context - Any context.
        Returns:
        Whether the app is running on an automotive device.
      • getCurrentDisplayModeSize

        public static Point getCurrentDisplayModeSize​(Context context)
        Gets the size of the current mode of the default display, in pixels.

        Note that due to application UI scaling, the number of pixels made available to applications (as reported by Display.getSize(Point) may differ from the mode's actual resolution (as reported by this function). For example, applications running on a display configured with a 4K mode may have their UI laid out and rendered in 1080p and then scaled up. Applications can take advantage of the full mode resolution through a SurfaceView using full size buffers.

        Parameters:
        context - Any context.
        Returns:
        The size of the current mode, in pixels.
      • getCurrentDisplayModeSize

        public static Point getCurrentDisplayModeSize​(Context context,
                                                      Display display)
        Gets the size of the current mode of the specified display, in pixels.

        Note that due to application UI scaling, the number of pixels made available to applications (as reported by Display.getSize(Point) may differ from the mode's actual resolution (as reported by this function). For example, applications running on a display configured with a 4K mode may have their UI laid out and rendered in 1080p and then scaled up. Applications can take advantage of the full mode resolution through a SurfaceView using full size buffers.

        Parameters:
        context - Any context.
        display - The display whose size is to be returned.
        Returns:
        The size of the current mode, in pixels.
      • getTrackTypeString

        public static String getTrackTypeString​(@com.google.android.exoplayer2.C.TrackType int trackType)
        Returns a string representation of a C.TrackType.
        Parameters:
        trackType - A C.TrackType constant,
        Returns:
        A string representation of this constant.
      • getNowUnixTimeMs

        public static long getNowUnixTimeMs​(long elapsedRealtimeEpochOffsetMs)
        Returns the current time in milliseconds since the epoch.
        Parameters:
        elapsedRealtimeEpochOffsetMs - The offset between SystemClock.elapsedRealtime() and the time since the Unix epoch, or C.TIME_UNSET if unknown.
        Returns:
        The Unix time in milliseconds since the epoch.
      • moveItems

        public static <T> void moveItems​(List<T> items,
                                         int fromIndex,
                                         int toIndex,
                                         int newFromIndex)
        Moves the elements starting at fromIndex to newFromIndex.
        Parameters:
        items - The list of which to move elements.
        fromIndex - The index at which the items to move start.
        toIndex - The index up to which elements should be moved (exclusive).
        newFromIndex - The new from index.
      • tableExists

        public static boolean tableExists​(SQLiteDatabase database,
                                          String tableName)
        Returns whether the table exists in the database.
      • getErrorCodeFromPlatformDiagnosticsInfo

        public static int getErrorCodeFromPlatformDiagnosticsInfo​(@Nullable
                                                                  String diagnosticsInfo)
        Attempts to parse an error code from a diagnostic string found in framework media exceptions.

        For example: android.media.MediaCodec.error_1 or android.media.MediaDrm.error_neg_2.

        Parameters:
        diagnosticsInfo - A string from which to parse the error code.
        Returns:
        The parser error code, or 0 if an error code could not be parsed.
      • getFormatSupportString

        public static String getFormatSupportString​(@FormatSupport
                                                    int formatSupport)
        Returns string representation of a C.FormatSupport flag.
        Parameters:
        formatSupport - A C.FormatSupport flag.
        Returns:
        A string representation of the flag.