blob: ff2419d03bef59f7b99132f7c25c3bcba394b6dc [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
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//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodecBufferChannel"
19#include <utils/Log.h>
20
21#include <numeric>
22
23#include <C2AllocatorGralloc.h>
24#include <C2PlatformSupport.h>
25#include <C2BlockInternal.h>
26#include <C2Config.h>
27#include <C2Debug.h>
28
29#include <android/hardware/cas/native/1.0/IDescrambler.h>
30#include <android-base/stringprintf.h>
31#include <binder/MemoryDealer.h>
32#include <gui/Surface.h>
33#include <media/openmax/OMX_Core.h>
34#include <media/stagefright/foundation/ABuffer.h>
35#include <media/stagefright/foundation/ALookup.h>
36#include <media/stagefright/foundation/AMessage.h>
37#include <media/stagefright/foundation/AUtils.h>
38#include <media/stagefright/foundation/hexdump.h>
39#include <media/stagefright/MediaCodec.h>
40#include <media/stagefright/MediaCodecConstants.h>
41#include <media/MediaCodecBuffer.h>
42#include <system/window.h>
43
44#include "CCodecBufferChannel.h"
45#include "Codec2Buffer.h"
46#include "SkipCutBuffer.h"
47
48namespace android {
49
50using android::base::StringPrintf;
51using hardware::hidl_handle;
52using hardware::hidl_string;
53using hardware::hidl_vec;
54using namespace hardware::cas::V1_0;
55using namespace hardware::cas::native::V1_0;
56
57using CasStatus = hardware::cas::V1_0::Status;
58
59/**
60 * Base class for representation of buffers at one port.
61 */
62class CCodecBufferChannel::Buffers {
63public:
64 Buffers(const char *componentName, const char *name = "Buffers")
65 : mComponentName(componentName),
66 mChannelName(std::string(componentName) + ":" + name),
67 mName(mChannelName.c_str()) {
68 }
69 virtual ~Buffers() = default;
70
71 /**
72 * Set format for MediaCodec-facing buffers.
73 */
74 void setFormat(const sp<AMessage> &format) {
75 CHECK(format != nullptr);
76 mFormat = format;
77 }
78
79 /**
80 * Return a copy of current format.
81 */
82 sp<AMessage> dupFormat() {
83 return mFormat != nullptr ? mFormat->dup() : nullptr;
84 }
85
86 /**
87 * Returns true if the buffers are operating under array mode.
88 */
89 virtual bool isArrayMode() const { return false; }
90
91 /**
92 * Fills the vector with MediaCodecBuffer's if in array mode; otherwise,
93 * no-op.
94 */
95 virtual void getArray(Vector<sp<MediaCodecBuffer>> *) const {}
96
Wonsik Kimdf5dd142019-02-06 10:15:46 -080097 /**
98 * Return number of buffers the client owns.
99 */
100 virtual size_t numClientBuffers() const = 0;
101
Pawin Vongmasa36653902018-11-15 00:10:25 -0800102protected:
103 std::string mComponentName; ///< name of component for debugging
104 std::string mChannelName; ///< name of channel for debugging
105 const char *mName; ///< C-string version of channel name
106 // Format to be used for creating MediaCodec-facing buffers.
107 sp<AMessage> mFormat;
108
109private:
110 DISALLOW_EVIL_CONSTRUCTORS(Buffers);
111};
112
113class CCodecBufferChannel::InputBuffers : public CCodecBufferChannel::Buffers {
114public:
115 InputBuffers(const char *componentName, const char *name = "Input[]")
116 : Buffers(componentName, name) { }
117 virtual ~InputBuffers() = default;
118
119 /**
120 * Set a block pool to obtain input memory blocks.
121 */
122 void setPool(const std::shared_ptr<C2BlockPool> &pool) { mPool = pool; }
123
124 /**
125 * Get a new MediaCodecBuffer for input and its corresponding index.
126 * Returns false if no new buffer can be obtained at the moment.
127 */
128 virtual bool requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) = 0;
129
130 /**
131 * Release the buffer obtained from requestNewBuffer() and get the
132 * associated C2Buffer object back. Returns true if the buffer was on file
133 * and released successfully.
134 */
135 virtual bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800136 const sp<MediaCodecBuffer> &buffer,
137 std::shared_ptr<C2Buffer> *c2buffer,
138 bool release) = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800139
140 /**
141 * Release the buffer that is no longer used by the codec process. Return
142 * true if and only if the buffer was on file and released successfully.
143 */
144 virtual bool expireComponentBuffer(
145 const std::shared_ptr<C2Buffer> &c2buffer) = 0;
146
147 /**
148 * Flush internal state. After this call, no index or buffer previously
149 * returned from requestNewBuffer() is valid.
150 */
151 virtual void flush() = 0;
152
153 /**
154 * Return array-backed version of input buffers. The returned object
155 * shall retain the internal state so that it will honor index and
156 * buffer from previous calls of requestNewBuffer().
157 */
158 virtual std::unique_ptr<InputBuffers> toArrayMode(size_t size) = 0;
159
160protected:
161 // Pool to obtain blocks for input buffers.
162 std::shared_ptr<C2BlockPool> mPool;
163
164private:
165 DISALLOW_EVIL_CONSTRUCTORS(InputBuffers);
166};
167
168class CCodecBufferChannel::OutputBuffers : public CCodecBufferChannel::Buffers {
169public:
170 OutputBuffers(const char *componentName, const char *name = "Output")
171 : Buffers(componentName, name) { }
172 virtual ~OutputBuffers() = default;
173
174 /**
175 * Register output C2Buffer from the component and obtain corresponding
176 * index and MediaCodecBuffer object. Returns false if registration
177 * fails.
178 */
179 virtual status_t registerBuffer(
180 const std::shared_ptr<C2Buffer> &buffer,
181 size_t *index,
182 sp<MediaCodecBuffer> *clientBuffer) = 0;
183
184 /**
185 * Register codec specific data as a buffer to be consistent with
186 * MediaCodec behavior.
187 */
188 virtual status_t registerCsd(
189 const C2StreamCsdInfo::output * /* csd */,
190 size_t * /* index */,
191 sp<MediaCodecBuffer> * /* clientBuffer */) = 0;
192
193 /**
194 * Release the buffer obtained from registerBuffer() and get the
195 * associated C2Buffer object back. Returns true if the buffer was on file
196 * and released successfully.
197 */
198 virtual bool releaseBuffer(
199 const sp<MediaCodecBuffer> &buffer, std::shared_ptr<C2Buffer> *c2buffer) = 0;
200
201 /**
202 * Flush internal state. After this call, no index or buffer previously
203 * returned from registerBuffer() is valid.
204 */
205 virtual void flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) = 0;
206
207 /**
208 * Return array-backed version of output buffers. The returned object
209 * shall retain the internal state so that it will honor index and
210 * buffer from previous calls of registerBuffer().
211 */
212 virtual std::unique_ptr<OutputBuffers> toArrayMode(size_t size) = 0;
213
214 /**
215 * Initialize SkipCutBuffer object.
216 */
217 void initSkipCutBuffer(
218 int32_t delay, int32_t padding, int32_t sampleRate, int32_t channelCount) {
219 CHECK(mSkipCutBuffer == nullptr);
220 mDelay = delay;
221 mPadding = padding;
222 mSampleRate = sampleRate;
223 setSkipCutBuffer(delay, padding, channelCount);
224 }
225
226 /**
227 * Update the SkipCutBuffer object. No-op if it's never initialized.
228 */
229 void updateSkipCutBuffer(int32_t sampleRate, int32_t channelCount) {
230 if (mSkipCutBuffer == nullptr) {
231 return;
232 }
233 int32_t delay = mDelay;
234 int32_t padding = mPadding;
235 if (sampleRate != mSampleRate) {
236 delay = ((int64_t)delay * sampleRate) / mSampleRate;
237 padding = ((int64_t)padding * sampleRate) / mSampleRate;
238 }
239 setSkipCutBuffer(delay, padding, channelCount);
240 }
241
242 /**
243 * Submit buffer to SkipCutBuffer object, if initialized.
244 */
245 void submit(const sp<MediaCodecBuffer> &buffer) {
246 if (mSkipCutBuffer != nullptr) {
247 mSkipCutBuffer->submit(buffer);
248 }
249 }
250
251 /**
252 * Transfer SkipCutBuffer object to the other Buffers object.
253 */
254 void transferSkipCutBuffer(const sp<SkipCutBuffer> &scb) {
255 mSkipCutBuffer = scb;
256 }
257
Wonsik Kimc48ddcf2019-02-11 16:16:57 -0800258 void handleImageData(const sp<Codec2Buffer> &buffer) {
259 sp<ABuffer> imageDataCandidate = buffer->getImageData();
260 if (imageDataCandidate == nullptr) {
261 return;
262 }
263 sp<ABuffer> imageData;
264 if (!mFormat->findBuffer("image-data", &imageData)
265 || imageDataCandidate->size() != imageData->size()
266 || memcmp(imageDataCandidate->data(), imageData->data(), imageData->size()) != 0) {
267 ALOGD("[%s] updating image-data", mName);
268 sp<AMessage> newFormat = dupFormat();
269 newFormat->setBuffer("image-data", imageDataCandidate);
270 MediaImage2 *img = (MediaImage2*)imageDataCandidate->data();
271 if (img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
272 int32_t stride = img->mPlane[0].mRowInc;
273 newFormat->setInt32(KEY_STRIDE, stride);
274 ALOGD("[%s] updating stride = %d", mName, stride);
275 if (img->mNumPlanes > 1 && stride > 0) {
276 int32_t vstride = (img->mPlane[1].mOffset - img->mPlane[0].mOffset) / stride;
277 newFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
278 ALOGD("[%s] updating vstride = %d", mName, vstride);
279 }
280 }
281 setFormat(newFormat);
282 buffer->setFormat(newFormat);
283 }
284 }
285
Pawin Vongmasa36653902018-11-15 00:10:25 -0800286protected:
287 sp<SkipCutBuffer> mSkipCutBuffer;
288
289private:
290 int32_t mDelay;
291 int32_t mPadding;
292 int32_t mSampleRate;
293
294 void setSkipCutBuffer(int32_t skip, int32_t cut, int32_t channelCount) {
295 if (mSkipCutBuffer != nullptr) {
296 size_t prevSize = mSkipCutBuffer->size();
297 if (prevSize != 0u) {
298 ALOGD("[%s] Replacing SkipCutBuffer holding %zu bytes", mName, prevSize);
299 }
300 }
301 mSkipCutBuffer = new SkipCutBuffer(skip, cut, channelCount);
302 }
303
304 DISALLOW_EVIL_CONSTRUCTORS(OutputBuffers);
305};
306
307namespace {
308
Wonsik Kim078b58e2019-01-09 15:08:06 -0800309const static size_t kSmoothnessFactor = 4;
310const static size_t kRenderingDepth = 3;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800311const static size_t kLinearBufferSize = 1048576;
312// This can fit 4K RGBA frame, and most likely client won't need more than this.
313const static size_t kMaxLinearBufferSize = 3840 * 2160 * 4;
314
315/**
316 * Simple local buffer pool backed by std::vector.
317 */
318class LocalBufferPool : public std::enable_shared_from_this<LocalBufferPool> {
319public:
320 /**
321 * Create a new LocalBufferPool object.
322 *
323 * \param poolCapacity max total size of buffers managed by this pool.
324 *
325 * \return a newly created pool object.
326 */
327 static std::shared_ptr<LocalBufferPool> Create(size_t poolCapacity) {
328 return std::shared_ptr<LocalBufferPool>(new LocalBufferPool(poolCapacity));
329 }
330
331 /**
332 * Return an ABuffer object whose size is at least |capacity|.
333 *
334 * \param capacity requested capacity
335 * \return nullptr if the pool capacity is reached
336 * an ABuffer object otherwise.
337 */
338 sp<ABuffer> newBuffer(size_t capacity) {
339 Mutex::Autolock lock(mMutex);
340 auto it = std::find_if(
341 mPool.begin(), mPool.end(),
342 [capacity](const std::vector<uint8_t> &vec) {
343 return vec.capacity() >= capacity;
344 });
345 if (it != mPool.end()) {
346 sp<ABuffer> buffer = new VectorBuffer(std::move(*it), shared_from_this());
347 mPool.erase(it);
348 return buffer;
349 }
350 if (mUsedSize + capacity > mPoolCapacity) {
351 while (!mPool.empty()) {
352 mUsedSize -= mPool.back().capacity();
353 mPool.pop_back();
354 }
355 if (mUsedSize + capacity > mPoolCapacity) {
356 ALOGD("mUsedSize = %zu, capacity = %zu, mPoolCapacity = %zu",
357 mUsedSize, capacity, mPoolCapacity);
358 return nullptr;
359 }
360 }
361 std::vector<uint8_t> vec(capacity);
362 mUsedSize += vec.capacity();
363 return new VectorBuffer(std::move(vec), shared_from_this());
364 }
365
366private:
367 /**
368 * ABuffer backed by std::vector.
369 */
370 class VectorBuffer : public ::android::ABuffer {
371 public:
372 /**
373 * Construct a VectorBuffer by taking the ownership of supplied vector.
374 *
375 * \param vec backing vector of the buffer. this object takes
376 * ownership at construction.
377 * \param pool a LocalBufferPool object to return the vector at
378 * destruction.
379 */
380 VectorBuffer(std::vector<uint8_t> &&vec, const std::shared_ptr<LocalBufferPool> &pool)
381 : ABuffer(vec.data(), vec.capacity()),
382 mVec(std::move(vec)),
383 mPool(pool) {
384 }
385
386 ~VectorBuffer() override {
387 std::shared_ptr<LocalBufferPool> pool = mPool.lock();
388 if (pool) {
389 // If pool is alive, return the vector back to the pool so that
390 // it can be recycled.
391 pool->returnVector(std::move(mVec));
392 }
393 }
394
395 private:
396 std::vector<uint8_t> mVec;
397 std::weak_ptr<LocalBufferPool> mPool;
398 };
399
400 Mutex mMutex;
401 size_t mPoolCapacity;
402 size_t mUsedSize;
403 std::list<std::vector<uint8_t>> mPool;
404
405 /**
406 * Private constructor to prevent constructing non-managed LocalBufferPool.
407 */
408 explicit LocalBufferPool(size_t poolCapacity)
409 : mPoolCapacity(poolCapacity), mUsedSize(0) {
410 }
411
412 /**
413 * Take back the ownership of vec from the destructed VectorBuffer and put
414 * it in front of the pool.
415 */
416 void returnVector(std::vector<uint8_t> &&vec) {
417 Mutex::Autolock lock(mMutex);
418 mPool.push_front(std::move(vec));
419 }
420
421 DISALLOW_EVIL_CONSTRUCTORS(LocalBufferPool);
422};
423
424sp<GraphicBlockBuffer> AllocateGraphicBuffer(
425 const std::shared_ptr<C2BlockPool> &pool,
426 const sp<AMessage> &format,
427 uint32_t pixelFormat,
428 const C2MemoryUsage &usage,
429 const std::shared_ptr<LocalBufferPool> &localBufferPool) {
430 int32_t width, height;
431 if (!format->findInt32("width", &width) || !format->findInt32("height", &height)) {
432 ALOGD("format lacks width or height");
433 return nullptr;
434 }
435
436 std::shared_ptr<C2GraphicBlock> block;
437 c2_status_t err = pool->fetchGraphicBlock(
438 width, height, pixelFormat, usage, &block);
439 if (err != C2_OK) {
440 ALOGD("fetch graphic block failed: %d", err);
441 return nullptr;
442 }
443
444 return GraphicBlockBuffer::Allocate(
445 format,
446 block,
447 [localBufferPool](size_t capacity) {
448 return localBufferPool->newBuffer(capacity);
449 });
450}
451
452class BuffersArrayImpl;
453
454/**
455 * Flexible buffer slots implementation.
456 */
457class FlexBuffersImpl {
458public:
459 FlexBuffersImpl(const char *name)
460 : mImplName(std::string(name) + ".Impl"),
461 mName(mImplName.c_str()) { }
462
463 /**
464 * Assign an empty slot for a buffer and return the index. If there's no
465 * empty slot, just add one at the end and return it.
466 *
467 * \param buffer[in] a new buffer to assign a slot.
468 * \return index of the assigned slot.
469 */
470 size_t assignSlot(const sp<Codec2Buffer> &buffer) {
471 for (size_t i = 0; i < mBuffers.size(); ++i) {
472 if (mBuffers[i].clientBuffer == nullptr
473 && mBuffers[i].compBuffer.expired()) {
474 mBuffers[i].clientBuffer = buffer;
475 return i;
476 }
477 }
478 mBuffers.push_back({ buffer, std::weak_ptr<C2Buffer>() });
479 return mBuffers.size() - 1;
480 }
481
482 /**
483 * Release the slot from the client, and get the C2Buffer object back from
484 * the previously assigned buffer. Note that the slot is not completely free
485 * until the returned C2Buffer object is freed.
486 *
487 * \param buffer[in] the buffer previously assigned a slot.
488 * \param c2buffer[in,out] pointer to C2Buffer to be populated. Ignored
489 * if null.
490 * \return true if the buffer is successfully released from a slot
491 * false otherwise
492 */
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800493 bool releaseSlot(
494 const sp<MediaCodecBuffer> &buffer,
495 std::shared_ptr<C2Buffer> *c2buffer,
496 bool release) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800497 sp<Codec2Buffer> clientBuffer;
498 size_t index = mBuffers.size();
499 for (size_t i = 0; i < mBuffers.size(); ++i) {
500 if (mBuffers[i].clientBuffer == buffer) {
501 clientBuffer = mBuffers[i].clientBuffer;
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800502 if (release) {
503 mBuffers[i].clientBuffer.clear();
504 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800505 index = i;
506 break;
507 }
508 }
509 if (clientBuffer == nullptr) {
510 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
511 return false;
512 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800513 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
514 if (!result) {
515 result = clientBuffer->asC2Buffer();
516 mBuffers[index].compBuffer = result;
517 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800518 if (c2buffer) {
519 *c2buffer = result;
520 }
521 return true;
522 }
523
524 bool expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
525 for (size_t i = 0; i < mBuffers.size(); ++i) {
526 std::shared_ptr<C2Buffer> compBuffer =
527 mBuffers[i].compBuffer.lock();
528 if (!compBuffer || compBuffer != c2buffer) {
529 continue;
530 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800531 mBuffers[i].compBuffer.reset();
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800532 ALOGV("[%s] codec released buffer #%zu", mName, i);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800533 return true;
534 }
535 ALOGV("[%s] codec released an unknown buffer", mName);
536 return false;
537 }
538
539 void flush() {
540 ALOGV("[%s] buffers are flushed %zu", mName, mBuffers.size());
541 mBuffers.clear();
542 }
543
Wonsik Kimab34ed62019-01-31 15:28:46 -0800544 size_t numClientBuffers() const {
545 return std::count_if(
546 mBuffers.begin(), mBuffers.end(),
547 [](const Entry &entry) {
548 return (entry.clientBuffer != nullptr);
549 });
550 }
551
Pawin Vongmasa36653902018-11-15 00:10:25 -0800552private:
553 friend class BuffersArrayImpl;
554
555 std::string mImplName; ///< name for debugging
556 const char *mName; ///< C-string version of name
557
558 struct Entry {
559 sp<Codec2Buffer> clientBuffer;
560 std::weak_ptr<C2Buffer> compBuffer;
561 };
562 std::vector<Entry> mBuffers;
563};
564
565/**
566 * Static buffer slots implementation based on a fixed-size array.
567 */
568class BuffersArrayImpl {
569public:
570 BuffersArrayImpl()
571 : mImplName("BuffersArrayImpl"),
572 mName(mImplName.c_str()) { }
573
574 /**
575 * Initialize buffer array from the original |impl|. The buffers known by
576 * the client is preserved, and the empty slots are populated so that the
577 * array size is at least |minSize|.
578 *
579 * \param impl[in] FlexBuffersImpl object used so far.
580 * \param minSize[in] minimum size of the buffer array.
581 * \param allocate[in] function to allocate a client buffer for an empty slot.
582 */
583 void initialize(
584 const FlexBuffersImpl &impl,
585 size_t minSize,
586 std::function<sp<Codec2Buffer>()> allocate) {
587 mImplName = impl.mImplName + "[N]";
588 mName = mImplName.c_str();
589 for (size_t i = 0; i < impl.mBuffers.size(); ++i) {
590 sp<Codec2Buffer> clientBuffer = impl.mBuffers[i].clientBuffer;
591 bool ownedByClient = (clientBuffer != nullptr);
592 if (!ownedByClient) {
593 clientBuffer = allocate();
594 }
595 mBuffers.push_back({ clientBuffer, impl.mBuffers[i].compBuffer, ownedByClient });
596 }
597 ALOGV("[%s] converted %zu buffers to array mode of %zu", mName, mBuffers.size(), minSize);
598 for (size_t i = impl.mBuffers.size(); i < minSize; ++i) {
599 mBuffers.push_back({ allocate(), std::weak_ptr<C2Buffer>(), false });
600 }
601 }
602
603 /**
604 * Grab a buffer from the underlying array which matches the criteria.
605 *
606 * \param index[out] index of the slot.
607 * \param buffer[out] the matching buffer.
608 * \param match[in] a function to test whether the buffer matches the
609 * criteria or not.
610 * \return OK if successful,
611 * WOULD_BLOCK if slots are being used,
612 * NO_MEMORY if no slot matches the criteria, even though it's
613 * available
614 */
615 status_t grabBuffer(
616 size_t *index,
617 sp<Codec2Buffer> *buffer,
618 std::function<bool(const sp<Codec2Buffer> &)> match =
619 [](const sp<Codec2Buffer> &) { return true; }) {
620 // allBuffersDontMatch remains true if all buffers are available but
621 // match() returns false for every buffer.
622 bool allBuffersDontMatch = true;
623 for (size_t i = 0; i < mBuffers.size(); ++i) {
624 if (!mBuffers[i].ownedByClient && mBuffers[i].compBuffer.expired()) {
625 if (match(mBuffers[i].clientBuffer)) {
626 mBuffers[i].ownedByClient = true;
627 *buffer = mBuffers[i].clientBuffer;
628 (*buffer)->meta()->clear();
629 (*buffer)->setRange(0, (*buffer)->capacity());
630 *index = i;
631 return OK;
632 }
633 } else {
634 allBuffersDontMatch = false;
635 }
636 }
637 return allBuffersDontMatch ? NO_MEMORY : WOULD_BLOCK;
638 }
639
640 /**
641 * Return the buffer from the client, and get the C2Buffer object back from
642 * the buffer. Note that the slot is not completely free until the returned
643 * C2Buffer object is freed.
644 *
645 * \param buffer[in] the buffer previously grabbed.
646 * \param c2buffer[in,out] pointer to C2Buffer to be populated. Ignored
647 * if null.
648 * \return true if the buffer is successfully returned
649 * false otherwise
650 */
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800651 bool returnBuffer(
652 const sp<MediaCodecBuffer> &buffer,
653 std::shared_ptr<C2Buffer> *c2buffer,
654 bool release) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800655 sp<Codec2Buffer> clientBuffer;
656 size_t index = mBuffers.size();
657 for (size_t i = 0; i < mBuffers.size(); ++i) {
658 if (mBuffers[i].clientBuffer == buffer) {
659 if (!mBuffers[i].ownedByClient) {
660 ALOGD("[%s] Client returned a buffer it does not own according to our record: %zu", mName, i);
661 }
662 clientBuffer = mBuffers[i].clientBuffer;
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800663 if (release) {
664 mBuffers[i].ownedByClient = false;
665 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800666 index = i;
667 break;
668 }
669 }
670 if (clientBuffer == nullptr) {
671 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
672 return false;
673 }
674 ALOGV("[%s] %s: matching buffer found (index=%zu)", mName, __func__, index);
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800675 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
676 if (!result) {
677 result = clientBuffer->asC2Buffer();
678 mBuffers[index].compBuffer = result;
679 }
Pawin Vongmasa36653902018-11-15 00:10:25 -0800680 if (c2buffer) {
681 *c2buffer = result;
682 }
683 return true;
684 }
685
686 bool expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
687 for (size_t i = 0; i < mBuffers.size(); ++i) {
688 std::shared_ptr<C2Buffer> compBuffer =
689 mBuffers[i].compBuffer.lock();
690 if (!compBuffer) {
691 continue;
692 }
693 if (c2buffer == compBuffer) {
694 if (mBuffers[i].ownedByClient) {
695 // This should not happen.
696 ALOGD("[%s] codec released a buffer owned by client "
697 "(index %zu)", mName, i);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800698 }
699 mBuffers[i].compBuffer.reset();
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800700 ALOGV("[%s] codec released buffer #%zu(array mode)", mName, i);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800701 return true;
702 }
703 }
704 ALOGV("[%s] codec released an unknown buffer (array mode)", mName);
705 return false;
706 }
707
708 /**
709 * Populate |array| with the underlying buffer array.
710 *
711 * \param array[out] an array to be filled with the underlying buffer array.
712 */
713 void getArray(Vector<sp<MediaCodecBuffer>> *array) const {
714 array->clear();
715 for (const Entry &entry : mBuffers) {
716 array->push(entry.clientBuffer);
717 }
718 }
719
720 /**
721 * The client abandoned all known buffers, so reclaim the ownership.
722 */
723 void flush() {
724 for (Entry &entry : mBuffers) {
725 entry.ownedByClient = false;
726 }
727 }
728
729 void realloc(std::function<sp<Codec2Buffer>()> alloc) {
730 size_t size = mBuffers.size();
731 mBuffers.clear();
732 for (size_t i = 0; i < size; ++i) {
733 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
734 }
735 }
736
Wonsik Kimab34ed62019-01-31 15:28:46 -0800737 size_t numClientBuffers() const {
738 return std::count_if(
739 mBuffers.begin(), mBuffers.end(),
740 [](const Entry &entry) {
741 return entry.ownedByClient;
742 });
743 }
744
Pawin Vongmasa36653902018-11-15 00:10:25 -0800745private:
746 std::string mImplName; ///< name for debugging
747 const char *mName; ///< C-string version of name
748
749 struct Entry {
750 const sp<Codec2Buffer> clientBuffer;
751 std::weak_ptr<C2Buffer> compBuffer;
752 bool ownedByClient;
753 };
754 std::vector<Entry> mBuffers;
755};
756
757class InputBuffersArray : public CCodecBufferChannel::InputBuffers {
758public:
759 InputBuffersArray(const char *componentName, const char *name = "Input[N]")
760 : InputBuffers(componentName, name) { }
761 ~InputBuffersArray() override = default;
762
763 void initialize(
764 const FlexBuffersImpl &impl,
765 size_t minSize,
766 std::function<sp<Codec2Buffer>()> allocate) {
767 mImpl.initialize(impl, minSize, allocate);
768 }
769
770 bool isArrayMode() const final { return true; }
771
772 std::unique_ptr<CCodecBufferChannel::InputBuffers> toArrayMode(
773 size_t) final {
774 return nullptr;
775 }
776
777 void getArray(Vector<sp<MediaCodecBuffer>> *array) const final {
778 mImpl.getArray(array);
779 }
780
781 bool requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) override {
782 sp<Codec2Buffer> c2Buffer;
783 status_t err = mImpl.grabBuffer(index, &c2Buffer);
784 if (err == OK) {
785 c2Buffer->setFormat(mFormat);
786 *buffer = c2Buffer;
787 return true;
788 }
789 return false;
790 }
791
792 bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800793 const sp<MediaCodecBuffer> &buffer,
794 std::shared_ptr<C2Buffer> *c2buffer,
795 bool release) override {
796 return mImpl.returnBuffer(buffer, c2buffer, release);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800797 }
798
799 bool expireComponentBuffer(
800 const std::shared_ptr<C2Buffer> &c2buffer) override {
801 return mImpl.expireComponentBuffer(c2buffer);
802 }
803
804 void flush() override {
805 mImpl.flush();
806 }
807
Wonsik Kimab34ed62019-01-31 15:28:46 -0800808 size_t numClientBuffers() const final {
809 return mImpl.numClientBuffers();
810 }
811
Pawin Vongmasa36653902018-11-15 00:10:25 -0800812private:
813 BuffersArrayImpl mImpl;
814};
815
816class LinearInputBuffers : public CCodecBufferChannel::InputBuffers {
817public:
818 LinearInputBuffers(const char *componentName, const char *name = "1D-Input")
819 : InputBuffers(componentName, name),
820 mImpl(mName) { }
821
822 bool requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) override {
823 int32_t capacity = kLinearBufferSize;
824 (void)mFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
825 if ((size_t)capacity > kMaxLinearBufferSize) {
826 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
827 capacity = kMaxLinearBufferSize;
828 }
829 // TODO: proper max input size
830 // TODO: read usage from intf
831 sp<Codec2Buffer> newBuffer = alloc((size_t)capacity);
832 if (newBuffer == nullptr) {
833 return false;
834 }
835 *index = mImpl.assignSlot(newBuffer);
836 *buffer = newBuffer;
837 return true;
838 }
839
840 bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800841 const sp<MediaCodecBuffer> &buffer,
842 std::shared_ptr<C2Buffer> *c2buffer,
843 bool release) override {
844 return mImpl.releaseSlot(buffer, c2buffer, release);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800845 }
846
847 bool expireComponentBuffer(
848 const std::shared_ptr<C2Buffer> &c2buffer) override {
849 return mImpl.expireComponentBuffer(c2buffer);
850 }
851
852 void flush() override {
853 // This is no-op by default unless we're in array mode where we need to keep
854 // track of the flushed work.
855 mImpl.flush();
856 }
857
858 std::unique_ptr<CCodecBufferChannel::InputBuffers> toArrayMode(
859 size_t size) final {
860 int32_t capacity = kLinearBufferSize;
Pawin Vongmasa8be93112018-12-11 14:01:42 -0800861 (void)mFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
862 if ((size_t)capacity > kMaxLinearBufferSize) {
863 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
864 capacity = kMaxLinearBufferSize;
865 }
866 // TODO: proper max input size
867 // TODO: read usage from intf
Pawin Vongmasa36653902018-11-15 00:10:25 -0800868 std::unique_ptr<InputBuffersArray> array(
869 new InputBuffersArray(mComponentName.c_str(), "1D-Input[N]"));
870 array->setPool(mPool);
871 array->setFormat(mFormat);
872 array->initialize(
873 mImpl,
874 size,
875 [this, capacity] () -> sp<Codec2Buffer> { return alloc(capacity); });
876 return std::move(array);
877 }
878
Wonsik Kimab34ed62019-01-31 15:28:46 -0800879 size_t numClientBuffers() const final {
880 return mImpl.numClientBuffers();
881 }
882
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800883 virtual sp<Codec2Buffer> alloc(size_t size) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800884 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
885 std::shared_ptr<C2LinearBlock> block;
886
887 c2_status_t err = mPool->fetchLinearBlock(size, usage, &block);
888 if (err != C2_OK) {
889 return nullptr;
890 }
891
892 return LinearBlockBuffer::Allocate(mFormat, block);
893 }
894
895private:
896 FlexBuffersImpl mImpl;
897};
898
899class EncryptedLinearInputBuffers : public LinearInputBuffers {
900public:
901 EncryptedLinearInputBuffers(
902 bool secure,
903 const sp<MemoryDealer> &dealer,
904 const sp<ICrypto> &crypto,
905 int32_t heapSeqNum,
906 size_t capacity,
Wonsik Kim078b58e2019-01-09 15:08:06 -0800907 size_t numInputSlots,
Pawin Vongmasa36653902018-11-15 00:10:25 -0800908 const char *componentName, const char *name = "EncryptedInput")
909 : LinearInputBuffers(componentName, name),
910 mUsage({0, 0}),
911 mDealer(dealer),
912 mCrypto(crypto),
913 mHeapSeqNum(heapSeqNum) {
914 if (secure) {
915 mUsage = { C2MemoryUsage::READ_PROTECTED, 0 };
916 } else {
917 mUsage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
918 }
Wonsik Kim078b58e2019-01-09 15:08:06 -0800919 for (size_t i = 0; i < numInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800920 sp<IMemory> memory = mDealer->allocate(capacity);
921 if (memory == nullptr) {
922 ALOGD("[%s] Failed to allocate memory from dealer: only %zu slots allocated", mName, i);
923 break;
924 }
925 mMemoryVector.push_back({std::weak_ptr<C2LinearBlock>(), memory});
926 }
927 }
928
929 ~EncryptedLinearInputBuffers() override {
930 }
931
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800932 sp<Codec2Buffer> alloc(size_t size) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800933 sp<IMemory> memory;
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800934 size_t slot = 0;
935 for (; slot < mMemoryVector.size(); ++slot) {
936 if (mMemoryVector[slot].block.expired()) {
937 memory = mMemoryVector[slot].memory;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800938 break;
939 }
940 }
941 if (memory == nullptr) {
942 return nullptr;
943 }
944
945 std::shared_ptr<C2LinearBlock> block;
946 c2_status_t err = mPool->fetchLinearBlock(size, mUsage, &block);
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800947 if (err != C2_OK || block == nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -0800948 return nullptr;
949 }
950
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800951 mMemoryVector[slot].block = block;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800952 return new EncryptedLinearBlockBuffer(mFormat, block, memory, mHeapSeqNum);
953 }
954
955private:
956 C2MemoryUsage mUsage;
957 sp<MemoryDealer> mDealer;
958 sp<ICrypto> mCrypto;
959 int32_t mHeapSeqNum;
960 struct Entry {
961 std::weak_ptr<C2LinearBlock> block;
962 sp<IMemory> memory;
963 };
964 std::vector<Entry> mMemoryVector;
965};
966
967class GraphicMetadataInputBuffers : public CCodecBufferChannel::InputBuffers {
968public:
969 GraphicMetadataInputBuffers(const char *componentName, const char *name = "2D-MetaInput")
970 : InputBuffers(componentName, name),
971 mImpl(mName),
972 mStore(GetCodec2PlatformAllocatorStore()) { }
973 ~GraphicMetadataInputBuffers() override = default;
974
975 bool requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) override {
976 std::shared_ptr<C2Allocator> alloc;
977 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
978 if (err != C2_OK) {
979 return false;
980 }
981 sp<GraphicMetadataBuffer> newBuffer = new GraphicMetadataBuffer(mFormat, alloc);
982 if (newBuffer == nullptr) {
983 return false;
984 }
985 *index = mImpl.assignSlot(newBuffer);
986 *buffer = newBuffer;
987 return true;
988 }
989
990 bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800991 const sp<MediaCodecBuffer> &buffer,
992 std::shared_ptr<C2Buffer> *c2buffer,
993 bool release) override {
994 return mImpl.releaseSlot(buffer, c2buffer, release);
Pawin Vongmasa36653902018-11-15 00:10:25 -0800995 }
996
997 bool expireComponentBuffer(
998 const std::shared_ptr<C2Buffer> &c2buffer) override {
999 return mImpl.expireComponentBuffer(c2buffer);
1000 }
1001
1002 void flush() override {
1003 // This is no-op by default unless we're in array mode where we need to keep
1004 // track of the flushed work.
1005 }
1006
1007 std::unique_ptr<CCodecBufferChannel::InputBuffers> toArrayMode(
1008 size_t size) final {
1009 std::shared_ptr<C2Allocator> alloc;
1010 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
1011 if (err != C2_OK) {
1012 return nullptr;
1013 }
1014 std::unique_ptr<InputBuffersArray> array(
1015 new InputBuffersArray(mComponentName.c_str(), "2D-MetaInput[N]"));
1016 array->setPool(mPool);
1017 array->setFormat(mFormat);
1018 array->initialize(
1019 mImpl,
1020 size,
1021 [format = mFormat, alloc]() -> sp<Codec2Buffer> {
1022 return new GraphicMetadataBuffer(format, alloc);
1023 });
1024 return std::move(array);
1025 }
1026
Wonsik Kimab34ed62019-01-31 15:28:46 -08001027 size_t numClientBuffers() const final {
1028 return mImpl.numClientBuffers();
1029 }
1030
Pawin Vongmasa36653902018-11-15 00:10:25 -08001031private:
1032 FlexBuffersImpl mImpl;
1033 std::shared_ptr<C2AllocatorStore> mStore;
1034};
1035
1036class GraphicInputBuffers : public CCodecBufferChannel::InputBuffers {
1037public:
Wonsik Kim078b58e2019-01-09 15:08:06 -08001038 GraphicInputBuffers(
1039 size_t numInputSlots, const char *componentName, const char *name = "2D-BB-Input")
Pawin Vongmasa36653902018-11-15 00:10:25 -08001040 : InputBuffers(componentName, name),
1041 mImpl(mName),
1042 mLocalBufferPool(LocalBufferPool::Create(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001043 kMaxLinearBufferSize * numInputSlots)) { }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001044 ~GraphicInputBuffers() override = default;
1045
1046 bool requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) override {
1047 // TODO: proper max input size
1048 // TODO: read usage from intf
1049 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1050 sp<GraphicBlockBuffer> newBuffer = AllocateGraphicBuffer(
1051 mPool, mFormat, HAL_PIXEL_FORMAT_YV12, usage, mLocalBufferPool);
1052 if (newBuffer == nullptr) {
1053 return false;
1054 }
1055 *index = mImpl.assignSlot(newBuffer);
1056 *buffer = newBuffer;
1057 return true;
1058 }
1059
1060 bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001061 const sp<MediaCodecBuffer> &buffer,
1062 std::shared_ptr<C2Buffer> *c2buffer,
1063 bool release) override {
1064 return mImpl.releaseSlot(buffer, c2buffer, release);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001065 }
1066
1067 bool expireComponentBuffer(
1068 const std::shared_ptr<C2Buffer> &c2buffer) override {
1069 return mImpl.expireComponentBuffer(c2buffer);
1070 }
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001071
Pawin Vongmasa36653902018-11-15 00:10:25 -08001072 void flush() override {
1073 // This is no-op by default unless we're in array mode where we need to keep
1074 // track of the flushed work.
1075 }
1076
1077 std::unique_ptr<CCodecBufferChannel::InputBuffers> toArrayMode(
1078 size_t size) final {
1079 std::unique_ptr<InputBuffersArray> array(
1080 new InputBuffersArray(mComponentName.c_str(), "2D-BB-Input[N]"));
1081 array->setPool(mPool);
1082 array->setFormat(mFormat);
1083 array->initialize(
1084 mImpl,
1085 size,
1086 [pool = mPool, format = mFormat, lbp = mLocalBufferPool]() -> sp<Codec2Buffer> {
1087 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1088 return AllocateGraphicBuffer(
1089 pool, format, HAL_PIXEL_FORMAT_YV12, usage, lbp);
1090 });
1091 return std::move(array);
1092 }
1093
Wonsik Kimab34ed62019-01-31 15:28:46 -08001094 size_t numClientBuffers() const final {
1095 return mImpl.numClientBuffers();
1096 }
1097
Pawin Vongmasa36653902018-11-15 00:10:25 -08001098private:
1099 FlexBuffersImpl mImpl;
1100 std::shared_ptr<LocalBufferPool> mLocalBufferPool;
1101};
1102
1103class DummyInputBuffers : public CCodecBufferChannel::InputBuffers {
1104public:
1105 DummyInputBuffers(const char *componentName, const char *name = "2D-Input")
1106 : InputBuffers(componentName, name) { }
1107
1108 bool requestNewBuffer(size_t *, sp<MediaCodecBuffer> *) override {
1109 return false;
1110 }
1111
1112 bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001113 const sp<MediaCodecBuffer> &, std::shared_ptr<C2Buffer> *, bool) override {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001114 return false;
1115 }
1116
1117 bool expireComponentBuffer(const std::shared_ptr<C2Buffer> &) override {
1118 return false;
1119 }
1120 void flush() override {
1121 }
1122
1123 std::unique_ptr<CCodecBufferChannel::InputBuffers> toArrayMode(
1124 size_t) final {
1125 return nullptr;
1126 }
1127
1128 bool isArrayMode() const final { return true; }
1129
1130 void getArray(Vector<sp<MediaCodecBuffer>> *array) const final {
1131 array->clear();
1132 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08001133
1134 size_t numClientBuffers() const final {
1135 return 0u;
1136 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001137};
1138
1139class OutputBuffersArray : public CCodecBufferChannel::OutputBuffers {
1140public:
1141 OutputBuffersArray(const char *componentName, const char *name = "Output[N]")
1142 : OutputBuffers(componentName, name) { }
1143 ~OutputBuffersArray() override = default;
1144
1145 void initialize(
1146 const FlexBuffersImpl &impl,
1147 size_t minSize,
1148 std::function<sp<Codec2Buffer>()> allocate) {
1149 mImpl.initialize(impl, minSize, allocate);
1150 }
1151
1152 bool isArrayMode() const final { return true; }
1153
1154 std::unique_ptr<CCodecBufferChannel::OutputBuffers> toArrayMode(
1155 size_t) final {
1156 return nullptr;
1157 }
1158
1159 status_t registerBuffer(
1160 const std::shared_ptr<C2Buffer> &buffer,
1161 size_t *index,
1162 sp<MediaCodecBuffer> *clientBuffer) final {
1163 sp<Codec2Buffer> c2Buffer;
1164 status_t err = mImpl.grabBuffer(
1165 index,
1166 &c2Buffer,
1167 [buffer](const sp<Codec2Buffer> &clientBuffer) {
1168 return clientBuffer->canCopy(buffer);
1169 });
1170 if (err == WOULD_BLOCK) {
1171 ALOGV("[%s] buffers temporarily not available", mName);
1172 return err;
1173 } else if (err != OK) {
1174 ALOGD("[%s] grabBuffer failed: %d", mName, err);
1175 return err;
1176 }
1177 c2Buffer->setFormat(mFormat);
1178 if (!c2Buffer->copy(buffer)) {
1179 ALOGD("[%s] copy buffer failed", mName);
1180 return WOULD_BLOCK;
1181 }
1182 submit(c2Buffer);
Wonsik Kimc48ddcf2019-02-11 16:16:57 -08001183 handleImageData(c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001184 *clientBuffer = c2Buffer;
1185 ALOGV("[%s] grabbed buffer %zu", mName, *index);
1186 return OK;
1187 }
1188
1189 status_t registerCsd(
1190 const C2StreamCsdInfo::output *csd,
1191 size_t *index,
1192 sp<MediaCodecBuffer> *clientBuffer) final {
1193 sp<Codec2Buffer> c2Buffer;
1194 status_t err = mImpl.grabBuffer(
1195 index,
1196 &c2Buffer,
1197 [csd](const sp<Codec2Buffer> &clientBuffer) {
1198 return clientBuffer->base() != nullptr
1199 && clientBuffer->capacity() >= csd->flexCount();
1200 });
1201 if (err != OK) {
1202 return err;
1203 }
1204 memcpy(c2Buffer->base(), csd->m.value, csd->flexCount());
1205 c2Buffer->setRange(0, csd->flexCount());
1206 c2Buffer->setFormat(mFormat);
1207 *clientBuffer = c2Buffer;
1208 return OK;
1209 }
1210
1211 bool releaseBuffer(
1212 const sp<MediaCodecBuffer> &buffer, std::shared_ptr<C2Buffer> *c2buffer) override {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001213 return mImpl.returnBuffer(buffer, c2buffer, true);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001214 }
1215
1216 void flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) override {
1217 (void)flushedWork;
1218 mImpl.flush();
1219 if (mSkipCutBuffer != nullptr) {
1220 mSkipCutBuffer->clear();
1221 }
1222 }
1223
1224 void getArray(Vector<sp<MediaCodecBuffer>> *array) const final {
1225 mImpl.getArray(array);
1226 }
1227
1228 void realloc(const std::shared_ptr<C2Buffer> &c2buffer) {
1229 std::function<sp<Codec2Buffer>()> alloc;
1230 switch (c2buffer->data().type()) {
1231 case C2BufferData::LINEAR: {
1232 uint32_t size = kLinearBufferSize;
1233 const C2ConstLinearBlock &block = c2buffer->data().linearBlocks().front();
1234 if (block.size() < kMaxLinearBufferSize / 2) {
1235 size = block.size() * 2;
1236 } else {
1237 size = kMaxLinearBufferSize;
1238 }
1239 alloc = [format = mFormat, size] {
1240 return new LocalLinearBuffer(format, new ABuffer(size));
1241 };
1242 break;
1243 }
1244
1245 // TODO: add support
1246 case C2BufferData::GRAPHIC: FALLTHROUGH_INTENDED;
1247
1248 case C2BufferData::INVALID: FALLTHROUGH_INTENDED;
1249 case C2BufferData::LINEAR_CHUNKS: FALLTHROUGH_INTENDED;
1250 case C2BufferData::GRAPHIC_CHUNKS: FALLTHROUGH_INTENDED;
1251 default:
1252 ALOGD("Unsupported type: %d", (int)c2buffer->data().type());
1253 return;
1254 }
1255 mImpl.realloc(alloc);
1256 }
1257
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001258 size_t numClientBuffers() const final {
1259 return mImpl.numClientBuffers();
1260 }
1261
Pawin Vongmasa36653902018-11-15 00:10:25 -08001262private:
1263 BuffersArrayImpl mImpl;
1264};
1265
1266class FlexOutputBuffers : public CCodecBufferChannel::OutputBuffers {
1267public:
1268 FlexOutputBuffers(const char *componentName, const char *name = "Output[]")
1269 : OutputBuffers(componentName, name),
1270 mImpl(mName) { }
1271
1272 status_t registerBuffer(
1273 const std::shared_ptr<C2Buffer> &buffer,
1274 size_t *index,
1275 sp<MediaCodecBuffer> *clientBuffer) override {
1276 sp<Codec2Buffer> newBuffer = wrap(buffer);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001277 if (newBuffer == nullptr) {
1278 return NO_MEMORY;
1279 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001280 newBuffer->setFormat(mFormat);
1281 *index = mImpl.assignSlot(newBuffer);
Wonsik Kimc48ddcf2019-02-11 16:16:57 -08001282 handleImageData(newBuffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001283 *clientBuffer = newBuffer;
1284 ALOGV("[%s] registered buffer %zu", mName, *index);
1285 return OK;
1286 }
1287
1288 status_t registerCsd(
1289 const C2StreamCsdInfo::output *csd,
1290 size_t *index,
1291 sp<MediaCodecBuffer> *clientBuffer) final {
1292 sp<Codec2Buffer> newBuffer = new LocalLinearBuffer(
1293 mFormat, ABuffer::CreateAsCopy(csd->m.value, csd->flexCount()));
1294 *index = mImpl.assignSlot(newBuffer);
1295 *clientBuffer = newBuffer;
1296 return OK;
1297 }
1298
1299 bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001300 const sp<MediaCodecBuffer> &buffer,
1301 std::shared_ptr<C2Buffer> *c2buffer) override {
1302 return mImpl.releaseSlot(buffer, c2buffer, true);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001303 }
1304
1305 void flush(
1306 const std::list<std::unique_ptr<C2Work>> &flushedWork) override {
1307 (void) flushedWork;
1308 // This is no-op by default unless we're in array mode where we need to keep
1309 // track of the flushed work.
1310 }
1311
1312 std::unique_ptr<CCodecBufferChannel::OutputBuffers> toArrayMode(
1313 size_t size) override {
1314 std::unique_ptr<OutputBuffersArray> array(new OutputBuffersArray(mComponentName.c_str()));
1315 array->setFormat(mFormat);
1316 array->transferSkipCutBuffer(mSkipCutBuffer);
1317 array->initialize(
1318 mImpl,
1319 size,
1320 [this]() { return allocateArrayBuffer(); });
1321 return std::move(array);
1322 }
1323
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001324 size_t numClientBuffers() const final {
1325 return mImpl.numClientBuffers();
1326 }
1327
Pawin Vongmasa36653902018-11-15 00:10:25 -08001328 /**
1329 * Return an appropriate Codec2Buffer object for the type of buffers.
1330 *
1331 * \param buffer C2Buffer object to wrap.
1332 *
1333 * \return appropriate Codec2Buffer object to wrap |buffer|.
1334 */
1335 virtual sp<Codec2Buffer> wrap(const std::shared_ptr<C2Buffer> &buffer) = 0;
1336
1337 /**
1338 * Return an appropriate Codec2Buffer object for the type of buffers, to be
1339 * used as an empty array buffer.
1340 *
1341 * \return appropriate Codec2Buffer object which can copy() from C2Buffers.
1342 */
1343 virtual sp<Codec2Buffer> allocateArrayBuffer() = 0;
1344
1345private:
1346 FlexBuffersImpl mImpl;
1347};
1348
1349class LinearOutputBuffers : public FlexOutputBuffers {
1350public:
1351 LinearOutputBuffers(const char *componentName, const char *name = "1D-Output")
1352 : FlexOutputBuffers(componentName, name) { }
1353
1354 void flush(
1355 const std::list<std::unique_ptr<C2Work>> &flushedWork) override {
1356 if (mSkipCutBuffer != nullptr) {
1357 mSkipCutBuffer->clear();
1358 }
1359 FlexOutputBuffers::flush(flushedWork);
1360 }
1361
1362 sp<Codec2Buffer> wrap(const std::shared_ptr<C2Buffer> &buffer) override {
1363 if (buffer == nullptr) {
1364 ALOGV("[%s] using a dummy buffer", mName);
1365 return new LocalLinearBuffer(mFormat, new ABuffer(0));
1366 }
1367 if (buffer->data().type() != C2BufferData::LINEAR) {
1368 ALOGV("[%s] non-linear buffer %d", mName, buffer->data().type());
1369 // We expect linear output buffers from the component.
1370 return nullptr;
1371 }
1372 if (buffer->data().linearBlocks().size() != 1u) {
1373 ALOGV("[%s] no linear buffers", mName);
1374 // We expect one and only one linear block from the component.
1375 return nullptr;
1376 }
1377 sp<Codec2Buffer> clientBuffer = ConstLinearBlockBuffer::Allocate(mFormat, buffer);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001378 if (clientBuffer == nullptr) {
1379 ALOGD("[%s] ConstLinearBlockBuffer::Allocate failed", mName);
1380 return nullptr;
1381 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001382 submit(clientBuffer);
1383 return clientBuffer;
1384 }
1385
1386 sp<Codec2Buffer> allocateArrayBuffer() override {
1387 // TODO: proper max output size
1388 return new LocalLinearBuffer(mFormat, new ABuffer(kLinearBufferSize));
1389 }
1390};
1391
1392class GraphicOutputBuffers : public FlexOutputBuffers {
1393public:
1394 GraphicOutputBuffers(const char *componentName, const char *name = "2D-Output")
1395 : FlexOutputBuffers(componentName, name) { }
1396
1397 sp<Codec2Buffer> wrap(const std::shared_ptr<C2Buffer> &buffer) override {
1398 return new DummyContainerBuffer(mFormat, buffer);
1399 }
1400
1401 sp<Codec2Buffer> allocateArrayBuffer() override {
1402 return new DummyContainerBuffer(mFormat);
1403 }
1404};
1405
1406class RawGraphicOutputBuffers : public FlexOutputBuffers {
1407public:
Wonsik Kim078b58e2019-01-09 15:08:06 -08001408 RawGraphicOutputBuffers(
1409 size_t numOutputSlots, const char *componentName, const char *name = "2D-BB-Output")
Pawin Vongmasa36653902018-11-15 00:10:25 -08001410 : FlexOutputBuffers(componentName, name),
1411 mLocalBufferPool(LocalBufferPool::Create(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001412 kMaxLinearBufferSize * numOutputSlots)) { }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001413 ~RawGraphicOutputBuffers() override = default;
1414
1415 sp<Codec2Buffer> wrap(const std::shared_ptr<C2Buffer> &buffer) override {
1416 if (buffer == nullptr) {
1417 sp<Codec2Buffer> c2buffer = ConstGraphicBlockBuffer::AllocateEmpty(
1418 mFormat,
1419 [lbp = mLocalBufferPool](size_t capacity) {
1420 return lbp->newBuffer(capacity);
1421 });
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001422 if (c2buffer == nullptr) {
1423 ALOGD("[%s] ConstGraphicBlockBuffer::AllocateEmpty failed", mName);
1424 return nullptr;
1425 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001426 c2buffer->setRange(0, 0);
1427 return c2buffer;
1428 } else {
1429 return ConstGraphicBlockBuffer::Allocate(
1430 mFormat,
1431 buffer,
1432 [lbp = mLocalBufferPool](size_t capacity) {
1433 return lbp->newBuffer(capacity);
1434 });
1435 }
1436 }
1437
1438 sp<Codec2Buffer> allocateArrayBuffer() override {
1439 return ConstGraphicBlockBuffer::AllocateEmpty(
1440 mFormat,
1441 [lbp = mLocalBufferPool](size_t capacity) {
1442 return lbp->newBuffer(capacity);
1443 });
1444 }
1445
1446private:
1447 std::shared_ptr<LocalBufferPool> mLocalBufferPool;
1448};
1449
1450} // namespace
1451
1452CCodecBufferChannel::QueueGuard::QueueGuard(
1453 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
1454 Mutex::Autolock l(mSync.mGuardLock);
1455 // At this point it's guaranteed that mSync is not under state transition,
1456 // as we are holding its mutex.
1457
1458 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
1459 if (count->value == -1) {
1460 mRunning = false;
1461 } else {
1462 ++count->value;
1463 mRunning = true;
1464 }
1465}
1466
1467CCodecBufferChannel::QueueGuard::~QueueGuard() {
1468 if (mRunning) {
1469 // We are not holding mGuardLock at this point so that QueueSync::stop() can
1470 // keep holding the lock until mCount reaches zero.
1471 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
1472 --count->value;
1473 count->cond.broadcast();
1474 }
1475}
1476
1477void CCodecBufferChannel::QueueSync::start() {
1478 Mutex::Autolock l(mGuardLock);
1479 // If stopped, it goes to running state; otherwise no-op.
1480 Mutexed<Counter>::Locked count(mCount);
1481 if (count->value == -1) {
1482 count->value = 0;
1483 }
1484}
1485
1486void CCodecBufferChannel::QueueSync::stop() {
1487 Mutex::Autolock l(mGuardLock);
1488 Mutexed<Counter>::Locked count(mCount);
1489 if (count->value == -1) {
1490 // no-op
1491 return;
1492 }
1493 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
1494 // mCount can only decrement. In other words, threads that acquired the lock
1495 // are allowed to finish execution but additional threads trying to acquire
1496 // the lock at this point will block, and then get QueueGuard at STOPPED
1497 // state.
1498 while (count->value != 0) {
1499 count.waitForCondition(count->cond);
1500 }
1501 count->value = -1;
1502}
1503
Pawin Vongmasa36653902018-11-15 00:10:25 -08001504// CCodecBufferChannel::ReorderStash
1505
1506CCodecBufferChannel::ReorderStash::ReorderStash() {
1507 clear();
1508}
1509
1510void CCodecBufferChannel::ReorderStash::clear() {
1511 mPending.clear();
1512 mStash.clear();
1513 mDepth = 0;
1514 mKey = C2Config::ORDINAL;
1515}
1516
Wonsik Kim6897f222019-01-30 13:29:24 -08001517void CCodecBufferChannel::ReorderStash::flush() {
1518 mPending.clear();
1519 mStash.clear();
1520}
1521
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522void CCodecBufferChannel::ReorderStash::setDepth(uint32_t depth) {
1523 mPending.splice(mPending.end(), mStash);
1524 mDepth = depth;
1525}
1526void CCodecBufferChannel::ReorderStash::setKey(C2Config::ordinal_key_t key) {
1527 mPending.splice(mPending.end(), mStash);
1528 mKey = key;
1529}
1530
1531bool CCodecBufferChannel::ReorderStash::pop(Entry *entry) {
1532 if (mPending.empty()) {
1533 return false;
1534 }
1535 entry->buffer = mPending.front().buffer;
1536 entry->timestamp = mPending.front().timestamp;
1537 entry->flags = mPending.front().flags;
1538 entry->ordinal = mPending.front().ordinal;
1539 mPending.pop_front();
1540 return true;
1541}
1542
1543void CCodecBufferChannel::ReorderStash::emplace(
1544 const std::shared_ptr<C2Buffer> &buffer,
1545 int64_t timestamp,
1546 int32_t flags,
1547 const C2WorkOrdinalStruct &ordinal) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001548 auto it = mStash.begin();
1549 for (; it != mStash.end(); ++it) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001550 if (less(ordinal, it->ordinal)) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001551 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001552 }
1553 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001554 mStash.emplace(it, buffer, timestamp, flags, ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001555 while (!mStash.empty() && mStash.size() > mDepth) {
1556 mPending.push_back(mStash.front());
1557 mStash.pop_front();
1558 }
1559}
1560
1561void CCodecBufferChannel::ReorderStash::defer(
1562 const CCodecBufferChannel::ReorderStash::Entry &entry) {
1563 mPending.push_front(entry);
1564}
1565
1566bool CCodecBufferChannel::ReorderStash::hasPending() const {
1567 return !mPending.empty();
1568}
1569
1570bool CCodecBufferChannel::ReorderStash::less(
1571 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) {
1572 switch (mKey) {
1573 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
1574 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
1575 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
1576 default:
1577 ALOGD("Unrecognized key; default to timestamp");
1578 return o1.frameIndex < o2.frameIndex;
1579 }
1580}
1581
1582// CCodecBufferChannel
1583
1584CCodecBufferChannel::CCodecBufferChannel(
1585 const std::shared_ptr<CCodecCallback> &callback)
1586 : mHeapSeqNum(-1),
1587 mCCodecCallback(callback),
Wonsik Kim078b58e2019-01-09 15:08:06 -08001588 mNumInputSlots(kSmoothnessFactor),
1589 mNumOutputSlots(kSmoothnessFactor),
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08001590 mDelay(0),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001591 mFrameIndex(0u),
1592 mFirstValidFrameIndex(0u),
1593 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001594 mInputMetEos(false) {
1595 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1596 buffers->reset(new DummyInputBuffers(""));
1597}
1598
1599CCodecBufferChannel::~CCodecBufferChannel() {
1600 if (mCrypto != nullptr && mDealer != nullptr && mHeapSeqNum >= 0) {
1601 mCrypto->unsetHeap(mHeapSeqNum);
1602 }
1603}
1604
1605void CCodecBufferChannel::setComponent(
1606 const std::shared_ptr<Codec2Client::Component> &component) {
1607 mComponent = component;
1608 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
1609 mName = mComponentName.c_str();
1610}
1611
1612status_t CCodecBufferChannel::setInputSurface(
1613 const std::shared_ptr<InputSurfaceWrapper> &surface) {
1614 ALOGV("[%s] setInputSurface", mName);
1615 mInputSurface = surface;
1616 return mInputSurface->connect(mComponent);
1617}
1618
1619status_t CCodecBufferChannel::signalEndOfInputStream() {
1620 if (mInputSurface == nullptr) {
1621 return INVALID_OPERATION;
1622 }
1623 return mInputSurface->signalEndOfInputStream();
1624}
1625
1626status_t CCodecBufferChannel::queueInputBufferInternal(const sp<MediaCodecBuffer> &buffer) {
1627 int64_t timeUs;
1628 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1629
1630 if (mInputMetEos) {
1631 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
1632 return OK;
1633 }
1634
1635 int32_t flags = 0;
1636 int32_t tmp = 0;
1637 bool eos = false;
1638 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
1639 eos = true;
1640 mInputMetEos = true;
1641 ALOGV("[%s] input EOS", mName);
1642 }
1643 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
1644 flags |= C2FrameData::FLAG_CODEC_CONFIG;
1645 }
1646 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
1647 std::unique_ptr<C2Work> work(new C2Work);
1648 work->input.ordinal.timestamp = timeUs;
1649 work->input.ordinal.frameIndex = mFrameIndex++;
1650 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
1651 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
1652 // Keep client timestamp in customOrdinal
1653 work->input.ordinal.customOrdinal = timeUs;
1654 work->input.buffers.clear();
1655
Wonsik Kimab34ed62019-01-31 15:28:46 -08001656 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
1657 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
1658
Pawin Vongmasa36653902018-11-15 00:10:25 -08001659 if (buffer->size() > 0u) {
1660 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1661 std::shared_ptr<C2Buffer> c2buffer;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001662 if (!(*buffers)->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001663 return -ENOENT;
1664 }
1665 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001666 queuedBuffers.push_back(c2buffer);
1667 } else if (eos) {
1668 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001669 }
1670 work->input.flags = (C2FrameData::flags_t)flags;
1671 // TODO: fill info's
1672
1673 work->input.configUpdate = std::move(mParamsToBeSet);
1674 work->worklets.clear();
1675 work->worklets.emplace_back(new C2Worklet);
1676
1677 std::list<std::unique_ptr<C2Work>> items;
1678 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -08001679 mPipelineWatcher.lock()->onWorkQueued(
1680 queuedFrameIndex,
1681 std::move(queuedBuffers),
1682 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001683 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001684 if (err != C2_OK) {
1685 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
1686 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001687
1688 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001689 work.reset(new C2Work);
1690 work->input.ordinal.timestamp = timeUs;
1691 work->input.ordinal.frameIndex = mFrameIndex++;
1692 // WORKAROUND: keep client timestamp in customOrdinal
1693 work->input.ordinal.customOrdinal = timeUs;
1694 work->input.buffers.clear();
1695 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001696 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001697
Wonsik Kimab34ed62019-01-31 15:28:46 -08001698 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
1699 queuedBuffers.clear();
1700
Pawin Vongmasa36653902018-11-15 00:10:25 -08001701 items.clear();
1702 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -08001703
1704 mPipelineWatcher.lock()->onWorkQueued(
1705 queuedFrameIndex,
1706 std::move(queuedBuffers),
1707 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001708 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001709 if (err != C2_OK) {
1710 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
1711 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001712 }
1713 if (err == C2_OK) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001714 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1715 bool released = (*buffers)->releaseBuffer(buffer, nullptr, true);
1716 ALOGV("[%s] queueInputBuffer: buffer %sreleased", mName, released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001717 }
1718
1719 feedInputBufferIfAvailableInternal();
1720 return err;
1721}
1722
1723status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
1724 QueueGuard guard(mSync);
1725 if (!guard.isRunning()) {
1726 ALOGD("[%s] setParameters is only supported in the running state.", mName);
1727 return -ENOSYS;
1728 }
1729 mParamsToBeSet.insert(mParamsToBeSet.end(),
1730 std::make_move_iterator(params.begin()),
1731 std::make_move_iterator(params.end()));
1732 params.clear();
1733 return OK;
1734}
1735
1736status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
1737 QueueGuard guard(mSync);
1738 if (!guard.isRunning()) {
1739 ALOGD("[%s] No more buffers should be queued at current state.", mName);
1740 return -ENOSYS;
1741 }
1742 return queueInputBufferInternal(buffer);
1743}
1744
1745status_t CCodecBufferChannel::queueSecureInputBuffer(
1746 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
1747 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
1748 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
1749 AString *errorDetailMsg) {
1750 QueueGuard guard(mSync);
1751 if (!guard.isRunning()) {
1752 ALOGD("[%s] No more buffers should be queued at current state.", mName);
1753 return -ENOSYS;
1754 }
1755
1756 if (!hasCryptoOrDescrambler()) {
1757 return -ENOSYS;
1758 }
1759 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
1760
1761 ssize_t result = -1;
1762 ssize_t codecDataOffset = 0;
1763 if (mCrypto != nullptr) {
1764 ICrypto::DestinationBuffer destination;
1765 if (secure) {
1766 destination.mType = ICrypto::kDestinationTypeNativeHandle;
1767 destination.mHandle = encryptedBuffer->handle();
1768 } else {
1769 destination.mType = ICrypto::kDestinationTypeSharedMemory;
1770 destination.mSharedMemory = mDecryptDestination;
1771 }
1772 ICrypto::SourceBuffer source;
1773 encryptedBuffer->fillSourceBuffer(&source);
1774 result = mCrypto->decrypt(
1775 key, iv, mode, pattern, source, buffer->offset(),
1776 subSamples, numSubSamples, destination, errorDetailMsg);
1777 if (result < 0) {
1778 return result;
1779 }
1780 if (destination.mType == ICrypto::kDestinationTypeSharedMemory) {
1781 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
1782 }
1783 } else {
1784 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
1785 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
1786 hidl_vec<SubSample> hidlSubSamples;
1787 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
1788
1789 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
1790 encryptedBuffer->fillSourceBuffer(&srcBuffer);
1791
1792 DestinationBuffer dstBuffer;
1793 if (secure) {
1794 dstBuffer.type = BufferType::NATIVE_HANDLE;
1795 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
1796 } else {
1797 dstBuffer.type = BufferType::SHARED_MEMORY;
1798 dstBuffer.nonsecureMemory = srcBuffer;
1799 }
1800
1801 CasStatus status = CasStatus::OK;
1802 hidl_string detailedError;
1803 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
1804
1805 if (key != nullptr) {
1806 sctrl = (ScramblingControl)key[0];
1807 // Adjust for the PES offset
1808 codecDataOffset = key[2] | (key[3] << 8);
1809 }
1810
1811 auto returnVoid = mDescrambler->descramble(
1812 sctrl,
1813 hidlSubSamples,
1814 srcBuffer,
1815 0,
1816 dstBuffer,
1817 0,
1818 [&status, &result, &detailedError] (
1819 CasStatus _status, uint32_t _bytesWritten,
1820 const hidl_string& _detailedError) {
1821 status = _status;
1822 result = (ssize_t)_bytesWritten;
1823 detailedError = _detailedError;
1824 });
1825
1826 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
1827 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
1828 mName, returnVoid.description().c_str(), status, result);
1829 return UNKNOWN_ERROR;
1830 }
1831
1832 if (result < codecDataOffset) {
1833 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
1834 return BAD_VALUE;
1835 }
1836
1837 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
1838
1839 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
1840 encryptedBuffer->copyDecryptedContentFromMemory(result);
1841 }
1842 }
1843
1844 buffer->setRange(codecDataOffset, result - codecDataOffset);
1845 return queueInputBufferInternal(buffer);
1846}
1847
1848void CCodecBufferChannel::feedInputBufferIfAvailable() {
1849 QueueGuard guard(mSync);
1850 if (!guard.isRunning()) {
1851 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1852 return;
1853 }
1854 feedInputBufferIfAvailableInternal();
1855}
1856
1857void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001858 if (mInputMetEos ||
1859 mReorderStash.lock()->hasPending() ||
1860 mPipelineWatcher.lock()->pipelineFull()) {
1861 return;
1862 } else {
1863 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1864 if ((*buffers)->numClientBuffers() >= mNumOutputSlots) {
1865 return;
1866 }
1867 }
1868 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001869 sp<MediaCodecBuffer> inBuffer;
1870 size_t index;
1871 {
1872 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001873 if ((*buffers)->numClientBuffers() >= mNumInputSlots) {
1874 return;
1875 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001876 if (!(*buffers)->requestNewBuffer(&index, &inBuffer)) {
1877 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001878 break;
1879 }
1880 }
1881 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1882 mCallback->onInputBufferAvailable(index, inBuffer);
1883 }
1884}
1885
1886status_t CCodecBufferChannel::renderOutputBuffer(
1887 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001888 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001889 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001890 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001891 {
1892 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1893 if (*buffers) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001894 released = (*buffers)->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001895 }
1896 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001897 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1898 // set to true.
1899 sendOutputBuffers();
1900 // input buffer feeding may have been gated by pending output buffers
1901 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001902 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001903 if (released) {
1904 ALOGD("[%s] The app is calling releaseOutputBuffer() with "
1905 "timestamp or render=true with non-video buffers. Apps should "
1906 "call releaseOutputBuffer() with render=false for those.",
1907 mName);
1908 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001909 return INVALID_OPERATION;
1910 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001911
1912#if 0
1913 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1914 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1915 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1916 AString res;
1917 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1918 if (ix) res.append(", ");
1919 res.append(*((int32_t*)info.get() + (ix / 4)));
1920 }
1921 ALOGV(" [%s]", res.c_str());
1922 }
1923#endif
1924 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1925 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1926 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1927 bool flip = rotation && (rotation->flip & 1);
1928 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
1929 uint32_t transform = 0;
1930 switch (quarters) {
1931 case 0: // no rotation
1932 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1933 break;
1934 case 1: // 90 degrees counter-clockwise
1935 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1936 : HAL_TRANSFORM_ROT_270;
1937 break;
1938 case 2: // 180 degrees
1939 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1940 break;
1941 case 3: // 90 degrees clockwise
1942 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1943 : HAL_TRANSFORM_ROT_90;
1944 break;
1945 }
1946
1947 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1948 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1949 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1950 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1951 if (surfaceScaling) {
1952 videoScalingMode = surfaceScaling->value;
1953 }
1954
1955 // Use dataspace from format as it has the default aspects already applied
1956 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1957 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1958
1959 // HDR static info
1960 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1961 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1962 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1963
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001964 // HDR10 plus info
1965 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1966 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1967 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
1968
Pawin Vongmasa36653902018-11-15 00:10:25 -08001969 {
1970 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1971 if (output->surface == nullptr) {
1972 ALOGI("[%s] cannot render buffer without surface", mName);
1973 return OK;
1974 }
1975 }
1976
1977 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1978 if (blocks.size() != 1u) {
1979 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1980 return UNKNOWN_ERROR;
1981 }
1982 const C2ConstGraphicBlock &block = blocks.front();
1983
1984 // TODO: revisit this after C2Fence implementation.
1985 android::IGraphicBufferProducer::QueueBufferInput qbi(
1986 timestampNs,
1987 false, // droppable
1988 dataSpace,
1989 Rect(blocks.front().crop().left,
1990 blocks.front().crop().top,
1991 blocks.front().crop().right(),
1992 blocks.front().crop().bottom()),
1993 videoScalingMode,
1994 transform,
1995 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001996 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001997 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001998 if (hdrStaticInfo) {
1999 struct android_smpte2086_metadata smpte2086_meta = {
2000 .displayPrimaryRed = {
2001 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
2002 },
2003 .displayPrimaryGreen = {
2004 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
2005 },
2006 .displayPrimaryBlue = {
2007 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
2008 },
2009 .whitePoint = {
2010 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
2011 },
2012 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
2013 .minLuminance = hdrStaticInfo->mastering.minLuminance,
2014 };
2015
2016 struct android_cta861_3_metadata cta861_meta = {
2017 .maxContentLightLevel = hdrStaticInfo->maxCll,
2018 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
2019 };
2020
2021 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
2022 hdr.smpte2086 = smpte2086_meta;
2023 hdr.cta8613 = cta861_meta;
2024 }
2025 if (hdr10PlusInfo) {
2026 hdr.validTypes |= HdrMetadata::HDR10PLUS;
2027 hdr.hdr10plus.assign(
2028 hdr10PlusInfo->m.value,
2029 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
2030 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002031 qbi.setHdrMetadata(hdr);
2032 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002033 // we don't have dirty regions
2034 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002035 android::IGraphicBufferProducer::QueueBufferOutput qbo;
2036 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
2037 if (result != OK) {
2038 ALOGI("[%s] queueBuffer failed: %d", mName, result);
2039 return result;
2040 }
2041 ALOGV("[%s] queue buffer successful", mName);
2042
2043 int64_t mediaTimeUs = 0;
2044 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
2045 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
2046
2047 return OK;
2048}
2049
2050status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
2051 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
2052 bool released = false;
2053 {
2054 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002055 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002056 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002057 }
2058 }
2059 {
2060 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2061 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002062 released = true;
2063 }
2064 }
2065 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002066 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002067 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002068 } else {
2069 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
2070 }
2071 return OK;
2072}
2073
2074void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
2075 array->clear();
2076 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2077
2078 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002079 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002080 }
2081
2082 (*buffers)->getArray(array);
2083}
2084
2085void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
2086 array->clear();
2087 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2088
2089 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002090 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002091 }
2092
2093 (*buffers)->getArray(array);
2094}
2095
2096status_t CCodecBufferChannel::start(
2097 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
2098 C2StreamBufferTypeSetting::input iStreamFormat(0u);
2099 C2StreamBufferTypeSetting::output oStreamFormat(0u);
2100 C2PortReorderBufferDepthTuning::output reorderDepth;
2101 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08002102 C2PortActualDelayTuning::input inputDelay(0);
2103 C2PortActualDelayTuning::output outputDelay(0);
2104 C2ActualPipelineDelayTuning pipelineDelay(0);
2105
Pawin Vongmasa36653902018-11-15 00:10:25 -08002106 c2_status_t err = mComponent->query(
2107 {
2108 &iStreamFormat,
2109 &oStreamFormat,
2110 &reorderDepth,
2111 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08002112 &inputDelay,
2113 &pipelineDelay,
2114 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002115 },
2116 {},
2117 C2_DONT_BLOCK,
2118 nullptr);
2119 if (err == C2_BAD_INDEX) {
2120 if (!iStreamFormat || !oStreamFormat) {
2121 return UNKNOWN_ERROR;
2122 }
2123 } else if (err != C2_OK) {
2124 return UNKNOWN_ERROR;
2125 }
2126
2127 {
2128 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2129 reorder->clear();
2130 if (reorderDepth) {
2131 reorder->setDepth(reorderDepth.value);
2132 }
2133 if (reorderKey) {
2134 reorder->setKey(reorderKey.value);
2135 }
2136 }
Wonsik Kim078b58e2019-01-09 15:08:06 -08002137
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002138 uint32_t inputDelayValue = inputDelay ? inputDelay.value : 0;
2139 uint32_t pipelineDelayValue = pipelineDelay ? pipelineDelay.value : 0;
2140 uint32_t outputDelayValue = outputDelay ? outputDelay.value : 0;
2141
2142 mNumInputSlots = inputDelayValue + pipelineDelayValue + kSmoothnessFactor;
2143 mNumOutputSlots = outputDelayValue + kSmoothnessFactor;
2144 mDelay = inputDelayValue + pipelineDelayValue + outputDelayValue;
Wonsik Kim078b58e2019-01-09 15:08:06 -08002145
Pawin Vongmasa36653902018-11-15 00:10:25 -08002146 // TODO: get this from input format
2147 bool secure = mComponent->getName().find(".secure") != std::string::npos;
2148
2149 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
2150 int poolMask = property_get_int32(
2151 "debug.stagefright.c2-poolmask",
2152 1 << C2PlatformAllocatorStore::ION |
2153 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
2154
2155 if (inputFormat != nullptr) {
2156 bool graphic = (iStreamFormat.value == C2FormatVideo);
2157 std::shared_ptr<C2BlockPool> pool;
2158 {
2159 Mutexed<BlockPools>::Locked pools(mBlockPools);
2160
2161 // set default allocator ID.
2162 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
2163 : C2PlatformAllocatorStore::ION;
2164
2165 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
2166 // from component, create the input block pool with given ID. Otherwise, use default IDs.
2167 std::vector<std::unique_ptr<C2Param>> params;
2168 err = mComponent->query({ },
2169 { C2PortAllocatorsTuning::input::PARAM_TYPE },
2170 C2_DONT_BLOCK,
2171 &params);
2172 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2173 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
2174 mName, params.size(), asString(err), err);
2175 } else if (err == C2_OK && params.size() == 1) {
2176 C2PortAllocatorsTuning::input *inputAllocators =
2177 C2PortAllocatorsTuning::input::From(params[0].get());
2178 if (inputAllocators && inputAllocators->flexCount() > 0) {
2179 std::shared_ptr<C2Allocator> allocator;
2180 // verify allocator IDs and resolve default allocator
2181 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
2182 if (allocator) {
2183 pools->inputAllocatorId = allocator->getId();
2184 } else {
2185 ALOGD("[%s] component requested invalid input allocator ID %u",
2186 mName, inputAllocators->m.values[0]);
2187 }
2188 }
2189 }
2190
2191 // TODO: use C2Component wrapper to associate this pool with ourselves
2192 if ((poolMask >> pools->inputAllocatorId) & 1) {
2193 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
2194 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
2195 mName, pools->inputAllocatorId,
2196 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
2197 asString(err), err);
2198 } else {
2199 err = C2_NOT_FOUND;
2200 }
2201 if (err != C2_OK) {
2202 C2BlockPool::local_id_t inputPoolId =
2203 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
2204 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
2205 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
2206 mName, (unsigned long long)inputPoolId,
2207 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
2208 asString(err), err);
2209 if (err != C2_OK) {
2210 return NO_MEMORY;
2211 }
2212 }
2213 pools->inputPool = pool;
2214 }
2215
Wonsik Kim51051262018-11-28 13:59:05 -08002216 bool forceArrayMode = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002217 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2218 if (graphic) {
2219 if (mInputSurface) {
2220 buffers->reset(new DummyInputBuffers(mName));
2221 } else if (mMetaMode == MODE_ANW) {
2222 buffers->reset(new GraphicMetadataInputBuffers(mName));
2223 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002224 buffers->reset(new GraphicInputBuffers(mNumInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002225 }
2226 } else {
2227 if (hasCryptoOrDescrambler()) {
2228 int32_t capacity = kLinearBufferSize;
2229 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
2230 if ((size_t)capacity > kMaxLinearBufferSize) {
2231 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
2232 capacity = kMaxLinearBufferSize;
2233 }
2234 if (mDealer == nullptr) {
2235 mDealer = new MemoryDealer(
2236 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim078b58e2019-01-09 15:08:06 -08002237 * (mNumInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08002238 "EncryptedLinearInputBuffers");
2239 mDecryptDestination = mDealer->allocate((size_t)capacity);
2240 }
2241 if (mCrypto != nullptr && mHeapSeqNum < 0) {
2242 mHeapSeqNum = mCrypto->setHeap(mDealer->getMemoryHeap());
2243 } else {
2244 mHeapSeqNum = -1;
2245 }
2246 buffers->reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08002247 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
2248 mNumInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08002249 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002250 } else {
2251 buffers->reset(new LinearInputBuffers(mName));
2252 }
2253 }
2254 (*buffers)->setFormat(inputFormat);
2255
2256 if (err == C2_OK) {
2257 (*buffers)->setPool(pool);
2258 } else {
2259 // TODO: error
2260 }
Wonsik Kim51051262018-11-28 13:59:05 -08002261
2262 if (forceArrayMode) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002263 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08002264 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002265 }
2266
2267 if (outputFormat != nullptr) {
2268 sp<IGraphicBufferProducer> outputSurface;
2269 uint32_t outputGeneration;
2270 {
2271 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2272 outputSurface = output->surface ?
2273 output->surface->getIGraphicBufferProducer() : nullptr;
2274 outputGeneration = output->generation;
2275 }
2276
2277 bool graphic = (oStreamFormat.value == C2FormatVideo);
2278 C2BlockPool::local_id_t outputPoolId_;
2279
2280 {
2281 Mutexed<BlockPools>::Locked pools(mBlockPools);
2282
2283 // set default allocator ID.
2284 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
2285 : C2PlatformAllocatorStore::ION;
2286
2287 // query C2PortAllocatorsTuning::output from component, or use default allocator if
2288 // unsuccessful.
2289 std::vector<std::unique_ptr<C2Param>> params;
2290 err = mComponent->query({ },
2291 { C2PortAllocatorsTuning::output::PARAM_TYPE },
2292 C2_DONT_BLOCK,
2293 &params);
2294 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2295 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
2296 mName, params.size(), asString(err), err);
2297 } else if (err == C2_OK && params.size() == 1) {
2298 C2PortAllocatorsTuning::output *outputAllocators =
2299 C2PortAllocatorsTuning::output::From(params[0].get());
2300 if (outputAllocators && outputAllocators->flexCount() > 0) {
2301 std::shared_ptr<C2Allocator> allocator;
2302 // verify allocator IDs and resolve default allocator
2303 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
2304 if (allocator) {
2305 pools->outputAllocatorId = allocator->getId();
2306 } else {
2307 ALOGD("[%s] component requested invalid output allocator ID %u",
2308 mName, outputAllocators->m.values[0]);
2309 }
2310 }
2311 }
2312
2313 // use bufferqueue if outputting to a surface.
2314 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
2315 // if unsuccessful.
2316 if (outputSurface) {
2317 params.clear();
2318 err = mComponent->query({ },
2319 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
2320 C2_DONT_BLOCK,
2321 &params);
2322 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2323 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
2324 mName, params.size(), asString(err), err);
2325 } else if (err == C2_OK && params.size() == 1) {
2326 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
2327 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
2328 if (surfaceAllocator) {
2329 std::shared_ptr<C2Allocator> allocator;
2330 // verify allocator IDs and resolve default allocator
2331 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
2332 if (allocator) {
2333 pools->outputAllocatorId = allocator->getId();
2334 } else {
2335 ALOGD("[%s] component requested invalid surface output allocator ID %u",
2336 mName, surfaceAllocator->value);
2337 err = C2_BAD_VALUE;
2338 }
2339 }
2340 }
2341 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
2342 && err != C2_OK
2343 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
2344 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
2345 }
2346 }
2347
2348 if ((poolMask >> pools->outputAllocatorId) & 1) {
2349 err = mComponent->createBlockPool(
2350 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
2351 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
2352 mName, pools->outputAllocatorId,
2353 (unsigned long long)pools->outputPoolId,
2354 asString(err));
2355 } else {
2356 err = C2_NOT_FOUND;
2357 }
2358 if (err != C2_OK) {
2359 // use basic pool instead
2360 pools->outputPoolId =
2361 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
2362 }
2363
2364 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
2365 // component.
2366 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
2367 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
2368
2369 std::vector<std::unique_ptr<C2SettingResult>> failures;
2370 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
2371 ALOGD("[%s] Configured output block pool ids %llu => %s",
2372 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
2373 outputPoolId_ = pools->outputPoolId;
2374 }
2375
2376 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2377
2378 if (graphic) {
2379 if (outputSurface) {
2380 buffers->reset(new GraphicOutputBuffers(mName));
2381 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002382 buffers->reset(new RawGraphicOutputBuffers(mNumOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002383 }
2384 } else {
2385 buffers->reset(new LinearOutputBuffers(mName));
2386 }
2387 (*buffers)->setFormat(outputFormat->dup());
2388
2389
2390 // Try to set output surface to created block pool if given.
2391 if (outputSurface) {
2392 mComponent->setOutputSurface(
2393 outputPoolId_,
2394 outputSurface,
2395 outputGeneration);
2396 }
2397
2398 if (oStreamFormat.value == C2BufferData::LINEAR
2399 && mComponentName.find("c2.qti.") == std::string::npos) {
2400 // WORKAROUND: if we're using early CSD workaround we convert to
2401 // array mode, to appease apps assuming the output
2402 // buffers to be of the same size.
Wonsik Kim078b58e2019-01-09 15:08:06 -08002403 (*buffers) = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002404
2405 int32_t channelCount;
2406 int32_t sampleRate;
2407 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
2408 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
2409 int32_t delay = 0;
2410 int32_t padding = 0;;
2411 if (!outputFormat->findInt32("encoder-delay", &delay)) {
2412 delay = 0;
2413 }
2414 if (!outputFormat->findInt32("encoder-padding", &padding)) {
2415 padding = 0;
2416 }
2417 if (delay || padding) {
2418 // We need write access to the buffers, and we're already in
2419 // array mode.
2420 (*buffers)->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
2421 }
2422 }
2423 }
2424 }
2425
2426 // Set up pipeline control. This has to be done after mInputBuffers and
2427 // mOutputBuffers are initialized to make sure that lingering callbacks
2428 // about buffers from the previous generation do not interfere with the
2429 // newly initialized pipeline capacity.
2430
Wonsik Kimab34ed62019-01-31 15:28:46 -08002431 {
2432 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002433 watcher->inputDelay(inputDelayValue)
2434 .pipelineDelay(pipelineDelayValue)
2435 .outputDelay(outputDelayValue)
Wonsik Kimab34ed62019-01-31 15:28:46 -08002436 .smoothnessFactor(kSmoothnessFactor);
2437 watcher->flush();
2438 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002439
2440 mInputMetEos = false;
2441 mSync.start();
2442 return OK;
2443}
2444
2445status_t CCodecBufferChannel::requestInitialInputBuffers() {
2446 if (mInputSurface) {
2447 return OK;
2448 }
2449
2450 C2StreamFormatConfig::output oStreamFormat(0u);
2451 c2_status_t err = mComponent->query({ &oStreamFormat }, {}, C2_DONT_BLOCK, nullptr);
2452 if (err != C2_OK) {
2453 return UNKNOWN_ERROR;
2454 }
2455 std::vector<sp<MediaCodecBuffer>> toBeQueued;
2456 // TODO: use proper buffer depth instead of this random value
Wonsik Kim078b58e2019-01-09 15:08:06 -08002457 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002458 size_t index;
2459 sp<MediaCodecBuffer> buffer;
2460 {
2461 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2462 if (!(*buffers)->requestNewBuffer(&index, &buffer)) {
2463 if (i == 0) {
2464 ALOGW("[%s] start: cannot allocate memory at all", mName);
2465 return NO_MEMORY;
2466 } else {
2467 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
2468 mName, i);
2469 }
2470 break;
2471 }
2472 }
2473 if (buffer) {
2474 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
2475 ALOGV("[%s] input buffer %zu available", mName, index);
2476 bool post = true;
2477 if (!configs->empty()) {
2478 sp<ABuffer> config = configs->front();
2479 if (buffer->capacity() >= config->size()) {
2480 memcpy(buffer->base(), config->data(), config->size());
2481 buffer->setRange(0, config->size());
2482 buffer->meta()->clear();
2483 buffer->meta()->setInt64("timeUs", 0);
2484 buffer->meta()->setInt32("csd", 1);
2485 post = false;
2486 } else {
2487 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
2488 mName, buffer->capacity(), config->size());
2489 }
2490 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
2491 && mComponentName.find("c2.qti.") == std::string::npos) {
2492 // WORKAROUND: Some apps expect CSD available without queueing
2493 // any input. Queue an empty buffer to get the CSD.
2494 buffer->setRange(0, 0);
2495 buffer->meta()->clear();
2496 buffer->meta()->setInt64("timeUs", 0);
2497 post = false;
2498 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002499 if (post) {
2500 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002501 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002502 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002503 }
2504 }
2505 }
2506 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
2507 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002508 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002509 }
2510 }
2511 return OK;
2512}
2513
2514void CCodecBufferChannel::stop() {
2515 mSync.stop();
2516 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
2517 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002518 mInputSurface.reset();
2519 }
2520}
2521
2522void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2523 ALOGV("[%s] flush", mName);
2524 {
2525 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
2526 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2527 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2528 continue;
2529 }
2530 if (work->input.buffers.empty()
2531 || work->input.buffers.front()->data().linearBlocks().empty()) {
2532 ALOGD("[%s] no linear codec config data found", mName);
2533 continue;
2534 }
2535 C2ReadView view =
2536 work->input.buffers.front()->data().linearBlocks().front().map().get();
2537 if (view.error() != C2_OK) {
2538 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
2539 continue;
2540 }
2541 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
2542 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
2543 }
2544 }
2545 {
2546 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2547 (*buffers)->flush();
2548 }
2549 {
2550 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2551 (*buffers)->flush(flushedWork);
2552 }
Wonsik Kim6897f222019-01-30 13:29:24 -08002553 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002554 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002555}
2556
2557void CCodecBufferChannel::onWorkDone(
2558 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002559 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002560 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002561 feedInputBufferIfAvailable();
2562 }
2563}
2564
2565void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002566 uint64_t frameIndex, size_t arrayIndex) {
2567 std::shared_ptr<C2Buffer> buffer =
2568 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002569 bool newInputSlotAvailable;
2570 {
2571 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2572 newInputSlotAvailable = (*buffers)->expireComponentBuffer(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002573 }
2574 if (newInputSlotAvailable) {
2575 feedInputBufferIfAvailable();
2576 }
2577}
2578
2579bool CCodecBufferChannel::handleWork(
2580 std::unique_ptr<C2Work> work,
2581 const sp<AMessage> &outputFormat,
2582 const C2StreamInitDataInfo::output *initData) {
2583 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
2584 // Discard frames from previous generation.
2585 ALOGD("[%s] Discard frames from previous generation.", mName);
2586 return false;
2587 }
2588
2589 if (work->worklets.size() != 1u
2590 || !work->worklets.front()
2591 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE)) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002592 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002593 }
2594
2595 if (work->result == C2_NOT_FOUND) {
2596 ALOGD("[%s] flushed work; ignored.", mName);
2597 return true;
2598 }
2599
2600 if (work->result != C2_OK) {
2601 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2602 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2603 return false;
2604 }
2605
2606 // NOTE: MediaCodec usage supposedly have only one worklet
2607 if (work->worklets.size() != 1u) {
2608 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2609 mName, work->worklets.size());
2610 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2611 return false;
2612 }
2613
2614 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2615
2616 std::shared_ptr<C2Buffer> buffer;
2617 // NOTE: MediaCodec usage supposedly have only one output stream.
2618 if (worklet->output.buffers.size() > 1u) {
2619 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2620 mName, worklet->output.buffers.size());
2621 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2622 return false;
2623 } else if (worklet->output.buffers.size() == 1u) {
2624 buffer = worklet->output.buffers[0];
2625 if (!buffer) {
2626 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2627 }
2628 }
2629
2630 while (!worklet->output.configUpdate.empty()) {
2631 std::unique_ptr<C2Param> param;
2632 worklet->output.configUpdate.back().swap(param);
2633 worklet->output.configUpdate.pop_back();
2634 switch (param->coreIndex().coreIndex()) {
2635 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2636 C2PortReorderBufferDepthTuning::output reorderDepth;
2637 if (reorderDepth.updateFrom(*param)) {
2638 mReorderStash.lock()->setDepth(reorderDepth.value);
2639 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2640 mName, reorderDepth.value);
2641 } else {
2642 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
2643 }
2644 break;
2645 }
2646 case C2PortReorderKeySetting::CORE_INDEX: {
2647 C2PortReorderKeySetting::output reorderKey;
2648 if (reorderKey.updateFrom(*param)) {
2649 mReorderStash.lock()->setKey(reorderKey.value);
2650 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2651 mName, reorderKey.value);
2652 } else {
2653 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2654 }
2655 break;
2656 }
2657 default:
2658 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2659 mName, param->index());
2660 break;
2661 }
2662 }
2663
2664 if (outputFormat != nullptr) {
2665 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2666 ALOGD("[%s] onWorkDone: output format changed to %s",
2667 mName, outputFormat->debugString().c_str());
2668 (*buffers)->setFormat(outputFormat);
2669
2670 AString mediaType;
2671 if (outputFormat->findString(KEY_MIME, &mediaType)
2672 && mediaType == MIMETYPE_AUDIO_RAW) {
2673 int32_t channelCount;
2674 int32_t sampleRate;
2675 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
2676 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
2677 (*buffers)->updateSkipCutBuffer(sampleRate, channelCount);
2678 }
2679 }
2680 }
2681
2682 int32_t flags = 0;
2683 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
2684 flags |= MediaCodec::BUFFER_FLAG_EOS;
2685 ALOGV("[%s] onWorkDone: output EOS", mName);
2686 }
2687
2688 sp<MediaCodecBuffer> outBuffer;
2689 size_t index;
2690
2691 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2692 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2693 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2694 // shall correspond to the client input timesamp (in customOrdinal). By using the
2695 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2696 // produces multiple output.
2697 c2_cntr64_t timestamp =
2698 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2699 - work->input.ordinal.timestamp;
2700 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2701 mName,
2702 work->input.ordinal.customOrdinal.peekll(),
2703 work->input.ordinal.timestamp.peekll(),
2704 worklet->output.ordinal.timestamp.peekll(),
2705 timestamp.peekll());
2706
2707 if (initData != nullptr) {
2708 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2709 if ((*buffers)->registerCsd(initData, &index, &outBuffer) == OK) {
2710 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
2711 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
2712 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2713
2714 buffers.unlock();
2715 mCallback->onOutputBufferAvailable(index, outBuffer);
2716 buffers.lock();
2717 } else {
2718 ALOGD("[%s] onWorkDone: unable to register csd", mName);
2719 buffers.unlock();
2720 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2721 buffers.lock();
2722 return false;
2723 }
2724 }
2725
2726 if (!buffer && !flags) {
2727 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2728 mName, work->input.ordinal.frameIndex.peekull());
2729 return true;
2730 }
2731
2732 if (buffer) {
2733 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2734 // TODO: properly translate these to metadata
2735 switch (info->coreIndex().coreIndex()) {
2736 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
2737 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2PictureTypeKeyFrame) {
2738 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
2739 }
2740 break;
2741 default:
2742 break;
2743 }
2744 }
2745 }
2746
2747 {
2748 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2749 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
2750 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
2751 // Flush reorder stash
2752 reorder->setDepth(0);
2753 }
2754 }
2755 sendOutputBuffers();
2756 return true;
2757}
2758
2759void CCodecBufferChannel::sendOutputBuffers() {
2760 ReorderStash::Entry entry;
2761 sp<MediaCodecBuffer> outBuffer;
2762 size_t index;
2763
2764 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08002765 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2766 if (!reorder->hasPending()) {
2767 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002768 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08002769 if (!reorder->pop(&entry)) {
2770 break;
2771 }
2772
Pawin Vongmasa36653902018-11-15 00:10:25 -08002773 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2774 status_t err = (*buffers)->registerBuffer(entry.buffer, &index, &outBuffer);
2775 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08002776 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002777 if (err != WOULD_BLOCK) {
Wonsik Kim186fdbf2019-01-29 13:30:01 -08002778 if (!(*buffers)->isArrayMode()) {
2779 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
2780 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002781 OutputBuffersArray *array = (OutputBuffersArray *)buffers->get();
2782 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08002783 outputBuffersChanged = true;
2784 }
2785 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
2786 reorder->defer(entry);
2787
2788 buffers.unlock();
2789 reorder.unlock();
2790
2791 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002792 mCCodecCallback->onOutputBuffersChanged();
2793 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002794 return;
2795 }
2796 buffers.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08002797 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002798
2799 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
2800 outBuffer->meta()->setInt32("flags", entry.flags);
2801 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu",
2802 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size());
2803 mCallback->onOutputBufferAvailable(index, outBuffer);
2804 }
2805}
2806
2807status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2808 static std::atomic_uint32_t surfaceGeneration{0};
2809 uint32_t generation = (getpid() << 10) |
2810 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2811 & ((1 << 10) - 1));
2812
2813 sp<IGraphicBufferProducer> producer;
2814 if (newSurface) {
2815 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Wonsik Kim078b58e2019-01-09 15:08:06 -08002816 newSurface->setMaxDequeuedBufferCount(mNumOutputSlots + kRenderingDepth);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002817 producer = newSurface->getIGraphicBufferProducer();
2818 producer->setGenerationNumber(generation);
2819 } else {
2820 ALOGE("[%s] setting output surface to null", mName);
2821 return INVALID_OPERATION;
2822 }
2823
2824 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2825 C2BlockPool::local_id_t outputPoolId;
2826 {
2827 Mutexed<BlockPools>::Locked pools(mBlockPools);
2828 outputPoolId = pools->outputPoolId;
2829 outputPoolIntf = pools->outputPoolIntf;
2830 }
2831
2832 if (outputPoolIntf) {
2833 if (mComponent->setOutputSurface(
2834 outputPoolId,
2835 producer,
2836 generation) != C2_OK) {
2837 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2838 return INVALID_OPERATION;
2839 }
2840 }
2841
2842 {
2843 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2844 output->surface = newSurface;
2845 output->generation = generation;
2846 }
2847
2848 return OK;
2849}
2850
Wonsik Kimab34ed62019-01-31 15:28:46 -08002851PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
Wonsik Kim4fa4f2b2019-02-13 11:02:58 -08002852 // When client pushed EOS, we want all the work to be done quickly.
2853 // Otherwise, component may have stalled work due to input starvation up to
2854 // the sum of the delay in the pipeline.
2855 size_t n = mInputMetEos ? 0 : mDelay;
2856 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now(), n);
Wonsik Kimab34ed62019-01-31 15:28:46 -08002857}
2858
Pawin Vongmasa36653902018-11-15 00:10:25 -08002859void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2860 mMetaMode = mode;
2861}
2862
2863status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2864 // C2_OK is always translated to OK.
2865 if (c2s == C2_OK) {
2866 return OK;
2867 }
2868
2869 // Operation-dependent translation
2870 // TODO: Add as necessary
2871 switch (c2op) {
2872 case C2_OPERATION_Component_start:
2873 switch (c2s) {
2874 case C2_NO_MEMORY:
2875 return NO_MEMORY;
2876 default:
2877 return UNKNOWN_ERROR;
2878 }
2879 default:
2880 break;
2881 }
2882
2883 // Backup operation-agnostic translation
2884 switch (c2s) {
2885 case C2_BAD_INDEX:
2886 return BAD_INDEX;
2887 case C2_BAD_VALUE:
2888 return BAD_VALUE;
2889 case C2_BLOCKING:
2890 return WOULD_BLOCK;
2891 case C2_DUPLICATE:
2892 return ALREADY_EXISTS;
2893 case C2_NO_INIT:
2894 return NO_INIT;
2895 case C2_NO_MEMORY:
2896 return NO_MEMORY;
2897 case C2_NOT_FOUND:
2898 return NAME_NOT_FOUND;
2899 case C2_TIMED_OUT:
2900 return TIMED_OUT;
2901 case C2_BAD_STATE:
2902 case C2_CANCELED:
2903 case C2_CANNOT_DO:
2904 case C2_CORRUPTED:
2905 case C2_OMITTED:
2906 case C2_REFUSED:
2907 return UNKNOWN_ERROR;
2908 default:
2909 return -static_cast<status_t>(c2s);
2910 }
2911}
2912
2913} // namespace android