/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.media; import static android.media.codec.Flags.FLAG_NULL_OUTPUT_SURFACE; import static android.media.codec.Flags.FLAG_REGION_OF_INTEREST; import static com.android.media.codec.flags.Flags.FLAG_LARGE_AUDIO_FRAME; import android.Manifest; import android.annotation.FlaggedApi; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.RequiresPermission; import android.annotation.SystemApi; import android.compat.annotation.UnsupportedAppUsage; import android.graphics.ImageFormat; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.hardware.HardwareBuffer; import android.media.MediaCodecInfo.CodecCapabilities; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IHwBinder; import android.os.Looper; import android.os.Message; import android.os.PersistableBundle; import android.view.Surface; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ReadOnlyBufferException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; /** MediaCodec class can be used to access low-level media codecs, i.e. encoder/decoder components. It is part of the Android low-level multimedia support infrastructure (normally used together with {@link MediaExtractor}, {@link MediaSync}, {@link MediaMuxer}, {@link MediaCrypto}, {@link MediaDrm}, {@link Image}, {@link Surface}, and {@link AudioTrack}.)
In broad terms, a codec processes input data to generate output data. It processes data asynchronously and uses a set of input and output buffers. At a simplistic level, you request (or receive) an empty input buffer, fill it up with data and send it to the codec for processing. The codec uses up the data and transforms it into one of its empty output buffers. Finally, you request (or receive) a filled output buffer, consume its contents and release it back to the codec.
Beginning with {@link android.os.Build.VERSION_CODES#S}, Android's Video MediaCodecs enforce a minimum quality floor. The intent is to eliminate poor quality video encodings. This quality floor is applied when the codec is in Variable Bitrate (VBR) mode; it is not applied when the codec is in Constant Bitrate (CBR) mode. The quality floor enforcement is also restricted to a particular size range; this size range is currently for video resolutions larger than 320x240 up through 1920x1080.
When this quality floor is in effect, the codec and supporting framework code will work to ensure that the generated video is of at least a "fair" or "good" quality. The metric used to choose these targets is the VMAF (Video Multi-method Assessment Function) with a target score of 70 for selected test sequences.
The typical effect is that some videos will generate a higher bitrate than originally configured. This will be most notable for videos which were configured with very low bitrates; the codec will use a bitrate that is determined to be more likely to generate an "fair" or "good" quality video. Another situation is where a video includes very complicated content (lots of motion and detail); in such configurations, the codec will use extra bitrate as needed to avoid losing all of the content's finer detail.
This quality floor will not impact content captured at high bitrates (a high bitrate should already provide the codec with sufficient capacity to encode all of the detail). The quality floor does not operate on CBR encodings. The quality floor currently does not operate on resolutions of 320x240 or lower, nor on videos with resolution above 1920x1080.
Codecs operate on three kinds of data: compressed data, raw audio data and raw video data. All three kinds of data can be processed using {@link ByteBuffer ByteBuffers}, but you should use a {@link Surface} for raw video data to improve codec performance. Surface uses native video buffers without mapping or copying them to ByteBuffers; thus, it is much more efficient. You normally cannot access the raw video data when using a Surface, but you can use the {@link ImageReader} class to access unsecured decoded (raw) video frames. This may still be more efficient than using ByteBuffers, as some native buffers may be mapped into {@linkplain ByteBuffer#isDirect direct} ByteBuffers. When using ByteBuffer mode, you can access raw video frames using the {@link Image} class and {@link #getInputImage getInput}/{@link #getOutputImage OutputImage(int)}.
Input buffers (for decoders) and output buffers (for encoders) contain compressed data according to the {@linkplain MediaFormat#KEY_MIME format's type}. For video types this is normally a single compressed video frame. For audio data this is normally a single access unit (an encoded audio segment typically containing a few milliseconds of audio as dictated by the format type), but this requirement is slightly relaxed in that a buffer may contain multiple encoded access units of audio. In either case, buffers do not start or end on arbitrary byte boundaries, but rather on frame/access unit boundaries unless they are flagged with {@link #BUFFER_FLAG_PARTIAL_FRAME}.
Raw audio buffers contain entire frames of PCM audio data, which is one sample for each channel in channel order. Each PCM audio sample is either a 16 bit signed integer or a float, in native byte order. Raw audio buffers in the float PCM encoding are only possible if the MediaFormat's {@linkplain MediaFormat#KEY_PCM_ENCODING} is set to {@linkplain AudioFormat#ENCODING_PCM_FLOAT} during MediaCodec {@link #configure configure(…)} and confirmed by {@link #getOutputFormat} for decoders or {@link #getInputFormat} for encoders. A sample method to check for float PCM in the MediaFormat is as follows:
static boolean isPcmFloat(MediaFormat format) { return format.getInteger(MediaFormat.KEY_PCM_ENCODING, AudioFormat.ENCODING_PCM_16BIT) == AudioFormat.ENCODING_PCM_FLOAT; }In order to extract, in a short array, one channel of a buffer containing 16 bit signed integer audio data, the following code may be used:
// Assumes the buffer PCM encoding is 16 bit. short[] getSamplesForChannel(MediaCodec codec, int bufferId, int channelIx) { ByteBuffer outputBuffer = codec.getOutputBuffer(bufferId); MediaFormat format = codec.getOutputFormat(bufferId); ShortBuffer samples = outputBuffer.order(ByteOrder.nativeOrder()).asShortBuffer(); int numChannels = format.getInteger(MediaFormat.KEY_CHANNEL_COUNT); if (channelIx < 0 || channelIx >= numChannels) { return null; } short[] res = new short[samples.remaining() / numChannels]; for (int i = 0; i < res.length; ++i) { res[i] = samples.get(i * numChannels + channelIx); } return res; }
In ByteBuffer mode video buffers are laid out according to their {@linkplain MediaFormat#KEY_COLOR_FORMAT color format}. You can get the supported color formats as an array from {@link #getCodecInfo}{@code .}{@link MediaCodecInfo#getCapabilitiesForType getCapabilitiesForType(…)}{@code .}{@link CodecCapabilities#colorFormats colorFormats}. Video codecs may support three kinds of color formats:
All video codecs support flexible YUV 4:2:0 buffers since {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}.
Prior to {@link android.os.Build.VERSION_CODES#LOLLIPOP} and {@link Image} support, you need to use the {@link MediaFormat#KEY_STRIDE} and {@link MediaFormat#KEY_SLICE_HEIGHT} output format values to understand the layout of the raw output buffers.
Note that on some devices the slice-height is advertised as 0. This could mean either that the slice-height is the same as the frame height, or that the slice-height is the frame height aligned to some value (usually a power of 2). Unfortunately, there is no standard and simple way to tell the actual slice height in this case. Furthermore, the vertical stride of the {@code U} plane in planar formats is also not specified or defined, though usually it is half of the slice height.
The {@link MediaFormat#KEY_WIDTH} and {@link MediaFormat#KEY_HEIGHT} keys specify the size of the video frames; however, for most encondings the video (picture) only occupies a portion of the video frame. This is represented by the 'crop rectangle'.
You need to use the following keys to get the crop rectangle of raw output images from the {@linkplain #getOutputFormat output format}. If these keys are not present, the video occupies the entire video frame.The crop rectangle is understood in the context of the output frame before applying any {@linkplain MediaFormat#KEY_ROTATION rotation}.
Format Key | Type | Description |
---|---|---|
{@link MediaFormat#KEY_CROP_LEFT} | Integer | The left-coordinate (x) of the crop rectangle |
{@link MediaFormat#KEY_CROP_TOP} | Integer | The top-coordinate (y) of the crop rectangle |
{@link MediaFormat#KEY_CROP_RIGHT} | Integer | The right-coordinate (x) MINUS 1 of the crop rectangle |
{@link MediaFormat#KEY_CROP_BOTTOM} | Integer | The bottom-coordinate (y) MINUS 1 of the crop rectangle |
The right and bottom coordinates can be understood as the coordinates of the right-most valid column/bottom-most valid row of the cropped output image. |
The size of the video frame (before rotation) can be calculated as such:
MediaFormat format = decoder.getOutputFormat(…); int width = format.getInteger(MediaFormat.KEY_WIDTH); if (format.containsKey(MediaFormat.KEY_CROP_LEFT) && format.containsKey(MediaFormat.KEY_CROP_RIGHT)) { width = format.getInteger(MediaFormat.KEY_CROP_RIGHT) + 1 - format.getInteger(MediaFormat.KEY_CROP_LEFT); } int height = format.getInteger(MediaFormat.KEY_HEIGHT); if (format.containsKey(MediaFormat.KEY_CROP_TOP) && format.containsKey(MediaFormat.KEY_CROP_BOTTOM)) { height = format.getInteger(MediaFormat.KEY_CROP_BOTTOM) + 1 - format.getInteger(MediaFormat.KEY_CROP_TOP); }
Also note that the meaning of {@link BufferInfo#offset BufferInfo.offset} was not consistent across devices. On some devices the offset pointed to the top-left pixel of the crop rectangle, while on most devices it pointed to the top-left pixel of the entire frame.
During its life a codec conceptually exists in one of three states: Stopped, Executing or Released. The Stopped collective state is actually the conglomeration of three states: Uninitialized, Configured and Error, whereas the Executing state conceptually progresses through three sub-states: Flushed, Running and End-of-Stream.
When you create a codec using one of the factory methods, the codec is in the Uninitialized state. First, you need to configure it via {@link #configure configure(…)}, which brings it to the Configured state, then call {@link #start} to move it to the Executing state. In this state you can process data through the buffer queue manipulation described above.
The Executing state has three sub-states: Flushed, Running and End-of-Stream. Immediately after {@link #start} the codec is in the Flushed sub-state, where it holds all the buffers. As soon as the first input buffer is dequeued, the codec moves to the Running sub-state, where it spends most of its life. When you queue an input buffer with the {@linkplain #BUFFER_FLAG_END_OF_STREAM end-of-stream marker}, the codec transitions to the End-of-Stream sub-state. In this state the codec no longer accepts further input buffers, but still generates output buffers until the end-of-stream is reached on the output. For decoders, you can move back to the Flushed sub-state at any time while in the Executing state using {@link #flush}.
Note: Going back to Flushed state is only supported for decoders, and may not work for encoders (the behavior is undefined).
Call {@link #stop} to return the codec to the Uninitialized state, whereupon it may be configured again. When you are done using a codec, you must release it by calling {@link #release}.
On rare occasions the codec may encounter an error and move to the Error state. This is communicated using an invalid return value from a queuing operation, or sometimes via an exception. Call {@link #reset} to make the codec usable again. You can call it from any state to move the codec back to the Uninitialized state. Otherwise, call {@link #release} to move to the terminal Released state.
Use {@link MediaCodecList} to create a MediaCodec for a specific {@link MediaFormat}. When decoding a file or a stream, you can get the desired format from {@link MediaExtractor#getTrackFormat MediaExtractor.getTrackFormat}. Inject any specific features that you want to add using {@link MediaFormat#setFeatureEnabled MediaFormat.setFeatureEnabled}, then call {@link MediaCodecList#findDecoderForFormat MediaCodecList.findDecoderForFormat} to get the name of a codec that can handle that specific media format. Finally, create the codec using {@link #createByCodecName}.
Note: On {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the format to
{@code MediaCodecList.findDecoder}/{@code EncoderForFormat} must not contain a {@linkplain
MediaFormat#KEY_FRAME_RATE frame rate}. Use
format.setString(MediaFormat.KEY_FRAME_RATE, null)
to clear any existing frame rate setting in the format.
You can also create the preferred codec for a specific MIME type using {@link #createDecoderByType createDecoder}/{@link #createEncoderByType EncoderByType(String)}. This, however, cannot be used to inject features, and may create a codec that cannot handle the specific desired media format.
On versions {@link android.os.Build.VERSION_CODES#KITKAT_WATCH} and earlier, secure codecs might not be listed in {@link MediaCodecList}, but may still be available on the system. Secure codecs that exist can be instantiated by name only, by appending {@code ".secure"} to the name of a regular codec (the name of all secure codecs must end in {@code ".secure"}.) {@link #createByCodecName} will throw an {@code IOException} if the codec is not present on the system.
From {@link android.os.Build.VERSION_CODES#LOLLIPOP} onwards, you should use the {@link CodecCapabilities#FEATURE_SecurePlayback} feature in the media format to create a secure decoder.
After creating the codec, you can set a callback using {@link #setCallback setCallback} if you want to process data asynchronously. Then, {@linkplain #configure configure} the codec using the specific media format. This is when you can specify the output {@link Surface} for video producers – codecs that generate raw video data (e.g. video decoders). This is also when you can set the decryption parameters for secure codecs (see {@link MediaCrypto}). Finally, since some codecs can operate in multiple modes, you must specify whether you want it to work as a decoder or an encoder.
Since {@link android.os.Build.VERSION_CODES#LOLLIPOP}, you can query the resulting input and output format in the Configured state. You can use this to verify the resulting configuration, e.g. color formats, before starting the codec.
If you want to process raw input video buffers natively with a video consumer – a codec that processes raw video input, such as a video encoder – create a destination Surface for your input data using {@link #createInputSurface} after configuration. Alternately, set up the codec to use a previously created {@linkplain #createPersistentInputSurface persistent input surface} by calling {@link #setInputSurface}.
When using an encoder, it is recommended to set the desired codec {@link MediaFormat#KEY_PROFILE profile} during {@link #configure configure()}. (This is only meaningful for {@link MediaFormat#KEY_MIME media formats} for which profiles are defined.)
If a profile is not specified during {@code configure}, the encoder will choose a profile for the session based on the available information. We will call this value the default profile. The selection of the default profile is device specific and may not be deterministic (could be ad hoc or even experimental). The encoder may choose a default profile that is not suitable for the intended encoding session, which may result in the encoder ultimately rejecting the session.
The encoder may reject the encoding session if the configured (or default if unspecified) profile does not support the codec input (mainly the {@link MediaFormat#KEY_COLOR_FORMAT color format} for video/image codecs, or the {@link MediaFormat#KEY_PCM_ENCODING sample encoding} and the {@link MediaFormat#KEY_CHANNEL_COUNT number of channels} for audio codecs, but also possibly {@link MediaFormat#KEY_WIDTH width}, {@link MediaFormat#KEY_HEIGHT height}, {@link MediaFormat#KEY_FRAME_RATE frame rate}, {@link MediaFormat#KEY_BIT_RATE bitrate} or {@link MediaFormat#KEY_SAMPLE_RATE sample rate}.) Alternatively, the encoder may choose to (but is not required to) convert the input to support the selected (or default) profile - or adjust the chosen profile based on the presumed or detected input format - to ensure a successful encoding session. Note: Converting the input to match an incompatible profile will in most cases result in decreased codec performance.
To ensure backward compatibility, the following guarantees are provided by Android:
Note: the accepted profile can be queried through the {@link #getOutputFormat output format} of the encoder after {@code configure} to allow applications to set up their codec input to a format supported by the encoder profile.
Implication:
Some formats, notably AAC audio and MPEG4, H.264 and H.265 video formats require the actual data to be prefixed by a number of buffers containing setup data, or codec specific data. When processing such compressed formats, this data must be submitted to the codec after {@link #start} and before any frame data. Such data must be marked using the flag {@link #BUFFER_FLAG_CODEC_CONFIG} in a call to {@link #queueInputBuffer queueInputBuffer}.
Codec-specific data can also be included in the format passed to {@link #configure configure} in ByteBuffer entries with keys "csd-0", "csd-1", etc. These keys are always included in the track {@link MediaFormat} obtained from the {@link MediaExtractor#getTrackFormat MediaExtractor}. Codec-specific data in the format is automatically submitted to the codec upon {@link #start}; you MUST NOT submit this data explicitly. If the format did not contain codec specific data, you can choose to submit it using the specified number of buffers in the correct order, according to the format requirements. In case of H.264 AVC, you can also concatenate all codec-specific data and submit it as a single codec-config buffer.
Android uses the following codec-specific data buffers. These are also required to be set in the track format for proper {@link MediaMuxer} track configuration. Each parameter set and the codec-specific-data sections marked with (*) must start with a start code of {@code "\x00\x00\x00\x01"}.
Format | CSD buffer #0 | CSD buffer #1 | CSD buffer #2 |
---|---|---|---|
AAC | Decoder-specific information from ESDS* | Not Used | Not Used |
VORBIS | Identification header | Setup header | Not Used |
OPUS | Identification header | Pre-skip in nanosecs (unsigned 64-bit {@linkplain ByteOrder#nativeOrder native-order} integer.) This overrides the pre-skip value in the identification header. |
Seek Pre-roll in nanosecs (unsigned 64-bit {@linkplain ByteOrder#nativeOrder native-order} integer.) |
FLAC | "fLaC", the FLAC stream marker in ASCII, followed by the STREAMINFO block (the mandatory metadata block), optionally followed by any number of other metadata blocks |
Not Used | Not Used |
MPEG-4 | Decoder-specific information from ESDS* | Not Used | Not Used |
H.264 AVC | SPS (Sequence Parameter Sets*) | PPS (Picture Parameter Sets*) | Not Used |
H.265 HEVC | VPS (Video Parameter Sets*) + SPS (Sequence Parameter Sets*) + PPS (Picture Parameter Sets*) |
Not Used | Not Used |
VP9 | VP9 CodecPrivate Data (optional) | Not Used | Not Used |
AV1 | AV1 AV1CodecConfigurationRecord Data (optional) | Not Used | Not Used |
Note: care must be taken if the codec is flushed immediately or shortly after start, before any output buffer or output format change has been returned, as the codec specific data may be lost during the flush. You must resubmit the data using buffers marked with {@link #BUFFER_FLAG_CODEC_CONFIG} after such flush to ensure proper codec operation.
Encoders (or codecs that generate compressed data) will create and return the codec specific data before any valid output buffer in output buffers marked with the {@linkplain #BUFFER_FLAG_CODEC_CONFIG codec-config flag}. Buffers containing codec-specific-data have no meaningful timestamps.
Each codec maintains a set of input and output buffers that are referred to by a buffer-ID in API calls. After a successful call to {@link #start} the client "owns" neither input nor output buffers. In synchronous mode, call {@link #dequeueInputBuffer dequeueInput}/{@link #dequeueOutputBuffer OutputBuffer(…)} to obtain (get ownership of) an input or output buffer from the codec. In asynchronous mode, you will automatically receive available buffers via the {@link Callback#onInputBufferAvailable MediaCodec.Callback.onInput}/{@link Callback#onOutputBufferAvailable OutputBufferAvailable(…)} callbacks.
Upon obtaining an input buffer, fill it with data and submit it to the codec using {@link #queueInputBuffer queueInputBuffer} – or {@link #queueSecureInputBuffer queueSecureInputBuffer} if using decryption. Do not submit multiple input buffers with the same timestamp (unless it is codec-specific data marked as such).
The codec in turn will return a read-only output buffer via the {@link Callback#onOutputBufferAvailable onOutputBufferAvailable} callback in asynchronous mode, or in response to a {@link #dequeueOutputBuffer dequeueOutputBuffer} call in synchronous mode. After the output buffer has been processed, call one of the {@link #releaseOutputBuffer releaseOutputBuffer} methods to return the buffer to the codec.
While you are not required to resubmit/release buffers immediately to the codec, holding onto input and/or output buffers may stall the codec, and this behavior is device dependent. Specifically, it is possible that a codec may hold off on generating output buffers until all outstanding buffers have been released/resubmitted. Therefore, try to hold onto to available buffers as little as possible.
Depending on the API version, you can process data in three ways:
Processing Mode | API version <= 20 Jelly Bean/KitKat |
API version >= 21 Lollipop and later |
---|---|---|
Synchronous API using buffer arrays | Supported | Deprecated |
Synchronous API using buffers | Not Available | Supported |
Asynchronous API using buffers | Not Available | Supported |
Since {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the preferred method is to process data asynchronously by setting a callback before calling {@link #configure configure}. Asynchronous mode changes the state transitions slightly, because you must call {@link #start} after {@link #flush} to transition the codec to the Running sub-state and start receiving input buffers. Similarly, upon an initial call to {@code start} the codec will move directly to the Running sub-state and start passing available input buffers via the callback.
MediaCodec is typically used like this in asynchronous mode:
MediaCodec codec = MediaCodec.createByCodecName(name); MediaFormat mOutputFormat; // member variable codec.setCallback(new MediaCodec.Callback() { {@literal @Override} void onInputBufferAvailable(MediaCodec mc, int inputBufferId) { ByteBuffer inputBuffer = codec.getInputBuffer(inputBufferId); // fill inputBuffer with valid data … codec.queueInputBuffer(inputBufferId, …); } {@literal @Override} void onOutputBufferAvailable(MediaCodec mc, int outputBufferId, …) { ByteBuffer outputBuffer = codec.getOutputBuffer(outputBufferId); MediaFormat bufferFormat = codec.getOutputFormat(outputBufferId); // option A // bufferFormat is equivalent to mOutputFormat // outputBuffer is ready to be processed or rendered. … codec.releaseOutputBuffer(outputBufferId, …); } {@literal @Override} void onOutputFormatChanged(MediaCodec mc, MediaFormat format) { // Subsequent data will conform to new format. // Can ignore if using getOutputFormat(outputBufferId) mOutputFormat = format; // option B } {@literal @Override} void onError(…) { … } {@literal @Override} void onCryptoError(…) { … } }); codec.configure(format, …); mOutputFormat = codec.getOutputFormat(); // option B codec.start(); // wait for processing to complete codec.stop(); codec.release();
Since {@link android.os.Build.VERSION_CODES#LOLLIPOP}, you should retrieve input and output buffers using {@link #getInputBuffer getInput}/{@link #getOutputBuffer OutputBuffer(int)} and/or {@link #getInputImage getInput}/{@link #getOutputImage OutputImage(int)} even when using the codec in synchronous mode. This allows certain optimizations by the framework, e.g. when processing dynamic content. This optimization is disabled if you call {@link #getInputBuffers getInput}/{@link #getOutputBuffers OutputBuffers()}.
Note: do not mix the methods of using buffers and buffer arrays at the same time. Specifically, only call {@code getInput}/{@code OutputBuffers} directly after {@link #start} or after having dequeued an output buffer ID with the value of {@link #INFO_OUTPUT_FORMAT_CHANGED}.
MediaCodec is typically used like this in synchronous mode:
MediaCodec codec = MediaCodec.createByCodecName(name); codec.configure(format, …); MediaFormat outputFormat = codec.getOutputFormat(); // option B codec.start(); for (;;) { int inputBufferId = codec.dequeueInputBuffer(timeoutUs); if (inputBufferId >= 0) { ByteBuffer inputBuffer = codec.getInputBuffer(…); // fill inputBuffer with valid data … codec.queueInputBuffer(inputBufferId, …); } int outputBufferId = codec.dequeueOutputBuffer(…); if (outputBufferId >= 0) { ByteBuffer outputBuffer = codec.getOutputBuffer(outputBufferId); MediaFormat bufferFormat = codec.getOutputFormat(outputBufferId); // option A // bufferFormat is identical to outputFormat // outputBuffer is ready to be processed or rendered. … codec.releaseOutputBuffer(outputBufferId, …); } else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // Subsequent data will conform to new format. // Can ignore if using getOutputFormat(outputBufferId) outputFormat = codec.getOutputFormat(); // option B } } codec.stop(); codec.release();
In versions {@link android.os.Build.VERSION_CODES#KITKAT_WATCH} and before, the set of input and output buffers are represented by the {@code ByteBuffer[]} arrays. After a successful call to {@link #start}, retrieve the buffer arrays using {@link #getInputBuffers getInput}/{@link #getOutputBuffers OutputBuffers()}. Use the buffer ID-s as indices into these arrays (when non-negative), as demonstrated in the sample below. Note that there is no inherent correlation between the size of the arrays and the number of input and output buffers used by the system, although the array size provides an upper bound.
MediaCodec codec = MediaCodec.createByCodecName(name); codec.configure(format, …); codec.start(); ByteBuffer[] inputBuffers = codec.getInputBuffers(); ByteBuffer[] outputBuffers = codec.getOutputBuffers(); for (;;) { int inputBufferId = codec.dequeueInputBuffer(…); if (inputBufferId >= 0) { // fill inputBuffers[inputBufferId] with valid data … codec.queueInputBuffer(inputBufferId, …); } int outputBufferId = codec.dequeueOutputBuffer(…); if (outputBufferId >= 0) { // outputBuffers[outputBufferId] is ready to be processed or rendered. … codec.releaseOutputBuffer(outputBufferId, …); } else if (outputBufferId == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { outputBuffers = codec.getOutputBuffers(); } else if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // Subsequent data will conform to new format. MediaFormat format = codec.getOutputFormat(); } } codec.stop(); codec.release();
When you reach the end of the input data, you must signal it to the codec by specifying the {@link #BUFFER_FLAG_END_OF_STREAM} flag in the call to {@link #queueInputBuffer queueInputBuffer}. You can do this on the last valid input buffer, or by submitting an additional empty input buffer with the end-of-stream flag set. If using an empty buffer, the timestamp will be ignored.
The codec will continue to return output buffers until it eventually signals the end of the output stream by specifying the same end-of-stream flag in the {@link BufferInfo} set in {@link #dequeueOutputBuffer dequeueOutputBuffer} or returned via {@link Callback#onOutputBufferAvailable onOutputBufferAvailable}. This can be set on the last valid output buffer, or on an empty buffer after the last valid output buffer. The timestamp of such empty buffer should be ignored.
Do not submit additional input buffers after signaling the end of the input stream, unless the codec has been flushed, or stopped and restarted.
The data processing is nearly identical to the ByteBuffer mode when using an output {@link Surface}; however, the output buffers will not be accessible, and are represented as {@code null} values. E.g. {@link #getOutputBuffer getOutputBuffer}/{@link #getOutputImage Image(int)} will return {@code null} and {@link #getOutputBuffers} will return an array containing only {@code null}-s.
When using an output Surface, you can select whether or not to render each output buffer on the surface. You have three choices:
Since {@link android.os.Build.VERSION_CODES#M}, the default timestamp is the {@linkplain BufferInfo#presentationTimeUs presentation timestamp} of the buffer (converted to nanoseconds). It was not defined prior to that.
Also since {@link android.os.Build.VERSION_CODES#M}, you can change the output Surface dynamically using {@link #setOutputSurface setOutputSurface}.
When rendering output to a Surface, the Surface may be configured to drop excessive frames (that are not consumed by the Surface in a timely manner). Or it may be configured to not drop excessive frames. In the latter mode if the Surface is not consuming output frames fast enough, it will eventually block the decoder. Prior to {@link android.os.Build.VERSION_CODES#Q} the exact behavior was undefined, with the exception that View surfaces (SurfaceView or TextureView) always dropped excessive frames. Since {@link android.os.Build.VERSION_CODES#Q} the default behavior is to drop excessive frames. Applications can opt out of this behavior for non-View surfaces (such as ImageReader or SurfaceTexture) by targeting SDK {@link android.os.Build.VERSION_CODES#Q} and setting the key {@link MediaFormat#KEY_ALLOW_FRAME_DROP} to {@code 0} in their configure format.
Prior to the {@link android.os.Build.VERSION_CODES#M} release, software decoders may not have applied the rotation when being rendered onto a Surface. Unfortunately, there is no standard and simple way to identify software decoders, or if they apply the rotation other than by trying it out.
There are also some caveats.
Note that the pixel aspect ratio is not considered when displaying the output onto the Surface. This means that if you are using {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT} mode, you must position the output Surface so that it has the proper final display aspect ratio. Conversely, you can only use {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING} mode for content with square pixels (pixel aspect ratio or 1:1).
Note also that as of {@link android.os.Build.VERSION_CODES#N} release, {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING} mode may not work correctly for videos rotated by 90 or 270 degrees.
When setting the video scaling mode, note that it must be reset after each time the output buffers change. Since the {@link #INFO_OUTPUT_BUFFERS_CHANGED} event is deprecated, you can do this after each time the output format changes.
When using an input Surface, there are no accessible input buffers, as buffers are automatically passed from the input surface to the codec. Calling {@link #dequeueInputBuffer dequeueInputBuffer} will throw an {@code IllegalStateException}, and {@link #getInputBuffers} returns a bogus {@code ByteBuffer[]} array that MUST NOT be written into.
Call {@link #signalEndOfInputStream} to signal end-of-stream. The input surface will stop submitting data to the codec immediately after this call.
Video decoders (and in general codecs that consume compressed video data) behave differently regarding seek and format change whether or not they support and are configured for adaptive playback. You can check if a decoder supports {@linkplain CodecCapabilities#FEATURE_AdaptivePlayback adaptive playback} via {@link CodecCapabilities#isFeatureSupported CodecCapabilities.isFeatureSupported(String)}. Adaptive playback support for video decoders is only activated if you configure the codec to decode onto a {@link Surface}.
It is important that the input data after {@link #start} or {@link #flush} starts at a suitable stream boundary: the first frame must be a key frame. A key frame can be decoded completely on its own (for most codecs this means an I-frame), and no frames that are to be displayed after a key frame refer to frames before the key frame.
The following table summarizes suitable key frames for various video formats.
Format | Suitable key frame |
---|---|
VP9/VP8 | a suitable intraframe where no subsequent frames refer to frames prior to this frame. (There is no specific name for such key frame.) |
H.265 HEVC | IDR or CRA |
H.264 AVC | IDR |
MPEG-4 H.263 MPEG-2 |
a suitable I-frame where no subsequent frames refer to frames prior to this frame. (There is no specific name for such key frame.) |
In order to start decoding data that is not adjacent to previously submitted data (i.e. after a seek) you MUST flush the decoder. Since all output buffers are immediately revoked at the point of the flush, you may want to first signal then wait for the end-of-stream before you call {@code flush}. It is important that the input data after a flush starts at a suitable stream boundary/key frame.
Note: the format of the data submitted after a flush must not change; {@link #flush} does not support format discontinuities; for that, a full {@link #stop} - {@link #configure configure(…)} - {@link #start} cycle is necessary.
Also note: if you flush the codec too soon after {@link #start} – generally, before the first output buffer or output format change is received – you will need to resubmit the codec-specific-data to the codec. See the codec-specific-data section for more info.
In order to start decoding data that is not adjacent to previously submitted data (i.e. after a seek) it is not necessary to flush the decoder; however, input data after the discontinuity must start at a suitable stream boundary/key frame.
For some video formats - namely H.264, H.265, VP8 and VP9 - it is also possible to change the picture size or configuration mid-stream. To do this you must package the entire new codec-specific configuration data together with the key frame into a single buffer (including any start codes), and submit it as a regular input buffer.
You will receive an {@link #INFO_OUTPUT_FORMAT_CHANGED} return value from {@link #dequeueOutputBuffer dequeueOutputBuffer} or a {@link Callback#onOutputBufferAvailable onOutputFormatChanged} callback just after the picture-size change takes place and before any frames with the new size have been returned.
Note: just as the case for codec-specific data, be careful when calling {@link #flush} shortly after you have changed the picture size. If you have not received confirmation of the picture size change, you will need to repeat the request for the new picture size.
The factory methods {@link #createByCodecName createByCodecName} and {@link #createDecoderByType createDecoder}/{@link #createEncoderByType EncoderByType} throw {@code IOException} on failure which you must catch or declare to pass up. MediaCodec methods throw {@code IllegalStateException} when the method is called from a codec state that does not allow it; this is typically due to incorrect application API usage. Methods involving secure buffers may throw {@link CryptoException}, which has further error information obtainable from {@link CryptoException#getErrorCode}.
Internal codec errors result in a {@link CodecException}, which may be due to media content corruption, hardware failure, resource exhaustion, and so forth, even when the application is correctly using the API. The recommended action when receiving a {@code CodecException} can be determined by calling {@link CodecException#isRecoverable} and {@link CodecException#isTransient}:
Both {@code isRecoverable()} and {@code isTransient()} do not return true at the same time.
This sections summarizes the valid API calls in each state and the API history of the MediaCodec class. For API version numbers, see {@link android.os.Build.VERSION_CODES}.
Symbol | Meaning |
---|---|
● | Supported |
⁕ | Semantics changed |
○ | Experimental support |
[ ] | Deprecated |
⎋ | Restricted to surface input mode |
⎆ | Restricted to surface output mode |
▧ | Restricted to ByteBuffer input mode |
↩ | Restricted to synchronous mode |
⇄ | Restricted to asynchronous mode |
( ) | Can be called, but shouldn't |
Uninitialized |
Configured |
Flushed |
Running |
End of Stream |
Error |
Released |
SDK Version | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
State | Method | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | ||||||
{@link #createByCodecName createByCodecName} | ● | ● | ● | ● | ● | ● | ● | ● | |||||||
{@link #createDecoderByType createDecoderByType} | ● | ● | ● | ● | ● | ● | ● | ● | |||||||
{@link #createEncoderByType createEncoderByType} | ● | ● | ● | ● | ● | ● | ● | ● | |||||||
{@link #createPersistentInputSurface createPersistentInputSurface} | ● | ||||||||||||||
16+ | - | - | - | - | - | - | {@link #configure configure} | ● | ● | ● | ● | ● | ⁕ | ● | ● |
- | 18+ | - | - | - | - | - | {@link #createInputSurface createInputSurface} | ⎋ | ⎋ | ⎋ | ⎋ | ⎋ | ⎋ | ||
- | - | 16+ | 16+ | (16+) | - | - | {@link #dequeueInputBuffer dequeueInputBuffer} | ● | ● | ▧ | ▧ | ▧ | ⁕▧↩ | ▧↩ | ▧↩ |
- | - | 16+ | 16+ | 16+ | - | - | {@link #dequeueOutputBuffer dequeueOutputBuffer} | ● | ● | ● | ● | ● | ⁕↩ | ↩ | ↩ |
- | - | 16+ | 16+ | 16+ | - | - | {@link #flush flush} | ● | ● | ● | ● | ● | ● | ● | ● |
18+ | 18+ | 18+ | 18+ | 18+ | 18+ | - | {@link #getCodecInfo getCodecInfo} | ● | ● | ● | ● | ● | ● | ||
- | - | (21+) | 21+ | (21+) | - | - | {@link #getInputBuffer getInputBuffer} | ● | ● | ● | |||||
- | - | 16+ | (16+) | (16+) | - | - | {@link #getInputBuffers getInputBuffers} | ● | ● | ● | ● | ● | [⁕↩] | [↩] | [↩] |
- | 21+ | (21+) | (21+) | (21+) | - | - | {@link #getInputFormat getInputFormat} | ● | ● | ● | |||||
- | - | (21+) | 21+ | (21+) | - | - | {@link #getInputImage getInputImage} | ○ | ● | ● | |||||
18+ | 18+ | 18+ | 18+ | 18+ | 18+ | - | {@link #getName getName} | ● | ● | ● | ● | ● | ● | ||
- | - | (21+) | 21+ | 21+ | - | - | {@link #getOutputBuffer getOutputBuffer} | ● | ● | ● | |||||
- | - | 16+ | 16+ | 16+ | - | - | {@link #getOutputBuffers getOutputBuffers} | ● | ● | ● | ● | ● | [⁕↩] | [↩] | [↩] |
- | 21+ | 16+ | 16+ | 16+ | - | - | {@link #getOutputFormat()} | ● | ● | ● | ● | ● | ● | ● | ● |
- | - | (21+) | 21+ | 21+ | - | - | {@link #getOutputFormat(int)} | ● | ● | ● | |||||
- | - | (21+) | 21+ | 21+ | - | - | {@link #getOutputImage getOutputImage} | ○ | ● | ● | |||||
- | - | - | 16+ | (16+) | - | - | {@link #queueInputBuffer queueInputBuffer} | ● | ● | ● | ● | ● | ⁕ | ● | ● |
- | - | - | 16+ | (16+) | - | - | {@link #queueSecureInputBuffer queueSecureInputBuffer} | ● | ● | ● | ● | ● | ⁕ | ● | ● |
16+ | 16+ | 16+ | 16+ | 16+ | 16+ | 16+ | {@link #release release} | ● | ● | ● | ● | ● | ● | ● | ● |
- | - | - | 16+ | 16+ | - | - | {@link #releaseOutputBuffer(int, boolean)} | ● | ● | ● | ● | ● | ⁕ | ● | ⁕ |
- | - | - | 21+ | 21+ | - | - | {@link #releaseOutputBuffer(int, long)} | ⎆ | ⎆ | ⎆ | |||||
21+ | 21+ | 21+ | 21+ | 21+ | 21+ | - | {@link #reset reset} | ● | ● | ● | |||||
21+ | - | - | - | - | - | - | {@link #setCallback(Callback) setCallback} | ● | ● | {@link #setCallback(Callback, Handler) ⁕} | |||||
- | 23+ | - | - | - | - | - | {@link #setInputSurface setInputSurface} | ⎋ | |||||||
23+ | 23+ | 23+ | 23+ | 23+ | (23+) | (23+) | {@link #setOnFrameRenderedListener setOnFrameRenderedListener} | ○ ⎆ | |||||||
- | 23+ | 23+ | 23+ | 23+ | - | - | {@link #setOutputSurface setOutputSurface} | ⎆ | |||||||
19+ | 19+ | 19+ | 19+ | 19+ | (19+) | - | {@link #setParameters setParameters} | ● | ● | ● | ● | ● | |||
- | (16+) | (16+) | 16+ | (16+) | (16+) | - | {@link #setVideoScalingMode setVideoScalingMode} | ⎆ | ⎆ | ⎆ | ⎆ | ⎆ | ⎆ | ⎆ | ⎆ |
(29+) | 29+ | 29+ | 29+ | (29+) | (29+) | - | {@link #setAudioPresentation setAudioPresentation} | ||||||||
- | - | 18+ | 18+ | - | - | - | {@link #signalEndOfInputStream signalEndOfInputStream} | ⎋ | ⎋ | ⎋ | ⎋ | ⎋ | ⎋ | ||
- | 16+ | 21+(⇄) | - | - | - | - | {@link #start start} | ● | ● | ● | ● | ● | ⁕ | ● | ● |
- | - | 16+ | 16+ | 16+ | - | - | {@link #stop stop} | ● | ● | ● | ● | ● | ● | ● | ● |
Encoded buffers that are key frames are marked with * {@link #BUFFER_FLAG_KEY_FRAME}. * *
The last output buffer corresponding to the input buffer
* marked with {@link #BUFFER_FLAG_END_OF_STREAM} will also be marked
* with {@link #BUFFER_FLAG_END_OF_STREAM}. In some cases this could
* be an empty buffer, whose sole purpose is to carry the end-of-stream
* marker.
*/
@BufferFlag
public int flags;
/** @hide */
@NonNull
public BufferInfo dup() {
BufferInfo copy = new BufferInfo();
copy.set(offset, size, presentationTimeUs, flags);
return copy;
}
};
// The follow flag constants MUST stay in sync with their equivalents
// in MediaCodec.h !
/**
* This indicates that the (encoded) buffer marked as such contains
* the data for a key frame.
*
* @deprecated Use {@link #BUFFER_FLAG_KEY_FRAME} instead.
*/
public static final int BUFFER_FLAG_SYNC_FRAME = 1;
/**
* This indicates that the (encoded) buffer marked as such contains
* the data for a key frame.
*/
public static final int BUFFER_FLAG_KEY_FRAME = 1;
/**
* This indicated that the buffer marked as such contains codec
* initialization / codec specific data instead of media data.
*/
public static final int BUFFER_FLAG_CODEC_CONFIG = 2;
/**
* This signals the end of stream, i.e. no buffers will be available
* after this, unless of course, {@link #flush} follows.
*/
public static final int BUFFER_FLAG_END_OF_STREAM = 4;
/**
* This indicates that the buffer only contains part of a frame,
* and the decoder should batch the data until a buffer without
* this flag appears before decoding the frame.
*/
public static final int BUFFER_FLAG_PARTIAL_FRAME = 8;
/**
* This indicates that the buffer contains non-media data for the
* muxer to process.
*
* All muxer data should start with a FOURCC header that determines the type of data.
*
* For example, when it contains Exif data sent to a MediaMuxer track of
* {@link MediaFormat#MIMETYPE_IMAGE_ANDROID_HEIC} type, the data must start with
* Exif header ("Exif\0\0"), followed by the TIFF header (See JEITA CP-3451C Section 4.5.2.)
*
* @hide
*/
public static final int BUFFER_FLAG_MUXER_DATA = 16;
/**
* This indicates that the buffer is decoded and updates the internal state of the decoder,
* but does not produce any output buffer.
*
* When a buffer has this flag set,
* {@link OnFrameRenderedListener#onFrameRendered(MediaCodec, long, long)} and
* {@link Callback#onOutputBufferAvailable(MediaCodec, int, BufferInfo)} will not be called for
* that given buffer.
*
* For example, when seeking to a certain frame, that frame may need to reference previous
* frames in order for it to produce output. The preceding frames can be marked with this flag
* so that they are only decoded and their data is used when decoding the latter frame that
* should be initially displayed post-seek.
* Another example would be trick play, trick play is when a video is fast-forwarded and only a
* subset of the frames is to be rendered on the screen. The frames not to be rendered can be
* marked with this flag for the same reason as the above one.
* Marking frames with this flag improves the overall performance of playing a video stream as
* fewer frames need to be passed back to the app.
*
* In {@link CodecCapabilities#FEATURE_TunneledPlayback}, buffers marked with this flag
* are not rendered on the output surface.
*
* A frame should not be marked with this flag and {@link #BUFFER_FLAG_END_OF_STREAM}
* simultaneously, doing so will produce a {@link InvalidBufferFlagsException}
*/
public static final int BUFFER_FLAG_DECODE_ONLY = 32;
/** @hide */
@IntDef(
flag = true,
value = {
BUFFER_FLAG_SYNC_FRAME,
BUFFER_FLAG_KEY_FRAME,
BUFFER_FLAG_CODEC_CONFIG,
BUFFER_FLAG_END_OF_STREAM,
BUFFER_FLAG_PARTIAL_FRAME,
BUFFER_FLAG_MUXER_DATA,
BUFFER_FLAG_DECODE_ONLY,
})
@Retention(RetentionPolicy.SOURCE)
public @interface BufferFlag {}
private EventHandler mEventHandler;
private EventHandler mOnFirstTunnelFrameReadyHandler;
private EventHandler mOnFrameRenderedHandler;
private EventHandler mCallbackHandler;
private Callback mCallback;
private OnFirstTunnelFrameReadyListener mOnFirstTunnelFrameReadyListener;
private OnFrameRenderedListener mOnFrameRenderedListener;
private final Object mListenerLock = new Object();
private MediaCodecInfo mCodecInfo;
private final Object mCodecInfoLock = new Object();
private MediaCrypto mCrypto;
private static final int EVENT_CALLBACK = 1;
private static final int EVENT_SET_CALLBACK = 2;
private static final int EVENT_FRAME_RENDERED = 3;
private static final int EVENT_FIRST_TUNNEL_FRAME_READY = 4;
private static final int CB_INPUT_AVAILABLE = 1;
private static final int CB_OUTPUT_AVAILABLE = 2;
private static final int CB_ERROR = 3;
private static final int CB_OUTPUT_FORMAT_CHANGE = 4;
private static final String EOS_AND_DECODE_ONLY_ERROR_MESSAGE = "An input buffer cannot have "
+ "both BUFFER_FLAG_END_OF_STREAM and BUFFER_FLAG_DECODE_ONLY flags";
private static final int CB_CRYPTO_ERROR = 6;
private static final int CB_LARGE_FRAME_OUTPUT_AVAILABLE = 7;
private class EventHandler extends Handler {
private MediaCodec mCodec;
public EventHandler(@NonNull MediaCodec codec, @NonNull Looper looper) {
super(looper);
mCodec = codec;
}
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case EVENT_CALLBACK:
{
handleCallback(msg);
break;
}
case EVENT_SET_CALLBACK:
{
mCallback = (MediaCodec.Callback) msg.obj;
break;
}
case EVENT_FRAME_RENDERED:
Map
* When this flag is set, the following APIs throw {@link IncompatibleWithBlockModelException}.
*
* This flag is only defined for a video decoder. MediaCodec
* configured with this flag will be in Surface mode even though
* the surface parameter is null.
*
* @see detachOutputSurface
*/
@FlaggedApi(FLAG_NULL_OUTPUT_SURFACE)
public static final int CONFIGURE_FLAG_DETACHED_SURFACE = 8;
/** @hide */
@IntDef(
flag = true,
value = {
CONFIGURE_FLAG_ENCODE,
CONFIGURE_FLAG_USE_BLOCK_MODEL,
CONFIGURE_FLAG_USE_CRYPTO_ASYNC,
})
@Retention(RetentionPolicy.SOURCE)
public @interface ConfigureFlag {}
/**
* Thrown when the codec is configured for block model and an incompatible API is called.
*/
public class IncompatibleWithBlockModelException extends RuntimeException {
IncompatibleWithBlockModelException() { }
IncompatibleWithBlockModelException(String message) {
super(message);
}
IncompatibleWithBlockModelException(String message, Throwable cause) {
super(message, cause);
}
IncompatibleWithBlockModelException(Throwable cause) {
super(cause);
}
}
/**
* Thrown when a buffer is marked with an invalid combination of flags
* (e.g. both {@link #BUFFER_FLAG_END_OF_STREAM} and {@link #BUFFER_FLAG_DECODE_ONLY})
*/
public class InvalidBufferFlagsException extends RuntimeException {
InvalidBufferFlagsException(String message) {
super(message);
}
}
/**
* Configures a component.
*
* @param format The format of the input data (decoder) or the desired
* format of the output data (encoder). Passing {@code null}
* as {@code format} is equivalent to passing an
* {@link MediaFormat#MediaFormat an empty mediaformat}.
* @param surface Specify a surface on which to render the output of this
* decoder. Pass {@code null} as {@code surface} if the
* codec does not generate raw video output (e.g. not a video
* decoder) and/or if you want to configure the codec for
* {@link ByteBuffer} output.
* @param crypto Specify a crypto object to facilitate secure decryption
* of the media data. Pass {@code null} as {@code crypto} for
* non-secure codecs.
* Please note that {@link MediaCodec} does NOT take ownership
* of the {@link MediaCrypto} object; it is the application's
* responsibility to properly cleanup the {@link MediaCrypto} object
* when not in use.
* @param flags Specify {@link #CONFIGURE_FLAG_ENCODE} to configure the
* component as an encoder.
* @throws IllegalArgumentException if the surface has been released (or is invalid),
* or the format is unacceptable (e.g. missing a mandatory key),
* or the flags are not set properly
* (e.g. missing {@link #CONFIGURE_FLAG_ENCODE} for an encoder).
* @throws IllegalStateException if not in the Uninitialized state.
* @throws CryptoException upon DRM error.
* @throws CodecException upon codec error.
*/
public void configure(
@Nullable MediaFormat format,
@Nullable Surface surface, @Nullable MediaCrypto crypto,
@ConfigureFlag int flags) {
configure(format, surface, crypto, null, flags);
}
/**
* Configure a component to be used with a descrambler.
* @param format The format of the input data (decoder) or the desired
* format of the output data (encoder). Passing {@code null}
* as {@code format} is equivalent to passing an
* {@link MediaFormat#MediaFormat an empty mediaformat}.
* @param surface Specify a surface on which to render the output of this
* decoder. Pass {@code null} as {@code surface} if the
* codec does not generate raw video output (e.g. not a video
* decoder) and/or if you want to configure the codec for
* {@link ByteBuffer} output.
* @param flags Specify {@link #CONFIGURE_FLAG_ENCODE} to configure the
* component as an encoder.
* @param descrambler Specify a descrambler object to facilitate secure
* descrambling of the media data, or null for non-secure codecs.
* @throws IllegalArgumentException if the surface has been released (or is invalid),
* or the format is unacceptable (e.g. missing a mandatory key),
* or the flags are not set properly
* (e.g. missing {@link #CONFIGURE_FLAG_ENCODE} for an encoder).
* @throws IllegalStateException if not in the Uninitialized state.
* @throws CryptoException upon DRM error.
* @throws CodecException upon codec error.
*/
public void configure(
@Nullable MediaFormat format, @Nullable Surface surface,
@ConfigureFlag int flags, @Nullable MediaDescrambler descrambler) {
configure(format, surface, null,
descrambler != null ? descrambler.getBinder() : null, flags);
}
private static final int BUFFER_MODE_INVALID = -1;
private static final int BUFFER_MODE_LEGACY = 0;
private static final int BUFFER_MODE_BLOCK = 1;
private int mBufferMode = BUFFER_MODE_INVALID;
private void configure(
@Nullable MediaFormat format, @Nullable Surface surface,
@Nullable MediaCrypto crypto, @Nullable IHwBinder descramblerBinder,
@ConfigureFlag int flags) {
if (crypto != null && descramblerBinder != null) {
throw new IllegalArgumentException("Can't use crypto and descrambler together!");
}
// at the moment no codecs support detachable surface
boolean canDetach = GetFlag(() -> android.media.codec.Flags.nullOutputSurfaceSupport());
if (GetFlag(() -> android.media.codec.Flags.nullOutputSurface())) {
// Detached surface flag is only meaningful if surface is null. Otherwise, it is
// ignored.
if (surface == null && (flags & CONFIGURE_FLAG_DETACHED_SURFACE) != 0 && !canDetach) {
throw new IllegalArgumentException("Codec does not support detached surface");
}
} else {
// don't allow detaching if API is disabled
canDetach = false;
}
String[] keys = null;
Object[] values = null;
if (format != null) {
Map
* This can only be used if the codec was configured with an output surface. The
* new output surface should have a compatible usage type to the original output surface.
* E.g. codecs may not support switching from a SurfaceTexture (GPU readable) output
* to ImageReader (software readable) output.
* @param surface the output surface to use. It must not be {@code null}.
* @throws IllegalStateException if the codec does not support setting the output
* surface in the current state.
* @throws IllegalArgumentException if the new surface is not of a suitable type for the codec.
*/
public void setOutputSurface(@NonNull Surface surface) {
if (!mHasSurface) {
throw new IllegalStateException("codec was not configured for an output surface");
}
native_setSurface(surface);
}
private native void native_setSurface(@NonNull Surface surface);
/**
* Detach the current output surface of a codec.
*
* Detaches the currently associated output Surface from the
* MediaCodec decoder. This allows the SurfaceView or other
* component holding the Surface to be safely destroyed or
* modified without affecting the decoder's operation. After
* calling this method (and after it returns), the decoder will
* enter detached-Surface mode and will no longer render
* output.
*
* @throws IllegalStateException if the codec was not
* configured in surface mode or if the codec does not support
* detaching the output surface.
* @see CONFIGURE_FLAG_DETACHED_SURFACE
*/
@FlaggedApi(FLAG_NULL_OUTPUT_SURFACE)
public void detachOutputSurface() {
if (!mHasSurface) {
throw new IllegalStateException("codec was not configured for an output surface");
}
// note: we still have a surface in detached mode, so keep mHasSurface
// we also technically allow calling detachOutputSurface multiple times in a row
if (GetFlag(() -> android.media.codec.Flags.nullOutputSurfaceSupport())) {
native_detachOutputSurface();
} else {
throw new IllegalStateException("codec does not support detaching output surface");
}
}
private native void native_detachOutputSurface();
/**
* Create a persistent input surface that can be used with codecs that normally have an input
* surface, such as video encoders. A persistent input can be reused by subsequent
* {@link MediaCodec} or {@link MediaRecorder} instances, but can only be used by at
* most one codec or recorder instance concurrently.
*
* The application is responsible for calling release() on the Surface when done.
*
* @return an input surface that can be used with {@link #setInputSurface}.
*/
@NonNull
public static Surface createPersistentInputSurface() {
return native_createPersistentInputSurface();
}
static class PersistentSurface extends Surface {
@SuppressWarnings("unused")
PersistentSurface() {} // used by native
@Override
public void release() {
native_releasePersistentInputSurface(this);
super.release();
}
private long mPersistentObject;
};
/**
* Configures the codec (e.g. encoder) to use a persistent input surface in place of input
* buffers. This may only be called after {@link #configure} and before {@link #start}, in
* lieu of {@link #createInputSurface}.
* @param surface a persistent input surface created by {@link #createPersistentInputSurface}
* @throws IllegalStateException if not in the Configured state or does not require an input
* surface.
* @throws IllegalArgumentException if the surface was not created by
* {@link #createPersistentInputSurface}.
*/
public void setInputSurface(@NonNull Surface surface) {
if (!(surface instanceof PersistentSurface)) {
throw new IllegalArgumentException("not a PersistentSurface");
}
native_setInputSurface(surface);
}
@NonNull
private static native final PersistentSurface native_createPersistentInputSurface();
private static native final void native_releasePersistentInputSurface(@NonNull Surface surface);
private native final void native_setInputSurface(@NonNull Surface surface);
private native final void native_setCallback(@Nullable Callback cb);
private native final void native_configure(
@Nullable String[] keys, @Nullable Object[] values,
@Nullable Surface surface, @Nullable MediaCrypto crypto,
@Nullable IHwBinder descramblerBinder, @ConfigureFlag int flags);
/**
* Requests a Surface to use as the input to an encoder, in place of input buffers. This
* may only be called after {@link #configure} and before {@link #start}.
*
* The application is responsible for calling release() on the Surface when
* done.
*
* The Surface must be rendered with a hardware-accelerated API, such as OpenGL ES.
* {@link android.view.Surface#lockCanvas(android.graphics.Rect)} may fail or produce
* unexpected results.
* @throws IllegalStateException if not in the Configured state.
*/
@NonNull
public native final Surface createInputSurface();
/**
* After successfully configuring the component, call {@code start}.
*
* Call {@code start} also if the codec is configured in asynchronous mode,
* and it has just been flushed, to resume requesting input buffers.
* @throws IllegalStateException if not in the Configured state
* or just after {@link #flush} for a codec that is configured
* in asynchronous mode.
* @throws MediaCodec.CodecException upon codec error. Note that some codec errors
* for start may be attributed to future method calls.
*/
public final void start() {
native_start();
}
private native final void native_start();
/**
* Finish the decode/encode session, note that the codec instance
* remains active and ready to be {@link #start}ed again.
* To ensure that it is available to other client call {@link #release}
* and don't just rely on garbage collection to eventually do this for you.
* @throws IllegalStateException if in the Released state.
*/
public final void stop() {
native_stop();
freeAllTrackedBuffers();
synchronized (mListenerLock) {
if (mCallbackHandler != null) {
mCallbackHandler.removeMessages(EVENT_SET_CALLBACK);
mCallbackHandler.removeMessages(EVENT_CALLBACK);
}
if (mOnFirstTunnelFrameReadyHandler != null) {
mOnFirstTunnelFrameReadyHandler.removeMessages(EVENT_FIRST_TUNNEL_FRAME_READY);
}
if (mOnFrameRenderedHandler != null) {
mOnFrameRenderedHandler.removeMessages(EVENT_FRAME_RENDERED);
}
}
}
private native final void native_stop();
/**
* Flush both input and output ports of the component.
*
* Upon return, all indices previously returned in calls to {@link #dequeueInputBuffer
* dequeueInputBuffer} and {@link #dequeueOutputBuffer dequeueOutputBuffer} — or obtained
* via {@link Callback#onInputBufferAvailable onInputBufferAvailable} or
* {@link Callback#onOutputBufferAvailable onOutputBufferAvailable} callbacks — become
* invalid, and all buffers are owned by the codec.
*
* If the codec is configured in asynchronous mode, call {@link #start}
* after {@code flush} has returned to resume codec operations. The codec
* will not request input buffers until this has happened.
* Note, however, that there may still be outstanding {@code onOutputBufferAvailable}
* callbacks that were not handled prior to calling {@code flush}.
* The indices returned via these callbacks also become invalid upon calling {@code flush} and
* should be discarded.
*
* If the codec is configured in synchronous mode, codec will resume
* automatically if it is configured with an input surface. Otherwise, it
* will resume when {@link #dequeueInputBuffer dequeueInputBuffer} is called.
*
* @throws IllegalStateException if not in the Executing state.
* @throws MediaCodec.CodecException upon codec error.
*/
public final void flush() {
synchronized(mBufferLock) {
invalidateByteBuffersLocked(mCachedInputBuffers);
invalidateByteBuffersLocked(mCachedOutputBuffers);
mValidInputIndices.clear();
mValidOutputIndices.clear();
mDequeuedInputBuffers.clear();
mDequeuedOutputBuffers.clear();
}
native_flush();
}
private native final void native_flush();
/**
* Thrown when an internal codec error occurs.
*/
public final static class CodecException extends IllegalStateException {
@UnsupportedAppUsage
CodecException(int errorCode, int actionCode, @Nullable String detailMessage) {
super(detailMessage);
mErrorCode = errorCode;
mActionCode = actionCode;
// TODO get this from codec
final String sign = errorCode < 0 ? "neg_" : "";
mDiagnosticInfo =
"android.media.MediaCodec.error_" + sign + Math.abs(errorCode);
}
/**
* Returns true if the codec exception is a transient issue,
* perhaps due to resource constraints, and that the method
* (or encoding/decoding) may be retried at a later time.
*/
public boolean isTransient() {
return mActionCode == ACTION_TRANSIENT;
}
/**
* Returns true if the codec cannot proceed further,
* but can be recovered by stopping, configuring,
* and starting again.
*/
public boolean isRecoverable() {
return mActionCode == ACTION_RECOVERABLE;
}
/**
* Retrieve the error code associated with a CodecException
*/
public int getErrorCode() {
return mErrorCode;
}
/**
* Retrieve a developer-readable diagnostic information string
* associated with the exception. Do not show this to end-users,
* since this string will not be localized or generally
* comprehensible to end-users.
*/
public @NonNull String getDiagnosticInfo() {
return mDiagnosticInfo;
}
/**
* This indicates required resource was not able to be allocated.
*/
public static final int ERROR_INSUFFICIENT_RESOURCE = 1100;
/**
* This indicates the resource manager reclaimed the media resource used by the codec.
*
* With this exception, the codec must be released, as it has moved to terminal state.
*/
public static final int ERROR_RECLAIMED = 1101;
/** @hide */
@IntDef({
ERROR_INSUFFICIENT_RESOURCE,
ERROR_RECLAIMED,
})
@Retention(RetentionPolicy.SOURCE)
public @interface ReasonCode {}
/* Must be in sync with android_media_MediaCodec.cpp */
private final static int ACTION_TRANSIENT = 1;
private final static int ACTION_RECOVERABLE = 2;
private final String mDiagnosticInfo;
private final int mErrorCode;
private final int mActionCode;
}
/**
* Thrown when a crypto error occurs while queueing a secure input buffer.
*/
public final static class CryptoException extends RuntimeException
implements MediaDrmThrowable {
public CryptoException(int errorCode, @Nullable String detailMessage) {
this(detailMessage, errorCode, 0, 0, 0, null);
}
/**
* @hide
*/
public CryptoException(String message, int errorCode, int vendorError, int oemError,
int errorContext, @Nullable CryptoInfo cryptoInfo) {
super(message);
mErrorCode = errorCode;
mVendorError = vendorError;
mOemError = oemError;
mErrorContext = errorContext;
mCryptoInfo = cryptoInfo;
}
/**
* This indicates that the requested key was not found when trying to
* perform a decrypt operation. The operation can be retried after adding
* the correct decryption key.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_NO_KEY}.
*/
public static final int ERROR_NO_KEY = MediaDrm.ErrorCodes.ERROR_NO_KEY;
/**
* This indicates that the key used for decryption is no longer
* valid due to license term expiration. The operation can be retried
* after updating the expired keys.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_KEY_EXPIRED}.
*/
public static final int ERROR_KEY_EXPIRED = MediaDrm.ErrorCodes.ERROR_KEY_EXPIRED;
/**
* This indicates that a required crypto resource was not able to be
* allocated while attempting the requested operation. The operation
* can be retried if the app is able to release resources.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_RESOURCE_BUSY}
*/
public static final int ERROR_RESOURCE_BUSY = MediaDrm.ErrorCodes.ERROR_RESOURCE_BUSY;
/**
* This indicates that the output protection levels supported by the
* device are not sufficient to meet the requirements set by the
* content owner in the license policy.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_INSUFFICIENT_OUTPUT_PROTECTION}
*/
public static final int ERROR_INSUFFICIENT_OUTPUT_PROTECTION =
MediaDrm.ErrorCodes.ERROR_INSUFFICIENT_OUTPUT_PROTECTION;
/**
* This indicates that decryption was attempted on a session that is
* not opened, which could be due to a failure to open the session,
* closing the session prematurely, or the session being reclaimed
* by the resource manager.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_SESSION_NOT_OPENED}
*/
public static final int ERROR_SESSION_NOT_OPENED =
MediaDrm.ErrorCodes.ERROR_SESSION_NOT_OPENED;
/**
* This indicates that an operation was attempted that could not be
* supported by the crypto system of the device in its current
* configuration. It may occur when the license policy requires
* device security features that aren't supported by the device,
* or due to an internal error in the crypto system that prevents
* the specified security policy from being met.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_UNSUPPORTED_OPERATION}
*/
public static final int ERROR_UNSUPPORTED_OPERATION =
MediaDrm.ErrorCodes.ERROR_UNSUPPORTED_OPERATION;
/**
* This indicates that the security level of the device is not
* sufficient to meet the requirements set by the content owner
* in the license policy.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_INSUFFICIENT_SECURITY}
*/
public static final int ERROR_INSUFFICIENT_SECURITY =
MediaDrm.ErrorCodes.ERROR_INSUFFICIENT_SECURITY;
/**
* This indicates that the video frame being decrypted exceeds
* the size of the device's protected output buffers. When
* encountering this error the app should try playing content
* of a lower resolution.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_FRAME_TOO_LARGE}
*/
public static final int ERROR_FRAME_TOO_LARGE = MediaDrm.ErrorCodes.ERROR_FRAME_TOO_LARGE;
/**
* This error indicates that session state has been
* invalidated. It can occur on devices that are not capable
* of retaining crypto session state across device
* suspend/resume. The session must be closed and a new
* session opened to resume operation.
* @deprecated Please use {@link MediaDrm.ErrorCodes#ERROR_LOST_STATE}
*/
public static final int ERROR_LOST_STATE = MediaDrm.ErrorCodes.ERROR_LOST_STATE;
/** @hide */
@IntDef({
MediaDrm.ErrorCodes.ERROR_NO_KEY,
MediaDrm.ErrorCodes.ERROR_KEY_EXPIRED,
MediaDrm.ErrorCodes.ERROR_RESOURCE_BUSY,
MediaDrm.ErrorCodes.ERROR_INSUFFICIENT_OUTPUT_PROTECTION,
MediaDrm.ErrorCodes.ERROR_SESSION_NOT_OPENED,
MediaDrm.ErrorCodes.ERROR_UNSUPPORTED_OPERATION,
MediaDrm.ErrorCodes.ERROR_INSUFFICIENT_SECURITY,
MediaDrm.ErrorCodes.ERROR_FRAME_TOO_LARGE,
MediaDrm.ErrorCodes.ERROR_LOST_STATE,
MediaDrm.ErrorCodes.ERROR_GENERIC_OEM,
MediaDrm.ErrorCodes.ERROR_GENERIC_PLUGIN,
MediaDrm.ErrorCodes.ERROR_LICENSE_PARSE,
MediaDrm.ErrorCodes.ERROR_MEDIA_FRAMEWORK,
MediaDrm.ErrorCodes.ERROR_ZERO_SUBSAMPLES
})
@Retention(RetentionPolicy.SOURCE)
public @interface CryptoErrorCode {}
/**
* Returns error code associated with this {@link CryptoException}.
*
* Please refer to {@link MediaDrm.ErrorCodes} for the general error
* handling strategy and details about each possible return value.
*
* @return an error code defined in {@link MediaDrm.ErrorCodes}.
*/
@CryptoErrorCode
public int getErrorCode() {
return mErrorCode;
}
/**
* Returns CryptoInfo associated with this {@link CryptoException}
* if any
*
* @return CryptoInfo object if any. {@link MediaCodec.CryptoException}
*/
public @Nullable CryptoInfo getCryptoInfo() {
return mCryptoInfo;
}
@Override
public int getVendorError() {
return mVendorError;
}
@Override
public int getOemError() {
return mOemError;
}
@Override
public int getErrorContext() {
return mErrorContext;
}
private final int mErrorCode, mVendorError, mOemError, mErrorContext;
private CryptoInfo mCryptoInfo;
}
/**
* After filling a range of the input buffer at the specified index
* submit it to the component. Once an input buffer is queued to
* the codec, it MUST NOT be used until it is later retrieved by
* {@link #getInputBuffer} in response to a {@link #dequeueInputBuffer}
* return value or a {@link Callback#onInputBufferAvailable}
* callback.
*
* Many decoders require the actual compressed data stream to be
* preceded by "codec specific data", i.e. setup data used to initialize
* the codec such as PPS/SPS in the case of AVC video or code tables
* in the case of vorbis audio.
* The class {@link android.media.MediaExtractor} provides codec
* specific data as part of
* the returned track format in entries named "csd-0", "csd-1" ...
*
* These buffers can be submitted directly after {@link #start} or
* {@link #flush} by specifying the flag {@link
* #BUFFER_FLAG_CODEC_CONFIG}. However, if you configure the
* codec with a {@link MediaFormat} containing these keys, they
* will be automatically submitted by MediaCodec directly after
* start. Therefore, the use of {@link
* #BUFFER_FLAG_CODEC_CONFIG} flag is discouraged and is
* recommended only for advanced users.
*
* To indicate that this is the final piece of input data (or rather that
* no more input data follows unless the decoder is subsequently flushed)
* specify the flag {@link #BUFFER_FLAG_END_OF_STREAM}.
*
* Note: Prior to {@link android.os.Build.VERSION_CODES#M},
* {@code presentationTimeUs} was not propagated to the frame timestamp of (rendered)
* Surface output buffers, and the resulting frame timestamp was undefined.
* Use {@link #releaseOutputBuffer(int, long)} to ensure a specific frame timestamp is set.
* Similarly, since frame timestamps can be used by the destination surface for rendering
* synchronization, care must be taken to normalize presentationTimeUs so as to not be
* mistaken for a system time. (See {@linkplain #releaseOutputBuffer(int, long)
* SurfaceView specifics}).
*
* @param index The index of a client-owned input buffer previously returned
* in a call to {@link #dequeueInputBuffer}.
* @param offset The byte offset into the input buffer at which the data starts.
* @param size The number of bytes of valid input data.
* @param presentationTimeUs The presentation timestamp in microseconds for this
* buffer. This is normally the media time at which this
* buffer should be presented (rendered). When using an output
* surface, this will be propagated as the {@link
* SurfaceTexture#getTimestamp timestamp} for the frame (after
* conversion to nanoseconds).
* @param flags A bitmask of flags
* {@link #BUFFER_FLAG_CODEC_CONFIG} and {@link #BUFFER_FLAG_END_OF_STREAM}.
* While not prohibited, most codecs do not use the
* {@link #BUFFER_FLAG_KEY_FRAME} flag for input buffers.
* @throws IllegalStateException if not in the Executing state.
* @throws MediaCodec.CodecException upon codec error.
* @throws CryptoException if a crypto object has been specified in
* {@link #configure}
*/
public final void queueInputBuffer(
int index,
int offset, int size, long presentationTimeUs, int flags)
throws CryptoException {
if ((flags & BUFFER_FLAG_DECODE_ONLY) != 0
&& (flags & BUFFER_FLAG_END_OF_STREAM) != 0) {
throw new InvalidBufferFlagsException(EOS_AND_DECODE_ONLY_ERROR_MESSAGE);
}
synchronized(mBufferLock) {
if (mBufferMode == BUFFER_MODE_BLOCK) {
throw new IncompatibleWithBlockModelException("queueInputBuffer() "
+ "is not compatible with CONFIGURE_FLAG_USE_BLOCK_MODEL. "
+ "Please use getQueueRequest() to queue buffers");
}
invalidateByteBufferLocked(mCachedInputBuffers, index, true /* input */);
mDequeuedInputBuffers.remove(index);
}
try {
native_queueInputBuffer(
index, offset, size, presentationTimeUs, flags);
} catch (CryptoException | IllegalStateException e) {
revalidateByteBuffer(mCachedInputBuffers, index, true /* input */);
throw e;
}
}
/**
* Submit multiple access units to the codec along with multiple
* {@link MediaCodec.BufferInfo} describing the contents of the buffer. This method
* is supported only in asynchronous mode. While this method can be used for all codecs,
* it is meant for buffer batching, which is only supported by codecs that advertise
* FEATURE_MultipleFrames. Other codecs will not output large output buffers via
* onOutputBuffersAvailable, and instead will output single-access-unit output via
* onOutputBufferAvailable.
*
* Output buffer size can be configured using the following MediaFormat keys.
* {@link MediaFormat#KEY_BUFFER_BATCH_MAX_OUTPUT_SIZE} and
* {@link MediaFormat#KEY_BUFFER_BATCH_THRESHOLD_OUTPUT_SIZE}.
* Details for each access unit present in the buffer should be described using
* {@link MediaCodec.BufferInfo}. Access units must be laid out contiguously (without any gaps)
* and in order. Multiple access units in the output if present, will be available in
* {@link Callback#onOutputBuffersAvailable} or {@link Callback#onOutputBufferAvailable}
* in case of single-access-unit output or when output does not contain any buffers,
* such as flags.
*
* All other details for populating {@link MediaCodec.BufferInfo} is the same as described in
* {@link #queueInputBuffer}.
*
* @param index The index of a client-owned input buffer previously returned
* in a call to {@link #dequeueInputBuffer}.
* @param bufferInfos ArrayDeque of {@link MediaCodec.BufferInfo} that describes the
* contents in the buffer. The ArrayDeque and the BufferInfo objects provided
* can be recycled by the caller for re-use.
* @throws IllegalStateException if not in the Executing state or not in asynchronous mode.
* @throws MediaCodec.CodecException upon codec error.
* @throws IllegalArgumentException upon if bufferInfos is empty, contains null, or if the
* access units are not contiguous.
* @throws CryptoException if a crypto object has been specified in
* {@link #configure}
*/
@FlaggedApi(FLAG_LARGE_AUDIO_FRAME)
public final void queueInputBuffers(
int index,
@NonNull ArrayDeque
* A buffer's data is considered to be partitioned into "subSamples". Each subSample starts with
* a run of plain, unencrypted bytes followed by a run of encrypted bytes. Either of these runs
* may be empty. If pattern encryption applies, each of the encrypted runs is encrypted only
* partly, according to a repeating pattern of "encrypt" and "skip" blocks.
* {@link #numBytesOfClearData} can be null to indicate that all data is encrypted, and
* {@link #numBytesOfEncryptedData} can be null to indicate that all data is clear. At least one
* of {@link #numBytesOfClearData} and {@link #numBytesOfEncryptedData} must be non-null.
*
* This information encapsulates per-sample metadata as outlined in ISO/IEC FDIS 23001-7:2016
* "Common encryption in ISO base media file format files".
*
*
*
* The returned memory region becomes inaccessible after
* {@link #recycle}, or the buffer is queued to the codecs and not
* returned to the client yet.
*
* @return mapped memory region as {@link ByteBuffer} object
* @throws IllegalStateException if not mappable or invalid
*/
public @NonNull ByteBuffer map() {
synchronized (mLock) {
if (!mValid) {
throw new IllegalStateException("The linear block is invalid");
}
if (!mMappable) {
throw new IllegalStateException("The linear block is not mappable");
}
if (mMapped == null) {
mMapped = native_map();
}
return mMapped;
}
}
private native ByteBuffer native_map();
/**
* Mark this block as ready to be recycled by the framework once it is
* no longer in use. All operations to this object after
* this call will cause exceptions, as well as attempt to access the
* previously mapped memory region. Caller should clear all references
* to this object after this call.
*
* To avoid excessive memory consumption, it is recommended that callers
* recycle buffers as soon as they no longer need the buffers
*
* @throws IllegalStateException if invalid
*/
public void recycle() {
synchronized (mLock) {
if (!mValid) {
throw new IllegalStateException("The linear block is invalid");
}
if (mMapped != null) {
mMapped.setAccessible(false);
mMapped = null;
}
native_recycle();
mValid = false;
mNativeContext = 0;
}
if (!mInternal) {
sPool.offer(this);
}
}
private native void native_recycle();
private native void native_obtain(int capacity, String[] codecNames);
@Override
protected void finalize() {
native_recycle();
}
/**
* Returns true if it is possible to allocate a linear block that can be
* passed to all listed codecs as input buffers without copying the
* content.
*
* Note that even if this function returns true, {@link #obtain} may
* still throw due to invalid arguments or allocation failure.
*
* @param codecNames list of codecs that the client wants to use a
* linear block without copying. Null entries are
* ignored.
*/
public static boolean isCodecCopyFreeCompatible(@NonNull String[] codecNames) {
return native_checkCompatible(codecNames);
}
private static native boolean native_checkCompatible(@NonNull String[] codecNames);
/**
* Obtain a linear block object no smaller than {@code capacity}.
* If {@link #isCodecCopyFreeCompatible} with the same
* {@code codecNames} returned true, the returned
* {@link LinearBlock} object can be queued to the listed codecs without
* copying. The returned {@link LinearBlock} object is always
* read/write mappable.
*
* @param capacity requested capacity of the linear block in bytes
* @param codecNames list of codecs that the client wants to use this
* linear block without copying. Null entries are
* ignored.
* @return a linear block object.
* @throws IllegalArgumentException if the capacity is invalid or
* codecNames contains invalid name
* @throws IOException if an error occurred while allocating a buffer
*/
public static @Nullable LinearBlock obtain(
int capacity, @NonNull String[] codecNames) {
LinearBlock buffer = sPool.poll();
if (buffer == null) {
buffer = new LinearBlock();
}
synchronized (buffer.mLock) {
buffer.native_obtain(capacity, codecNames);
}
return buffer;
}
// Called from native
private void setInternalStateLocked(long context, boolean isMappable) {
mNativeContext = context;
mMappable = isMappable;
mValid = (context != 0);
mInternal = true;
}
private static final BlockingQueue
* Note: buffers should have format {@link HardwareBuffer#YCBCR_420_888},
* a single layer, and an appropriate usage ({@link HardwareBuffer#USAGE_CPU_READ_OFTEN}
* for software codecs and {@link HardwareBuffer#USAGE_VIDEO_ENCODE} for hardware)
* for codecs to recognize. Format {@link ImageFormat#PRIVATE} together with
* usage {@link HardwareBuffer#USAGE_VIDEO_ENCODE} will also work for hardware codecs.
* Codecs may throw exception if the buffer is not recognizable.
*
* @param buffer The hardware graphic buffer object
* @return this object
* @throws IllegalStateException if a buffer is already set
*/
public @NonNull QueueRequest setHardwareBuffer(
@NonNull HardwareBuffer buffer) {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
if (mLinearBlock != null || mHardwareBuffer != null) {
throw new IllegalStateException("Cannot set block twice");
}
mHardwareBuffer = buffer;
return this;
}
/**
* Set timestamp to this queue request.
*
* @param presentationTimeUs The presentation timestamp in microseconds for this
* buffer. This is normally the media time at which this
* buffer should be presented (rendered). When using an output
* surface, this will be propagated as the {@link
* SurfaceTexture#getTimestamp timestamp} for the frame (after
* conversion to nanoseconds).
* @return this object
*/
public @NonNull QueueRequest setPresentationTimeUs(long presentationTimeUs) {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
mPresentationTimeUs = presentationTimeUs;
return this;
}
/**
* Set flags to this queue request.
*
* @param flags A bitmask of flags
* {@link #BUFFER_FLAG_CODEC_CONFIG} and {@link #BUFFER_FLAG_END_OF_STREAM}.
* While not prohibited, most codecs do not use the
* {@link #BUFFER_FLAG_KEY_FRAME} flag for input buffers.
* @return this object
*/
public @NonNull QueueRequest setFlags(@BufferFlag int flags) {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
mFlags = flags;
return this;
}
/**
* Add an integer parameter.
* See {@link MediaFormat} for an exhaustive list of supported keys with
* values of type int, that can also be set with {@link MediaFormat#setInteger}.
*
* If there was {@link MediaCodec#setParameters}
* call with the same key which is not processed by the codec yet, the
* value set from this method will override the unprocessed value.
*
* @return this object
*/
public @NonNull QueueRequest setIntegerParameter(
@NonNull String key, int value) {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
mTuningKeys.add(key);
mTuningValues.add(Integer.valueOf(value));
return this;
}
/**
* Add a long parameter.
* See {@link MediaFormat} for an exhaustive list of supported keys with
* values of type long, that can also be set with {@link MediaFormat#setLong}.
*
* If there was {@link MediaCodec#setParameters}
* call with the same key which is not processed by the codec yet, the
* value set from this method will override the unprocessed value.
*
* @return this object
*/
public @NonNull QueueRequest setLongParameter(
@NonNull String key, long value) {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
mTuningKeys.add(key);
mTuningValues.add(Long.valueOf(value));
return this;
}
/**
* Add a float parameter.
* See {@link MediaFormat} for an exhaustive list of supported keys with
* values of type float, that can also be set with {@link MediaFormat#setFloat}.
*
* If there was {@link MediaCodec#setParameters}
* call with the same key which is not processed by the codec yet, the
* value set from this method will override the unprocessed value.
*
* @return this object
*/
public @NonNull QueueRequest setFloatParameter(
@NonNull String key, float value) {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
mTuningKeys.add(key);
mTuningValues.add(Float.valueOf(value));
return this;
}
/**
* Add a {@link ByteBuffer} parameter.
* See {@link MediaFormat} for an exhaustive list of supported keys with
* values of byte buffer, that can also be set with {@link MediaFormat#setByteBuffer}.
*
* If there was {@link MediaCodec#setParameters}
* call with the same key which is not processed by the codec yet, the
* value set from this method will override the unprocessed value.
*
* @return this object
*/
public @NonNull QueueRequest setByteBufferParameter(
@NonNull String key, @NonNull ByteBuffer value) {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
mTuningKeys.add(key);
mTuningValues.add(value);
return this;
}
/**
* Add a string parameter.
* See {@link MediaFormat} for an exhaustive list of supported keys with
* values of type string, that can also be set with {@link MediaFormat#setString}.
*
* If there was {@link MediaCodec#setParameters}
* call with the same key which is not processed by the codec yet, the
* value set from this method will override the unprocessed value.
*
* @return this object
*/
public @NonNull QueueRequest setStringParameter(
@NonNull String key, @NonNull String value) {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
mTuningKeys.add(key);
mTuningValues.add(value);
return this;
}
/**
* Finish building a queue request and queue the buffers with tunings.
*/
public void queue() {
if (!isAccessible()) {
throw new IllegalStateException("The request is stale");
}
if (mLinearBlock == null && mHardwareBuffer == null) {
throw new IllegalStateException("No block is set");
}
setAccessible(false);
if (mBufferInfos.isEmpty()) {
BufferInfo info = new BufferInfo();
info.size = mSize;
info.offset = mOffset;
info.presentationTimeUs = mPresentationTimeUs;
info.flags = mFlags;
mBufferInfos.add(info);
}
if (mLinearBlock != null) {
mCodec.native_queueLinearBlock(
mIndex, mLinearBlock,
mCryptoInfos.isEmpty() ? null : mCryptoInfos.toArray(),
mBufferInfos.toArray(),
mTuningKeys, mTuningValues);
} else if (mHardwareBuffer != null) {
mCodec.native_queueHardwareBuffer(
mIndex, mHardwareBuffer, mPresentationTimeUs, mFlags,
mTuningKeys, mTuningValues);
}
clear();
}
@NonNull QueueRequest clear() {
mLinearBlock = null;
mOffset = 0;
mSize = 0;
mHardwareBuffer = null;
mPresentationTimeUs = 0;
mFlags = 0;
mBufferInfos.clear();
mCryptoInfos.clear();
mTuningKeys.clear();
mTuningValues.clear();
return this;
}
boolean isAccessible() {
return mAccessible;
}
@NonNull QueueRequest setAccessible(boolean accessible) {
mAccessible = accessible;
return this;
}
private final MediaCodec mCodec;
private final int mIndex;
private LinearBlock mLinearBlock = null;
private int mOffset = 0;
private int mSize = 0;
private HardwareBuffer mHardwareBuffer = null;
private long mPresentationTimeUs = 0;
private @BufferFlag int mFlags = 0;
private final ArrayDeque
*
*
* Note: It is preferred to use {@link MediaCodecList#findDecoderForFormat}
* and {@link #createByCodecName} to ensure that the resulting codec can handle a
* given format.
*
* @param type The mime type of the input data.
* @throws IOException if the codec cannot be created.
* @throws IllegalArgumentException if type is not a valid mime type.
* @throws NullPointerException if type is null.
*/
@NonNull
public static MediaCodec createDecoderByType(@NonNull String type)
throws IOException {
return new MediaCodec(type, true /* nameIsType */, false /* encoder */);
}
/**
* Instantiate the preferred encoder supporting output data of the given mime type.
*
* Note: It is preferred to use {@link MediaCodecList#findEncoderForFormat}
* and {@link #createByCodecName} to ensure that the resulting codec can handle a
* given format.
*
* @param type The desired mime type of the output data.
* @throws IOException if the codec cannot be created.
* @throws IllegalArgumentException if type is not a valid mime type.
* @throws NullPointerException if type is null.
*/
@NonNull
public static MediaCodec createEncoderByType(@NonNull String type)
throws IOException {
return new MediaCodec(type, true /* nameIsType */, true /* encoder */);
}
/**
* If you know the exact name of the component you want to instantiate
* use this method to instantiate it. Use with caution.
* Likely to be used with information obtained from {@link android.media.MediaCodecList}
* @param name The name of the codec to be instantiated.
* @throws IOException if the codec cannot be created.
* @throws IllegalArgumentException if name is not valid.
* @throws NullPointerException if name is null.
*/
@NonNull
public static MediaCodec createByCodecName(@NonNull String name)
throws IOException {
return new MediaCodec(name, false /* nameIsType */, false /* encoder */);
}
/**
* This is the same as createByCodecName, but allows for instantiating a codec on behalf of a
* client process. This is used for system apps or system services that create MediaCodecs on
* behalf of other processes and will reclaim resources as necessary from processes with lower
* priority than the client process, rather than processes with lower priority than the system
* app or system service. Likely to be used with information obtained from
* {@link android.media.MediaCodecList}.
* @param name
* @param clientPid
* @param clientUid
* @throws IOException if the codec cannot be created.
* @throws IllegalArgumentException if name is not valid.
* @throws NullPointerException if name is null.
* @throws SecurityException if the MEDIA_RESOURCE_OVERRIDE_PID permission is not granted.
*
* @hide
*/
@NonNull
@SystemApi
@RequiresPermission(Manifest.permission.MEDIA_RESOURCE_OVERRIDE_PID)
public static MediaCodec createByCodecNameForClient(@NonNull String name, int clientPid,
int clientUid) throws IOException {
return new MediaCodec(name, false /* nameIsType */, false /* encoder */, clientPid,
clientUid);
}
private MediaCodec(@NonNull String name, boolean nameIsType, boolean encoder) {
this(name, nameIsType, encoder, -1 /* pid */, -1 /* uid */);
}
private MediaCodec(@NonNull String name, boolean nameIsType, boolean encoder, int pid,
int uid) {
Looper looper;
if ((looper = Looper.myLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else if ((looper = Looper.getMainLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else {
mEventHandler = null;
}
mCallbackHandler = mEventHandler;
mOnFirstTunnelFrameReadyHandler = mEventHandler;
mOnFrameRenderedHandler = mEventHandler;
mBufferLock = new Object();
// save name used at creation
mNameAtCreation = nameIsType ? null : name;
native_setup(name, nameIsType, encoder, pid, uid);
}
private String mNameAtCreation;
@Override
protected void finalize() {
native_finalize();
mCrypto = null;
}
/**
* Returns the codec to its initial (Uninitialized) state.
*
* Call this if an {@link MediaCodec.CodecException#isRecoverable unrecoverable}
* error has occured to reset the codec to its initial state after creation.
*
* @throws CodecException if an unrecoverable error has occured and the codec
* could not be reset.
* @throws IllegalStateException if in the Released state.
*/
public final void reset() {
freeAllTrackedBuffers(); // free buffers first
native_reset();
mCrypto = null;
}
private native final void native_reset();
/**
* Free up resources used by the codec instance.
*
* Make sure you call this when you're done to free up any opened
* component instance instead of relying on the garbage collector
* to do this for you at some point in the future.
*/
public final void release() {
freeAllTrackedBuffers(); // free buffers first
native_release();
mCrypto = null;
}
private native final void native_release();
/**
* If this codec is to be used as an encoder, pass this flag.
*/
public static final int CONFIGURE_FLAG_ENCODE = 1;
/**
* If this codec is to be used with {@link LinearBlock} and/or {@link
* HardwareBuffer}, pass this flag.
*
*
*/
public static final int CONFIGURE_FLAG_USE_BLOCK_MODEL = 2;
/**
* This flag should be used on a secure decoder only. MediaCodec configured with this
* flag does decryption in a separate thread. The flag requires MediaCodec to operate
* asynchronously and will throw CryptoException if any, in the onCryptoError()
* callback. Applications should override the default implementation of
* onCryptoError() and access the associated CryptoException.
*
* CryptoException thrown will contain {@link MediaCodec.CryptoInfo}
* This can be accessed using getCryptoInfo()
*/
public static final int CONFIGURE_FLAG_USE_CRYPTO_ASYNC = 4;
/**
* Configure the codec with a detached output surface.
* ISO-CENC Schemes
* ISO/IEC FDIS 23001-7:2016 defines four possible schemes by which media may be encrypted,
* corresponding to each possible combination of an AES mode with the presence or absence of
* patterned encryption.
*
*
*
*
*
* For {@code CryptoInfo}, the scheme is selected implicitly by the combination of the
* {@link #mode} field and the value set with {@link #setPattern}. For the pattern, setting the
* pattern to all zeroes (that is, both {@code blocksToEncrypt} and {@code blocksToSkip} are
* zero) is interpreted as turning patterns off completely. A scheme that does not use patterns
* will be selected, either cenc or cbc1. Setting the pattern to any nonzero value will choose
* one of the pattern-supporting schemes, cens or cbcs. The default pattern if
* {@link #setPattern} is never called is all zeroes.
*
*
*
*
*
* AES-CTR
* AES-CBC
*
* Without Patterns
* cenc
* cbc1
*
*
*
* With Patterns
* cens
* cbcs
* HLS SAMPLE-AES Audio
* HLS SAMPLE-AES audio is encrypted in a manner compatible with the cbcs scheme, except that it
* does not use patterned encryption. However, if {@link #setPattern} is used to set the pattern
* to all zeroes, this will be interpreted as selecting the cbc1 scheme. The cbc1 scheme cannot
* successfully decrypt HLS SAMPLE-AES audio because of differences in how the IVs are handled.
* For this reason, it is recommended that a pattern of {@code 1} encrypted block and {@code 0}
* skip blocks be used with HLS SAMPLE-AES audio. This will trigger decryption to use cbcs mode
* while still decrypting every block.
*/
public final static class CryptoInfo {
/**
* The number of subSamples that make up the buffer's contents.
*/
public int numSubSamples;
/**
* The number of leading unencrypted bytes in each subSample. If null, all bytes are treated
* as encrypted and {@link #numBytesOfEncryptedData} must be specified.
*/
public int[] numBytesOfClearData;
/**
* The number of trailing encrypted bytes in each subSample. If null, all bytes are treated
* as clear and {@link #numBytesOfClearData} must be specified.
*/
public int[] numBytesOfEncryptedData;
/**
* A 16-byte key id
*/
public byte[] key;
/**
* A 16-byte initialization vector
*/
public byte[] iv;
/**
* The type of encryption that has been applied,
* see {@link #CRYPTO_MODE_UNENCRYPTED}, {@link #CRYPTO_MODE_AES_CTR}
* and {@link #CRYPTO_MODE_AES_CBC}
*/
public int mode;
/**
* Metadata describing an encryption pattern for the protected bytes in a subsample. An
* encryption pattern consists of a repeating sequence of crypto blocks comprised of a
* number of encrypted blocks followed by a number of unencrypted, or skipped, blocks.
*/
public final static class Pattern {
/**
* Number of blocks to be encrypted in the pattern. If both this and
* {@link #mSkipBlocks} are zero, pattern encryption is inoperative.
*/
private int mEncryptBlocks;
/**
* Number of blocks to be skipped (left clear) in the pattern. If both this and
* {@link #mEncryptBlocks} are zero, pattern encryption is inoperative.
*/
private int mSkipBlocks;
/**
* Construct a sample encryption pattern given the number of blocks to encrypt and skip
* in the pattern. If both parameters are zero, pattern encryption is inoperative.
*/
public Pattern(int blocksToEncrypt, int blocksToSkip) {
set(blocksToEncrypt, blocksToSkip);
}
/**
* Set the number of blocks to encrypt and skip in a sample encryption pattern. If both
* parameters are zero, pattern encryption is inoperative.
*/
public void set(int blocksToEncrypt, int blocksToSkip) {
mEncryptBlocks = blocksToEncrypt;
mSkipBlocks = blocksToSkip;
}
/**
* Return the number of blocks to skip in a sample encryption pattern.
*/
public int getSkipBlocks() {
return mSkipBlocks;
}
/**
* Return the number of blocks to encrypt in a sample encryption pattern.
*/
public int getEncryptBlocks() {
return mEncryptBlocks;
}
};
private static final Pattern ZERO_PATTERN = new Pattern(0, 0);
/**
* The pattern applicable to the protected data in each subsample.
*/
private Pattern mPattern = ZERO_PATTERN;
/**
* Set the subsample count, clear/encrypted sizes, key, IV and mode fields of
* a {@link MediaCodec.CryptoInfo} instance.
*/
public void set(
int newNumSubSamples,
@NonNull int[] newNumBytesOfClearData,
@NonNull int[] newNumBytesOfEncryptedData,
@NonNull byte[] newKey,
@NonNull byte[] newIV,
int newMode) {
numSubSamples = newNumSubSamples;
numBytesOfClearData = newNumBytesOfClearData;
numBytesOfEncryptedData = newNumBytesOfEncryptedData;
key = newKey;
iv = newIV;
mode = newMode;
mPattern = ZERO_PATTERN;
}
/**
* Returns the {@link Pattern encryption pattern}.
*/
public @NonNull Pattern getPattern() {
return new Pattern(mPattern.getEncryptBlocks(), mPattern.getSkipBlocks());
}
/**
* Set the encryption pattern on a {@link MediaCodec.CryptoInfo} instance.
* See {@link Pattern}.
*/
public void setPattern(Pattern newPattern) {
if (newPattern == null) {
newPattern = ZERO_PATTERN;
}
setPattern(newPattern.getEncryptBlocks(), newPattern.getSkipBlocks());
}
// Accessed from android_media_MediaExtractor.cpp.
private void setPattern(int blocksToEncrypt, int blocksToSkip) {
mPattern = new Pattern(blocksToEncrypt, blocksToSkip);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(numSubSamples + " subsamples, key [");
String hexdigits = "0123456789abcdef";
for (int i = 0; i < key.length; i++) {
builder.append(hexdigits.charAt((key[i] & 0xf0) >> 4));
builder.append(hexdigits.charAt(key[i] & 0x0f));
}
builder.append("], iv [");
for (int i = 0; i < iv.length; i++) {
builder.append(hexdigits.charAt((iv[i] & 0xf0) >> 4));
builder.append(hexdigits.charAt(iv[i] & 0x0f));
}
builder.append("], clear ");
builder.append(Arrays.toString(numBytesOfClearData));
builder.append(", encrypted ");
builder.append(Arrays.toString(numBytesOfEncryptedData));
builder.append(", pattern (encrypt: ");
builder.append(mPattern.mEncryptBlocks);
builder.append(", skip: ");
builder.append(mPattern.mSkipBlocks);
builder.append(")");
return builder.toString();
}
};
/**
* Similar to {@link #queueInputBuffer queueInputBuffer} but submits a buffer that is
* potentially encrypted.
* Check out further notes at {@link #queueInputBuffer queueInputBuffer}.
*
* @param index The index of a client-owned input buffer previously returned
* in a call to {@link #dequeueInputBuffer}.
* @param offset The byte offset into the input buffer at which the data starts.
* @param info Metadata required to facilitate decryption, the object can be
* reused immediately after this call returns.
* @param presentationTimeUs The presentation timestamp in microseconds for this
* buffer. This is normally the media time at which this
* buffer should be presented (rendered).
* @param flags A bitmask of flags
* {@link #BUFFER_FLAG_CODEC_CONFIG} and {@link #BUFFER_FLAG_END_OF_STREAM}.
* While not prohibited, most codecs do not use the
* {@link #BUFFER_FLAG_KEY_FRAME} flag for input buffers.
* @throws IllegalStateException if not in the Executing state.
* @throws MediaCodec.CodecException upon codec error.
* @throws CryptoException if an error occurs while attempting to decrypt the buffer.
* An error code associated with the exception helps identify the
* reason for the failure.
*/
public final void queueSecureInputBuffer(
int index,
int offset,
@NonNull CryptoInfo info,
long presentationTimeUs,
int flags) throws CryptoException {
if ((flags & BUFFER_FLAG_DECODE_ONLY) != 0
&& (flags & BUFFER_FLAG_END_OF_STREAM) != 0) {
throw new InvalidBufferFlagsException(EOS_AND_DECODE_ONLY_ERROR_MESSAGE);
}
synchronized(mBufferLock) {
if (mBufferMode == BUFFER_MODE_BLOCK) {
throw new IncompatibleWithBlockModelException("queueSecureInputBuffer() "
+ "is not compatible with CONFIGURE_FLAG_USE_BLOCK_MODEL. "
+ "Please use getQueueRequest() to queue buffers");
}
invalidateByteBufferLocked(mCachedInputBuffers, index, true /* input */);
mDequeuedInputBuffers.remove(index);
}
try {
native_queueSecureInputBuffer(
index, offset, info, presentationTimeUs, flags);
} catch (CryptoException | IllegalStateException e) {
revalidateByteBuffer(mCachedInputBuffers, index, true /* input */);
throw e;
}
}
/**
* Similar to {@link #queueInputBuffers queueInputBuffers} but submits multiple access units
* in a buffer that is potentially encrypted.
* Check out further notes at {@link #queueInputBuffers queueInputBuffers}.
*
* @param index The index of a client-owned input buffer previously returned
* in a call to {@link #dequeueInputBuffer}.
* @param bufferInfos ArrayDeque of {@link MediaCodec.BufferInfo} that describes the
* contents in the buffer. The ArrayDeque and the BufferInfo objects provided
* can be recycled by the caller for re-use.
* @param cryptoInfos ArrayDeque of {@link MediaCodec.CryptoInfo} objects to facilitate the
* decryption of the contents. The ArrayDeque and the CryptoInfo objects
* provided can be reused immediately after the call returns. These objects
* should correspond to bufferInfo objects to ensure correct decryption.
* @throws IllegalStateException if not in the Executing state or not in asynchronous mode.
* @throws MediaCodec.CodecException upon codec error.
* @throws IllegalArgumentException upon if bufferInfos is empty, contains null, or if the
* access units are not contiguous.
* @throws CryptoException if an error occurs while attempting to decrypt the buffer.
* An error code associated with the exception helps identify the
* reason for the failure.
*/
@FlaggedApi(FLAG_LARGE_AUDIO_FRAME)
public final void queueSecureInputBuffers(
int index,
@NonNull ArrayDeque