1 /* 2 * Copyright 2017, 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 CCODEC_BUFFER_CHANNEL_H_ 18 19 #define CCODEC_BUFFER_CHANNEL_H_ 20 21 #include <map> 22 #include <memory> 23 #include <vector> 24 25 #include <C2Buffer.h> 26 #include <C2Component.h> 27 #include <Codec2Mapper.h> 28 29 #include <codec2/hidl/client.h> 30 #include <media/stagefright/bqhelper/GraphicBufferSource.h> 31 #include <media/stagefright/codec2/1.0/InputSurface.h> 32 #include <media/stagefright/foundation/Mutexed.h> 33 #include <media/stagefright/CodecBase.h> 34 #include <media/ICrypto.h> 35 36 #include "InputSurfaceWrapper.h" 37 38 namespace android { 39 40 class CCodecCallback { 41 public: 42 virtual ~CCodecCallback() = default; 43 virtual void onError(status_t err, enum ActionCode actionCode) = 0; 44 virtual void onOutputFramesRendered(int64_t mediaTimeUs, nsecs_t renderTimeNs) = 0; 45 virtual void onWorkQueued(bool eos) = 0; 46 virtual void onOutputBuffersChanged() = 0; 47 }; 48 49 /** 50 * BufferChannelBase implementation for CCodec. 51 */ 52 class CCodecBufferChannel 53 : public BufferChannelBase, public std::enable_shared_from_this<CCodecBufferChannel> { 54 public: 55 explicit CCodecBufferChannel(const std::shared_ptr<CCodecCallback> &callback); 56 virtual ~CCodecBufferChannel(); 57 58 // BufferChannelBase interface 59 virtual status_t queueInputBuffer(const sp<MediaCodecBuffer> &buffer) override; 60 virtual status_t queueSecureInputBuffer( 61 const sp<MediaCodecBuffer> &buffer, 62 bool secure, 63 const uint8_t *key, 64 const uint8_t *iv, 65 CryptoPlugin::Mode mode, 66 CryptoPlugin::Pattern pattern, 67 const CryptoPlugin::SubSample *subSamples, 68 size_t numSubSamples, 69 AString *errorDetailMsg) override; 70 virtual status_t renderOutputBuffer( 71 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) override; 72 virtual status_t discardBuffer(const sp<MediaCodecBuffer> &buffer) override; 73 virtual void getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) override; 74 virtual void getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) override; 75 76 // Methods below are interface for CCodec to use. 77 78 /** 79 * Set the component object for buffer processing. 80 */ 81 void setComponent(const std::shared_ptr<Codec2Client::Component> &component); 82 83 /** 84 * Set output graphic surface for rendering. 85 */ 86 status_t setSurface(const sp<Surface> &surface); 87 88 /** 89 * Set GraphicBufferSource object from which the component extracts input 90 * buffers. 91 */ 92 status_t setInputSurface(const std::shared_ptr<InputSurfaceWrapper> &surface); 93 94 /** 95 * Signal EOS to input surface. 96 */ 97 status_t signalEndOfInputStream(); 98 99 /** 100 * Set parameters. 101 */ 102 status_t setParameters(std::vector<std::unique_ptr<C2Param>> ¶ms); 103 104 /** 105 * Start queueing buffers to the component. This object should never queue 106 * buffers before this call has completed. 107 */ 108 status_t start(const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat); 109 110 /** 111 * Request initial input buffers to be filled by client. 112 */ 113 status_t requestInitialInputBuffers(); 114 115 /** 116 * Stop queueing buffers to the component. This object should never queue 117 * buffers after this call, until start() is called. 118 */ 119 void stop(); 120 121 void flush(const std::list<std::unique_ptr<C2Work>> &flushedWork); 122 123 /** 124 * Notify input client about work done. 125 * 126 * @param workItems finished work item. 127 * @param outputFormat new output format if it has changed, otherwise nullptr 128 * @param initData new init data (CSD) if it has changed, otherwise nullptr 129 * @param numDiscardedInputBuffers the number of input buffers that are 130 * returned for the first time (not previously returned by 131 * onInputBufferDone()). 132 */ 133 void onWorkDone( 134 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat, 135 const C2StreamInitDataInfo::output *initData, 136 size_t numDiscardedInputBuffers); 137 138 /** 139 * Make an input buffer available for the client as it is no longer needed 140 * by the codec. 141 * 142 * @param buffer The buffer that becomes unused. 143 */ 144 void onInputBufferDone(const std::shared_ptr<C2Buffer>& buffer); 145 146 enum MetaMode { 147 MODE_NONE, 148 MODE_ANW, 149 }; 150 151 void setMetaMode(MetaMode mode); 152 153 // Internal classes 154 class Buffers; 155 class InputBuffers; 156 class OutputBuffers; 157 158 private: 159 class QueueGuard; 160 161 /** 162 * Special mutex-like object with the following properties: 163 * 164 * - At STOPPED state (initial, or after stop()) 165 * - QueueGuard object gets created at STOPPED state, and the client is 166 * supposed to return immediately. 167 * - At RUNNING state (after start()) 168 * - Each QueueGuard object 169 */ 170 class QueueSync { 171 public: 172 /** 173 * At construction the sync object is in STOPPED state. 174 */ QueueSync()175 inline QueueSync() {} 176 ~QueueSync() = default; 177 178 /** 179 * Transition to RUNNING state when stopped. No-op if already in RUNNING 180 * state. 181 */ 182 void start(); 183 184 /** 185 * At RUNNING state, wait until all QueueGuard object created during 186 * RUNNING state are destroyed, and then transition to STOPPED state. 187 * No-op if already in STOPPED state. 188 */ 189 void stop(); 190 191 private: 192 Mutex mGuardLock; 193 194 struct Counter { CounterCounter195 inline Counter() : value(-1) {} 196 int32_t value; 197 Condition cond; 198 }; 199 Mutexed<Counter> mCount; 200 201 friend class CCodecBufferChannel::QueueGuard; 202 }; 203 204 class QueueGuard { 205 public: 206 QueueGuard(QueueSync &sync); 207 ~QueueGuard(); isRunning()208 inline bool isRunning() { return mRunning; } 209 210 private: 211 QueueSync &mSync; 212 bool mRunning; 213 }; 214 215 void feedInputBufferIfAvailable(); 216 void feedInputBufferIfAvailableInternal(); 217 status_t queueInputBufferInternal(const sp<MediaCodecBuffer> &buffer); 218 bool handleWork( 219 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat, 220 const C2StreamInitDataInfo::output *initData); 221 void sendOutputBuffers(); 222 223 QueueSync mSync; 224 sp<MemoryDealer> mDealer; 225 sp<IMemory> mDecryptDestination; 226 int32_t mHeapSeqNum; 227 228 std::shared_ptr<Codec2Client::Component> mComponent; 229 std::string mComponentName; ///< component name for debugging 230 const char *mName; ///< C-string version of component name 231 std::shared_ptr<CCodecCallback> mCCodecCallback; 232 std::shared_ptr<C2BlockPool> mInputAllocator; 233 QueueSync mQueueSync; 234 std::vector<std::unique_ptr<C2Param>> mParamsToBeSet; 235 236 Mutexed<std::unique_ptr<InputBuffers>> mInputBuffers; 237 Mutexed<std::list<sp<ABuffer>>> mFlushedConfigs; 238 Mutexed<std::unique_ptr<OutputBuffers>> mOutputBuffers; 239 240 std::atomic_uint64_t mFrameIndex; 241 std::atomic_uint64_t mFirstValidFrameIndex; 242 243 sp<MemoryDealer> makeMemoryDealer(size_t heapSize); 244 245 struct OutputSurface { 246 sp<Surface> surface; 247 uint32_t generation; 248 }; 249 Mutexed<OutputSurface> mOutputSurface; 250 251 struct BlockPools { 252 C2Allocator::id_t inputAllocatorId; 253 std::shared_ptr<C2BlockPool> inputPool; 254 C2Allocator::id_t outputAllocatorId; 255 C2BlockPool::local_id_t outputPoolId; 256 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf; 257 }; 258 Mutexed<BlockPools> mBlockPools; 259 260 std::shared_ptr<InputSurfaceWrapper> mInputSurface; 261 262 MetaMode mMetaMode; 263 264 // PipelineCapacity is used in the input buffer gating logic. 265 // 266 // There are three criteria that need to be met before 267 // onInputBufferAvailable() is called: 268 // 1. The number of input buffers that have been received by 269 // CCodecBufferChannel but not returned via onWorkDone() or 270 // onInputBufferDone() does not exceed a certain limit. (Let us call this 271 // number the "input" capacity.) 272 // 2. The number of work items that have been received by 273 // CCodecBufferChannel whose outputs have not been returned from the 274 // component (by calling onWorkDone()) does not exceed a certain limit. 275 // (Let us call this the "component" capacity.) 276 // 277 // These three criteria guarantee that a new input buffer that arrives from 278 // the invocation of onInputBufferAvailable() will not 279 // 1. overload CCodecBufferChannel's input buffers; 280 // 2. overload the component; or 281 // 282 struct PipelineCapacity { 283 // The number of available input capacity. 284 std::atomic_int input; 285 // The number of available component capacity. 286 std::atomic_int component; 287 288 PipelineCapacity(); 289 // Set the values of #input and #component. 290 void initialize(int newInput, int newComponent, 291 const char* newName = "<UNKNOWN COMPONENT>", 292 const char* callerTag = nullptr); 293 294 // Return true and decrease #input and #component by one if 295 // they are all greater than zero; return false otherwise. 296 // 297 // callerTag is used for logging only. 298 // 299 // allocate() is called by CCodecBufferChannel to check whether it can 300 // receive another input buffer. If the return value is true, 301 // onInputBufferAvailable() and onOutputBufferAvailable() can be called 302 // afterwards. 303 bool allocate(const char* callerTag = nullptr); 304 305 // Increase #input and #component by one. 306 // 307 // callerTag is used for logging only. 308 // 309 // free() is called by CCodecBufferChannel after allocate() returns true 310 // but onInputBufferAvailable() cannot be called for any reasons. It 311 // essentially undoes an allocate() call. 312 void free(const char* callerTag = nullptr); 313 314 // Increase #input by @p numDiscardedInputBuffers. 315 // 316 // callerTag is used for logging only. 317 // 318 // freeInputSlots() is called by CCodecBufferChannel when onWorkDone() 319 // or onInputBufferDone() is called. @p numDiscardedInputBuffers is 320 // provided in onWorkDone(), and is 1 in onInputBufferDone(). 321 int freeInputSlots(size_t numDiscardedInputBuffers, 322 const char* callerTag = nullptr); 323 324 // Increase #component by one and return the updated value. 325 // 326 // callerTag is used for logging only. 327 // 328 // freeComponentSlot() is called by CCodecBufferChannel when 329 // onWorkDone() is called. 330 int freeComponentSlot(const char* callerTag = nullptr); 331 332 private: 333 // Component name. Used for logging. 334 const char* mName; 335 }; 336 PipelineCapacity mAvailablePipelineCapacity; 337 338 class ReorderStash { 339 public: 340 struct Entry { EntryEntry341 inline Entry() : buffer(nullptr), timestamp(0), flags(0), ordinal({0, 0, 0}) {} EntryEntry342 inline Entry( 343 const std::shared_ptr<C2Buffer> &b, 344 int64_t t, 345 int32_t f, 346 const C2WorkOrdinalStruct &o) 347 : buffer(b), timestamp(t), flags(f), ordinal(o) {} 348 std::shared_ptr<C2Buffer> buffer; 349 int64_t timestamp; 350 int32_t flags; 351 C2WorkOrdinalStruct ordinal; 352 }; 353 354 ReorderStash(); 355 356 void clear(); 357 void setDepth(uint32_t depth); 358 void setKey(C2Config::ordinal_key_t key); 359 bool pop(Entry *entry); 360 void emplace( 361 const std::shared_ptr<C2Buffer> &buffer, 362 int64_t timestamp, 363 int32_t flags, 364 const C2WorkOrdinalStruct &ordinal); 365 void defer(const Entry &entry); 366 bool hasPending() const; 367 368 private: 369 std::list<Entry> mPending; 370 std::list<Entry> mStash; 371 uint32_t mDepth; 372 C2Config::ordinal_key_t mKey; 373 374 bool less(const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2); 375 }; 376 Mutexed<ReorderStash> mReorderStash; 377 378 std::atomic_bool mInputMetEos; 379 hasCryptoOrDescrambler()380 inline bool hasCryptoOrDescrambler() { 381 return mCrypto != nullptr || mDescrambler != nullptr; 382 } 383 }; 384 385 // Conversion of a c2_status_t value to a status_t value may depend on the 386 // operation that returns the c2_status_t value. 387 enum c2_operation_t { 388 C2_OPERATION_NONE, 389 C2_OPERATION_Component_connectToOmxInputSurface, 390 C2_OPERATION_Component_createBlockPool, 391 C2_OPERATION_Component_destroyBlockPool, 392 C2_OPERATION_Component_disconnectFromInputSurface, 393 C2_OPERATION_Component_drain, 394 C2_OPERATION_Component_flush, 395 C2_OPERATION_Component_queue, 396 C2_OPERATION_Component_release, 397 C2_OPERATION_Component_reset, 398 C2_OPERATION_Component_setOutputSurface, 399 C2_OPERATION_Component_start, 400 C2_OPERATION_Component_stop, 401 C2_OPERATION_ComponentStore_copyBuffer, 402 C2_OPERATION_ComponentStore_createComponent, 403 C2_OPERATION_ComponentStore_createInputSurface, 404 C2_OPERATION_ComponentStore_createInterface, 405 C2_OPERATION_Configurable_config, 406 C2_OPERATION_Configurable_query, 407 C2_OPERATION_Configurable_querySupportedParams, 408 C2_OPERATION_Configurable_querySupportedValues, 409 C2_OPERATION_InputSurface_connectToComponent, 410 C2_OPERATION_InputSurfaceConnection_disconnect, 411 }; 412 413 status_t toStatusT(c2_status_t c2s, c2_operation_t c2op = C2_OPERATION_NONE); 414 415 } // namespace android 416 417 #endif // CCODEC_BUFFER_CHANNEL_H_ 418