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