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