1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef A_CODEC_H_
18 #define A_CODEC_H_
19 
20 #include <stdint.h>
21 #include <android/native_window.h>
22 #include <media/hardware/MetadataBufferType.h>
23 #include <media/MediaCodecInfo.h>
24 #include <media/IOMX.h>
25 #include <media/stagefright/AHierarchicalStateMachine.h>
26 #include <media/stagefright/CodecBase.h>
27 #include <media/stagefright/FrameRenderTracker.h>
28 #include <media/stagefright/MediaDefs.h>
29 #include <media/stagefright/SkipCutBuffer.h>
30 #include <utils/NativeHandle.h>
31 #include <OMX_Audio.h>
32 #include <hardware/gralloc.h>
33 #include <nativebase/nativebase.h>
34 #include <android/hardware/graphics/common/1.2/types.h>
35 #include <android/hidl/allocator/1.0/IAllocator.h>
36 #include <android/hidl/memory/1.0/IMemory.h>
37 
38 #define TRACK_BUFFER_TIMING     0
39 
40 namespace android {
41 namespace hardware {
42 namespace media {
43 namespace omx {
44 namespace V1_0 {
45 struct IGraphicBufferSource;
46 }  // namespace V1_0
47 }  // namespace omx
48 }  // namespace media
49 }  // namespace hardware
50 
51 struct ABuffer;
52 class ACodecBufferChannel;
53 class MediaCodecBuffer;
54 class MemoryDealer;
55 struct DescribeColorFormat2Params;
56 struct DataConverter;
57 
58 using android::hardware::graphics::common::V1_2::BufferUsage;
59 typedef hidl::allocator::V1_0::IAllocator TAllocator;
60 typedef hidl::memory::V1_0::IMemory TMemory;
61 
62 struct ACodec : public AHierarchicalStateMachine, public CodecBase {
63     ACodec();
64 
65     void initiateSetup(const sp<AMessage> &msg);
66 
67     virtual std::shared_ptr<BufferChannelBase> getBufferChannel() override;
68     virtual void initiateAllocateComponent(const sp<AMessage> &msg);
69     virtual void initiateConfigureComponent(const sp<AMessage> &msg);
70     virtual void initiateCreateInputSurface();
71     virtual void initiateSetInputSurface(const sp<PersistentSurface> &surface);
72     virtual void initiateStart();
73     virtual void initiateShutdown(bool keepComponentAllocated = false);
74 
75     status_t queryCapabilities(
76             const char* owner, const char* name,
77             const char* mime, bool isEncoder,
78             MediaCodecInfo::CapabilitiesWriter* caps);
79 
80     virtual status_t setSurface(const sp<Surface> &surface);
81 
82     virtual void signalFlush();
83     virtual void signalResume();
84 
85     virtual void signalSetParameters(const sp<AMessage> &msg);
86     virtual void signalEndOfInputStream();
87     virtual void signalRequestIDRFrame();
88 
89     // AHierarchicalStateMachine implements the message handling
onMessageReceivedACodec90     virtual void onMessageReceived(const sp<AMessage> &msg) {
91         handleMessage(msg);
92     }
93 
94     // Returns 0 if configuration is not supported.  NOTE: this is treated by
95     // some OMX components as auto level, and by others as invalid level.
96     static int /* OMX_VIDEO_AVCLEVELTYPE */ getAVCLevelFor(
97             int width, int height, int rate, int bitrate,
98             OMX_VIDEO_AVCPROFILEEXTTYPE profile =
99                 (OMX_VIDEO_AVCPROFILEEXTTYPE)OMX_VIDEO_AVCProfileBaseline);
100 
101     // Quirk still supported, even though deprecated
102     enum Quirks {
103         kRequiresAllocateBufferOnInputPorts   = 1,
104         kRequiresAllocateBufferOnOutputPorts  = 2,
105     };
106 
107     static status_t getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]);
108 
109 protected:
110     virtual ~ACodec();
111 
112 private:
113     struct BaseState;
114     struct UninitializedState;
115     struct LoadedState;
116     struct LoadedToIdleState;
117     struct IdleToExecutingState;
118     struct ExecutingState;
119     struct OutputPortSettingsChangedState;
120     struct ExecutingToIdleState;
121     struct IdleToLoadedState;
122     struct FlushingState;
123     struct DeathNotifier;
124 
125     enum {
126         kWhatSetup                   = 'setu',
127         kWhatOMXMessage              = 'omx ',
128         // same as kWhatOMXMessage - but only used with
129         // handleMessage during OMX message-list handling
130         kWhatOMXMessageItem          = 'omxI',
131         kWhatOMXMessageList          = 'omxL',
132         kWhatInputBufferFilled       = 'inpF',
133         kWhatOutputBufferDrained     = 'outD',
134         kWhatShutdown                = 'shut',
135         kWhatFlush                   = 'flus',
136         kWhatResume                  = 'resm',
137         kWhatDrainDeferredMessages   = 'drai',
138         kWhatAllocateComponent       = 'allo',
139         kWhatConfigureComponent      = 'conf',
140         kWhatSetSurface              = 'setS',
141         kWhatCreateInputSurface      = 'cisf',
142         kWhatSetInputSurface         = 'sisf',
143         kWhatSignalEndOfInputStream  = 'eois',
144         kWhatStart                   = 'star',
145         kWhatRequestIDRFrame         = 'ridr',
146         kWhatSetParameters           = 'setP',
147         kWhatSubmitOutputMetadataBufferIfEOS = 'subm',
148         kWhatOMXDied                 = 'OMXd',
149         kWhatReleaseCodecInstance    = 'relC',
150         kWhatForceStateTransition    = 'fstt',
151         kWhatCheckIfStuck            = 'Cstk',
152         kWhatSubmitExtraOutputMetadataBuffer = 'sbxo',
153     };
154 
155     enum {
156         kPortIndexInput  = 0,
157         kPortIndexOutput = 1
158     };
159 
160     enum {
161         kFlagIsSecure                                 = 1,
162         kFlagPushBlankBuffersToNativeWindowOnShutdown = 2,
163         kFlagIsGrallocUsageProtected                  = 4,
164         kFlagPreregisterMetadataBuffers               = 8,
165     };
166 
167     enum {
168         kVideoGrallocUsage = (GRALLOC_USAGE_HW_TEXTURE
169                             | GRALLOC_USAGE_HW_COMPOSER
170                             | GRALLOC_USAGE_EXTERNAL_DISP)
171                             | static_cast<uint64_t>(BufferUsage::VIDEO_DECODER),
172     };
173 
174     struct BufferInfo {
175         enum Status {
176             OWNED_BY_US,
177             OWNED_BY_COMPONENT,
178             OWNED_BY_UPSTREAM,
179             OWNED_BY_DOWNSTREAM,
180             OWNED_BY_NATIVE_WINDOW,
181             UNRECOGNIZED,            // not a tracked buffer
182         };
183 
getSafeStatusACodec::BufferInfo184         static inline Status getSafeStatus(BufferInfo *info) {
185             return info == NULL ? UNRECOGNIZED : info->mStatus;
186         }
187 
188         IOMX::buffer_id mBufferID;
189         Status mStatus;
190         unsigned mDequeuedAt;
191 
192         sp<MediaCodecBuffer> mData;  // the client's buffer; if not using data conversion, this is
193                                      // the codec buffer; otherwise, it is allocated separately
194         sp<RefBase> mMemRef;         // and a reference to the IMemory, so it does not go away
195         sp<MediaCodecBuffer> mCodecData;  // the codec's buffer
196         sp<RefBase> mCodecRef;            // and a reference to the IMemory
197 
198         sp<GraphicBuffer> mGraphicBuffer;
199         bool mNewGraphicBuffer;
200         int mFenceFd;
201         FrameRenderTracker::Info *mRenderInfo;
202 
203         // The following field and 4 methods are used for debugging only
204         bool mIsReadFence;
205         // Store |fenceFd| and set read/write flag. Log error, if there is already a fence stored.
206         void setReadFence(int fenceFd, const char *dbg);
207         void setWriteFence(int fenceFd, const char *dbg);
208         // Log error, if the current fence is not a read/write fence.
209         void checkReadFence(const char *dbg);
210         void checkWriteFence(const char *dbg);
211     };
212 
213     static const char *_asString(BufferInfo::Status s);
214     void dumpBuffers(OMX_U32 portIndex);
215 
216     // If |fd| is non-negative, waits for fence with |fd| and logs an error if it fails. Returns
217     // the error code or OK on success. If |fd| is negative, it returns OK
218     status_t waitForFence(int fd, const char *dbg);
219 
220 #if TRACK_BUFFER_TIMING
221     struct BufferStats {
222         int64_t mEmptyBufferTimeUs;
223         int64_t mFillBufferDoneTimeUs;
224     };
225 
226     KeyedVector<int64_t, BufferStats> mBufferStats;
227 #endif
228 
229     sp<UninitializedState> mUninitializedState;
230     sp<LoadedState> mLoadedState;
231     sp<LoadedToIdleState> mLoadedToIdleState;
232     sp<IdleToExecutingState> mIdleToExecutingState;
233     sp<ExecutingState> mExecutingState;
234     sp<OutputPortSettingsChangedState> mOutputPortSettingsChangedState;
235     sp<ExecutingToIdleState> mExecutingToIdleState;
236     sp<IdleToLoadedState> mIdleToLoadedState;
237     sp<FlushingState> mFlushingState;
238     sp<SkipCutBuffer> mSkipCutBuffer;
239     int32_t mSampleRate;
240 
241     AString mComponentName;
242     uint32_t mFlags;
243     sp<IOMX> mOMX;
244     sp<IOMXNode> mOMXNode;
245     int32_t mNodeGeneration;
246     sp<TAllocator> mAllocator[2];
247 
248     bool mUsingNativeWindow;
249     sp<ANativeWindow> mNativeWindow;
250     int mNativeWindowUsageBits;
251     android_native_rect_t mLastNativeWindowCrop;
252     int32_t mLastNativeWindowDataSpace;
253     HDRStaticInfo mLastHDRStaticInfo;
254     sp<ABuffer> mHdr10PlusScratchBuffer;
255     sp<ABuffer> mLastHdr10PlusBuffer;
256     sp<AMessage> mConfigFormat;
257     sp<AMessage> mInputFormat;
258     sp<AMessage> mOutputFormat;
259 
260     // Initial output format + configuration params that is reused as the base for all subsequent
261     // format updates. This will equal to mOutputFormat until the first actual frame is received.
262     sp<AMessage> mBaseOutputFormat;
263 
264     FrameRenderTracker mRenderTracker; // render information for buffers rendered by ACodec
265     Vector<BufferInfo> mBuffers[2];
266     bool mPortEOS[2];
267     status_t mInputEOSResult;
268 
269     List<sp<AMessage> > mDeferredQueue;
270 
271     sp<AMessage> mLastOutputFormat;
272     bool mIsVideo;
273     bool mIsImage;
274     bool mIsEncoder;
275     bool mFatalError;
276     bool mShutdownInProgress;
277     bool mExplicitShutdown;
278     bool mIsLegacyVP9Decoder;
279     bool mIsStreamCorruptFree;
280     bool mIsLowLatency;
281 
282     // If "mKeepComponentAllocated" we only transition back to Loaded state
283     // and do not release the component instance.
284     bool mKeepComponentAllocated;
285 
286     int32_t mEncoderDelay;
287     int32_t mEncoderPadding;
288     int32_t mRotationDegrees;
289 
290     bool mChannelMaskPresent;
291     int32_t mChannelMask;
292     unsigned mDequeueCounter;
293     IOMX::PortMode mPortMode[2];
294     int32_t mMetadataBuffersToSubmit;
295     size_t mNumUndequeuedBuffers;
296     sp<DataConverter> mConverter[2];
297 
298     sp<hardware::media::omx::V1_0::IGraphicBufferSource> mGraphicBufferSource;
299     int64_t mRepeatFrameDelayUs;
300     int64_t mMaxPtsGapUs;
301     float mMaxFps;
302     double mFps;
303     double mCaptureFps;
304     bool mCreateInputBuffersSuspended;
305     std::optional<uint32_t> mLatency;
306 
307     bool mTunneled;
308 
309     OMX_INDEXTYPE mDescribeColorAspectsIndex;
310     OMX_INDEXTYPE mDescribeHDRStaticInfoIndex;
311     OMX_INDEXTYPE mDescribeHDR10PlusInfoIndex;
312 
313     std::shared_ptr<ACodecBufferChannel> mBufferChannel;
314 
315     int32_t mStateGeneration;
316 
317     enum {
318         kExtensionsUnchecked,
319         kExtensionsNone,
320         kExtensionsExist,
321     } mVendorExtensionsStatus;
322 
323     status_t setCyclicIntraMacroblockRefresh(const sp<AMessage> &msg, int32_t mode);
324     status_t allocateBuffersOnPort(OMX_U32 portIndex);
325     status_t freeBuffersOnPort(OMX_U32 portIndex);
326     status_t freeBuffer(OMX_U32 portIndex, size_t i);
327 
328     status_t handleSetSurface(const sp<Surface> &surface);
329     status_t setPortMode(int32_t portIndex, IOMX::PortMode mode);
330     status_t setupNativeWindowSizeFormatAndUsage(
331             ANativeWindow *nativeWindow /* nonnull */, int *finalUsage /* nonnull */,
332             bool reconnect);
333 
334     status_t configureOutputBuffersFromNativeWindow(
335             OMX_U32 *nBufferCount, OMX_U32 *nBufferSize,
336             OMX_U32 *nMinUndequeuedBuffers, bool preregister);
337     status_t allocateOutputMetadataBuffers();
338     status_t submitOutputMetadataBuffer();
339     void signalSubmitOutputMetadataBufferIfEOS_workaround();
340     status_t allocateOutputBuffersFromNativeWindow();
341     status_t cancelBufferToNativeWindow(BufferInfo *info);
342     status_t freeOutputBuffersNotOwnedByComponent();
343     BufferInfo *dequeueBufferFromNativeWindow();
344 
storingMetadataInDecodedBuffersACodec345     inline bool storingMetadataInDecodedBuffers() {
346         return (mPortMode[kPortIndexOutput] == IOMX::kPortModeDynamicANWBuffer) && !mIsEncoder;
347     }
348 
usingSecureBufferOnEncoderOutputACodec349     inline bool usingSecureBufferOnEncoderOutput() {
350         return (mPortMode[kPortIndexOutput] == IOMX::kPortModePresetSecureBuffer) && mIsEncoder;
351     }
352 
353     BufferInfo *findBufferByID(
354             uint32_t portIndex, IOMX::buffer_id bufferID,
355             ssize_t *index = NULL);
356 
357     status_t fillBuffer(BufferInfo *info);
358 
359     status_t setComponentRole(bool isEncoder, const char *mime);
360 
361     status_t configureCodec(const char *mime, const sp<AMessage> &msg);
362 
363     status_t configureTunneledVideoPlayback(int32_t audioHwSync,
364             const sp<ANativeWindow> &nativeWindow);
365 
366     status_t setVideoPortFormatType(
367             OMX_U32 portIndex,
368             OMX_VIDEO_CODINGTYPE compressionFormat,
369             OMX_COLOR_FORMATTYPE colorFormat,
370             bool usingNativeBuffers = false);
371 
372     status_t setSupportedOutputFormat(bool getLegacyFlexibleFormat);
373 
374     status_t setupVideoDecoder(
375             const char *mime, const sp<AMessage> &msg, bool usingNativeBuffers, bool haveSwRenderer,
376             sp<AMessage> &outputformat);
377 
378     status_t setupVideoEncoder(
379             const char *mime, const sp<AMessage> &msg,
380             sp<AMessage> &outputformat, sp<AMessage> &inputformat);
381 
382     status_t setVideoFormatOnPort(
383             OMX_U32 portIndex,
384             int32_t width, int32_t height,
385             OMX_VIDEO_CODINGTYPE compressionFormat, float frameRate = -1.0);
386 
387     // sets |portIndex| port buffer numbers to be |bufferNum|. NOTE: Component could reject
388     // this setting if the |bufferNum| is less than the minimum buffer num of the port.
389     status_t setPortBufferNum(OMX_U32 portIndex, int bufferNum);
390 
391     // gets index or sets it to 0 on error. Returns error from codec.
392     status_t initDescribeColorAspectsIndex();
393 
394     // sets |params|. If |readBack| is true, it re-gets them afterwards if set succeeded.
395     // returns the codec error.
396     status_t setCodecColorAspects(DescribeColorAspectsParams &params, bool readBack = false);
397 
398     // gets |params|; returns the codec error. |param| should not change on error.
399     status_t getCodecColorAspects(DescribeColorAspectsParams &params);
400 
401     // gets dataspace guidance from codec and platform. |params| should be set up with the color
402     // aspects to use. If |tryCodec| is true, the codec is queried first. If it succeeds, we
403     // return OK. Otherwise, we fall back to the platform guidance and return the codec error;
404     // though, we return OK if the codec failed with UNSUPPORTED, as codec guidance is optional.
405     status_t getDataSpace(
406             DescribeColorAspectsParams &params, android_dataspace *dataSpace /* nonnull */,
407             bool tryCodec);
408 
409     // sets color aspects for the encoder for certain |width/height| based on |configFormat|, and
410     // set resulting color config into |outputFormat|. If |usingNativeWindow| is true, we use
411     // video defaults if config is unspecified. Returns error from the codec.
412     status_t setColorAspectsForVideoDecoder(
413             int32_t width, int32_t height, bool usingNativeWindow,
414             const sp<AMessage> &configFormat, sp<AMessage> &outputFormat);
415 
416     // gets color aspects for the encoder for certain |width/height| based on |configFormat|, and
417     // set resulting color config into |outputFormat|. If |dataSpace| is non-null, it requests
418     // dataspace guidance from the codec and platform and sets it into |dataSpace|. Returns the
419     // error from the codec.
420     status_t getColorAspectsAndDataSpaceForVideoDecoder(
421             int32_t width, int32_t height, const sp<AMessage> &configFormat,
422             sp<AMessage> &outputFormat, android_dataspace *dataSpace);
423 
424     // sets color aspects for the video encoder assuming bytebuffer mode for certain |configFormat|
425     // and sets resulting color config into |outputFormat|. For mediarecorder, also set dataspace
426     // into |inputFormat|. Returns the error from the codec.
427     status_t setColorAspectsForVideoEncoder(
428             const sp<AMessage> &configFormat,
429             sp<AMessage> &outputFormat, sp<AMessage> &inputFormat);
430 
431     // sets color aspects for the video encoder in surface mode. This basically sets the default
432     // video values for unspecified aspects and sets the dataspace to use in the input format.
433     // Also sets the dataspace into |dataSpace|.
434     // Returns any codec errors during this configuration, except for optional steps.
435     status_t setInitialColorAspectsForVideoEncoderSurfaceAndGetDataSpace(
436             android_dataspace *dataSpace /* nonnull */);
437 
438     // gets color aspects for the video encoder input port and sets them into the |format|.
439     // Returns any codec errors.
440     status_t getInputColorAspectsForVideoEncoder(sp<AMessage> &format);
441 
442     // updates the encoder output format with |aspects| defaulting to |dataSpace| for
443     // unspecified values.
444     void onDataSpaceChanged(android_dataspace dataSpace, const ColorAspects &aspects);
445 
446     // notifies the codec that the config with |configIndex| has changed, the value
447     // can be queried by OMX getConfig, and the config should be applied to the next
448     // output buffer notified after this callback.
449     void onConfigUpdate(OMX_INDEXTYPE configIndex);
450 
451     // gets index or sets it to 0 on error. Returns error from codec.
452     status_t initDescribeHDRStaticInfoIndex();
453 
454     // sets HDR static metadata for the video encoder/decoder based on |configFormat|, and
455     // sets resulting HDRStaticInfo config into |outputFormat|. Returns error from the codec.
456     status_t setHDRStaticInfoForVideoCodec(
457             OMX_U32 portIndex, const sp<AMessage> &configFormat, sp<AMessage> &outputFormat);
458 
459     // sets |params|. Returns the codec error.
460     status_t setHDRStaticInfo(const DescribeHDRStaticInfoParams &params);
461 
462     // sets |hdr10PlusInfo|. Returns the codec error.
463     status_t setHdr10PlusInfo(const sp<ABuffer> &hdr10PlusInfo);
464 
465     // gets |params|. Returns the codec error.
466     status_t getHDRStaticInfo(DescribeHDRStaticInfoParams &params);
467 
468     // gets HDR static information for the video encoder/decoder port and sets them into |format|.
469     status_t getHDRStaticInfoForVideoCodec(OMX_U32 portIndex, sp<AMessage> &format);
470 
471     // gets DescribeHDR10PlusInfoParams params. If |paramSizeUsed| is zero, it's
472     // possible that the returned DescribeHDR10PlusInfoParams only has the
473     // nParamSizeUsed field updated, because the size of the storage is insufficient.
474     // In this case, getHDR10PlusInfo() should be called again with |paramSizeUsed|
475     // specified to the previous returned value.
476     DescribeHDR10PlusInfoParams* getHDR10PlusInfo(size_t paramSizeUsed = 0);
477 
478     typedef struct drcParams {
479         int32_t drcCut;
480         int32_t drcBoost;
481         int32_t heavyCompression;
482         int32_t targetRefLevel;
483         int32_t encodedTargetLevel;
484         int32_t effectType;
485         int32_t albumMode;
486         int32_t outputLoudness;
487     } drcParams_t;
488 
489     status_t setupAACCodec(
490             bool encoder,
491             int32_t numChannels, int32_t sampleRate, int32_t bitRate,
492             int32_t aacProfile, bool isADTS, int32_t sbrMode,
493             int32_t maxOutputChannelCount, const drcParams_t& drc,
494             int32_t pcmLimiterEnable);
495 
496     status_t setupAC3Codec(bool encoder, int32_t numChannels, int32_t sampleRate);
497 
498     status_t setupEAC3Codec(bool encoder, int32_t numChannels, int32_t sampleRate);
499 
500     status_t setupAC4Codec(bool encoder, int32_t numChannels, int32_t sampleRate);
501 
502     status_t selectAudioPortFormat(
503             OMX_U32 portIndex, OMX_AUDIO_CODINGTYPE desiredFormat);
504 
505     status_t setupAMRCodec(bool encoder, bool isWAMR, int32_t bitRate);
506     status_t setupG711Codec(bool encoder, int32_t sampleRate, int32_t numChannels);
507 
508     status_t setupOpusCodec(bool encoder, int32_t sampleRate, int32_t numChannels);
509     status_t setupFlacCodec(
510             bool encoder, int32_t numChannels, int32_t sampleRate, int32_t compressionLevel,
511             AudioEncoding encoding);
512 
513     status_t setupRawAudioFormat(
514             OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels,
515             AudioEncoding encoding = kAudioEncodingPcm16bit);
516 
517     status_t setPriority(int32_t priority);
518     status_t setLowLatency(int32_t lowLatency);
519     status_t setLatency(uint32_t latency);
520     status_t getLatency(uint32_t *latency);
521     status_t setTunnelPeek(int32_t tunnelPeek);
522     status_t setAudioPresentation(int32_t presentationId, int32_t programId);
523     status_t setOperatingRate(float rateFloat, bool isVideo);
524     status_t getIntraRefreshPeriod(uint32_t *intraRefreshPeriod);
525     status_t setIntraRefreshPeriod(uint32_t intraRefreshPeriod, bool inConfigure);
526 
527     // Configures temporal layering based on |msg|. |inConfigure| shall be true iff this is called
528     // during configure() call. on success the configured layering is set in |outputFormat|. If
529     // |outputFormat| is mOutputFormat, it is copied to trigger an output format changed event.
530     status_t configureTemporalLayers(
531             const sp<AMessage> &msg, bool inConfigure, sp<AMessage> &outputFormat);
532 
533     status_t setMinBufferSize(OMX_U32 portIndex, size_t size);
534 
535     status_t setupMPEG4EncoderParameters(const sp<AMessage> &msg);
536     status_t setupH263EncoderParameters(const sp<AMessage> &msg);
537     status_t setupAVCEncoderParameters(const sp<AMessage> &msg);
538     status_t setupHEVCEncoderParameters(const sp<AMessage> &msg, sp<AMessage> &outputFormat);
539     status_t setupVPXEncoderParameters(const sp<AMessage> &msg, sp<AMessage> &outputFormat);
540 
541     status_t verifySupportForProfileAndLevel(
542             OMX_U32 portIndex, int32_t profile, int32_t level);
543 
544     status_t configureImageGrid(const sp<AMessage> &msg, sp<AMessage> &outputFormat);
545     status_t configureBitrate(
546             OMX_VIDEO_CONTROLRATETYPE bitrateMode, int32_t bitrate, int32_t quality = 0);
547     void configureEncoderLatency(const sp<AMessage> &msg);
548 
549     status_t setupErrorCorrectionParameters();
550 
551     // Returns true iff all buffers on the given port have status
552     // OWNED_BY_US or OWNED_BY_NATIVE_WINDOW.
553     bool allYourBuffersAreBelongToUs(OMX_U32 portIndex);
554 
555     bool allYourBuffersAreBelongToUs();
556 
557     void waitUntilAllPossibleNativeWindowBuffersAreReturnedToUs();
558 
559     size_t countBuffersOwnedByComponent(OMX_U32 portIndex) const;
560     size_t countBuffersOwnedByNativeWindow() const;
561 
562     void deferMessage(const sp<AMessage> &msg);
563     void processDeferredMessages();
564 
565     void onFrameRendered(int64_t mediaTimeUs, nsecs_t systemNano);
566     // called when we have dequeued a buffer |buf| from the native window to track render info.
567     // |fenceFd| is the dequeue fence, and |info| points to the buffer info where this buffer is
568     // stored.
569     void updateRenderInfoForDequeuedBuffer(
570             ANativeWindowBuffer *buf, int fenceFd, BufferInfo *info);
571 
572     // Checks to see if any frames have rendered up until |until|, and to notify client
573     // (MediaCodec) of rendered frames up-until the frame pointed to by |until| or the first
574     // unrendered frame. These frames are removed from the render queue.
575     // If |dropIncomplete| is true, unrendered frames up-until |until| will be dropped from the
576     // queue, allowing all rendered framed up till then to be notified of.
577     // (This will effectively clear the render queue up-until (and including) |until|.)
578     // If |until| is NULL, or is not in the rendered queue, this method will check all frames.
579     void notifyOfRenderedFrames(
580             bool dropIncomplete = false, FrameRenderTracker::Info *until = NULL);
581 
582     void onFirstTunnelFrameReady();
583 
584     // Pass |expectedFormat| to print a warning if the format differs from it.
585     // Using sp<> instead of const sp<>& because expectedFormat is likely the current mOutputFormat
586     // which will get updated inside.
587     void onOutputFormatChanged(sp<const AMessage> expectedFormat = NULL);
588     void addKeyFormatChangesToRenderBufferNotification(sp<AMessage> &notify);
589     void sendFormatChange();
590 
591     status_t getPortFormat(OMX_U32 portIndex, sp<AMessage> &notify);
592 
593     void signalError(
594             OMX_ERRORTYPE error = OMX_ErrorUndefined,
595             status_t internalError = UNKNOWN_ERROR);
596 
597     status_t requestIDRFrame();
598     status_t setParameters(const sp<AMessage> &params);
599 
600     // set vendor extension parameters specified in params that are supported by the codec
601     status_t setVendorParameters(const sp<AMessage> &params);
602 
603     // get vendor extension parameters supported by the codec for a specific port and add it to
604     // |format|
605     status_t getVendorParameters(OMX_U32 portIndex, sp<AMessage> &format);
606 
607     // Send EOS on input stream.
608     void onSignalEndOfInputStream();
609 
610     // Force EXEC->IDLE->LOADED shutdown sequence if not stale.
611     void forceStateTransition(int generation);
612 
613     DISALLOW_EVIL_CONSTRUCTORS(ACodec);
614 };
615 
616 }  // namespace android
617 
618 #endif  // A_CODEC_H_
619