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