blob: b529cbc3d56bcb048340d5342a7b763bb77559b5 [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;
1648
1649 items.clear();
1650 items.push_back(std::move(work));
1651 err = mComponent->queue(&items);
1652 }
1653 if (err == C2_OK) {
1654 mCCodecCallback->onWorkQueued(eos);
1655 }
1656
1657 feedInputBufferIfAvailableInternal();
1658 return err;
1659}
1660
1661status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
1662 QueueGuard guard(mSync);
1663 if (!guard.isRunning()) {
1664 ALOGD("[%s] setParameters is only supported in the running state.", mName);
1665 return -ENOSYS;
1666 }
1667 mParamsToBeSet.insert(mParamsToBeSet.end(),
1668 std::make_move_iterator(params.begin()),
1669 std::make_move_iterator(params.end()));
1670 params.clear();
1671 return OK;
1672}
1673
1674status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
1675 QueueGuard guard(mSync);
1676 if (!guard.isRunning()) {
1677 ALOGD("[%s] No more buffers should be queued at current state.", mName);
1678 return -ENOSYS;
1679 }
1680 return queueInputBufferInternal(buffer);
1681}
1682
1683status_t CCodecBufferChannel::queueSecureInputBuffer(
1684 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
1685 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
1686 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
1687 AString *errorDetailMsg) {
1688 QueueGuard guard(mSync);
1689 if (!guard.isRunning()) {
1690 ALOGD("[%s] No more buffers should be queued at current state.", mName);
1691 return -ENOSYS;
1692 }
1693
1694 if (!hasCryptoOrDescrambler()) {
1695 return -ENOSYS;
1696 }
1697 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
1698
1699 ssize_t result = -1;
1700 ssize_t codecDataOffset = 0;
1701 if (mCrypto != nullptr) {
1702 ICrypto::DestinationBuffer destination;
1703 if (secure) {
1704 destination.mType = ICrypto::kDestinationTypeNativeHandle;
1705 destination.mHandle = encryptedBuffer->handle();
1706 } else {
1707 destination.mType = ICrypto::kDestinationTypeSharedMemory;
1708 destination.mSharedMemory = mDecryptDestination;
1709 }
1710 ICrypto::SourceBuffer source;
1711 encryptedBuffer->fillSourceBuffer(&source);
1712 result = mCrypto->decrypt(
1713 key, iv, mode, pattern, source, buffer->offset(),
1714 subSamples, numSubSamples, destination, errorDetailMsg);
1715 if (result < 0) {
1716 return result;
1717 }
1718 if (destination.mType == ICrypto::kDestinationTypeSharedMemory) {
1719 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
1720 }
1721 } else {
1722 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
1723 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
1724 hidl_vec<SubSample> hidlSubSamples;
1725 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
1726
1727 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
1728 encryptedBuffer->fillSourceBuffer(&srcBuffer);
1729
1730 DestinationBuffer dstBuffer;
1731 if (secure) {
1732 dstBuffer.type = BufferType::NATIVE_HANDLE;
1733 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
1734 } else {
1735 dstBuffer.type = BufferType::SHARED_MEMORY;
1736 dstBuffer.nonsecureMemory = srcBuffer;
1737 }
1738
1739 CasStatus status = CasStatus::OK;
1740 hidl_string detailedError;
1741 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
1742
1743 if (key != nullptr) {
1744 sctrl = (ScramblingControl)key[0];
1745 // Adjust for the PES offset
1746 codecDataOffset = key[2] | (key[3] << 8);
1747 }
1748
1749 auto returnVoid = mDescrambler->descramble(
1750 sctrl,
1751 hidlSubSamples,
1752 srcBuffer,
1753 0,
1754 dstBuffer,
1755 0,
1756 [&status, &result, &detailedError] (
1757 CasStatus _status, uint32_t _bytesWritten,
1758 const hidl_string& _detailedError) {
1759 status = _status;
1760 result = (ssize_t)_bytesWritten;
1761 detailedError = _detailedError;
1762 });
1763
1764 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
1765 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
1766 mName, returnVoid.description().c_str(), status, result);
1767 return UNKNOWN_ERROR;
1768 }
1769
1770 if (result < codecDataOffset) {
1771 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
1772 return BAD_VALUE;
1773 }
1774
1775 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
1776
1777 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
1778 encryptedBuffer->copyDecryptedContentFromMemory(result);
1779 }
1780 }
1781
1782 buffer->setRange(codecDataOffset, result - codecDataOffset);
1783 return queueInputBufferInternal(buffer);
1784}
1785
1786void CCodecBufferChannel::feedInputBufferIfAvailable() {
1787 QueueGuard guard(mSync);
1788 if (!guard.isRunning()) {
1789 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1790 return;
1791 }
1792 feedInputBufferIfAvailableInternal();
1793}
1794
1795void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
1796 while (!mInputMetEos &&
1797 !mReorderStash.lock()->hasPending() &&
1798 mAvailablePipelineCapacity.allocate("feedInputBufferIfAvailable")) {
1799 sp<MediaCodecBuffer> inBuffer;
1800 size_t index;
1801 {
1802 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1803 if (!(*buffers)->requestNewBuffer(&index, &inBuffer)) {
1804 ALOGV("[%s] no new buffer available", mName);
1805 mAvailablePipelineCapacity.free("feedInputBufferIfAvailable");
1806 break;
1807 }
1808 }
1809 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1810 mCallback->onInputBufferAvailable(index, inBuffer);
1811 }
1812}
1813
1814status_t CCodecBufferChannel::renderOutputBuffer(
1815 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001816 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001817 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001818 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001819 {
1820 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1821 if (*buffers) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001822 released = (*buffers)->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001823 }
1824 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001825 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1826 // set to true.
1827 sendOutputBuffers();
1828 // input buffer feeding may have been gated by pending output buffers
1829 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001830 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001831 if (released) {
1832 ALOGD("[%s] The app is calling releaseOutputBuffer() with "
1833 "timestamp or render=true with non-video buffers. Apps should "
1834 "call releaseOutputBuffer() with render=false for those.",
1835 mName);
1836 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001837 return INVALID_OPERATION;
1838 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001839
1840#if 0
1841 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1842 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1843 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1844 AString res;
1845 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1846 if (ix) res.append(", ");
1847 res.append(*((int32_t*)info.get() + (ix / 4)));
1848 }
1849 ALOGV(" [%s]", res.c_str());
1850 }
1851#endif
1852 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1853 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1854 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1855 bool flip = rotation && (rotation->flip & 1);
1856 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
1857 uint32_t transform = 0;
1858 switch (quarters) {
1859 case 0: // no rotation
1860 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1861 break;
1862 case 1: // 90 degrees counter-clockwise
1863 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1864 : HAL_TRANSFORM_ROT_270;
1865 break;
1866 case 2: // 180 degrees
1867 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1868 break;
1869 case 3: // 90 degrees clockwise
1870 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1871 : HAL_TRANSFORM_ROT_90;
1872 break;
1873 }
1874
1875 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1876 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1877 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1878 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1879 if (surfaceScaling) {
1880 videoScalingMode = surfaceScaling->value;
1881 }
1882
1883 // Use dataspace from format as it has the default aspects already applied
1884 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1885 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1886
1887 // HDR static info
1888 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1889 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1890 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1891
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001892 // HDR10 plus info
1893 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1894 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1895 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
1896
Pawin Vongmasa36653902018-11-15 00:10:25 -08001897 {
1898 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1899 if (output->surface == nullptr) {
1900 ALOGI("[%s] cannot render buffer without surface", mName);
1901 return OK;
1902 }
1903 }
1904
1905 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1906 if (blocks.size() != 1u) {
1907 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1908 return UNKNOWN_ERROR;
1909 }
1910 const C2ConstGraphicBlock &block = blocks.front();
1911
1912 // TODO: revisit this after C2Fence implementation.
1913 android::IGraphicBufferProducer::QueueBufferInput qbi(
1914 timestampNs,
1915 false, // droppable
1916 dataSpace,
1917 Rect(blocks.front().crop().left,
1918 blocks.front().crop().top,
1919 blocks.front().crop().right(),
1920 blocks.front().crop().bottom()),
1921 videoScalingMode,
1922 transform,
1923 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001924 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001925 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001926 if (hdrStaticInfo) {
1927 struct android_smpte2086_metadata smpte2086_meta = {
1928 .displayPrimaryRed = {
1929 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1930 },
1931 .displayPrimaryGreen = {
1932 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1933 },
1934 .displayPrimaryBlue = {
1935 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1936 },
1937 .whitePoint = {
1938 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1939 },
1940 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1941 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1942 };
1943
1944 struct android_cta861_3_metadata cta861_meta = {
1945 .maxContentLightLevel = hdrStaticInfo->maxCll,
1946 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1947 };
1948
1949 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
1950 hdr.smpte2086 = smpte2086_meta;
1951 hdr.cta8613 = cta861_meta;
1952 }
1953 if (hdr10PlusInfo) {
1954 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1955 hdr.hdr10plus.assign(
1956 hdr10PlusInfo->m.value,
1957 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
1958 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001959 qbi.setHdrMetadata(hdr);
1960 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001961 // we don't have dirty regions
1962 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001963 android::IGraphicBufferProducer::QueueBufferOutput qbo;
1964 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
1965 if (result != OK) {
1966 ALOGI("[%s] queueBuffer failed: %d", mName, result);
1967 return result;
1968 }
1969 ALOGV("[%s] queue buffer successful", mName);
1970
1971 int64_t mediaTimeUs = 0;
1972 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
1973 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
1974
1975 return OK;
1976}
1977
1978status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
1979 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
1980 bool released = false;
1981 {
1982 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1983 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr)) {
1984 buffers.unlock();
1985 released = true;
1986 mAvailablePipelineCapacity.freeInputSlots(1, "discardBuffer");
1987 }
1988 }
1989 {
1990 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1991 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr)) {
1992 buffers.unlock();
1993 released = true;
1994 }
1995 }
1996 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001997 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001998 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001999 } else {
2000 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
2001 }
2002 return OK;
2003}
2004
2005void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
2006 array->clear();
2007 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2008
2009 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002010 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002011 }
2012
2013 (*buffers)->getArray(array);
2014}
2015
2016void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
2017 array->clear();
2018 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2019
2020 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002021 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002022 }
2023
2024 (*buffers)->getArray(array);
2025}
2026
2027status_t CCodecBufferChannel::start(
2028 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
2029 C2StreamBufferTypeSetting::input iStreamFormat(0u);
2030 C2StreamBufferTypeSetting::output oStreamFormat(0u);
2031 C2PortReorderBufferDepthTuning::output reorderDepth;
2032 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08002033 C2PortActualDelayTuning::input inputDelay(0);
2034 C2PortActualDelayTuning::output outputDelay(0);
2035 C2ActualPipelineDelayTuning pipelineDelay(0);
2036
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037 c2_status_t err = mComponent->query(
2038 {
2039 &iStreamFormat,
2040 &oStreamFormat,
2041 &reorderDepth,
2042 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08002043 &inputDelay,
2044 &pipelineDelay,
2045 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002046 },
2047 {},
2048 C2_DONT_BLOCK,
2049 nullptr);
2050 if (err == C2_BAD_INDEX) {
2051 if (!iStreamFormat || !oStreamFormat) {
2052 return UNKNOWN_ERROR;
2053 }
2054 } else if (err != C2_OK) {
2055 return UNKNOWN_ERROR;
2056 }
2057
2058 {
2059 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2060 reorder->clear();
2061 if (reorderDepth) {
2062 reorder->setDepth(reorderDepth.value);
2063 }
2064 if (reorderKey) {
2065 reorder->setKey(reorderKey.value);
2066 }
2067 }
Wonsik Kim078b58e2019-01-09 15:08:06 -08002068
2069 mNumInputSlots =
2070 (inputDelay ? inputDelay.value : 0) +
2071 (pipelineDelay ? pipelineDelay.value : 0) +
2072 kSmoothnessFactor;
2073 mNumOutputSlots = (outputDelay ? outputDelay.value : 0) + kSmoothnessFactor;
2074
Pawin Vongmasa36653902018-11-15 00:10:25 -08002075 // TODO: get this from input format
2076 bool secure = mComponent->getName().find(".secure") != std::string::npos;
2077
2078 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
2079 int poolMask = property_get_int32(
2080 "debug.stagefright.c2-poolmask",
2081 1 << C2PlatformAllocatorStore::ION |
2082 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
2083
2084 if (inputFormat != nullptr) {
2085 bool graphic = (iStreamFormat.value == C2FormatVideo);
2086 std::shared_ptr<C2BlockPool> pool;
2087 {
2088 Mutexed<BlockPools>::Locked pools(mBlockPools);
2089
2090 // set default allocator ID.
2091 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
2092 : C2PlatformAllocatorStore::ION;
2093
2094 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
2095 // from component, create the input block pool with given ID. Otherwise, use default IDs.
2096 std::vector<std::unique_ptr<C2Param>> params;
2097 err = mComponent->query({ },
2098 { C2PortAllocatorsTuning::input::PARAM_TYPE },
2099 C2_DONT_BLOCK,
2100 &params);
2101 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2102 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
2103 mName, params.size(), asString(err), err);
2104 } else if (err == C2_OK && params.size() == 1) {
2105 C2PortAllocatorsTuning::input *inputAllocators =
2106 C2PortAllocatorsTuning::input::From(params[0].get());
2107 if (inputAllocators && inputAllocators->flexCount() > 0) {
2108 std::shared_ptr<C2Allocator> allocator;
2109 // verify allocator IDs and resolve default allocator
2110 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
2111 if (allocator) {
2112 pools->inputAllocatorId = allocator->getId();
2113 } else {
2114 ALOGD("[%s] component requested invalid input allocator ID %u",
2115 mName, inputAllocators->m.values[0]);
2116 }
2117 }
2118 }
2119
2120 // TODO: use C2Component wrapper to associate this pool with ourselves
2121 if ((poolMask >> pools->inputAllocatorId) & 1) {
2122 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
2123 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
2124 mName, pools->inputAllocatorId,
2125 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
2126 asString(err), err);
2127 } else {
2128 err = C2_NOT_FOUND;
2129 }
2130 if (err != C2_OK) {
2131 C2BlockPool::local_id_t inputPoolId =
2132 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
2133 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
2134 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
2135 mName, (unsigned long long)inputPoolId,
2136 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
2137 asString(err), err);
2138 if (err != C2_OK) {
2139 return NO_MEMORY;
2140 }
2141 }
2142 pools->inputPool = pool;
2143 }
2144
Wonsik Kim51051262018-11-28 13:59:05 -08002145 bool forceArrayMode = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002146 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2147 if (graphic) {
2148 if (mInputSurface) {
2149 buffers->reset(new DummyInputBuffers(mName));
2150 } else if (mMetaMode == MODE_ANW) {
2151 buffers->reset(new GraphicMetadataInputBuffers(mName));
2152 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002153 buffers->reset(new GraphicInputBuffers(mNumInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002154 }
2155 } else {
2156 if (hasCryptoOrDescrambler()) {
2157 int32_t capacity = kLinearBufferSize;
2158 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
2159 if ((size_t)capacity > kMaxLinearBufferSize) {
2160 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
2161 capacity = kMaxLinearBufferSize;
2162 }
2163 if (mDealer == nullptr) {
2164 mDealer = new MemoryDealer(
2165 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim078b58e2019-01-09 15:08:06 -08002166 * (mNumInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08002167 "EncryptedLinearInputBuffers");
2168 mDecryptDestination = mDealer->allocate((size_t)capacity);
2169 }
2170 if (mCrypto != nullptr && mHeapSeqNum < 0) {
2171 mHeapSeqNum = mCrypto->setHeap(mDealer->getMemoryHeap());
2172 } else {
2173 mHeapSeqNum = -1;
2174 }
2175 buffers->reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08002176 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
2177 mNumInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08002178 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002179 } else {
2180 buffers->reset(new LinearInputBuffers(mName));
2181 }
2182 }
2183 (*buffers)->setFormat(inputFormat);
2184
2185 if (err == C2_OK) {
2186 (*buffers)->setPool(pool);
2187 } else {
2188 // TODO: error
2189 }
Wonsik Kim51051262018-11-28 13:59:05 -08002190
2191 if (forceArrayMode) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002192 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08002193 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002194 }
2195
2196 if (outputFormat != nullptr) {
2197 sp<IGraphicBufferProducer> outputSurface;
2198 uint32_t outputGeneration;
2199 {
2200 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2201 outputSurface = output->surface ?
2202 output->surface->getIGraphicBufferProducer() : nullptr;
2203 outputGeneration = output->generation;
2204 }
2205
2206 bool graphic = (oStreamFormat.value == C2FormatVideo);
2207 C2BlockPool::local_id_t outputPoolId_;
2208
2209 {
2210 Mutexed<BlockPools>::Locked pools(mBlockPools);
2211
2212 // set default allocator ID.
2213 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
2214 : C2PlatformAllocatorStore::ION;
2215
2216 // query C2PortAllocatorsTuning::output from component, or use default allocator if
2217 // unsuccessful.
2218 std::vector<std::unique_ptr<C2Param>> params;
2219 err = mComponent->query({ },
2220 { C2PortAllocatorsTuning::output::PARAM_TYPE },
2221 C2_DONT_BLOCK,
2222 &params);
2223 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2224 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
2225 mName, params.size(), asString(err), err);
2226 } else if (err == C2_OK && params.size() == 1) {
2227 C2PortAllocatorsTuning::output *outputAllocators =
2228 C2PortAllocatorsTuning::output::From(params[0].get());
2229 if (outputAllocators && outputAllocators->flexCount() > 0) {
2230 std::shared_ptr<C2Allocator> allocator;
2231 // verify allocator IDs and resolve default allocator
2232 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
2233 if (allocator) {
2234 pools->outputAllocatorId = allocator->getId();
2235 } else {
2236 ALOGD("[%s] component requested invalid output allocator ID %u",
2237 mName, outputAllocators->m.values[0]);
2238 }
2239 }
2240 }
2241
2242 // use bufferqueue if outputting to a surface.
2243 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
2244 // if unsuccessful.
2245 if (outputSurface) {
2246 params.clear();
2247 err = mComponent->query({ },
2248 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
2249 C2_DONT_BLOCK,
2250 &params);
2251 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2252 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
2253 mName, params.size(), asString(err), err);
2254 } else if (err == C2_OK && params.size() == 1) {
2255 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
2256 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
2257 if (surfaceAllocator) {
2258 std::shared_ptr<C2Allocator> allocator;
2259 // verify allocator IDs and resolve default allocator
2260 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
2261 if (allocator) {
2262 pools->outputAllocatorId = allocator->getId();
2263 } else {
2264 ALOGD("[%s] component requested invalid surface output allocator ID %u",
2265 mName, surfaceAllocator->value);
2266 err = C2_BAD_VALUE;
2267 }
2268 }
2269 }
2270 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
2271 && err != C2_OK
2272 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
2273 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
2274 }
2275 }
2276
2277 if ((poolMask >> pools->outputAllocatorId) & 1) {
2278 err = mComponent->createBlockPool(
2279 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
2280 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
2281 mName, pools->outputAllocatorId,
2282 (unsigned long long)pools->outputPoolId,
2283 asString(err));
2284 } else {
2285 err = C2_NOT_FOUND;
2286 }
2287 if (err != C2_OK) {
2288 // use basic pool instead
2289 pools->outputPoolId =
2290 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
2291 }
2292
2293 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
2294 // component.
2295 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
2296 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
2297
2298 std::vector<std::unique_ptr<C2SettingResult>> failures;
2299 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
2300 ALOGD("[%s] Configured output block pool ids %llu => %s",
2301 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
2302 outputPoolId_ = pools->outputPoolId;
2303 }
2304
2305 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2306
2307 if (graphic) {
2308 if (outputSurface) {
2309 buffers->reset(new GraphicOutputBuffers(mName));
2310 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002311 buffers->reset(new RawGraphicOutputBuffers(mNumOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002312 }
2313 } else {
2314 buffers->reset(new LinearOutputBuffers(mName));
2315 }
2316 (*buffers)->setFormat(outputFormat->dup());
2317
2318
2319 // Try to set output surface to created block pool if given.
2320 if (outputSurface) {
2321 mComponent->setOutputSurface(
2322 outputPoolId_,
2323 outputSurface,
2324 outputGeneration);
2325 }
2326
2327 if (oStreamFormat.value == C2BufferData::LINEAR
2328 && mComponentName.find("c2.qti.") == std::string::npos) {
2329 // WORKAROUND: if we're using early CSD workaround we convert to
2330 // array mode, to appease apps assuming the output
2331 // buffers to be of the same size.
Wonsik Kim078b58e2019-01-09 15:08:06 -08002332 (*buffers) = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002333
2334 int32_t channelCount;
2335 int32_t sampleRate;
2336 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
2337 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
2338 int32_t delay = 0;
2339 int32_t padding = 0;;
2340 if (!outputFormat->findInt32("encoder-delay", &delay)) {
2341 delay = 0;
2342 }
2343 if (!outputFormat->findInt32("encoder-padding", &padding)) {
2344 padding = 0;
2345 }
2346 if (delay || padding) {
2347 // We need write access to the buffers, and we're already in
2348 // array mode.
2349 (*buffers)->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
2350 }
2351 }
2352 }
2353 }
2354
2355 // Set up pipeline control. This has to be done after mInputBuffers and
2356 // mOutputBuffers are initialized to make sure that lingering callbacks
2357 // about buffers from the previous generation do not interfere with the
2358 // newly initialized pipeline capacity.
2359
Pawin Vongmasa36653902018-11-15 00:10:25 -08002360 mAvailablePipelineCapacity.initialize(
Wonsik Kim078b58e2019-01-09 15:08:06 -08002361 mNumInputSlots,
2362 mNumInputSlots + mNumOutputSlots,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002363 mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002364
2365 mInputMetEos = false;
2366 mSync.start();
2367 return OK;
2368}
2369
2370status_t CCodecBufferChannel::requestInitialInputBuffers() {
2371 if (mInputSurface) {
2372 return OK;
2373 }
2374
2375 C2StreamFormatConfig::output oStreamFormat(0u);
2376 c2_status_t err = mComponent->query({ &oStreamFormat }, {}, C2_DONT_BLOCK, nullptr);
2377 if (err != C2_OK) {
2378 return UNKNOWN_ERROR;
2379 }
2380 std::vector<sp<MediaCodecBuffer>> toBeQueued;
2381 // TODO: use proper buffer depth instead of this random value
Wonsik Kim078b58e2019-01-09 15:08:06 -08002382 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002383 size_t index;
2384 sp<MediaCodecBuffer> buffer;
2385 {
2386 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2387 if (!(*buffers)->requestNewBuffer(&index, &buffer)) {
2388 if (i == 0) {
2389 ALOGW("[%s] start: cannot allocate memory at all", mName);
2390 return NO_MEMORY;
2391 } else {
2392 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
2393 mName, i);
2394 }
2395 break;
2396 }
2397 }
2398 if (buffer) {
2399 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
2400 ALOGV("[%s] input buffer %zu available", mName, index);
2401 bool post = true;
2402 if (!configs->empty()) {
2403 sp<ABuffer> config = configs->front();
2404 if (buffer->capacity() >= config->size()) {
2405 memcpy(buffer->base(), config->data(), config->size());
2406 buffer->setRange(0, config->size());
2407 buffer->meta()->clear();
2408 buffer->meta()->setInt64("timeUs", 0);
2409 buffer->meta()->setInt32("csd", 1);
2410 post = false;
2411 } else {
2412 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
2413 mName, buffer->capacity(), config->size());
2414 }
2415 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
2416 && mComponentName.find("c2.qti.") == std::string::npos) {
2417 // WORKAROUND: Some apps expect CSD available without queueing
2418 // any input. Queue an empty buffer to get the CSD.
2419 buffer->setRange(0, 0);
2420 buffer->meta()->clear();
2421 buffer->meta()->setInt64("timeUs", 0);
2422 post = false;
2423 }
2424 if (mAvailablePipelineCapacity.allocate("requestInitialInputBuffers")) {
2425 if (post) {
2426 mCallback->onInputBufferAvailable(index, buffer);
2427 } else {
2428 toBeQueued.emplace_back(buffer);
2429 }
2430 } else {
2431 ALOGD("[%s] pipeline is full while requesting %zu-th input buffer",
2432 mName, i);
2433 }
2434 }
2435 }
2436 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
2437 if (queueInputBufferInternal(buffer) != OK) {
2438 mAvailablePipelineCapacity.freeComponentSlot("requestInitialInputBuffers");
2439 }
2440 }
2441 return OK;
2442}
2443
2444void CCodecBufferChannel::stop() {
2445 mSync.stop();
2446 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
2447 if (mInputSurface != nullptr) {
2448 mInputSurface->disconnect();
2449 mInputSurface.reset();
2450 }
2451}
2452
2453void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2454 ALOGV("[%s] flush", mName);
2455 {
2456 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
2457 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2458 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2459 continue;
2460 }
2461 if (work->input.buffers.empty()
2462 || work->input.buffers.front()->data().linearBlocks().empty()) {
2463 ALOGD("[%s] no linear codec config data found", mName);
2464 continue;
2465 }
2466 C2ReadView view =
2467 work->input.buffers.front()->data().linearBlocks().front().map().get();
2468 if (view.error() != C2_OK) {
2469 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
2470 continue;
2471 }
2472 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
2473 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
2474 }
2475 }
2476 {
2477 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2478 (*buffers)->flush();
2479 }
2480 {
2481 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2482 (*buffers)->flush(flushedWork);
2483 }
2484}
2485
2486void CCodecBufferChannel::onWorkDone(
2487 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
2488 const C2StreamInitDataInfo::output *initData,
2489 size_t numDiscardedInputBuffers) {
2490 if (handleWork(std::move(work), outputFormat, initData)) {
2491 mAvailablePipelineCapacity.freeInputSlots(numDiscardedInputBuffers,
2492 "onWorkDone");
2493 feedInputBufferIfAvailable();
2494 }
2495}
2496
2497void CCodecBufferChannel::onInputBufferDone(
2498 const std::shared_ptr<C2Buffer>& buffer) {
2499 bool newInputSlotAvailable;
2500 {
2501 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2502 newInputSlotAvailable = (*buffers)->expireComponentBuffer(buffer);
2503 if (newInputSlotAvailable) {
2504 mAvailablePipelineCapacity.freeInputSlots(1, "onInputBufferDone");
2505 }
2506 }
2507 if (newInputSlotAvailable) {
2508 feedInputBufferIfAvailable();
2509 }
2510}
2511
2512bool CCodecBufferChannel::handleWork(
2513 std::unique_ptr<C2Work> work,
2514 const sp<AMessage> &outputFormat,
2515 const C2StreamInitDataInfo::output *initData) {
2516 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
2517 // Discard frames from previous generation.
2518 ALOGD("[%s] Discard frames from previous generation.", mName);
2519 return false;
2520 }
2521
2522 if (work->worklets.size() != 1u
2523 || !work->worklets.front()
2524 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE)) {
2525 mAvailablePipelineCapacity.freeComponentSlot("handleWork");
2526 }
2527
2528 if (work->result == C2_NOT_FOUND) {
2529 ALOGD("[%s] flushed work; ignored.", mName);
2530 return true;
2531 }
2532
2533 if (work->result != C2_OK) {
2534 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2535 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2536 return false;
2537 }
2538
2539 // NOTE: MediaCodec usage supposedly have only one worklet
2540 if (work->worklets.size() != 1u) {
2541 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2542 mName, work->worklets.size());
2543 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2544 return false;
2545 }
2546
2547 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2548
2549 std::shared_ptr<C2Buffer> buffer;
2550 // NOTE: MediaCodec usage supposedly have only one output stream.
2551 if (worklet->output.buffers.size() > 1u) {
2552 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2553 mName, worklet->output.buffers.size());
2554 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2555 return false;
2556 } else if (worklet->output.buffers.size() == 1u) {
2557 buffer = worklet->output.buffers[0];
2558 if (!buffer) {
2559 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2560 }
2561 }
2562
2563 while (!worklet->output.configUpdate.empty()) {
2564 std::unique_ptr<C2Param> param;
2565 worklet->output.configUpdate.back().swap(param);
2566 worklet->output.configUpdate.pop_back();
2567 switch (param->coreIndex().coreIndex()) {
2568 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2569 C2PortReorderBufferDepthTuning::output reorderDepth;
2570 if (reorderDepth.updateFrom(*param)) {
2571 mReorderStash.lock()->setDepth(reorderDepth.value);
2572 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2573 mName, reorderDepth.value);
2574 } else {
2575 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
2576 }
2577 break;
2578 }
2579 case C2PortReorderKeySetting::CORE_INDEX: {
2580 C2PortReorderKeySetting::output reorderKey;
2581 if (reorderKey.updateFrom(*param)) {
2582 mReorderStash.lock()->setKey(reorderKey.value);
2583 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2584 mName, reorderKey.value);
2585 } else {
2586 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2587 }
2588 break;
2589 }
2590 default:
2591 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2592 mName, param->index());
2593 break;
2594 }
2595 }
2596
2597 if (outputFormat != nullptr) {
2598 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2599 ALOGD("[%s] onWorkDone: output format changed to %s",
2600 mName, outputFormat->debugString().c_str());
2601 (*buffers)->setFormat(outputFormat);
2602
2603 AString mediaType;
2604 if (outputFormat->findString(KEY_MIME, &mediaType)
2605 && mediaType == MIMETYPE_AUDIO_RAW) {
2606 int32_t channelCount;
2607 int32_t sampleRate;
2608 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
2609 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
2610 (*buffers)->updateSkipCutBuffer(sampleRate, channelCount);
2611 }
2612 }
2613 }
2614
2615 int32_t flags = 0;
2616 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
2617 flags |= MediaCodec::BUFFER_FLAG_EOS;
2618 ALOGV("[%s] onWorkDone: output EOS", mName);
2619 }
2620
2621 sp<MediaCodecBuffer> outBuffer;
2622 size_t index;
2623
2624 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2625 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2626 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2627 // shall correspond to the client input timesamp (in customOrdinal). By using the
2628 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2629 // produces multiple output.
2630 c2_cntr64_t timestamp =
2631 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2632 - work->input.ordinal.timestamp;
2633 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2634 mName,
2635 work->input.ordinal.customOrdinal.peekll(),
2636 work->input.ordinal.timestamp.peekll(),
2637 worklet->output.ordinal.timestamp.peekll(),
2638 timestamp.peekll());
2639
2640 if (initData != nullptr) {
2641 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2642 if ((*buffers)->registerCsd(initData, &index, &outBuffer) == OK) {
2643 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
2644 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
2645 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2646
2647 buffers.unlock();
2648 mCallback->onOutputBufferAvailable(index, outBuffer);
2649 buffers.lock();
2650 } else {
2651 ALOGD("[%s] onWorkDone: unable to register csd", mName);
2652 buffers.unlock();
2653 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2654 buffers.lock();
2655 return false;
2656 }
2657 }
2658
2659 if (!buffer && !flags) {
2660 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2661 mName, work->input.ordinal.frameIndex.peekull());
2662 return true;
2663 }
2664
2665 if (buffer) {
2666 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2667 // TODO: properly translate these to metadata
2668 switch (info->coreIndex().coreIndex()) {
2669 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
2670 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2PictureTypeKeyFrame) {
2671 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
2672 }
2673 break;
2674 default:
2675 break;
2676 }
2677 }
2678 }
2679
2680 {
2681 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2682 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
2683 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
2684 // Flush reorder stash
2685 reorder->setDepth(0);
2686 }
2687 }
2688 sendOutputBuffers();
2689 return true;
2690}
2691
2692void CCodecBufferChannel::sendOutputBuffers() {
2693 ReorderStash::Entry entry;
2694 sp<MediaCodecBuffer> outBuffer;
2695 size_t index;
2696
2697 while (true) {
2698 {
2699 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2700 if (!reorder->hasPending()) {
2701 break;
2702 }
2703 if (!reorder->pop(&entry)) {
2704 break;
2705 }
2706 }
2707 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2708 status_t err = (*buffers)->registerBuffer(entry.buffer, &index, &outBuffer);
2709 if (err != OK) {
2710 if (err != WOULD_BLOCK) {
2711 OutputBuffersArray *array = (OutputBuffersArray *)buffers->get();
2712 array->realloc(entry.buffer);
2713 mCCodecCallback->onOutputBuffersChanged();
2714 }
2715 buffers.unlock();
2716 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
2717 mReorderStash.lock()->defer(entry);
2718 return;
2719 }
2720 buffers.unlock();
2721
2722 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
2723 outBuffer->meta()->setInt32("flags", entry.flags);
2724 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu",
2725 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size());
2726 mCallback->onOutputBufferAvailable(index, outBuffer);
2727 }
2728}
2729
2730status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2731 static std::atomic_uint32_t surfaceGeneration{0};
2732 uint32_t generation = (getpid() << 10) |
2733 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2734 & ((1 << 10) - 1));
2735
2736 sp<IGraphicBufferProducer> producer;
2737 if (newSurface) {
2738 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Wonsik Kim078b58e2019-01-09 15:08:06 -08002739 newSurface->setMaxDequeuedBufferCount(mNumOutputSlots + kRenderingDepth);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002740 producer = newSurface->getIGraphicBufferProducer();
2741 producer->setGenerationNumber(generation);
2742 } else {
2743 ALOGE("[%s] setting output surface to null", mName);
2744 return INVALID_OPERATION;
2745 }
2746
2747 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2748 C2BlockPool::local_id_t outputPoolId;
2749 {
2750 Mutexed<BlockPools>::Locked pools(mBlockPools);
2751 outputPoolId = pools->outputPoolId;
2752 outputPoolIntf = pools->outputPoolIntf;
2753 }
2754
2755 if (outputPoolIntf) {
2756 if (mComponent->setOutputSurface(
2757 outputPoolId,
2758 producer,
2759 generation) != C2_OK) {
2760 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2761 return INVALID_OPERATION;
2762 }
2763 }
2764
2765 {
2766 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2767 output->surface = newSurface;
2768 output->generation = generation;
2769 }
2770
2771 return OK;
2772}
2773
2774void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2775 mMetaMode = mode;
2776}
2777
2778status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2779 // C2_OK is always translated to OK.
2780 if (c2s == C2_OK) {
2781 return OK;
2782 }
2783
2784 // Operation-dependent translation
2785 // TODO: Add as necessary
2786 switch (c2op) {
2787 case C2_OPERATION_Component_start:
2788 switch (c2s) {
2789 case C2_NO_MEMORY:
2790 return NO_MEMORY;
2791 default:
2792 return UNKNOWN_ERROR;
2793 }
2794 default:
2795 break;
2796 }
2797
2798 // Backup operation-agnostic translation
2799 switch (c2s) {
2800 case C2_BAD_INDEX:
2801 return BAD_INDEX;
2802 case C2_BAD_VALUE:
2803 return BAD_VALUE;
2804 case C2_BLOCKING:
2805 return WOULD_BLOCK;
2806 case C2_DUPLICATE:
2807 return ALREADY_EXISTS;
2808 case C2_NO_INIT:
2809 return NO_INIT;
2810 case C2_NO_MEMORY:
2811 return NO_MEMORY;
2812 case C2_NOT_FOUND:
2813 return NAME_NOT_FOUND;
2814 case C2_TIMED_OUT:
2815 return TIMED_OUT;
2816 case C2_BAD_STATE:
2817 case C2_CANCELED:
2818 case C2_CANNOT_DO:
2819 case C2_CORRUPTED:
2820 case C2_OMITTED:
2821 case C2_REFUSED:
2822 return UNKNOWN_ERROR;
2823 default:
2824 return -static_cast<status_t>(c2s);
2825 }
2826}
2827
2828} // namespace android