blob: 6842fa543dcd93a84739b34392e56b6c25a1785b [file] [log] [blame]
Pawin Vongmasa36653902018-11-15 00:10:25 -08001/*
2 * Copyright 2017, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodecBufferChannel"
19#include <utils/Log.h>
20
21#include <numeric>
22
23#include <C2AllocatorGralloc.h>
24#include <C2PlatformSupport.h>
25#include <C2BlockInternal.h>
26#include <C2Config.h>
27#include <C2Debug.h>
28
29#include <android/hardware/cas/native/1.0/IDescrambler.h>
30#include <android-base/stringprintf.h>
31#include <binder/MemoryDealer.h>
32#include <gui/Surface.h>
33#include <media/openmax/OMX_Core.h>
34#include <media/stagefright/foundation/ABuffer.h>
35#include <media/stagefright/foundation/ALookup.h>
36#include <media/stagefright/foundation/AMessage.h>
37#include <media/stagefright/foundation/AUtils.h>
38#include <media/stagefright/foundation/hexdump.h>
39#include <media/stagefright/MediaCodec.h>
40#include <media/stagefright/MediaCodecConstants.h>
41#include <media/MediaCodecBuffer.h>
42#include <system/window.h>
43
44#include "CCodecBufferChannel.h"
45#include "Codec2Buffer.h"
46#include "SkipCutBuffer.h"
47
48namespace android {
49
50using android::base::StringPrintf;
51using hardware::hidl_handle;
52using hardware::hidl_string;
53using hardware::hidl_vec;
54using namespace hardware::cas::V1_0;
55using namespace hardware::cas::native::V1_0;
56
57using CasStatus = hardware::cas::V1_0::Status;
58
59/**
60 * Base class for representation of buffers at one port.
61 */
62class CCodecBufferChannel::Buffers {
63public:
64 Buffers(const char *componentName, const char *name = "Buffers")
65 : mComponentName(componentName),
66 mChannelName(std::string(componentName) + ":" + name),
67 mName(mChannelName.c_str()) {
68 }
69 virtual ~Buffers() = default;
70
71 /**
72 * Set format for MediaCodec-facing buffers.
73 */
74 void setFormat(const sp<AMessage> &format) {
75 CHECK(format != nullptr);
76 mFormat = format;
77 }
78
79 /**
80 * Return a copy of current format.
81 */
82 sp<AMessage> dupFormat() {
83 return mFormat != nullptr ? mFormat->dup() : nullptr;
84 }
85
86 /**
87 * Returns true if the buffers are operating under array mode.
88 */
89 virtual bool isArrayMode() const { return false; }
90
91 /**
92 * Fills the vector with MediaCodecBuffer's if in array mode; otherwise,
93 * no-op.
94 */
95 virtual void getArray(Vector<sp<MediaCodecBuffer>> *) const {}
96
Wonsik Kimdf5dd142019-02-06 10:15:46 -080097 /**
98 * Return number of buffers the client owns.
99 */
100 virtual size_t numClientBuffers() const = 0;
101
Pawin Vongmasa36653902018-11-15 00:10:25 -0800102protected:
103 std::string mComponentName; ///< name of component for debugging
104 std::string mChannelName; ///< name of channel for debugging
105 const char *mName; ///< C-string version of channel name
106 // Format to be used for creating MediaCodec-facing buffers.
107 sp<AMessage> mFormat;
108
109private:
110 DISALLOW_EVIL_CONSTRUCTORS(Buffers);
111};
112
113class CCodecBufferChannel::InputBuffers : public CCodecBufferChannel::Buffers {
114public:
115 InputBuffers(const char *componentName, const char *name = "Input[]")
116 : Buffers(componentName, name) { }
117 virtual ~InputBuffers() = default;
118
119 /**
120 * Set a block pool to obtain input memory blocks.
121 */
122 void setPool(const std::shared_ptr<C2BlockPool> &pool) { mPool = pool; }
123
124 /**
125 * Get a new MediaCodecBuffer for input and its corresponding index.
126 * Returns false if no new buffer can be obtained at the moment.
127 */
128 virtual bool requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) = 0;
129
130 /**
131 * Release the buffer obtained from requestNewBuffer() and get the
132 * associated C2Buffer object back. Returns true if the buffer was on file
133 * and released successfully.
134 */
135 virtual bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -0800136 const sp<MediaCodecBuffer> &buffer,
137 std::shared_ptr<C2Buffer> *c2buffer,
138 bool release) = 0;
Pawin Vongmasa36653902018-11-15 00:10:25 -0800139
140 /**
141 * Release the buffer that is no longer used by the codec process. Return
142 * true if and only if the buffer was on file and released successfully.
143 */
144 virtual bool expireComponentBuffer(
145 const std::shared_ptr<C2Buffer> &c2buffer) = 0;
146
147 /**
148 * Flush internal state. After this call, no index or buffer previously
149 * returned from requestNewBuffer() is valid.
150 */
151 virtual void flush() = 0;
152
153 /**
154 * Return array-backed version of input buffers. The returned object
155 * shall retain the internal state so that it will honor index and
156 * buffer from previous calls of requestNewBuffer().
157 */
158 virtual std::unique_ptr<InputBuffers> toArrayMode(size_t size) = 0;
159
160protected:
161 // Pool to obtain blocks for input buffers.
162 std::shared_ptr<C2BlockPool> mPool;
163
164private:
165 DISALLOW_EVIL_CONSTRUCTORS(InputBuffers);
166};
167
168class CCodecBufferChannel::OutputBuffers : public CCodecBufferChannel::Buffers {
169public:
170 OutputBuffers(const char *componentName, const char *name = "Output")
171 : Buffers(componentName, name) { }
172 virtual ~OutputBuffers() = default;
173
174 /**
175 * Register output C2Buffer from the component and obtain corresponding
176 * index and MediaCodecBuffer object. Returns false if registration
177 * fails.
178 */
179 virtual status_t registerBuffer(
180 const std::shared_ptr<C2Buffer> &buffer,
181 size_t *index,
182 sp<MediaCodecBuffer> *clientBuffer) = 0;
183
184 /**
185 * Register codec specific data as a buffer to be consistent with
186 * MediaCodec behavior.
187 */
188 virtual status_t registerCsd(
189 const C2StreamCsdInfo::output * /* csd */,
190 size_t * /* index */,
191 sp<MediaCodecBuffer> * /* clientBuffer */) = 0;
192
193 /**
194 * Release the buffer obtained from registerBuffer() and get the
195 * associated C2Buffer object back. Returns true if the buffer was on file
196 * and released successfully.
197 */
198 virtual bool releaseBuffer(
199 const sp<MediaCodecBuffer> &buffer, std::shared_ptr<C2Buffer> *c2buffer) = 0;
200
201 /**
202 * Flush internal state. After this call, no index or buffer previously
203 * returned from registerBuffer() is valid.
204 */
205 virtual void flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) = 0;
206
207 /**
208 * Return array-backed version of output buffers. The returned object
209 * shall retain the internal state so that it will honor index and
210 * buffer from previous calls of registerBuffer().
211 */
212 virtual std::unique_ptr<OutputBuffers> toArrayMode(size_t size) = 0;
213
214 /**
215 * Initialize SkipCutBuffer object.
216 */
217 void initSkipCutBuffer(
218 int32_t delay, int32_t padding, int32_t sampleRate, int32_t channelCount) {
219 CHECK(mSkipCutBuffer == nullptr);
220 mDelay = delay;
221 mPadding = padding;
222 mSampleRate = sampleRate;
223 setSkipCutBuffer(delay, padding, channelCount);
224 }
225
226 /**
227 * Update the SkipCutBuffer object. No-op if it's never initialized.
228 */
229 void updateSkipCutBuffer(int32_t sampleRate, int32_t channelCount) {
230 if (mSkipCutBuffer == nullptr) {
231 return;
232 }
233 int32_t delay = mDelay;
234 int32_t padding = mPadding;
235 if (sampleRate != mSampleRate) {
236 delay = ((int64_t)delay * sampleRate) / mSampleRate;
237 padding = ((int64_t)padding * sampleRate) / mSampleRate;
238 }
239 setSkipCutBuffer(delay, padding, channelCount);
240 }
241
242 /**
243 * Submit buffer to SkipCutBuffer object, if initialized.
244 */
245 void submit(const sp<MediaCodecBuffer> &buffer) {
246 if (mSkipCutBuffer != nullptr) {
247 mSkipCutBuffer->submit(buffer);
248 }
249 }
250
251 /**
252 * Transfer SkipCutBuffer object to the other Buffers object.
253 */
254 void transferSkipCutBuffer(const sp<SkipCutBuffer> &scb) {
255 mSkipCutBuffer = scb;
256 }
257
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
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001229 size_t numClientBuffers() const final {
1230 return mImpl.numClientBuffers();
1231 }
1232
Pawin Vongmasa36653902018-11-15 00:10:25 -08001233private:
1234 BuffersArrayImpl mImpl;
1235};
1236
1237class FlexOutputBuffers : public CCodecBufferChannel::OutputBuffers {
1238public:
1239 FlexOutputBuffers(const char *componentName, const char *name = "Output[]")
1240 : OutputBuffers(componentName, name),
1241 mImpl(mName) { }
1242
1243 status_t registerBuffer(
1244 const std::shared_ptr<C2Buffer> &buffer,
1245 size_t *index,
1246 sp<MediaCodecBuffer> *clientBuffer) override {
1247 sp<Codec2Buffer> newBuffer = wrap(buffer);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001248 if (newBuffer == nullptr) {
1249 return NO_MEMORY;
1250 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001251 newBuffer->setFormat(mFormat);
1252 *index = mImpl.assignSlot(newBuffer);
1253 *clientBuffer = newBuffer;
1254 ALOGV("[%s] registered buffer %zu", mName, *index);
1255 return OK;
1256 }
1257
1258 status_t registerCsd(
1259 const C2StreamCsdInfo::output *csd,
1260 size_t *index,
1261 sp<MediaCodecBuffer> *clientBuffer) final {
1262 sp<Codec2Buffer> newBuffer = new LocalLinearBuffer(
1263 mFormat, ABuffer::CreateAsCopy(csd->m.value, csd->flexCount()));
1264 *index = mImpl.assignSlot(newBuffer);
1265 *clientBuffer = newBuffer;
1266 return OK;
1267 }
1268
1269 bool releaseBuffer(
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001270 const sp<MediaCodecBuffer> &buffer,
1271 std::shared_ptr<C2Buffer> *c2buffer) override {
1272 return mImpl.releaseSlot(buffer, c2buffer, true);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001273 }
1274
1275 void flush(
1276 const std::list<std::unique_ptr<C2Work>> &flushedWork) override {
1277 (void) flushedWork;
1278 // This is no-op by default unless we're in array mode where we need to keep
1279 // track of the flushed work.
1280 }
1281
1282 std::unique_ptr<CCodecBufferChannel::OutputBuffers> toArrayMode(
1283 size_t size) override {
1284 std::unique_ptr<OutputBuffersArray> array(new OutputBuffersArray(mComponentName.c_str()));
1285 array->setFormat(mFormat);
1286 array->transferSkipCutBuffer(mSkipCutBuffer);
1287 array->initialize(
1288 mImpl,
1289 size,
1290 [this]() { return allocateArrayBuffer(); });
1291 return std::move(array);
1292 }
1293
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001294 size_t numClientBuffers() const final {
1295 return mImpl.numClientBuffers();
1296 }
1297
Pawin Vongmasa36653902018-11-15 00:10:25 -08001298 /**
1299 * Return an appropriate Codec2Buffer object for the type of buffers.
1300 *
1301 * \param buffer C2Buffer object to wrap.
1302 *
1303 * \return appropriate Codec2Buffer object to wrap |buffer|.
1304 */
1305 virtual sp<Codec2Buffer> wrap(const std::shared_ptr<C2Buffer> &buffer) = 0;
1306
1307 /**
1308 * Return an appropriate Codec2Buffer object for the type of buffers, to be
1309 * used as an empty array buffer.
1310 *
1311 * \return appropriate Codec2Buffer object which can copy() from C2Buffers.
1312 */
1313 virtual sp<Codec2Buffer> allocateArrayBuffer() = 0;
1314
1315private:
1316 FlexBuffersImpl mImpl;
1317};
1318
1319class LinearOutputBuffers : public FlexOutputBuffers {
1320public:
1321 LinearOutputBuffers(const char *componentName, const char *name = "1D-Output")
1322 : FlexOutputBuffers(componentName, name) { }
1323
1324 void flush(
1325 const std::list<std::unique_ptr<C2Work>> &flushedWork) override {
1326 if (mSkipCutBuffer != nullptr) {
1327 mSkipCutBuffer->clear();
1328 }
1329 FlexOutputBuffers::flush(flushedWork);
1330 }
1331
1332 sp<Codec2Buffer> wrap(const std::shared_ptr<C2Buffer> &buffer) override {
1333 if (buffer == nullptr) {
1334 ALOGV("[%s] using a dummy buffer", mName);
1335 return new LocalLinearBuffer(mFormat, new ABuffer(0));
1336 }
1337 if (buffer->data().type() != C2BufferData::LINEAR) {
1338 ALOGV("[%s] non-linear buffer %d", mName, buffer->data().type());
1339 // We expect linear output buffers from the component.
1340 return nullptr;
1341 }
1342 if (buffer->data().linearBlocks().size() != 1u) {
1343 ALOGV("[%s] no linear buffers", mName);
1344 // We expect one and only one linear block from the component.
1345 return nullptr;
1346 }
1347 sp<Codec2Buffer> clientBuffer = ConstLinearBlockBuffer::Allocate(mFormat, buffer);
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001348 if (clientBuffer == nullptr) {
1349 ALOGD("[%s] ConstLinearBlockBuffer::Allocate failed", mName);
1350 return nullptr;
1351 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001352 submit(clientBuffer);
1353 return clientBuffer;
1354 }
1355
1356 sp<Codec2Buffer> allocateArrayBuffer() override {
1357 // TODO: proper max output size
1358 return new LocalLinearBuffer(mFormat, new ABuffer(kLinearBufferSize));
1359 }
1360};
1361
1362class GraphicOutputBuffers : public FlexOutputBuffers {
1363public:
1364 GraphicOutputBuffers(const char *componentName, const char *name = "2D-Output")
1365 : FlexOutputBuffers(componentName, name) { }
1366
1367 sp<Codec2Buffer> wrap(const std::shared_ptr<C2Buffer> &buffer) override {
1368 return new DummyContainerBuffer(mFormat, buffer);
1369 }
1370
1371 sp<Codec2Buffer> allocateArrayBuffer() override {
1372 return new DummyContainerBuffer(mFormat);
1373 }
1374};
1375
1376class RawGraphicOutputBuffers : public FlexOutputBuffers {
1377public:
Wonsik Kim078b58e2019-01-09 15:08:06 -08001378 RawGraphicOutputBuffers(
1379 size_t numOutputSlots, const char *componentName, const char *name = "2D-BB-Output")
Pawin Vongmasa36653902018-11-15 00:10:25 -08001380 : FlexOutputBuffers(componentName, name),
1381 mLocalBufferPool(LocalBufferPool::Create(
Wonsik Kim078b58e2019-01-09 15:08:06 -08001382 kMaxLinearBufferSize * numOutputSlots)) { }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001383 ~RawGraphicOutputBuffers() override = default;
1384
1385 sp<Codec2Buffer> wrap(const std::shared_ptr<C2Buffer> &buffer) override {
1386 if (buffer == nullptr) {
1387 sp<Codec2Buffer> c2buffer = ConstGraphicBlockBuffer::AllocateEmpty(
1388 mFormat,
1389 [lbp = mLocalBufferPool](size_t capacity) {
1390 return lbp->newBuffer(capacity);
1391 });
Wonsik Kim186fdbf2019-01-29 13:30:01 -08001392 if (c2buffer == nullptr) {
1393 ALOGD("[%s] ConstGraphicBlockBuffer::AllocateEmpty failed", mName);
1394 return nullptr;
1395 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001396 c2buffer->setRange(0, 0);
1397 return c2buffer;
1398 } else {
1399 return ConstGraphicBlockBuffer::Allocate(
1400 mFormat,
1401 buffer,
1402 [lbp = mLocalBufferPool](size_t capacity) {
1403 return lbp->newBuffer(capacity);
1404 });
1405 }
1406 }
1407
1408 sp<Codec2Buffer> allocateArrayBuffer() override {
1409 return ConstGraphicBlockBuffer::AllocateEmpty(
1410 mFormat,
1411 [lbp = mLocalBufferPool](size_t capacity) {
1412 return lbp->newBuffer(capacity);
1413 });
1414 }
1415
1416private:
1417 std::shared_ptr<LocalBufferPool> mLocalBufferPool;
1418};
1419
1420} // namespace
1421
1422CCodecBufferChannel::QueueGuard::QueueGuard(
1423 CCodecBufferChannel::QueueSync &sync) : mSync(sync) {
1424 Mutex::Autolock l(mSync.mGuardLock);
1425 // At this point it's guaranteed that mSync is not under state transition,
1426 // as we are holding its mutex.
1427
1428 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
1429 if (count->value == -1) {
1430 mRunning = false;
1431 } else {
1432 ++count->value;
1433 mRunning = true;
1434 }
1435}
1436
1437CCodecBufferChannel::QueueGuard::~QueueGuard() {
1438 if (mRunning) {
1439 // We are not holding mGuardLock at this point so that QueueSync::stop() can
1440 // keep holding the lock until mCount reaches zero.
1441 Mutexed<CCodecBufferChannel::QueueSync::Counter>::Locked count(mSync.mCount);
1442 --count->value;
1443 count->cond.broadcast();
1444 }
1445}
1446
1447void CCodecBufferChannel::QueueSync::start() {
1448 Mutex::Autolock l(mGuardLock);
1449 // If stopped, it goes to running state; otherwise no-op.
1450 Mutexed<Counter>::Locked count(mCount);
1451 if (count->value == -1) {
1452 count->value = 0;
1453 }
1454}
1455
1456void CCodecBufferChannel::QueueSync::stop() {
1457 Mutex::Autolock l(mGuardLock);
1458 Mutexed<Counter>::Locked count(mCount);
1459 if (count->value == -1) {
1460 // no-op
1461 return;
1462 }
1463 // Holding mGuardLock here blocks creation of additional QueueGuard objects, so
1464 // mCount can only decrement. In other words, threads that acquired the lock
1465 // are allowed to finish execution but additional threads trying to acquire
1466 // the lock at this point will block, and then get QueueGuard at STOPPED
1467 // state.
1468 while (count->value != 0) {
1469 count.waitForCondition(count->cond);
1470 }
1471 count->value = -1;
1472}
1473
Pawin Vongmasa36653902018-11-15 00:10:25 -08001474// CCodecBufferChannel::ReorderStash
1475
1476CCodecBufferChannel::ReorderStash::ReorderStash() {
1477 clear();
1478}
1479
1480void CCodecBufferChannel::ReorderStash::clear() {
1481 mPending.clear();
1482 mStash.clear();
1483 mDepth = 0;
1484 mKey = C2Config::ORDINAL;
1485}
1486
Wonsik Kim6897f222019-01-30 13:29:24 -08001487void CCodecBufferChannel::ReorderStash::flush() {
1488 mPending.clear();
1489 mStash.clear();
1490}
1491
Pawin Vongmasa36653902018-11-15 00:10:25 -08001492void CCodecBufferChannel::ReorderStash::setDepth(uint32_t depth) {
1493 mPending.splice(mPending.end(), mStash);
1494 mDepth = depth;
1495}
1496void CCodecBufferChannel::ReorderStash::setKey(C2Config::ordinal_key_t key) {
1497 mPending.splice(mPending.end(), mStash);
1498 mKey = key;
1499}
1500
1501bool CCodecBufferChannel::ReorderStash::pop(Entry *entry) {
1502 if (mPending.empty()) {
1503 return false;
1504 }
1505 entry->buffer = mPending.front().buffer;
1506 entry->timestamp = mPending.front().timestamp;
1507 entry->flags = mPending.front().flags;
1508 entry->ordinal = mPending.front().ordinal;
1509 mPending.pop_front();
1510 return true;
1511}
1512
1513void CCodecBufferChannel::ReorderStash::emplace(
1514 const std::shared_ptr<C2Buffer> &buffer,
1515 int64_t timestamp,
1516 int32_t flags,
1517 const C2WorkOrdinalStruct &ordinal) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001518 auto it = mStash.begin();
1519 for (; it != mStash.end(); ++it) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001520 if (less(ordinal, it->ordinal)) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08001521 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001522 }
1523 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08001524 mStash.emplace(it, buffer, timestamp, flags, ordinal);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001525 while (!mStash.empty() && mStash.size() > mDepth) {
1526 mPending.push_back(mStash.front());
1527 mStash.pop_front();
1528 }
1529}
1530
1531void CCodecBufferChannel::ReorderStash::defer(
1532 const CCodecBufferChannel::ReorderStash::Entry &entry) {
1533 mPending.push_front(entry);
1534}
1535
1536bool CCodecBufferChannel::ReorderStash::hasPending() const {
1537 return !mPending.empty();
1538}
1539
1540bool CCodecBufferChannel::ReorderStash::less(
1541 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) {
1542 switch (mKey) {
1543 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
1544 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
1545 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
1546 default:
1547 ALOGD("Unrecognized key; default to timestamp");
1548 return o1.frameIndex < o2.frameIndex;
1549 }
1550}
1551
1552// CCodecBufferChannel
1553
1554CCodecBufferChannel::CCodecBufferChannel(
1555 const std::shared_ptr<CCodecCallback> &callback)
1556 : mHeapSeqNum(-1),
1557 mCCodecCallback(callback),
Wonsik Kim078b58e2019-01-09 15:08:06 -08001558 mNumInputSlots(kSmoothnessFactor),
1559 mNumOutputSlots(kSmoothnessFactor),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001560 mFrameIndex(0u),
1561 mFirstValidFrameIndex(0u),
1562 mMetaMode(MODE_NONE),
Pawin Vongmasa36653902018-11-15 00:10:25 -08001563 mInputMetEos(false) {
1564 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1565 buffers->reset(new DummyInputBuffers(""));
1566}
1567
1568CCodecBufferChannel::~CCodecBufferChannel() {
1569 if (mCrypto != nullptr && mDealer != nullptr && mHeapSeqNum >= 0) {
1570 mCrypto->unsetHeap(mHeapSeqNum);
1571 }
1572}
1573
1574void CCodecBufferChannel::setComponent(
1575 const std::shared_ptr<Codec2Client::Component> &component) {
1576 mComponent = component;
1577 mComponentName = component->getName() + StringPrintf("#%d", int(uintptr_t(component.get()) % 997));
1578 mName = mComponentName.c_str();
1579}
1580
1581status_t CCodecBufferChannel::setInputSurface(
1582 const std::shared_ptr<InputSurfaceWrapper> &surface) {
1583 ALOGV("[%s] setInputSurface", mName);
1584 mInputSurface = surface;
1585 return mInputSurface->connect(mComponent);
1586}
1587
1588status_t CCodecBufferChannel::signalEndOfInputStream() {
1589 if (mInputSurface == nullptr) {
1590 return INVALID_OPERATION;
1591 }
1592 return mInputSurface->signalEndOfInputStream();
1593}
1594
1595status_t CCodecBufferChannel::queueInputBufferInternal(const sp<MediaCodecBuffer> &buffer) {
1596 int64_t timeUs;
1597 CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1598
1599 if (mInputMetEos) {
1600 ALOGD("[%s] buffers after EOS ignored (%lld us)", mName, (long long)timeUs);
1601 return OK;
1602 }
1603
1604 int32_t flags = 0;
1605 int32_t tmp = 0;
1606 bool eos = false;
1607 if (buffer->meta()->findInt32("eos", &tmp) && tmp) {
1608 eos = true;
1609 mInputMetEos = true;
1610 ALOGV("[%s] input EOS", mName);
1611 }
1612 if (buffer->meta()->findInt32("csd", &tmp) && tmp) {
1613 flags |= C2FrameData::FLAG_CODEC_CONFIG;
1614 }
1615 ALOGV("[%s] queueInputBuffer: buffer->size() = %zu", mName, buffer->size());
1616 std::unique_ptr<C2Work> work(new C2Work);
1617 work->input.ordinal.timestamp = timeUs;
1618 work->input.ordinal.frameIndex = mFrameIndex++;
1619 // WORKAROUND: until codecs support handling work after EOS and max output sizing, use timestamp
1620 // manipulation to achieve image encoding via video codec, and to constrain encoded output.
1621 // Keep client timestamp in customOrdinal
1622 work->input.ordinal.customOrdinal = timeUs;
1623 work->input.buffers.clear();
1624
Wonsik Kimab34ed62019-01-31 15:28:46 -08001625 uint64_t queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
1626 std::vector<std::shared_ptr<C2Buffer>> queuedBuffers;
1627
Pawin Vongmasa36653902018-11-15 00:10:25 -08001628 if (buffer->size() > 0u) {
1629 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1630 std::shared_ptr<C2Buffer> c2buffer;
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001631 if (!(*buffers)->releaseBuffer(buffer, &c2buffer, false)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001632 return -ENOENT;
1633 }
1634 work->input.buffers.push_back(c2buffer);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001635 queuedBuffers.push_back(c2buffer);
1636 } else if (eos) {
1637 flags |= C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001638 }
1639 work->input.flags = (C2FrameData::flags_t)flags;
1640 // TODO: fill info's
1641
1642 work->input.configUpdate = std::move(mParamsToBeSet);
1643 work->worklets.clear();
1644 work->worklets.emplace_back(new C2Worklet);
1645
1646 std::list<std::unique_ptr<C2Work>> items;
1647 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -08001648 mPipelineWatcher.lock()->onWorkQueued(
1649 queuedFrameIndex,
1650 std::move(queuedBuffers),
1651 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001652 c2_status_t err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001653 if (err != C2_OK) {
1654 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
1655 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001656
1657 if (err == C2_OK && eos && buffer->size() > 0u) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001658 work.reset(new C2Work);
1659 work->input.ordinal.timestamp = timeUs;
1660 work->input.ordinal.frameIndex = mFrameIndex++;
1661 // WORKAROUND: keep client timestamp in customOrdinal
1662 work->input.ordinal.customOrdinal = timeUs;
1663 work->input.buffers.clear();
1664 work->input.flags = C2FrameData::FLAG_END_OF_STREAM;
Pawin Vongmasa1c75a232019-01-09 04:41:52 -08001665 work->worklets.emplace_back(new C2Worklet);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001666
Wonsik Kimab34ed62019-01-31 15:28:46 -08001667 queuedFrameIndex = work->input.ordinal.frameIndex.peeku();
1668 queuedBuffers.clear();
1669
Pawin Vongmasa36653902018-11-15 00:10:25 -08001670 items.clear();
1671 items.push_back(std::move(work));
Wonsik Kimab34ed62019-01-31 15:28:46 -08001672
1673 mPipelineWatcher.lock()->onWorkQueued(
1674 queuedFrameIndex,
1675 std::move(queuedBuffers),
1676 PipelineWatcher::Clock::now());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001677 err = mComponent->queue(&items);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001678 if (err != C2_OK) {
1679 mPipelineWatcher.lock()->onWorkDone(queuedFrameIndex);
1680 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001681 }
1682 if (err == C2_OK) {
Pawin Vongmasa1f213362019-01-24 06:59:16 -08001683 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
1684 bool released = (*buffers)->releaseBuffer(buffer, nullptr, true);
1685 ALOGV("[%s] queueInputBuffer: buffer %sreleased", mName, released ? "" : "not ");
Pawin Vongmasa36653902018-11-15 00:10:25 -08001686 }
1687
1688 feedInputBufferIfAvailableInternal();
1689 return err;
1690}
1691
1692status_t CCodecBufferChannel::setParameters(std::vector<std::unique_ptr<C2Param>> &params) {
1693 QueueGuard guard(mSync);
1694 if (!guard.isRunning()) {
1695 ALOGD("[%s] setParameters is only supported in the running state.", mName);
1696 return -ENOSYS;
1697 }
1698 mParamsToBeSet.insert(mParamsToBeSet.end(),
1699 std::make_move_iterator(params.begin()),
1700 std::make_move_iterator(params.end()));
1701 params.clear();
1702 return OK;
1703}
1704
1705status_t CCodecBufferChannel::queueInputBuffer(const sp<MediaCodecBuffer> &buffer) {
1706 QueueGuard guard(mSync);
1707 if (!guard.isRunning()) {
1708 ALOGD("[%s] No more buffers should be queued at current state.", mName);
1709 return -ENOSYS;
1710 }
1711 return queueInputBufferInternal(buffer);
1712}
1713
1714status_t CCodecBufferChannel::queueSecureInputBuffer(
1715 const sp<MediaCodecBuffer> &buffer, bool secure, const uint8_t *key,
1716 const uint8_t *iv, CryptoPlugin::Mode mode, CryptoPlugin::Pattern pattern,
1717 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
1718 AString *errorDetailMsg) {
1719 QueueGuard guard(mSync);
1720 if (!guard.isRunning()) {
1721 ALOGD("[%s] No more buffers should be queued at current state.", mName);
1722 return -ENOSYS;
1723 }
1724
1725 if (!hasCryptoOrDescrambler()) {
1726 return -ENOSYS;
1727 }
1728 sp<EncryptedLinearBlockBuffer> encryptedBuffer((EncryptedLinearBlockBuffer *)buffer.get());
1729
1730 ssize_t result = -1;
1731 ssize_t codecDataOffset = 0;
1732 if (mCrypto != nullptr) {
1733 ICrypto::DestinationBuffer destination;
1734 if (secure) {
1735 destination.mType = ICrypto::kDestinationTypeNativeHandle;
1736 destination.mHandle = encryptedBuffer->handle();
1737 } else {
1738 destination.mType = ICrypto::kDestinationTypeSharedMemory;
1739 destination.mSharedMemory = mDecryptDestination;
1740 }
1741 ICrypto::SourceBuffer source;
1742 encryptedBuffer->fillSourceBuffer(&source);
1743 result = mCrypto->decrypt(
1744 key, iv, mode, pattern, source, buffer->offset(),
1745 subSamples, numSubSamples, destination, errorDetailMsg);
1746 if (result < 0) {
1747 return result;
1748 }
1749 if (destination.mType == ICrypto::kDestinationTypeSharedMemory) {
1750 encryptedBuffer->copyDecryptedContent(mDecryptDestination, result);
1751 }
1752 } else {
1753 // Here we cast CryptoPlugin::SubSample to hardware::cas::native::V1_0::SubSample
1754 // directly, the structure definitions should match as checked in DescramblerImpl.cpp.
1755 hidl_vec<SubSample> hidlSubSamples;
1756 hidlSubSamples.setToExternal((SubSample *)subSamples, numSubSamples, false /*own*/);
1757
1758 hardware::cas::native::V1_0::SharedBuffer srcBuffer;
1759 encryptedBuffer->fillSourceBuffer(&srcBuffer);
1760
1761 DestinationBuffer dstBuffer;
1762 if (secure) {
1763 dstBuffer.type = BufferType::NATIVE_HANDLE;
1764 dstBuffer.secureMemory = hidl_handle(encryptedBuffer->handle());
1765 } else {
1766 dstBuffer.type = BufferType::SHARED_MEMORY;
1767 dstBuffer.nonsecureMemory = srcBuffer;
1768 }
1769
1770 CasStatus status = CasStatus::OK;
1771 hidl_string detailedError;
1772 ScramblingControl sctrl = ScramblingControl::UNSCRAMBLED;
1773
1774 if (key != nullptr) {
1775 sctrl = (ScramblingControl)key[0];
1776 // Adjust for the PES offset
1777 codecDataOffset = key[2] | (key[3] << 8);
1778 }
1779
1780 auto returnVoid = mDescrambler->descramble(
1781 sctrl,
1782 hidlSubSamples,
1783 srcBuffer,
1784 0,
1785 dstBuffer,
1786 0,
1787 [&status, &result, &detailedError] (
1788 CasStatus _status, uint32_t _bytesWritten,
1789 const hidl_string& _detailedError) {
1790 status = _status;
1791 result = (ssize_t)_bytesWritten;
1792 detailedError = _detailedError;
1793 });
1794
1795 if (!returnVoid.isOk() || status != CasStatus::OK || result < 0) {
1796 ALOGI("[%s] descramble failed, trans=%s, status=%d, result=%zd",
1797 mName, returnVoid.description().c_str(), status, result);
1798 return UNKNOWN_ERROR;
1799 }
1800
1801 if (result < codecDataOffset) {
1802 ALOGD("invalid codec data offset: %zd, result %zd", codecDataOffset, result);
1803 return BAD_VALUE;
1804 }
1805
1806 ALOGV("[%s] descramble succeeded, %zd bytes", mName, result);
1807
1808 if (dstBuffer.type == BufferType::SHARED_MEMORY) {
1809 encryptedBuffer->copyDecryptedContentFromMemory(result);
1810 }
1811 }
1812
1813 buffer->setRange(codecDataOffset, result - codecDataOffset);
1814 return queueInputBufferInternal(buffer);
1815}
1816
1817void CCodecBufferChannel::feedInputBufferIfAvailable() {
1818 QueueGuard guard(mSync);
1819 if (!guard.isRunning()) {
1820 ALOGV("[%s] We're not running --- no input buffer reported", mName);
1821 return;
1822 }
1823 feedInputBufferIfAvailableInternal();
1824}
1825
1826void CCodecBufferChannel::feedInputBufferIfAvailableInternal() {
Wonsik Kimdf5dd142019-02-06 10:15:46 -08001827 if (mInputMetEos ||
1828 mReorderStash.lock()->hasPending() ||
1829 mPipelineWatcher.lock()->pipelineFull()) {
1830 return;
1831 } else {
1832 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1833 if ((*buffers)->numClientBuffers() >= mNumOutputSlots) {
1834 return;
1835 }
1836 }
1837 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001838 sp<MediaCodecBuffer> inBuffer;
1839 size_t index;
1840 {
1841 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Wonsik Kimab34ed62019-01-31 15:28:46 -08001842 if ((*buffers)->numClientBuffers() >= mNumInputSlots) {
1843 return;
1844 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001845 if (!(*buffers)->requestNewBuffer(&index, &inBuffer)) {
1846 ALOGV("[%s] no new buffer available", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001847 break;
1848 }
1849 }
1850 ALOGV("[%s] new input index = %zu [%p]", mName, index, inBuffer.get());
1851 mCallback->onInputBufferAvailable(index, inBuffer);
1852 }
1853}
1854
1855status_t CCodecBufferChannel::renderOutputBuffer(
1856 const sp<MediaCodecBuffer> &buffer, int64_t timestampNs) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001857 ALOGV("[%s] renderOutputBuffer: %p", mName, buffer.get());
Pawin Vongmasa36653902018-11-15 00:10:25 -08001858 std::shared_ptr<C2Buffer> c2Buffer;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001859 bool released = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08001860 {
1861 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
1862 if (*buffers) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001863 released = (*buffers)->releaseBuffer(buffer, &c2Buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08001864 }
1865 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001866 // NOTE: some apps try to releaseOutputBuffer() with timestamp and/or render
1867 // set to true.
1868 sendOutputBuffers();
1869 // input buffer feeding may have been gated by pending output buffers
1870 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08001871 if (!c2Buffer) {
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001872 if (released) {
1873 ALOGD("[%s] The app is calling releaseOutputBuffer() with "
1874 "timestamp or render=true with non-video buffers. Apps should "
1875 "call releaseOutputBuffer() with render=false for those.",
1876 mName);
1877 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001878 return INVALID_OPERATION;
1879 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08001880
1881#if 0
1882 const std::vector<std::shared_ptr<const C2Info>> infoParams = c2Buffer->info();
1883 ALOGV("[%s] queuing gfx buffer with %zu infos", mName, infoParams.size());
1884 for (const std::shared_ptr<const C2Info> &info : infoParams) {
1885 AString res;
1886 for (size_t ix = 0; ix + 3 < info->size(); ix += 4) {
1887 if (ix) res.append(", ");
1888 res.append(*((int32_t*)info.get() + (ix / 4)));
1889 }
1890 ALOGV(" [%s]", res.c_str());
1891 }
1892#endif
1893 std::shared_ptr<const C2StreamRotationInfo::output> rotation =
1894 std::static_pointer_cast<const C2StreamRotationInfo::output>(
1895 c2Buffer->getInfo(C2StreamRotationInfo::output::PARAM_TYPE));
1896 bool flip = rotation && (rotation->flip & 1);
1897 uint32_t quarters = ((rotation ? rotation->value : 0) / 90) & 3;
1898 uint32_t transform = 0;
1899 switch (quarters) {
1900 case 0: // no rotation
1901 transform = flip ? HAL_TRANSFORM_FLIP_H : 0;
1902 break;
1903 case 1: // 90 degrees counter-clockwise
1904 transform = flip ? (HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90)
1905 : HAL_TRANSFORM_ROT_270;
1906 break;
1907 case 2: // 180 degrees
1908 transform = flip ? HAL_TRANSFORM_FLIP_V : HAL_TRANSFORM_ROT_180;
1909 break;
1910 case 3: // 90 degrees clockwise
1911 transform = flip ? (HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90)
1912 : HAL_TRANSFORM_ROT_90;
1913 break;
1914 }
1915
1916 std::shared_ptr<const C2StreamSurfaceScalingInfo::output> surfaceScaling =
1917 std::static_pointer_cast<const C2StreamSurfaceScalingInfo::output>(
1918 c2Buffer->getInfo(C2StreamSurfaceScalingInfo::output::PARAM_TYPE));
1919 uint32_t videoScalingMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
1920 if (surfaceScaling) {
1921 videoScalingMode = surfaceScaling->value;
1922 }
1923
1924 // Use dataspace from format as it has the default aspects already applied
1925 android_dataspace_t dataSpace = HAL_DATASPACE_UNKNOWN; // this is 0
1926 (void)buffer->format()->findInt32("android._dataspace", (int32_t *)&dataSpace);
1927
1928 // HDR static info
1929 std::shared_ptr<const C2StreamHdrStaticInfo::output> hdrStaticInfo =
1930 std::static_pointer_cast<const C2StreamHdrStaticInfo::output>(
1931 c2Buffer->getInfo(C2StreamHdrStaticInfo::output::PARAM_TYPE));
1932
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001933 // HDR10 plus info
1934 std::shared_ptr<const C2StreamHdr10PlusInfo::output> hdr10PlusInfo =
1935 std::static_pointer_cast<const C2StreamHdr10PlusInfo::output>(
1936 c2Buffer->getInfo(C2StreamHdr10PlusInfo::output::PARAM_TYPE));
1937
Pawin Vongmasa36653902018-11-15 00:10:25 -08001938 {
1939 Mutexed<OutputSurface>::Locked output(mOutputSurface);
1940 if (output->surface == nullptr) {
1941 ALOGI("[%s] cannot render buffer without surface", mName);
1942 return OK;
1943 }
1944 }
1945
1946 std::vector<C2ConstGraphicBlock> blocks = c2Buffer->data().graphicBlocks();
1947 if (blocks.size() != 1u) {
1948 ALOGD("[%s] expected 1 graphic block, but got %zu", mName, blocks.size());
1949 return UNKNOWN_ERROR;
1950 }
1951 const C2ConstGraphicBlock &block = blocks.front();
1952
1953 // TODO: revisit this after C2Fence implementation.
1954 android::IGraphicBufferProducer::QueueBufferInput qbi(
1955 timestampNs,
1956 false, // droppable
1957 dataSpace,
1958 Rect(blocks.front().crop().left,
1959 blocks.front().crop().top,
1960 blocks.front().crop().right(),
1961 blocks.front().crop().bottom()),
1962 videoScalingMode,
1963 transform,
1964 Fence::NO_FENCE, 0);
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001965 if (hdrStaticInfo || hdr10PlusInfo) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08001966 HdrMetadata hdr;
Pawin Vongmasa8be93112018-12-11 14:01:42 -08001967 if (hdrStaticInfo) {
1968 struct android_smpte2086_metadata smpte2086_meta = {
1969 .displayPrimaryRed = {
1970 hdrStaticInfo->mastering.red.x, hdrStaticInfo->mastering.red.y
1971 },
1972 .displayPrimaryGreen = {
1973 hdrStaticInfo->mastering.green.x, hdrStaticInfo->mastering.green.y
1974 },
1975 .displayPrimaryBlue = {
1976 hdrStaticInfo->mastering.blue.x, hdrStaticInfo->mastering.blue.y
1977 },
1978 .whitePoint = {
1979 hdrStaticInfo->mastering.white.x, hdrStaticInfo->mastering.white.y
1980 },
1981 .maxLuminance = hdrStaticInfo->mastering.maxLuminance,
1982 .minLuminance = hdrStaticInfo->mastering.minLuminance,
1983 };
1984
1985 struct android_cta861_3_metadata cta861_meta = {
1986 .maxContentLightLevel = hdrStaticInfo->maxCll,
1987 .maxFrameAverageLightLevel = hdrStaticInfo->maxFall,
1988 };
1989
1990 hdr.validTypes = HdrMetadata::SMPTE2086 | HdrMetadata::CTA861_3;
1991 hdr.smpte2086 = smpte2086_meta;
1992 hdr.cta8613 = cta861_meta;
1993 }
1994 if (hdr10PlusInfo) {
1995 hdr.validTypes |= HdrMetadata::HDR10PLUS;
1996 hdr.hdr10plus.assign(
1997 hdr10PlusInfo->m.value,
1998 hdr10PlusInfo->m.value + hdr10PlusInfo->flexCount());
1999 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002000 qbi.setHdrMetadata(hdr);
2001 }
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002002 // we don't have dirty regions
2003 qbi.setSurfaceDamage(Region::INVALID_REGION);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002004 android::IGraphicBufferProducer::QueueBufferOutput qbo;
2005 status_t result = mComponent->queueToOutputSurface(block, qbi, &qbo);
2006 if (result != OK) {
2007 ALOGI("[%s] queueBuffer failed: %d", mName, result);
2008 return result;
2009 }
2010 ALOGV("[%s] queue buffer successful", mName);
2011
2012 int64_t mediaTimeUs = 0;
2013 (void)buffer->meta()->findInt64("timeUs", &mediaTimeUs);
2014 mCCodecCallback->onOutputFramesRendered(mediaTimeUs, timestampNs);
2015
2016 return OK;
2017}
2018
2019status_t CCodecBufferChannel::discardBuffer(const sp<MediaCodecBuffer> &buffer) {
2020 ALOGV("[%s] discardBuffer: %p", mName, buffer.get());
2021 bool released = false;
2022 {
2023 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
Pawin Vongmasa1f213362019-01-24 06:59:16 -08002024 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr, true)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002025 released = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002026 }
2027 }
2028 {
2029 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2030 if (*buffers && (*buffers)->releaseBuffer(buffer, nullptr)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002031 released = true;
2032 }
2033 }
2034 if (released) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002035 sendOutputBuffers();
Pawin Vongmasa8be93112018-12-11 14:01:42 -08002036 feedInputBufferIfAvailable();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002037 } else {
2038 ALOGD("[%s] MediaCodec discarded an unknown buffer", mName);
2039 }
2040 return OK;
2041}
2042
2043void CCodecBufferChannel::getInputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
2044 array->clear();
2045 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2046
2047 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002048 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002049 }
2050
2051 (*buffers)->getArray(array);
2052}
2053
2054void CCodecBufferChannel::getOutputBufferArray(Vector<sp<MediaCodecBuffer>> *array) {
2055 array->clear();
2056 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2057
2058 if (!(*buffers)->isArrayMode()) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002059 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002060 }
2061
2062 (*buffers)->getArray(array);
2063}
2064
2065status_t CCodecBufferChannel::start(
2066 const sp<AMessage> &inputFormat, const sp<AMessage> &outputFormat) {
2067 C2StreamBufferTypeSetting::input iStreamFormat(0u);
2068 C2StreamBufferTypeSetting::output oStreamFormat(0u);
2069 C2PortReorderBufferDepthTuning::output reorderDepth;
2070 C2PortReorderKeySetting::output reorderKey;
Wonsik Kim078b58e2019-01-09 15:08:06 -08002071 C2PortActualDelayTuning::input inputDelay(0);
2072 C2PortActualDelayTuning::output outputDelay(0);
2073 C2ActualPipelineDelayTuning pipelineDelay(0);
2074
Pawin Vongmasa36653902018-11-15 00:10:25 -08002075 c2_status_t err = mComponent->query(
2076 {
2077 &iStreamFormat,
2078 &oStreamFormat,
2079 &reorderDepth,
2080 &reorderKey,
Wonsik Kim078b58e2019-01-09 15:08:06 -08002081 &inputDelay,
2082 &pipelineDelay,
2083 &outputDelay,
Pawin Vongmasa36653902018-11-15 00:10:25 -08002084 },
2085 {},
2086 C2_DONT_BLOCK,
2087 nullptr);
2088 if (err == C2_BAD_INDEX) {
2089 if (!iStreamFormat || !oStreamFormat) {
2090 return UNKNOWN_ERROR;
2091 }
2092 } else if (err != C2_OK) {
2093 return UNKNOWN_ERROR;
2094 }
2095
2096 {
2097 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2098 reorder->clear();
2099 if (reorderDepth) {
2100 reorder->setDepth(reorderDepth.value);
2101 }
2102 if (reorderKey) {
2103 reorder->setKey(reorderKey.value);
2104 }
2105 }
Wonsik Kim078b58e2019-01-09 15:08:06 -08002106
2107 mNumInputSlots =
2108 (inputDelay ? inputDelay.value : 0) +
2109 (pipelineDelay ? pipelineDelay.value : 0) +
2110 kSmoothnessFactor;
2111 mNumOutputSlots = (outputDelay ? outputDelay.value : 0) + kSmoothnessFactor;
2112
Pawin Vongmasa36653902018-11-15 00:10:25 -08002113 // TODO: get this from input format
2114 bool secure = mComponent->getName().find(".secure") != std::string::npos;
2115
2116 std::shared_ptr<C2AllocatorStore> allocatorStore = GetCodec2PlatformAllocatorStore();
2117 int poolMask = property_get_int32(
2118 "debug.stagefright.c2-poolmask",
2119 1 << C2PlatformAllocatorStore::ION |
2120 1 << C2PlatformAllocatorStore::BUFFERQUEUE);
2121
2122 if (inputFormat != nullptr) {
2123 bool graphic = (iStreamFormat.value == C2FormatVideo);
2124 std::shared_ptr<C2BlockPool> pool;
2125 {
2126 Mutexed<BlockPools>::Locked pools(mBlockPools);
2127
2128 // set default allocator ID.
2129 pools->inputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
2130 : C2PlatformAllocatorStore::ION;
2131
2132 // query C2PortAllocatorsTuning::input from component. If an allocator ID is obtained
2133 // from component, create the input block pool with given ID. Otherwise, use default IDs.
2134 std::vector<std::unique_ptr<C2Param>> params;
2135 err = mComponent->query({ },
2136 { C2PortAllocatorsTuning::input::PARAM_TYPE },
2137 C2_DONT_BLOCK,
2138 &params);
2139 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2140 ALOGD("[%s] Query input allocators returned %zu params => %s (%u)",
2141 mName, params.size(), asString(err), err);
2142 } else if (err == C2_OK && params.size() == 1) {
2143 C2PortAllocatorsTuning::input *inputAllocators =
2144 C2PortAllocatorsTuning::input::From(params[0].get());
2145 if (inputAllocators && inputAllocators->flexCount() > 0) {
2146 std::shared_ptr<C2Allocator> allocator;
2147 // verify allocator IDs and resolve default allocator
2148 allocatorStore->fetchAllocator(inputAllocators->m.values[0], &allocator);
2149 if (allocator) {
2150 pools->inputAllocatorId = allocator->getId();
2151 } else {
2152 ALOGD("[%s] component requested invalid input allocator ID %u",
2153 mName, inputAllocators->m.values[0]);
2154 }
2155 }
2156 }
2157
2158 // TODO: use C2Component wrapper to associate this pool with ourselves
2159 if ((poolMask >> pools->inputAllocatorId) & 1) {
2160 err = CreateCodec2BlockPool(pools->inputAllocatorId, nullptr, &pool);
2161 ALOGD("[%s] Created input block pool with allocatorID %u => poolID %llu - %s (%d)",
2162 mName, pools->inputAllocatorId,
2163 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
2164 asString(err), err);
2165 } else {
2166 err = C2_NOT_FOUND;
2167 }
2168 if (err != C2_OK) {
2169 C2BlockPool::local_id_t inputPoolId =
2170 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
2171 err = GetCodec2BlockPool(inputPoolId, nullptr, &pool);
2172 ALOGD("[%s] Using basic input block pool with poolID %llu => got %llu - %s (%d)",
2173 mName, (unsigned long long)inputPoolId,
2174 (unsigned long long)(pool ? pool->getLocalId() : 111000111),
2175 asString(err), err);
2176 if (err != C2_OK) {
2177 return NO_MEMORY;
2178 }
2179 }
2180 pools->inputPool = pool;
2181 }
2182
Wonsik Kim51051262018-11-28 13:59:05 -08002183 bool forceArrayMode = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002184 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2185 if (graphic) {
2186 if (mInputSurface) {
2187 buffers->reset(new DummyInputBuffers(mName));
2188 } else if (mMetaMode == MODE_ANW) {
2189 buffers->reset(new GraphicMetadataInputBuffers(mName));
2190 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002191 buffers->reset(new GraphicInputBuffers(mNumInputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002192 }
2193 } else {
2194 if (hasCryptoOrDescrambler()) {
2195 int32_t capacity = kLinearBufferSize;
2196 (void)inputFormat->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
2197 if ((size_t)capacity > kMaxLinearBufferSize) {
2198 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
2199 capacity = kMaxLinearBufferSize;
2200 }
2201 if (mDealer == nullptr) {
2202 mDealer = new MemoryDealer(
2203 align(capacity, MemoryDealer::getAllocationAlignment())
Wonsik Kim078b58e2019-01-09 15:08:06 -08002204 * (mNumInputSlots + 1),
Pawin Vongmasa36653902018-11-15 00:10:25 -08002205 "EncryptedLinearInputBuffers");
2206 mDecryptDestination = mDealer->allocate((size_t)capacity);
2207 }
2208 if (mCrypto != nullptr && mHeapSeqNum < 0) {
2209 mHeapSeqNum = mCrypto->setHeap(mDealer->getMemoryHeap());
2210 } else {
2211 mHeapSeqNum = -1;
2212 }
2213 buffers->reset(new EncryptedLinearInputBuffers(
Wonsik Kim078b58e2019-01-09 15:08:06 -08002214 secure, mDealer, mCrypto, mHeapSeqNum, (size_t)capacity,
2215 mNumInputSlots, mName));
Wonsik Kim51051262018-11-28 13:59:05 -08002216 forceArrayMode = true;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002217 } else {
2218 buffers->reset(new LinearInputBuffers(mName));
2219 }
2220 }
2221 (*buffers)->setFormat(inputFormat);
2222
2223 if (err == C2_OK) {
2224 (*buffers)->setPool(pool);
2225 } else {
2226 // TODO: error
2227 }
Wonsik Kim51051262018-11-28 13:59:05 -08002228
2229 if (forceArrayMode) {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002230 *buffers = (*buffers)->toArrayMode(mNumInputSlots);
Wonsik Kim51051262018-11-28 13:59:05 -08002231 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002232 }
2233
2234 if (outputFormat != nullptr) {
2235 sp<IGraphicBufferProducer> outputSurface;
2236 uint32_t outputGeneration;
2237 {
2238 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2239 outputSurface = output->surface ?
2240 output->surface->getIGraphicBufferProducer() : nullptr;
2241 outputGeneration = output->generation;
2242 }
2243
2244 bool graphic = (oStreamFormat.value == C2FormatVideo);
2245 C2BlockPool::local_id_t outputPoolId_;
2246
2247 {
2248 Mutexed<BlockPools>::Locked pools(mBlockPools);
2249
2250 // set default allocator ID.
2251 pools->outputAllocatorId = (graphic) ? C2PlatformAllocatorStore::GRALLOC
2252 : C2PlatformAllocatorStore::ION;
2253
2254 // query C2PortAllocatorsTuning::output from component, or use default allocator if
2255 // unsuccessful.
2256 std::vector<std::unique_ptr<C2Param>> params;
2257 err = mComponent->query({ },
2258 { C2PortAllocatorsTuning::output::PARAM_TYPE },
2259 C2_DONT_BLOCK,
2260 &params);
2261 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2262 ALOGD("[%s] Query output allocators returned %zu params => %s (%u)",
2263 mName, params.size(), asString(err), err);
2264 } else if (err == C2_OK && params.size() == 1) {
2265 C2PortAllocatorsTuning::output *outputAllocators =
2266 C2PortAllocatorsTuning::output::From(params[0].get());
2267 if (outputAllocators && outputAllocators->flexCount() > 0) {
2268 std::shared_ptr<C2Allocator> allocator;
2269 // verify allocator IDs and resolve default allocator
2270 allocatorStore->fetchAllocator(outputAllocators->m.values[0], &allocator);
2271 if (allocator) {
2272 pools->outputAllocatorId = allocator->getId();
2273 } else {
2274 ALOGD("[%s] component requested invalid output allocator ID %u",
2275 mName, outputAllocators->m.values[0]);
2276 }
2277 }
2278 }
2279
2280 // use bufferqueue if outputting to a surface.
2281 // query C2PortSurfaceAllocatorTuning::output from component, or use default allocator
2282 // if unsuccessful.
2283 if (outputSurface) {
2284 params.clear();
2285 err = mComponent->query({ },
2286 { C2PortSurfaceAllocatorTuning::output::PARAM_TYPE },
2287 C2_DONT_BLOCK,
2288 &params);
2289 if ((err != C2_OK && err != C2_BAD_INDEX) || params.size() != 1) {
2290 ALOGD("[%s] Query output surface allocator returned %zu params => %s (%u)",
2291 mName, params.size(), asString(err), err);
2292 } else if (err == C2_OK && params.size() == 1) {
2293 C2PortSurfaceAllocatorTuning::output *surfaceAllocator =
2294 C2PortSurfaceAllocatorTuning::output::From(params[0].get());
2295 if (surfaceAllocator) {
2296 std::shared_ptr<C2Allocator> allocator;
2297 // verify allocator IDs and resolve default allocator
2298 allocatorStore->fetchAllocator(surfaceAllocator->value, &allocator);
2299 if (allocator) {
2300 pools->outputAllocatorId = allocator->getId();
2301 } else {
2302 ALOGD("[%s] component requested invalid surface output allocator ID %u",
2303 mName, surfaceAllocator->value);
2304 err = C2_BAD_VALUE;
2305 }
2306 }
2307 }
2308 if (pools->outputAllocatorId == C2PlatformAllocatorStore::GRALLOC
2309 && err != C2_OK
2310 && ((poolMask >> C2PlatformAllocatorStore::BUFFERQUEUE) & 1)) {
2311 pools->outputAllocatorId = C2PlatformAllocatorStore::BUFFERQUEUE;
2312 }
2313 }
2314
2315 if ((poolMask >> pools->outputAllocatorId) & 1) {
2316 err = mComponent->createBlockPool(
2317 pools->outputAllocatorId, &pools->outputPoolId, &pools->outputPoolIntf);
2318 ALOGI("[%s] Created output block pool with allocatorID %u => poolID %llu - %s",
2319 mName, pools->outputAllocatorId,
2320 (unsigned long long)pools->outputPoolId,
2321 asString(err));
2322 } else {
2323 err = C2_NOT_FOUND;
2324 }
2325 if (err != C2_OK) {
2326 // use basic pool instead
2327 pools->outputPoolId =
2328 graphic ? C2BlockPool::BASIC_GRAPHIC : C2BlockPool::BASIC_LINEAR;
2329 }
2330
2331 // Configure output block pool ID as parameter C2PortBlockPoolsTuning::output to
2332 // component.
2333 std::unique_ptr<C2PortBlockPoolsTuning::output> poolIdsTuning =
2334 C2PortBlockPoolsTuning::output::AllocUnique({ pools->outputPoolId });
2335
2336 std::vector<std::unique_ptr<C2SettingResult>> failures;
2337 err = mComponent->config({ poolIdsTuning.get() }, C2_MAY_BLOCK, &failures);
2338 ALOGD("[%s] Configured output block pool ids %llu => %s",
2339 mName, (unsigned long long)poolIdsTuning->m.values[0], asString(err));
2340 outputPoolId_ = pools->outputPoolId;
2341 }
2342
2343 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2344
2345 if (graphic) {
2346 if (outputSurface) {
2347 buffers->reset(new GraphicOutputBuffers(mName));
2348 } else {
Wonsik Kim078b58e2019-01-09 15:08:06 -08002349 buffers->reset(new RawGraphicOutputBuffers(mNumOutputSlots, mName));
Pawin Vongmasa36653902018-11-15 00:10:25 -08002350 }
2351 } else {
2352 buffers->reset(new LinearOutputBuffers(mName));
2353 }
2354 (*buffers)->setFormat(outputFormat->dup());
2355
2356
2357 // Try to set output surface to created block pool if given.
2358 if (outputSurface) {
2359 mComponent->setOutputSurface(
2360 outputPoolId_,
2361 outputSurface,
2362 outputGeneration);
2363 }
2364
2365 if (oStreamFormat.value == C2BufferData::LINEAR
2366 && mComponentName.find("c2.qti.") == std::string::npos) {
2367 // WORKAROUND: if we're using early CSD workaround we convert to
2368 // array mode, to appease apps assuming the output
2369 // buffers to be of the same size.
Wonsik Kim078b58e2019-01-09 15:08:06 -08002370 (*buffers) = (*buffers)->toArrayMode(mNumOutputSlots);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002371
2372 int32_t channelCount;
2373 int32_t sampleRate;
2374 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
2375 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
2376 int32_t delay = 0;
2377 int32_t padding = 0;;
2378 if (!outputFormat->findInt32("encoder-delay", &delay)) {
2379 delay = 0;
2380 }
2381 if (!outputFormat->findInt32("encoder-padding", &padding)) {
2382 padding = 0;
2383 }
2384 if (delay || padding) {
2385 // We need write access to the buffers, and we're already in
2386 // array mode.
2387 (*buffers)->initSkipCutBuffer(delay, padding, sampleRate, channelCount);
2388 }
2389 }
2390 }
2391 }
2392
2393 // Set up pipeline control. This has to be done after mInputBuffers and
2394 // mOutputBuffers are initialized to make sure that lingering callbacks
2395 // about buffers from the previous generation do not interfere with the
2396 // newly initialized pipeline capacity.
2397
Wonsik Kimab34ed62019-01-31 15:28:46 -08002398 {
2399 Mutexed<PipelineWatcher>::Locked watcher(mPipelineWatcher);
2400 watcher->inputDelay(inputDelay ? inputDelay.value : 0)
2401 .pipelineDelay(pipelineDelay ? pipelineDelay.value : 0)
2402 .outputDelay(outputDelay ? outputDelay.value : 0)
2403 .smoothnessFactor(kSmoothnessFactor);
2404 watcher->flush();
2405 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002406
2407 mInputMetEos = false;
2408 mSync.start();
2409 return OK;
2410}
2411
2412status_t CCodecBufferChannel::requestInitialInputBuffers() {
2413 if (mInputSurface) {
2414 return OK;
2415 }
2416
2417 C2StreamFormatConfig::output oStreamFormat(0u);
2418 c2_status_t err = mComponent->query({ &oStreamFormat }, {}, C2_DONT_BLOCK, nullptr);
2419 if (err != C2_OK) {
2420 return UNKNOWN_ERROR;
2421 }
2422 std::vector<sp<MediaCodecBuffer>> toBeQueued;
2423 // TODO: use proper buffer depth instead of this random value
Wonsik Kim078b58e2019-01-09 15:08:06 -08002424 for (size_t i = 0; i < mNumInputSlots; ++i) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002425 size_t index;
2426 sp<MediaCodecBuffer> buffer;
2427 {
2428 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2429 if (!(*buffers)->requestNewBuffer(&index, &buffer)) {
2430 if (i == 0) {
2431 ALOGW("[%s] start: cannot allocate memory at all", mName);
2432 return NO_MEMORY;
2433 } else {
2434 ALOGV("[%s] start: cannot allocate memory, only %zu buffers allocated",
2435 mName, i);
2436 }
2437 break;
2438 }
2439 }
2440 if (buffer) {
2441 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
2442 ALOGV("[%s] input buffer %zu available", mName, index);
2443 bool post = true;
2444 if (!configs->empty()) {
2445 sp<ABuffer> config = configs->front();
2446 if (buffer->capacity() >= config->size()) {
2447 memcpy(buffer->base(), config->data(), config->size());
2448 buffer->setRange(0, config->size());
2449 buffer->meta()->clear();
2450 buffer->meta()->setInt64("timeUs", 0);
2451 buffer->meta()->setInt32("csd", 1);
2452 post = false;
2453 } else {
2454 ALOGD("[%s] buffer capacity too small for the config (%zu < %zu)",
2455 mName, buffer->capacity(), config->size());
2456 }
2457 } else if (oStreamFormat.value == C2BufferData::LINEAR && i == 0
2458 && mComponentName.find("c2.qti.") == std::string::npos) {
2459 // WORKAROUND: Some apps expect CSD available without queueing
2460 // any input. Queue an empty buffer to get the CSD.
2461 buffer->setRange(0, 0);
2462 buffer->meta()->clear();
2463 buffer->meta()->setInt64("timeUs", 0);
2464 post = false;
2465 }
Wonsik Kimab34ed62019-01-31 15:28:46 -08002466 if (post) {
2467 mCallback->onInputBufferAvailable(index, buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002468 } else {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002469 toBeQueued.emplace_back(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002470 }
2471 }
2472 }
2473 for (const sp<MediaCodecBuffer> &buffer : toBeQueued) {
2474 if (queueInputBufferInternal(buffer) != OK) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002475 ALOGV("[%s] Error while queueing initial buffers", mName);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002476 }
2477 }
2478 return OK;
2479}
2480
2481void CCodecBufferChannel::stop() {
2482 mSync.stop();
2483 mFirstValidFrameIndex = mFrameIndex.load(std::memory_order_relaxed);
2484 if (mInputSurface != nullptr) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002485 mInputSurface.reset();
2486 }
2487}
2488
2489void CCodecBufferChannel::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
2490 ALOGV("[%s] flush", mName);
2491 {
2492 Mutexed<std::list<sp<ABuffer>>>::Locked configs(mFlushedConfigs);
2493 for (const std::unique_ptr<C2Work> &work : flushedWork) {
2494 if (!(work->input.flags & C2FrameData::FLAG_CODEC_CONFIG)) {
2495 continue;
2496 }
2497 if (work->input.buffers.empty()
2498 || work->input.buffers.front()->data().linearBlocks().empty()) {
2499 ALOGD("[%s] no linear codec config data found", mName);
2500 continue;
2501 }
2502 C2ReadView view =
2503 work->input.buffers.front()->data().linearBlocks().front().map().get();
2504 if (view.error() != C2_OK) {
2505 ALOGD("[%s] failed to map flushed codec config data: %d", mName, view.error());
2506 continue;
2507 }
2508 configs->push_back(ABuffer::CreateAsCopy(view.data(), view.capacity()));
2509 ALOGV("[%s] stashed flushed codec config data (size=%u)", mName, view.capacity());
2510 }
2511 }
2512 {
2513 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2514 (*buffers)->flush();
2515 }
2516 {
2517 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2518 (*buffers)->flush(flushedWork);
2519 }
Wonsik Kim6897f222019-01-30 13:29:24 -08002520 mReorderStash.lock()->flush();
Wonsik Kimab34ed62019-01-31 15:28:46 -08002521 mPipelineWatcher.lock()->flush();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002522}
2523
2524void CCodecBufferChannel::onWorkDone(
2525 std::unique_ptr<C2Work> work, const sp<AMessage> &outputFormat,
Wonsik Kimab34ed62019-01-31 15:28:46 -08002526 const C2StreamInitDataInfo::output *initData) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002527 if (handleWork(std::move(work), outputFormat, initData)) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002528 feedInputBufferIfAvailable();
2529 }
2530}
2531
2532void CCodecBufferChannel::onInputBufferDone(
Wonsik Kimab34ed62019-01-31 15:28:46 -08002533 uint64_t frameIndex, size_t arrayIndex) {
2534 std::shared_ptr<C2Buffer> buffer =
2535 mPipelineWatcher.lock()->onInputBufferReleased(frameIndex, arrayIndex);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002536 bool newInputSlotAvailable;
2537 {
2538 Mutexed<std::unique_ptr<InputBuffers>>::Locked buffers(mInputBuffers);
2539 newInputSlotAvailable = (*buffers)->expireComponentBuffer(buffer);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002540 }
2541 if (newInputSlotAvailable) {
2542 feedInputBufferIfAvailable();
2543 }
2544}
2545
2546bool CCodecBufferChannel::handleWork(
2547 std::unique_ptr<C2Work> work,
2548 const sp<AMessage> &outputFormat,
2549 const C2StreamInitDataInfo::output *initData) {
2550 if ((work->input.ordinal.frameIndex - mFirstValidFrameIndex.load()).peek() < 0) {
2551 // Discard frames from previous generation.
2552 ALOGD("[%s] Discard frames from previous generation.", mName);
2553 return false;
2554 }
2555
2556 if (work->worklets.size() != 1u
2557 || !work->worklets.front()
2558 || !(work->worklets.front()->output.flags & C2FrameData::FLAG_INCOMPLETE)) {
Wonsik Kimab34ed62019-01-31 15:28:46 -08002559 mPipelineWatcher.lock()->onWorkDone(work->input.ordinal.frameIndex.peeku());
Pawin Vongmasa36653902018-11-15 00:10:25 -08002560 }
2561
2562 if (work->result == C2_NOT_FOUND) {
2563 ALOGD("[%s] flushed work; ignored.", mName);
2564 return true;
2565 }
2566
2567 if (work->result != C2_OK) {
2568 ALOGD("[%s] work failed to complete: %d", mName, work->result);
2569 mCCodecCallback->onError(work->result, ACTION_CODE_FATAL);
2570 return false;
2571 }
2572
2573 // NOTE: MediaCodec usage supposedly have only one worklet
2574 if (work->worklets.size() != 1u) {
2575 ALOGI("[%s] onWorkDone: incorrect number of worklets: %zu",
2576 mName, work->worklets.size());
2577 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2578 return false;
2579 }
2580
2581 const std::unique_ptr<C2Worklet> &worklet = work->worklets.front();
2582
2583 std::shared_ptr<C2Buffer> buffer;
2584 // NOTE: MediaCodec usage supposedly have only one output stream.
2585 if (worklet->output.buffers.size() > 1u) {
2586 ALOGI("[%s] onWorkDone: incorrect number of output buffers: %zu",
2587 mName, worklet->output.buffers.size());
2588 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2589 return false;
2590 } else if (worklet->output.buffers.size() == 1u) {
2591 buffer = worklet->output.buffers[0];
2592 if (!buffer) {
2593 ALOGD("[%s] onWorkDone: nullptr found in buffers; ignored.", mName);
2594 }
2595 }
2596
2597 while (!worklet->output.configUpdate.empty()) {
2598 std::unique_ptr<C2Param> param;
2599 worklet->output.configUpdate.back().swap(param);
2600 worklet->output.configUpdate.pop_back();
2601 switch (param->coreIndex().coreIndex()) {
2602 case C2PortReorderBufferDepthTuning::CORE_INDEX: {
2603 C2PortReorderBufferDepthTuning::output reorderDepth;
2604 if (reorderDepth.updateFrom(*param)) {
2605 mReorderStash.lock()->setDepth(reorderDepth.value);
2606 ALOGV("[%s] onWorkDone: updated reorder depth to %u",
2607 mName, reorderDepth.value);
2608 } else {
2609 ALOGD("[%s] onWorkDone: failed to read reorder depth", mName);
2610 }
2611 break;
2612 }
2613 case C2PortReorderKeySetting::CORE_INDEX: {
2614 C2PortReorderKeySetting::output reorderKey;
2615 if (reorderKey.updateFrom(*param)) {
2616 mReorderStash.lock()->setKey(reorderKey.value);
2617 ALOGV("[%s] onWorkDone: updated reorder key to %u",
2618 mName, reorderKey.value);
2619 } else {
2620 ALOGD("[%s] onWorkDone: failed to read reorder key", mName);
2621 }
2622 break;
2623 }
2624 default:
2625 ALOGV("[%s] onWorkDone: unrecognized config update (%08X)",
2626 mName, param->index());
2627 break;
2628 }
2629 }
2630
2631 if (outputFormat != nullptr) {
2632 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2633 ALOGD("[%s] onWorkDone: output format changed to %s",
2634 mName, outputFormat->debugString().c_str());
2635 (*buffers)->setFormat(outputFormat);
2636
2637 AString mediaType;
2638 if (outputFormat->findString(KEY_MIME, &mediaType)
2639 && mediaType == MIMETYPE_AUDIO_RAW) {
2640 int32_t channelCount;
2641 int32_t sampleRate;
2642 if (outputFormat->findInt32(KEY_CHANNEL_COUNT, &channelCount)
2643 && outputFormat->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
2644 (*buffers)->updateSkipCutBuffer(sampleRate, channelCount);
2645 }
2646 }
2647 }
2648
2649 int32_t flags = 0;
2650 if (worklet->output.flags & C2FrameData::FLAG_END_OF_STREAM) {
2651 flags |= MediaCodec::BUFFER_FLAG_EOS;
2652 ALOGV("[%s] onWorkDone: output EOS", mName);
2653 }
2654
2655 sp<MediaCodecBuffer> outBuffer;
2656 size_t index;
2657
2658 // WORKAROUND: adjust output timestamp based on client input timestamp and codec
2659 // input timestamp. Codec output timestamp (in the timestamp field) shall correspond to
2660 // the codec input timestamp, but client output timestamp should (reported in timeUs)
2661 // shall correspond to the client input timesamp (in customOrdinal). By using the
2662 // delta between the two, this allows for some timestamp deviation - e.g. if one input
2663 // produces multiple output.
2664 c2_cntr64_t timestamp =
2665 worklet->output.ordinal.timestamp + work->input.ordinal.customOrdinal
2666 - work->input.ordinal.timestamp;
2667 ALOGV("[%s] onWorkDone: input %lld, codec %lld => output %lld => %lld",
2668 mName,
2669 work->input.ordinal.customOrdinal.peekll(),
2670 work->input.ordinal.timestamp.peekll(),
2671 worklet->output.ordinal.timestamp.peekll(),
2672 timestamp.peekll());
2673
2674 if (initData != nullptr) {
2675 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2676 if ((*buffers)->registerCsd(initData, &index, &outBuffer) == OK) {
2677 outBuffer->meta()->setInt64("timeUs", timestamp.peek());
2678 outBuffer->meta()->setInt32("flags", MediaCodec::BUFFER_FLAG_CODECCONFIG);
2679 ALOGV("[%s] onWorkDone: csd index = %zu [%p]", mName, index, outBuffer.get());
2680
2681 buffers.unlock();
2682 mCallback->onOutputBufferAvailable(index, outBuffer);
2683 buffers.lock();
2684 } else {
2685 ALOGD("[%s] onWorkDone: unable to register csd", mName);
2686 buffers.unlock();
2687 mCCodecCallback->onError(UNKNOWN_ERROR, ACTION_CODE_FATAL);
2688 buffers.lock();
2689 return false;
2690 }
2691 }
2692
2693 if (!buffer && !flags) {
2694 ALOGV("[%s] onWorkDone: Not reporting output buffer (%lld)",
2695 mName, work->input.ordinal.frameIndex.peekull());
2696 return true;
2697 }
2698
2699 if (buffer) {
2700 for (const std::shared_ptr<const C2Info> &info : buffer->info()) {
2701 // TODO: properly translate these to metadata
2702 switch (info->coreIndex().coreIndex()) {
2703 case C2StreamPictureTypeMaskInfo::CORE_INDEX:
2704 if (((C2StreamPictureTypeMaskInfo *)info.get())->value & C2PictureTypeKeyFrame) {
2705 flags |= MediaCodec::BUFFER_FLAG_SYNCFRAME;
2706 }
2707 break;
2708 default:
2709 break;
2710 }
2711 }
2712 }
2713
2714 {
2715 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2716 reorder->emplace(buffer, timestamp.peek(), flags, worklet->output.ordinal);
2717 if (flags & MediaCodec::BUFFER_FLAG_EOS) {
2718 // Flush reorder stash
2719 reorder->setDepth(0);
2720 }
2721 }
2722 sendOutputBuffers();
2723 return true;
2724}
2725
2726void CCodecBufferChannel::sendOutputBuffers() {
2727 ReorderStash::Entry entry;
2728 sp<MediaCodecBuffer> outBuffer;
2729 size_t index;
2730
2731 while (true) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08002732 Mutexed<ReorderStash>::Locked reorder(mReorderStash);
2733 if (!reorder->hasPending()) {
2734 break;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002735 }
Wonsik Kim38ad3412019-02-01 15:13:23 -08002736 if (!reorder->pop(&entry)) {
2737 break;
2738 }
2739
Pawin Vongmasa36653902018-11-15 00:10:25 -08002740 Mutexed<std::unique_ptr<OutputBuffers>>::Locked buffers(mOutputBuffers);
2741 status_t err = (*buffers)->registerBuffer(entry.buffer, &index, &outBuffer);
2742 if (err != OK) {
Wonsik Kim38ad3412019-02-01 15:13:23 -08002743 bool outputBuffersChanged = false;
Pawin Vongmasa36653902018-11-15 00:10:25 -08002744 if (err != WOULD_BLOCK) {
Wonsik Kim186fdbf2019-01-29 13:30:01 -08002745 if (!(*buffers)->isArrayMode()) {
2746 *buffers = (*buffers)->toArrayMode(mNumOutputSlots);
2747 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002748 OutputBuffersArray *array = (OutputBuffersArray *)buffers->get();
2749 array->realloc(entry.buffer);
Wonsik Kim38ad3412019-02-01 15:13:23 -08002750 outputBuffersChanged = true;
2751 }
2752 ALOGV("[%s] sendOutputBuffers: unable to register output buffer", mName);
2753 reorder->defer(entry);
2754
2755 buffers.unlock();
2756 reorder.unlock();
2757
2758 if (outputBuffersChanged) {
Pawin Vongmasa36653902018-11-15 00:10:25 -08002759 mCCodecCallback->onOutputBuffersChanged();
2760 }
Pawin Vongmasa36653902018-11-15 00:10:25 -08002761 return;
2762 }
2763 buffers.unlock();
Wonsik Kim38ad3412019-02-01 15:13:23 -08002764 reorder.unlock();
Pawin Vongmasa36653902018-11-15 00:10:25 -08002765
2766 outBuffer->meta()->setInt64("timeUs", entry.timestamp);
2767 outBuffer->meta()->setInt32("flags", entry.flags);
2768 ALOGV("[%s] sendOutputBuffers: out buffer index = %zu [%p] => %p + %zu",
2769 mName, index, outBuffer.get(), outBuffer->data(), outBuffer->size());
2770 mCallback->onOutputBufferAvailable(index, outBuffer);
2771 }
2772}
2773
2774status_t CCodecBufferChannel::setSurface(const sp<Surface> &newSurface) {
2775 static std::atomic_uint32_t surfaceGeneration{0};
2776 uint32_t generation = (getpid() << 10) |
2777 ((surfaceGeneration.fetch_add(1, std::memory_order_relaxed) + 1)
2778 & ((1 << 10) - 1));
2779
2780 sp<IGraphicBufferProducer> producer;
2781 if (newSurface) {
2782 newSurface->setScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Wonsik Kim078b58e2019-01-09 15:08:06 -08002783 newSurface->setMaxDequeuedBufferCount(mNumOutputSlots + kRenderingDepth);
Pawin Vongmasa36653902018-11-15 00:10:25 -08002784 producer = newSurface->getIGraphicBufferProducer();
2785 producer->setGenerationNumber(generation);
2786 } else {
2787 ALOGE("[%s] setting output surface to null", mName);
2788 return INVALID_OPERATION;
2789 }
2790
2791 std::shared_ptr<Codec2Client::Configurable> outputPoolIntf;
2792 C2BlockPool::local_id_t outputPoolId;
2793 {
2794 Mutexed<BlockPools>::Locked pools(mBlockPools);
2795 outputPoolId = pools->outputPoolId;
2796 outputPoolIntf = pools->outputPoolIntf;
2797 }
2798
2799 if (outputPoolIntf) {
2800 if (mComponent->setOutputSurface(
2801 outputPoolId,
2802 producer,
2803 generation) != C2_OK) {
2804 ALOGI("[%s] setSurface: component setOutputSurface failed", mName);
2805 return INVALID_OPERATION;
2806 }
2807 }
2808
2809 {
2810 Mutexed<OutputSurface>::Locked output(mOutputSurface);
2811 output->surface = newSurface;
2812 output->generation = generation;
2813 }
2814
2815 return OK;
2816}
2817
Wonsik Kimab34ed62019-01-31 15:28:46 -08002818PipelineWatcher::Clock::duration CCodecBufferChannel::elapsed() {
2819 return mPipelineWatcher.lock()->elapsed(PipelineWatcher::Clock::now());
2820}
2821
Pawin Vongmasa36653902018-11-15 00:10:25 -08002822void CCodecBufferChannel::setMetaMode(MetaMode mode) {
2823 mMetaMode = mode;
2824}
2825
2826status_t toStatusT(c2_status_t c2s, c2_operation_t c2op) {
2827 // C2_OK is always translated to OK.
2828 if (c2s == C2_OK) {
2829 return OK;
2830 }
2831
2832 // Operation-dependent translation
2833 // TODO: Add as necessary
2834 switch (c2op) {
2835 case C2_OPERATION_Component_start:
2836 switch (c2s) {
2837 case C2_NO_MEMORY:
2838 return NO_MEMORY;
2839 default:
2840 return UNKNOWN_ERROR;
2841 }
2842 default:
2843 break;
2844 }
2845
2846 // Backup operation-agnostic translation
2847 switch (c2s) {
2848 case C2_BAD_INDEX:
2849 return BAD_INDEX;
2850 case C2_BAD_VALUE:
2851 return BAD_VALUE;
2852 case C2_BLOCKING:
2853 return WOULD_BLOCK;
2854 case C2_DUPLICATE:
2855 return ALREADY_EXISTS;
2856 case C2_NO_INIT:
2857 return NO_INIT;
2858 case C2_NO_MEMORY:
2859 return NO_MEMORY;
2860 case C2_NOT_FOUND:
2861 return NAME_NOT_FOUND;
2862 case C2_TIMED_OUT:
2863 return TIMED_OUT;
2864 case C2_BAD_STATE:
2865 case C2_CANCELED:
2866 case C2_CANNOT_DO:
2867 case C2_CORRUPTED:
2868 case C2_OMITTED:
2869 case C2_REFUSED:
2870 return UNKNOWN_ERROR;
2871 default:
2872 return -static_cast<status_t>(c2s);
2873 }
2874}
2875
2876} // namespace android