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