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