blob: d656350b26b125ab0d5c9f44966c894da00b757e [file] [log] [blame]
Wonsik Kim469c8342019-04-11 16:46:09 -07001/*
2 * Copyright 2019, 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 "CCodecBuffers"
19#include <utils/Log.h>
20
21#include <C2PlatformSupport.h>
22
23#include <media/stagefright/foundation/ADebug.h>
Pawin Vongmasa9b906982020-04-11 05:07:15 -070024#include <media/stagefright/MediaCodec.h>
Wonsik Kim469c8342019-04-11 16:46:09 -070025#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070026#include <media/stagefright/SkipCutBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070027#include <mediadrm/ICrypto.h>
Wonsik Kim469c8342019-04-11 16:46:09 -070028
29#include "CCodecBuffers.h"
30
31namespace android {
32
33namespace {
34
35sp<GraphicBlockBuffer> AllocateGraphicBuffer(
36 const std::shared_ptr<C2BlockPool> &pool,
37 const sp<AMessage> &format,
38 uint32_t pixelFormat,
39 const C2MemoryUsage &usage,
40 const std::shared_ptr<LocalBufferPool> &localBufferPool) {
41 int32_t width, height;
42 if (!format->findInt32("width", &width) || !format->findInt32("height", &height)) {
43 ALOGD("format lacks width or height");
44 return nullptr;
45 }
46
47 std::shared_ptr<C2GraphicBlock> block;
48 c2_status_t err = pool->fetchGraphicBlock(
49 width, height, pixelFormat, usage, &block);
50 if (err != C2_OK) {
51 ALOGD("fetch graphic block failed: %d", err);
52 return nullptr;
53 }
54
55 return GraphicBlockBuffer::Allocate(
56 format,
57 block,
58 [localBufferPool](size_t capacity) {
59 return localBufferPool->newBuffer(capacity);
60 });
61}
62
63} // namespace
64
65// CCodecBuffers
66
67void CCodecBuffers::setFormat(const sp<AMessage> &format) {
68 CHECK(format != nullptr);
69 mFormat = format;
70}
71
72sp<AMessage> CCodecBuffers::dupFormat() {
73 return mFormat != nullptr ? mFormat->dup() : nullptr;
74}
75
76void CCodecBuffers::handleImageData(const sp<Codec2Buffer> &buffer) {
77 sp<ABuffer> imageDataCandidate = buffer->getImageData();
78 if (imageDataCandidate == nullptr) {
79 return;
80 }
81 sp<ABuffer> imageData;
82 if (!mFormat->findBuffer("image-data", &imageData)
83 || imageDataCandidate->size() != imageData->size()
84 || memcmp(imageDataCandidate->data(), imageData->data(), imageData->size()) != 0) {
85 ALOGD("[%s] updating image-data", mName);
86 sp<AMessage> newFormat = dupFormat();
87 newFormat->setBuffer("image-data", imageDataCandidate);
88 MediaImage2 *img = (MediaImage2*)imageDataCandidate->data();
89 if (img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
90 int32_t stride = img->mPlane[0].mRowInc;
91 newFormat->setInt32(KEY_STRIDE, stride);
92 ALOGD("[%s] updating stride = %d", mName, stride);
93 if (img->mNumPlanes > 1 && stride > 0) {
Taehwan Kimfd9b8092020-09-17 12:26:40 +090094 int64_t offsetDelta =
95 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
96 int32_t vstride = int32_t(offsetDelta / stride);
Wonsik Kim469c8342019-04-11 16:46:09 -070097 newFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
98 ALOGD("[%s] updating vstride = %d", mName, vstride);
Wonsik Kim2eb06312020-12-03 11:07:58 -080099 buffer->setRange(
100 img->mPlane[0].mOffset,
101 buffer->size() - img->mPlane[0].mOffset);
Wonsik Kim469c8342019-04-11 16:46:09 -0700102 }
103 }
104 setFormat(newFormat);
105 buffer->setFormat(newFormat);
106 }
107}
108
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700109// InputBuffers
110
111sp<Codec2Buffer> InputBuffers::cloneAndReleaseBuffer(const sp<MediaCodecBuffer> &buffer) {
112 sp<Codec2Buffer> copy = createNewBuffer();
113 if (copy == nullptr) {
114 return nullptr;
115 }
116 std::shared_ptr<C2Buffer> c2buffer;
117 if (!releaseBuffer(buffer, &c2buffer, true)) {
118 return nullptr;
119 }
120 if (!copy->canCopy(c2buffer)) {
121 return nullptr;
122 }
123 if (!copy->copy(c2buffer)) {
124 return nullptr;
125 }
126 return copy;
127}
128
Wonsik Kim469c8342019-04-11 16:46:09 -0700129// OutputBuffers
130
Wonsik Kim41d83432020-04-27 16:40:49 -0700131OutputBuffers::OutputBuffers(const char *componentName, const char *name)
132 : CCodecBuffers(componentName, name) { }
133
134OutputBuffers::~OutputBuffers() = default;
135
Wonsik Kim469c8342019-04-11 16:46:09 -0700136void OutputBuffers::initSkipCutBuffer(
137 int32_t delay, int32_t padding, int32_t sampleRate, int32_t channelCount) {
138 CHECK(mSkipCutBuffer == nullptr);
139 mDelay = delay;
140 mPadding = padding;
141 mSampleRate = sampleRate;
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700142 mChannelCount = channelCount;
143 setSkipCutBuffer(delay, padding);
Wonsik Kim469c8342019-04-11 16:46:09 -0700144}
145
146void OutputBuffers::updateSkipCutBuffer(int32_t sampleRate, int32_t channelCount) {
147 if (mSkipCutBuffer == nullptr) {
148 return;
149 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700150 if (mSampleRate == sampleRate && mChannelCount == channelCount) {
151 return;
152 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700153 int32_t delay = mDelay;
154 int32_t padding = mPadding;
155 if (sampleRate != mSampleRate) {
156 delay = ((int64_t)delay * sampleRate) / mSampleRate;
157 padding = ((int64_t)padding * sampleRate) / mSampleRate;
158 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700159 mSampleRate = sampleRate;
160 mChannelCount = channelCount;
161 setSkipCutBuffer(delay, padding);
Wonsik Kim469c8342019-04-11 16:46:09 -0700162}
163
Wonsik Kim8ec93ab2020-11-13 16:17:04 -0800164void OutputBuffers::updateSkipCutBuffer(
165 const sp<AMessage> &format, bool notify) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700166 AString mediaType;
167 if (format->findString(KEY_MIME, &mediaType)
168 && mediaType == MIMETYPE_AUDIO_RAW) {
169 int32_t channelCount;
170 int32_t sampleRate;
171 if (format->findInt32(KEY_CHANNEL_COUNT, &channelCount)
172 && format->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
173 updateSkipCutBuffer(sampleRate, channelCount);
174 }
175 }
Wonsik Kim8ec93ab2020-11-13 16:17:04 -0800176 if (notify) {
177 mUnreportedFormat = nullptr;
178 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700179}
180
Wonsik Kim469c8342019-04-11 16:46:09 -0700181void OutputBuffers::submit(const sp<MediaCodecBuffer> &buffer) {
182 if (mSkipCutBuffer != nullptr) {
183 mSkipCutBuffer->submit(buffer);
184 }
185}
186
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700187void OutputBuffers::setSkipCutBuffer(int32_t skip, int32_t cut) {
Wonsik Kim469c8342019-04-11 16:46:09 -0700188 if (mSkipCutBuffer != nullptr) {
189 size_t prevSize = mSkipCutBuffer->size();
190 if (prevSize != 0u) {
191 ALOGD("[%s] Replacing SkipCutBuffer holding %zu bytes", mName, prevSize);
192 }
193 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700194 mSkipCutBuffer = new SkipCutBuffer(skip, cut, mChannelCount);
Wonsik Kim469c8342019-04-11 16:46:09 -0700195}
196
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700197void OutputBuffers::clearStash() {
198 mPending.clear();
199 mReorderStash.clear();
200 mDepth = 0;
201 mKey = C2Config::ORDINAL;
Wonsik Kim8ec93ab2020-11-13 16:17:04 -0800202 mUnreportedFormat = nullptr;
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700203}
204
205void OutputBuffers::flushStash() {
206 for (StashEntry& e : mPending) {
207 e.notify = false;
208 }
209 for (StashEntry& e : mReorderStash) {
210 e.notify = false;
211 }
212}
213
214uint32_t OutputBuffers::getReorderDepth() const {
215 return mDepth;
216}
217
218void OutputBuffers::setReorderDepth(uint32_t depth) {
219 mPending.splice(mPending.end(), mReorderStash);
220 mDepth = depth;
221}
222
223void OutputBuffers::setReorderKey(C2Config::ordinal_key_t key) {
224 mPending.splice(mPending.end(), mReorderStash);
225 mKey = key;
226}
227
228void OutputBuffers::pushToStash(
229 const std::shared_ptr<C2Buffer>& buffer,
230 bool notify,
231 int64_t timestamp,
232 int32_t flags,
233 const sp<AMessage>& format,
234 const C2WorkOrdinalStruct& ordinal) {
235 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
236 if (!buffer && eos) {
237 // TRICKY: we may be violating ordering of the stash here. Because we
238 // don't expect any more emplace() calls after this, the ordering should
239 // not matter.
240 mReorderStash.emplace_back(
241 buffer, notify, timestamp, flags, format, ordinal);
242 } else {
243 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
244 auto it = mReorderStash.begin();
245 for (; it != mReorderStash.end(); ++it) {
246 if (less(ordinal, it->ordinal)) {
247 break;
248 }
249 }
250 mReorderStash.emplace(it,
251 buffer, notify, timestamp, flags, format, ordinal);
252 if (eos) {
253 mReorderStash.back().flags =
254 mReorderStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
255 }
256 }
257 while (!mReorderStash.empty() && mReorderStash.size() > mDepth) {
258 mPending.push_back(mReorderStash.front());
259 mReorderStash.pop_front();
260 }
261 ALOGV("[%s] %s: pushToStash -- pending size = %zu", mName, __func__, mPending.size());
262}
263
264OutputBuffers::BufferAction OutputBuffers::popFromStashAndRegister(
265 std::shared_ptr<C2Buffer>* c2Buffer,
266 size_t* index,
267 sp<MediaCodecBuffer>* outBuffer) {
268 if (mPending.empty()) {
269 return SKIP;
270 }
271
272 // Retrieve the first entry.
273 StashEntry &entry = mPending.front();
274
275 *c2Buffer = entry.buffer;
276 sp<AMessage> outputFormat = entry.format;
277
Wonsik Kim8ec93ab2020-11-13 16:17:04 -0800278 // The output format can be processed without a registered slot.
279 if (outputFormat) {
280 updateSkipCutBuffer(outputFormat, entry.notify);
281 }
282
283 if (entry.notify) {
284 if (outputFormat) {
285 setFormat(outputFormat);
286 } else if (mUnreportedFormat) {
287 outputFormat = mUnreportedFormat;
288 setFormat(outputFormat);
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700289 }
Wonsik Kim8ec93ab2020-11-13 16:17:04 -0800290 mUnreportedFormat = nullptr;
291 } else {
292 if (outputFormat) {
293 mUnreportedFormat = outputFormat;
294 } else if (!mUnreportedFormat) {
295 mUnreportedFormat = mFormat;
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700296 }
297 }
298
299 // Flushing mReorderStash because no other buffers should come after output
300 // EOS.
301 if (entry.flags & MediaCodec::BUFFER_FLAG_EOS) {
302 // Flush reorder stash
303 setReorderDepth(0);
304 }
305
306 if (!entry.notify) {
Wonsik Kim8ec93ab2020-11-13 16:17:04 -0800307 if (outputFormat) {
308 ALOGD("[%s] popFromStashAndRegister: output format changed to %s",
309 mName, outputFormat->debugString().c_str());
310 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700311 mPending.pop_front();
312 return DISCARD;
313 }
314
315 // Try to register the buffer.
316 status_t err = registerBuffer(*c2Buffer, index, outBuffer);
317 if (err != OK) {
318 if (err != WOULD_BLOCK) {
319 return REALLOCATE;
320 }
321 return RETRY;
322 }
323
324 // Append information from the front stash entry to outBuffer.
325 (*outBuffer)->meta()->setInt64("timeUs", entry.timestamp);
326 (*outBuffer)->meta()->setInt32("flags", entry.flags);
Byeongjo Park2eef13e2020-06-12 17:24:21 +0900327 (*outBuffer)->meta()->setInt64("frameIndex", entry.ordinal.frameIndex.peekll());
Wonsik Kim8ec93ab2020-11-13 16:17:04 -0800328 if (outputFormat) {
329 ALOGD("[%s] popFromStashAndRegister: output format changed to %s",
330 mName, outputFormat->debugString().c_str());
331 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700332 ALOGV("[%s] popFromStashAndRegister: "
333 "out buffer index = %zu [%p] => %p + %zu (%lld)",
334 mName, *index, outBuffer->get(),
335 (*outBuffer)->data(), (*outBuffer)->size(),
336 (long long)entry.timestamp);
337
338 // The front entry of mPending will be removed now that the registration
339 // succeeded.
340 mPending.pop_front();
341 return NOTIFY_CLIENT;
342}
343
344bool OutputBuffers::popPending(StashEntry *entry) {
345 if (mPending.empty()) {
346 return false;
347 }
348 *entry = mPending.front();
349 mPending.pop_front();
350 return true;
351}
352
353void OutputBuffers::deferPending(const OutputBuffers::StashEntry &entry) {
354 mPending.push_front(entry);
355}
356
357bool OutputBuffers::hasPending() const {
358 return !mPending.empty();
359}
360
361bool OutputBuffers::less(
362 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) const {
363 switch (mKey) {
364 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
365 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
366 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
367 default:
368 ALOGD("Unrecognized key; default to timestamp");
369 return o1.frameIndex < o2.frameIndex;
370 }
371}
372
Wonsik Kim469c8342019-04-11 16:46:09 -0700373// LocalBufferPool
374
Wonsik Kim41d83432020-04-27 16:40:49 -0700375constexpr size_t kInitialPoolCapacity = kMaxLinearBufferSize;
376constexpr size_t kMaxPoolCapacity = kMaxLinearBufferSize * 32;
377
378std::shared_ptr<LocalBufferPool> LocalBufferPool::Create() {
379 return std::shared_ptr<LocalBufferPool>(new LocalBufferPool(kInitialPoolCapacity));
Wonsik Kim469c8342019-04-11 16:46:09 -0700380}
381
382sp<ABuffer> LocalBufferPool::newBuffer(size_t capacity) {
383 Mutex::Autolock lock(mMutex);
384 auto it = std::find_if(
385 mPool.begin(), mPool.end(),
386 [capacity](const std::vector<uint8_t> &vec) {
387 return vec.capacity() >= capacity;
388 });
389 if (it != mPool.end()) {
390 sp<ABuffer> buffer = new VectorBuffer(std::move(*it), shared_from_this());
391 mPool.erase(it);
392 return buffer;
393 }
394 if (mUsedSize + capacity > mPoolCapacity) {
395 while (!mPool.empty()) {
396 mUsedSize -= mPool.back().capacity();
397 mPool.pop_back();
398 }
Wonsik Kim41d83432020-04-27 16:40:49 -0700399 while (mUsedSize + capacity > mPoolCapacity && mPoolCapacity * 2 <= kMaxPoolCapacity) {
400 ALOGD("Increasing local buffer pool capacity from %zu to %zu",
401 mPoolCapacity, mPoolCapacity * 2);
402 mPoolCapacity *= 2;
403 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700404 if (mUsedSize + capacity > mPoolCapacity) {
405 ALOGD("mUsedSize = %zu, capacity = %zu, mPoolCapacity = %zu",
406 mUsedSize, capacity, mPoolCapacity);
407 return nullptr;
408 }
409 }
410 std::vector<uint8_t> vec(capacity);
411 mUsedSize += vec.capacity();
412 return new VectorBuffer(std::move(vec), shared_from_this());
413}
414
415LocalBufferPool::VectorBuffer::VectorBuffer(
416 std::vector<uint8_t> &&vec, const std::shared_ptr<LocalBufferPool> &pool)
417 : ABuffer(vec.data(), vec.capacity()),
418 mVec(std::move(vec)),
419 mPool(pool) {
420}
421
422LocalBufferPool::VectorBuffer::~VectorBuffer() {
423 std::shared_ptr<LocalBufferPool> pool = mPool.lock();
424 if (pool) {
425 // If pool is alive, return the vector back to the pool so that
426 // it can be recycled.
427 pool->returnVector(std::move(mVec));
428 }
429}
430
431void LocalBufferPool::returnVector(std::vector<uint8_t> &&vec) {
432 Mutex::Autolock lock(mMutex);
433 mPool.push_front(std::move(vec));
434}
435
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700436// FlexBuffersImpl
437
Wonsik Kim469c8342019-04-11 16:46:09 -0700438size_t FlexBuffersImpl::assignSlot(const sp<Codec2Buffer> &buffer) {
439 for (size_t i = 0; i < mBuffers.size(); ++i) {
440 if (mBuffers[i].clientBuffer == nullptr
441 && mBuffers[i].compBuffer.expired()) {
442 mBuffers[i].clientBuffer = buffer;
443 return i;
444 }
445 }
446 mBuffers.push_back({ buffer, std::weak_ptr<C2Buffer>() });
447 return mBuffers.size() - 1;
448}
449
Wonsik Kim469c8342019-04-11 16:46:09 -0700450bool FlexBuffersImpl::releaseSlot(
451 const sp<MediaCodecBuffer> &buffer,
452 std::shared_ptr<C2Buffer> *c2buffer,
453 bool release) {
454 sp<Codec2Buffer> clientBuffer;
455 size_t index = mBuffers.size();
456 for (size_t i = 0; i < mBuffers.size(); ++i) {
457 if (mBuffers[i].clientBuffer == buffer) {
458 clientBuffer = mBuffers[i].clientBuffer;
459 if (release) {
460 mBuffers[i].clientBuffer.clear();
461 }
462 index = i;
463 break;
464 }
465 }
466 if (clientBuffer == nullptr) {
467 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
468 return false;
469 }
470 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
471 if (!result) {
472 result = clientBuffer->asC2Buffer();
Wonsik Kimf9b32122020-04-02 11:30:17 -0700473 clientBuffer->clearC2BufferRefs();
Wonsik Kim469c8342019-04-11 16:46:09 -0700474 mBuffers[index].compBuffer = result;
475 }
476 if (c2buffer) {
477 *c2buffer = result;
478 }
479 return true;
480}
481
482bool FlexBuffersImpl::expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
483 for (size_t i = 0; i < mBuffers.size(); ++i) {
484 std::shared_ptr<C2Buffer> compBuffer =
485 mBuffers[i].compBuffer.lock();
486 if (!compBuffer || compBuffer != c2buffer) {
487 continue;
488 }
489 mBuffers[i].compBuffer.reset();
490 ALOGV("[%s] codec released buffer #%zu", mName, i);
491 return true;
492 }
493 ALOGV("[%s] codec released an unknown buffer", mName);
494 return false;
495}
496
497void FlexBuffersImpl::flush() {
498 ALOGV("[%s] buffers are flushed %zu", mName, mBuffers.size());
499 mBuffers.clear();
500}
501
Wonsik Kim0487b782020-10-28 11:45:50 -0700502size_t FlexBuffersImpl::numActiveSlots() const {
Wonsik Kim469c8342019-04-11 16:46:09 -0700503 return std::count_if(
504 mBuffers.begin(), mBuffers.end(),
505 [](const Entry &entry) {
Wonsik Kim0487b782020-10-28 11:45:50 -0700506 return (entry.clientBuffer != nullptr
507 || !entry.compBuffer.expired());
Wonsik Kim469c8342019-04-11 16:46:09 -0700508 });
509}
510
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700511size_t FlexBuffersImpl::numComponentBuffers() const {
512 return std::count_if(
513 mBuffers.begin(), mBuffers.end(),
514 [](const Entry &entry) {
515 return !entry.compBuffer.expired();
516 });
517}
518
Wonsik Kim469c8342019-04-11 16:46:09 -0700519// BuffersArrayImpl
520
521void BuffersArrayImpl::initialize(
522 const FlexBuffersImpl &impl,
523 size_t minSize,
524 std::function<sp<Codec2Buffer>()> allocate) {
525 mImplName = impl.mImplName + "[N]";
526 mName = mImplName.c_str();
527 for (size_t i = 0; i < impl.mBuffers.size(); ++i) {
528 sp<Codec2Buffer> clientBuffer = impl.mBuffers[i].clientBuffer;
529 bool ownedByClient = (clientBuffer != nullptr);
530 if (!ownedByClient) {
531 clientBuffer = allocate();
532 }
533 mBuffers.push_back({ clientBuffer, impl.mBuffers[i].compBuffer, ownedByClient });
534 }
535 ALOGV("[%s] converted %zu buffers to array mode of %zu", mName, mBuffers.size(), minSize);
536 for (size_t i = impl.mBuffers.size(); i < minSize; ++i) {
537 mBuffers.push_back({ allocate(), std::weak_ptr<C2Buffer>(), false });
538 }
539}
540
541status_t BuffersArrayImpl::grabBuffer(
542 size_t *index,
543 sp<Codec2Buffer> *buffer,
544 std::function<bool(const sp<Codec2Buffer> &)> match) {
545 // allBuffersDontMatch remains true if all buffers are available but
546 // match() returns false for every buffer.
547 bool allBuffersDontMatch = true;
548 for (size_t i = 0; i < mBuffers.size(); ++i) {
549 if (!mBuffers[i].ownedByClient && mBuffers[i].compBuffer.expired()) {
550 if (match(mBuffers[i].clientBuffer)) {
551 mBuffers[i].ownedByClient = true;
552 *buffer = mBuffers[i].clientBuffer;
553 (*buffer)->meta()->clear();
554 (*buffer)->setRange(0, (*buffer)->capacity());
555 *index = i;
556 return OK;
557 }
558 } else {
559 allBuffersDontMatch = false;
560 }
561 }
562 return allBuffersDontMatch ? NO_MEMORY : WOULD_BLOCK;
563}
564
565bool BuffersArrayImpl::returnBuffer(
566 const sp<MediaCodecBuffer> &buffer,
567 std::shared_ptr<C2Buffer> *c2buffer,
568 bool release) {
569 sp<Codec2Buffer> clientBuffer;
570 size_t index = mBuffers.size();
571 for (size_t i = 0; i < mBuffers.size(); ++i) {
572 if (mBuffers[i].clientBuffer == buffer) {
573 if (!mBuffers[i].ownedByClient) {
574 ALOGD("[%s] Client returned a buffer it does not own according to our record: %zu",
575 mName, i);
576 }
577 clientBuffer = mBuffers[i].clientBuffer;
578 if (release) {
579 mBuffers[i].ownedByClient = false;
580 }
581 index = i;
582 break;
583 }
584 }
585 if (clientBuffer == nullptr) {
586 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
587 return false;
588 }
589 ALOGV("[%s] %s: matching buffer found (index=%zu)", mName, __func__, index);
590 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
591 if (!result) {
592 result = clientBuffer->asC2Buffer();
Wonsik Kimf9b32122020-04-02 11:30:17 -0700593 clientBuffer->clearC2BufferRefs();
Wonsik Kim469c8342019-04-11 16:46:09 -0700594 mBuffers[index].compBuffer = result;
595 }
596 if (c2buffer) {
597 *c2buffer = result;
598 }
599 return true;
600}
601
602bool BuffersArrayImpl::expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
603 for (size_t i = 0; i < mBuffers.size(); ++i) {
604 std::shared_ptr<C2Buffer> compBuffer =
605 mBuffers[i].compBuffer.lock();
606 if (!compBuffer) {
607 continue;
608 }
609 if (c2buffer == compBuffer) {
610 if (mBuffers[i].ownedByClient) {
611 // This should not happen.
612 ALOGD("[%s] codec released a buffer owned by client "
613 "(index %zu)", mName, i);
614 }
615 mBuffers[i].compBuffer.reset();
616 ALOGV("[%s] codec released buffer #%zu(array mode)", mName, i);
617 return true;
618 }
619 }
620 ALOGV("[%s] codec released an unknown buffer (array mode)", mName);
621 return false;
622}
623
624void BuffersArrayImpl::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
625 array->clear();
626 for (const Entry &entry : mBuffers) {
627 array->push(entry.clientBuffer);
628 }
629}
630
631void BuffersArrayImpl::flush() {
632 for (Entry &entry : mBuffers) {
633 entry.ownedByClient = false;
634 }
635}
636
637void BuffersArrayImpl::realloc(std::function<sp<Codec2Buffer>()> alloc) {
638 size_t size = mBuffers.size();
639 mBuffers.clear();
640 for (size_t i = 0; i < size; ++i) {
641 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
642 }
643}
644
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700645void BuffersArrayImpl::grow(
646 size_t newSize, std::function<sp<Codec2Buffer>()> alloc) {
647 CHECK_LT(mBuffers.size(), newSize);
648 while (mBuffers.size() < newSize) {
649 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
650 }
651}
652
Wonsik Kim0487b782020-10-28 11:45:50 -0700653size_t BuffersArrayImpl::numActiveSlots() const {
Wonsik Kim469c8342019-04-11 16:46:09 -0700654 return std::count_if(
655 mBuffers.begin(), mBuffers.end(),
656 [](const Entry &entry) {
Wonsik Kim0487b782020-10-28 11:45:50 -0700657 return entry.ownedByClient || !entry.compBuffer.expired();
Wonsik Kim469c8342019-04-11 16:46:09 -0700658 });
659}
660
Wonsik Kima39882b2019-06-20 16:13:56 -0700661size_t BuffersArrayImpl::arraySize() const {
662 return mBuffers.size();
663}
664
Wonsik Kim469c8342019-04-11 16:46:09 -0700665// InputBuffersArray
666
667void InputBuffersArray::initialize(
668 const FlexBuffersImpl &impl,
669 size_t minSize,
670 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700671 mAllocate = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -0700672 mImpl.initialize(impl, minSize, allocate);
673}
674
675void InputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
676 mImpl.getArray(array);
677}
678
679bool InputBuffersArray::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
680 sp<Codec2Buffer> c2Buffer;
681 status_t err = mImpl.grabBuffer(index, &c2Buffer);
682 if (err == OK) {
683 c2Buffer->setFormat(mFormat);
684 handleImageData(c2Buffer);
685 *buffer = c2Buffer;
686 return true;
687 }
688 return false;
689}
690
691bool InputBuffersArray::releaseBuffer(
692 const sp<MediaCodecBuffer> &buffer,
693 std::shared_ptr<C2Buffer> *c2buffer,
694 bool release) {
695 return mImpl.returnBuffer(buffer, c2buffer, release);
696}
697
698bool InputBuffersArray::expireComponentBuffer(
699 const std::shared_ptr<C2Buffer> &c2buffer) {
700 return mImpl.expireComponentBuffer(c2buffer);
701}
702
703void InputBuffersArray::flush() {
704 mImpl.flush();
705}
706
Wonsik Kim0487b782020-10-28 11:45:50 -0700707size_t InputBuffersArray::numActiveSlots() const {
708 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700709}
710
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700711sp<Codec2Buffer> InputBuffersArray::createNewBuffer() {
712 return mAllocate();
713}
714
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800715// SlotInputBuffers
716
717bool SlotInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
718 sp<Codec2Buffer> newBuffer = createNewBuffer();
719 *index = mImpl.assignSlot(newBuffer);
720 *buffer = newBuffer;
721 return true;
722}
723
724bool SlotInputBuffers::releaseBuffer(
725 const sp<MediaCodecBuffer> &buffer,
726 std::shared_ptr<C2Buffer> *c2buffer,
727 bool release) {
728 return mImpl.releaseSlot(buffer, c2buffer, release);
729}
730
731bool SlotInputBuffers::expireComponentBuffer(
732 const std::shared_ptr<C2Buffer> &c2buffer) {
733 return mImpl.expireComponentBuffer(c2buffer);
734}
735
736void SlotInputBuffers::flush() {
737 mImpl.flush();
738}
739
740std::unique_ptr<InputBuffers> SlotInputBuffers::toArrayMode(size_t) {
741 TRESPASS("Array mode should not be called at non-legacy mode");
742 return nullptr;
743}
744
Wonsik Kim0487b782020-10-28 11:45:50 -0700745size_t SlotInputBuffers::numActiveSlots() const {
746 return mImpl.numActiveSlots();
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800747}
748
749sp<Codec2Buffer> SlotInputBuffers::createNewBuffer() {
750 return new DummyContainerBuffer{mFormat, nullptr};
751}
752
Wonsik Kim469c8342019-04-11 16:46:09 -0700753// LinearInputBuffers
754
755bool LinearInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700756 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700757 if (newBuffer == nullptr) {
758 return false;
759 }
760 *index = mImpl.assignSlot(newBuffer);
761 *buffer = newBuffer;
762 return true;
763}
764
765bool LinearInputBuffers::releaseBuffer(
766 const sp<MediaCodecBuffer> &buffer,
767 std::shared_ptr<C2Buffer> *c2buffer,
768 bool release) {
769 return mImpl.releaseSlot(buffer, c2buffer, release);
770}
771
772bool LinearInputBuffers::expireComponentBuffer(
773 const std::shared_ptr<C2Buffer> &c2buffer) {
774 return mImpl.expireComponentBuffer(c2buffer);
775}
776
777void LinearInputBuffers::flush() {
778 // This is no-op by default unless we're in array mode where we need to keep
779 // track of the flushed work.
780 mImpl.flush();
781}
782
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700783std::unique_ptr<InputBuffers> LinearInputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -0700784 std::unique_ptr<InputBuffersArray> array(
785 new InputBuffersArray(mComponentName.c_str(), "1D-Input[N]"));
786 array->setPool(mPool);
787 array->setFormat(mFormat);
788 array->initialize(
789 mImpl,
790 size,
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700791 [pool = mPool, format = mFormat] () -> sp<Codec2Buffer> {
792 return Alloc(pool, format);
793 });
Wonsik Kim469c8342019-04-11 16:46:09 -0700794 return std::move(array);
795}
796
Wonsik Kim0487b782020-10-28 11:45:50 -0700797size_t LinearInputBuffers::numActiveSlots() const {
798 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700799}
800
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700801// static
802sp<Codec2Buffer> LinearInputBuffers::Alloc(
803 const std::shared_ptr<C2BlockPool> &pool, const sp<AMessage> &format) {
804 int32_t capacity = kLinearBufferSize;
805 (void)format->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
806 if ((size_t)capacity > kMaxLinearBufferSize) {
807 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
808 capacity = kMaxLinearBufferSize;
809 }
810
Wonsik Kim666604a2020-05-14 16:57:49 -0700811 int64_t usageValue = 0;
812 (void)format->findInt64("android._C2MemoryUsage", &usageValue);
813 C2MemoryUsage usage{usageValue | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE};
Wonsik Kim469c8342019-04-11 16:46:09 -0700814 std::shared_ptr<C2LinearBlock> block;
815
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700816 c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block);
Wonsik Kim469c8342019-04-11 16:46:09 -0700817 if (err != C2_OK) {
818 return nullptr;
819 }
820
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700821 return LinearBlockBuffer::Allocate(format, block);
822}
823
824sp<Codec2Buffer> LinearInputBuffers::createNewBuffer() {
825 return Alloc(mPool, mFormat);
Wonsik Kim469c8342019-04-11 16:46:09 -0700826}
827
828// EncryptedLinearInputBuffers
829
830EncryptedLinearInputBuffers::EncryptedLinearInputBuffers(
831 bool secure,
832 const sp<MemoryDealer> &dealer,
833 const sp<ICrypto> &crypto,
834 int32_t heapSeqNum,
835 size_t capacity,
836 size_t numInputSlots,
837 const char *componentName, const char *name)
838 : LinearInputBuffers(componentName, name),
839 mUsage({0, 0}),
840 mDealer(dealer),
841 mCrypto(crypto),
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700842 mMemoryVector(new std::vector<Entry>){
Wonsik Kim469c8342019-04-11 16:46:09 -0700843 if (secure) {
844 mUsage = { C2MemoryUsage::READ_PROTECTED, 0 };
845 } else {
846 mUsage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
847 }
848 for (size_t i = 0; i < numInputSlots; ++i) {
849 sp<IMemory> memory = mDealer->allocate(capacity);
850 if (memory == nullptr) {
851 ALOGD("[%s] Failed to allocate memory from dealer: only %zu slots allocated",
852 mName, i);
853 break;
854 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700855 mMemoryVector->push_back({std::weak_ptr<C2LinearBlock>(), memory, heapSeqNum});
Wonsik Kim469c8342019-04-11 16:46:09 -0700856 }
857}
858
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700859std::unique_ptr<InputBuffers> EncryptedLinearInputBuffers::toArrayMode(size_t size) {
860 std::unique_ptr<InputBuffersArray> array(
861 new InputBuffersArray(mComponentName.c_str(), "1D-EncryptedInput[N]"));
862 array->setPool(mPool);
863 array->setFormat(mFormat);
864 array->initialize(
865 mImpl,
866 size,
867 [pool = mPool,
868 format = mFormat,
869 usage = mUsage,
870 memoryVector = mMemoryVector] () -> sp<Codec2Buffer> {
871 return Alloc(pool, format, usage, memoryVector);
872 });
873 return std::move(array);
874}
875
876
877// static
878sp<Codec2Buffer> EncryptedLinearInputBuffers::Alloc(
879 const std::shared_ptr<C2BlockPool> &pool,
880 const sp<AMessage> &format,
881 C2MemoryUsage usage,
882 const std::shared_ptr<std::vector<EncryptedLinearInputBuffers::Entry>> &memoryVector) {
883 int32_t capacity = kLinearBufferSize;
884 (void)format->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
885 if ((size_t)capacity > kMaxLinearBufferSize) {
886 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
887 capacity = kMaxLinearBufferSize;
888 }
889
Wonsik Kim469c8342019-04-11 16:46:09 -0700890 sp<IMemory> memory;
891 size_t slot = 0;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700892 int32_t heapSeqNum = -1;
893 for (; slot < memoryVector->size(); ++slot) {
894 if (memoryVector->at(slot).block.expired()) {
895 memory = memoryVector->at(slot).memory;
896 heapSeqNum = memoryVector->at(slot).heapSeqNum;
Wonsik Kim469c8342019-04-11 16:46:09 -0700897 break;
898 }
899 }
900 if (memory == nullptr) {
901 return nullptr;
902 }
903
904 std::shared_ptr<C2LinearBlock> block;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700905 c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block);
Wonsik Kim469c8342019-04-11 16:46:09 -0700906 if (err != C2_OK || block == nullptr) {
907 return nullptr;
908 }
909
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700910 memoryVector->at(slot).block = block;
911 return new EncryptedLinearBlockBuffer(format, block, memory, heapSeqNum);
912}
913
914sp<Codec2Buffer> EncryptedLinearInputBuffers::createNewBuffer() {
915 // TODO: android_2020
916 return nullptr;
Wonsik Kim469c8342019-04-11 16:46:09 -0700917}
918
919// GraphicMetadataInputBuffers
920
921GraphicMetadataInputBuffers::GraphicMetadataInputBuffers(
922 const char *componentName, const char *name)
923 : InputBuffers(componentName, name),
924 mImpl(mName),
925 mStore(GetCodec2PlatformAllocatorStore()) { }
926
927bool GraphicMetadataInputBuffers::requestNewBuffer(
928 size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700929 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700930 if (newBuffer == nullptr) {
931 return false;
932 }
933 *index = mImpl.assignSlot(newBuffer);
934 *buffer = newBuffer;
935 return true;
936}
937
938bool GraphicMetadataInputBuffers::releaseBuffer(
939 const sp<MediaCodecBuffer> &buffer,
940 std::shared_ptr<C2Buffer> *c2buffer,
941 bool release) {
942 return mImpl.releaseSlot(buffer, c2buffer, release);
943}
944
945bool GraphicMetadataInputBuffers::expireComponentBuffer(
946 const std::shared_ptr<C2Buffer> &c2buffer) {
947 return mImpl.expireComponentBuffer(c2buffer);
948}
949
950void GraphicMetadataInputBuffers::flush() {
951 // This is no-op by default unless we're in array mode where we need to keep
952 // track of the flushed work.
953}
954
955std::unique_ptr<InputBuffers> GraphicMetadataInputBuffers::toArrayMode(
956 size_t size) {
957 std::shared_ptr<C2Allocator> alloc;
958 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
959 if (err != C2_OK) {
960 return nullptr;
961 }
962 std::unique_ptr<InputBuffersArray> array(
963 new InputBuffersArray(mComponentName.c_str(), "2D-MetaInput[N]"));
964 array->setPool(mPool);
965 array->setFormat(mFormat);
966 array->initialize(
967 mImpl,
968 size,
969 [format = mFormat, alloc]() -> sp<Codec2Buffer> {
970 return new GraphicMetadataBuffer(format, alloc);
971 });
972 return std::move(array);
973}
974
Wonsik Kim0487b782020-10-28 11:45:50 -0700975size_t GraphicMetadataInputBuffers::numActiveSlots() const {
976 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700977}
978
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700979sp<Codec2Buffer> GraphicMetadataInputBuffers::createNewBuffer() {
980 std::shared_ptr<C2Allocator> alloc;
981 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
982 if (err != C2_OK) {
983 return nullptr;
984 }
985 return new GraphicMetadataBuffer(mFormat, alloc);
986}
987
Wonsik Kim469c8342019-04-11 16:46:09 -0700988// GraphicInputBuffers
989
990GraphicInputBuffers::GraphicInputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -0700991 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -0700992 : InputBuffers(componentName, name),
993 mImpl(mName),
Wonsik Kim41d83432020-04-27 16:40:49 -0700994 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -0700995
996bool GraphicInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700997 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700998 if (newBuffer == nullptr) {
999 return false;
1000 }
1001 *index = mImpl.assignSlot(newBuffer);
1002 handleImageData(newBuffer);
1003 *buffer = newBuffer;
1004 return true;
1005}
1006
1007bool GraphicInputBuffers::releaseBuffer(
1008 const sp<MediaCodecBuffer> &buffer,
1009 std::shared_ptr<C2Buffer> *c2buffer,
1010 bool release) {
1011 return mImpl.releaseSlot(buffer, c2buffer, release);
1012}
1013
1014bool GraphicInputBuffers::expireComponentBuffer(
1015 const std::shared_ptr<C2Buffer> &c2buffer) {
1016 return mImpl.expireComponentBuffer(c2buffer);
1017}
1018
1019void GraphicInputBuffers::flush() {
1020 // This is no-op by default unless we're in array mode where we need to keep
1021 // track of the flushed work.
1022}
1023
1024std::unique_ptr<InputBuffers> GraphicInputBuffers::toArrayMode(size_t size) {
1025 std::unique_ptr<InputBuffersArray> array(
1026 new InputBuffersArray(mComponentName.c_str(), "2D-BB-Input[N]"));
1027 array->setPool(mPool);
1028 array->setFormat(mFormat);
1029 array->initialize(
1030 mImpl,
1031 size,
1032 [pool = mPool, format = mFormat, lbp = mLocalBufferPool]() -> sp<Codec2Buffer> {
1033 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1034 return AllocateGraphicBuffer(
1035 pool, format, HAL_PIXEL_FORMAT_YV12, usage, lbp);
1036 });
1037 return std::move(array);
1038}
1039
Wonsik Kim0487b782020-10-28 11:45:50 -07001040size_t GraphicInputBuffers::numActiveSlots() const {
1041 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001042}
1043
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001044sp<Codec2Buffer> GraphicInputBuffers::createNewBuffer() {
Wonsik Kim666604a2020-05-14 16:57:49 -07001045 int64_t usageValue = 0;
1046 (void)mFormat->findInt64("android._C2MemoryUsage", &usageValue);
1047 C2MemoryUsage usage{usageValue | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE};
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001048 return AllocateGraphicBuffer(
1049 mPool, mFormat, HAL_PIXEL_FORMAT_YV12, usage, mLocalBufferPool);
1050}
1051
Wonsik Kim469c8342019-04-11 16:46:09 -07001052// OutputBuffersArray
1053
1054void OutputBuffersArray::initialize(
1055 const FlexBuffersImpl &impl,
1056 size_t minSize,
1057 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001058 mAlloc = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -07001059 mImpl.initialize(impl, minSize, allocate);
1060}
1061
1062status_t OutputBuffersArray::registerBuffer(
1063 const std::shared_ptr<C2Buffer> &buffer,
1064 size_t *index,
1065 sp<MediaCodecBuffer> *clientBuffer) {
1066 sp<Codec2Buffer> c2Buffer;
1067 status_t err = mImpl.grabBuffer(
1068 index,
1069 &c2Buffer,
1070 [buffer](const sp<Codec2Buffer> &clientBuffer) {
1071 return clientBuffer->canCopy(buffer);
1072 });
1073 if (err == WOULD_BLOCK) {
1074 ALOGV("[%s] buffers temporarily not available", mName);
1075 return err;
1076 } else if (err != OK) {
1077 ALOGD("[%s] grabBuffer failed: %d", mName, err);
1078 return err;
1079 }
1080 c2Buffer->setFormat(mFormat);
1081 if (!c2Buffer->copy(buffer)) {
1082 ALOGD("[%s] copy buffer failed", mName);
1083 return WOULD_BLOCK;
1084 }
1085 submit(c2Buffer);
1086 handleImageData(c2Buffer);
1087 *clientBuffer = c2Buffer;
1088 ALOGV("[%s] grabbed buffer %zu", mName, *index);
1089 return OK;
1090}
1091
1092status_t OutputBuffersArray::registerCsd(
1093 const C2StreamInitDataInfo::output *csd,
1094 size_t *index,
1095 sp<MediaCodecBuffer> *clientBuffer) {
1096 sp<Codec2Buffer> c2Buffer;
1097 status_t err = mImpl.grabBuffer(
1098 index,
1099 &c2Buffer,
1100 [csd](const sp<Codec2Buffer> &clientBuffer) {
1101 return clientBuffer->base() != nullptr
1102 && clientBuffer->capacity() >= csd->flexCount();
1103 });
1104 if (err != OK) {
1105 return err;
1106 }
1107 memcpy(c2Buffer->base(), csd->m.value, csd->flexCount());
1108 c2Buffer->setRange(0, csd->flexCount());
1109 c2Buffer->setFormat(mFormat);
1110 *clientBuffer = c2Buffer;
1111 return OK;
1112}
1113
1114bool OutputBuffersArray::releaseBuffer(
1115 const sp<MediaCodecBuffer> &buffer, std::shared_ptr<C2Buffer> *c2buffer) {
1116 return mImpl.returnBuffer(buffer, c2buffer, true);
1117}
1118
1119void OutputBuffersArray::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1120 (void)flushedWork;
1121 mImpl.flush();
1122 if (mSkipCutBuffer != nullptr) {
1123 mSkipCutBuffer->clear();
1124 }
1125}
1126
1127void OutputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
1128 mImpl.getArray(array);
1129}
1130
Wonsik Kim0487b782020-10-28 11:45:50 -07001131size_t OutputBuffersArray::numActiveSlots() const {
1132 return mImpl.numActiveSlots();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001133}
1134
Wonsik Kim469c8342019-04-11 16:46:09 -07001135void OutputBuffersArray::realloc(const std::shared_ptr<C2Buffer> &c2buffer) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001136 switch (c2buffer->data().type()) {
1137 case C2BufferData::LINEAR: {
1138 uint32_t size = kLinearBufferSize;
Nick Desaulniersd09eaea2019-10-07 20:19:39 -07001139 const std::vector<C2ConstLinearBlock> &linear_blocks = c2buffer->data().linearBlocks();
1140 const uint32_t block_size = linear_blocks.front().size();
1141 if (block_size < kMaxLinearBufferSize / 2) {
1142 size = block_size * 2;
Wonsik Kim469c8342019-04-11 16:46:09 -07001143 } else {
1144 size = kMaxLinearBufferSize;
1145 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001146 mAlloc = [format = mFormat, size] {
Wonsik Kim469c8342019-04-11 16:46:09 -07001147 return new LocalLinearBuffer(format, new ABuffer(size));
1148 };
Wonsik Kima39882b2019-06-20 16:13:56 -07001149 ALOGD("[%s] reallocating with linear buffer of size %u", mName, size);
Wonsik Kim469c8342019-04-11 16:46:09 -07001150 break;
1151 }
1152
Wonsik Kima39882b2019-06-20 16:13:56 -07001153 case C2BufferData::GRAPHIC: {
1154 // This is only called for RawGraphicOutputBuffers.
1155 mAlloc = [format = mFormat,
Wonsik Kim41d83432020-04-27 16:40:49 -07001156 lbp = LocalBufferPool::Create()] {
Wonsik Kima39882b2019-06-20 16:13:56 -07001157 return ConstGraphicBlockBuffer::AllocateEmpty(
1158 format,
1159 [lbp](size_t capacity) {
1160 return lbp->newBuffer(capacity);
1161 });
1162 };
1163 ALOGD("[%s] reallocating with graphic buffer: format = %s",
1164 mName, mFormat->debugString().c_str());
1165 break;
1166 }
Wonsik Kim469c8342019-04-11 16:46:09 -07001167
1168 case C2BufferData::INVALID: [[fallthrough]];
1169 case C2BufferData::LINEAR_CHUNKS: [[fallthrough]];
1170 case C2BufferData::GRAPHIC_CHUNKS: [[fallthrough]];
1171 default:
1172 ALOGD("Unsupported type: %d", (int)c2buffer->data().type());
1173 return;
1174 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001175 mImpl.realloc(mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001176}
1177
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001178void OutputBuffersArray::grow(size_t newSize) {
1179 mImpl.grow(newSize, mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001180}
1181
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001182void OutputBuffersArray::transferFrom(OutputBuffers* source) {
1183 mFormat = source->mFormat;
1184 mSkipCutBuffer = source->mSkipCutBuffer;
Wonsik Kim8ec93ab2020-11-13 16:17:04 -08001185 mUnreportedFormat = source->mUnreportedFormat;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001186 mPending = std::move(source->mPending);
1187 mReorderStash = std::move(source->mReorderStash);
1188 mDepth = source->mDepth;
1189 mKey = source->mKey;
1190}
1191
Wonsik Kim469c8342019-04-11 16:46:09 -07001192// FlexOutputBuffers
1193
1194status_t FlexOutputBuffers::registerBuffer(
1195 const std::shared_ptr<C2Buffer> &buffer,
1196 size_t *index,
1197 sp<MediaCodecBuffer> *clientBuffer) {
1198 sp<Codec2Buffer> newBuffer = wrap(buffer);
1199 if (newBuffer == nullptr) {
1200 return NO_MEMORY;
1201 }
1202 newBuffer->setFormat(mFormat);
1203 *index = mImpl.assignSlot(newBuffer);
1204 handleImageData(newBuffer);
1205 *clientBuffer = newBuffer;
1206 ALOGV("[%s] registered buffer %zu", mName, *index);
1207 return OK;
1208}
1209
1210status_t FlexOutputBuffers::registerCsd(
1211 const C2StreamInitDataInfo::output *csd,
1212 size_t *index,
1213 sp<MediaCodecBuffer> *clientBuffer) {
1214 sp<Codec2Buffer> newBuffer = new LocalLinearBuffer(
1215 mFormat, ABuffer::CreateAsCopy(csd->m.value, csd->flexCount()));
1216 *index = mImpl.assignSlot(newBuffer);
1217 *clientBuffer = newBuffer;
1218 return OK;
1219}
1220
1221bool FlexOutputBuffers::releaseBuffer(
1222 const sp<MediaCodecBuffer> &buffer,
1223 std::shared_ptr<C2Buffer> *c2buffer) {
1224 return mImpl.releaseSlot(buffer, c2buffer, true);
1225}
1226
1227void FlexOutputBuffers::flush(
1228 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1229 (void) flushedWork;
1230 // This is no-op by default unless we're in array mode where we need to keep
1231 // track of the flushed work.
1232}
1233
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001234std::unique_ptr<OutputBuffersArray> FlexOutputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001235 std::unique_ptr<OutputBuffersArray> array(new OutputBuffersArray(mComponentName.c_str()));
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001236 array->transferFrom(this);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001237 std::function<sp<Codec2Buffer>()> alloc = getAlloc();
1238 array->initialize(mImpl, size, alloc);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001239 return array;
Wonsik Kim469c8342019-04-11 16:46:09 -07001240}
1241
Wonsik Kim0487b782020-10-28 11:45:50 -07001242size_t FlexOutputBuffers::numActiveSlots() const {
1243 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001244}
1245
1246// LinearOutputBuffers
1247
1248void LinearOutputBuffers::flush(
1249 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1250 if (mSkipCutBuffer != nullptr) {
1251 mSkipCutBuffer->clear();
1252 }
1253 FlexOutputBuffers::flush(flushedWork);
1254}
1255
1256sp<Codec2Buffer> LinearOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1257 if (buffer == nullptr) {
1258 ALOGV("[%s] using a dummy buffer", mName);
1259 return new LocalLinearBuffer(mFormat, new ABuffer(0));
1260 }
1261 if (buffer->data().type() != C2BufferData::LINEAR) {
1262 ALOGV("[%s] non-linear buffer %d", mName, buffer->data().type());
1263 // We expect linear output buffers from the component.
1264 return nullptr;
1265 }
1266 if (buffer->data().linearBlocks().size() != 1u) {
1267 ALOGV("[%s] no linear buffers", mName);
1268 // We expect one and only one linear block from the component.
1269 return nullptr;
1270 }
1271 sp<Codec2Buffer> clientBuffer = ConstLinearBlockBuffer::Allocate(mFormat, buffer);
1272 if (clientBuffer == nullptr) {
1273 ALOGD("[%s] ConstLinearBlockBuffer::Allocate failed", mName);
1274 return nullptr;
1275 }
1276 submit(clientBuffer);
1277 return clientBuffer;
1278}
1279
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001280std::function<sp<Codec2Buffer>()> LinearOutputBuffers::getAlloc() {
1281 return [format = mFormat]{
1282 // TODO: proper max output size
1283 return new LocalLinearBuffer(format, new ABuffer(kLinearBufferSize));
1284 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001285}
1286
1287// GraphicOutputBuffers
1288
1289sp<Codec2Buffer> GraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1290 return new DummyContainerBuffer(mFormat, buffer);
1291}
1292
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001293std::function<sp<Codec2Buffer>()> GraphicOutputBuffers::getAlloc() {
1294 return [format = mFormat]{
1295 return new DummyContainerBuffer(format);
1296 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001297}
1298
1299// RawGraphicOutputBuffers
1300
1301RawGraphicOutputBuffers::RawGraphicOutputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -07001302 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -07001303 : FlexOutputBuffers(componentName, name),
Wonsik Kim41d83432020-04-27 16:40:49 -07001304 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -07001305
1306sp<Codec2Buffer> RawGraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1307 if (buffer == nullptr) {
1308 sp<Codec2Buffer> c2buffer = ConstGraphicBlockBuffer::AllocateEmpty(
1309 mFormat,
1310 [lbp = mLocalBufferPool](size_t capacity) {
1311 return lbp->newBuffer(capacity);
1312 });
1313 if (c2buffer == nullptr) {
1314 ALOGD("[%s] ConstGraphicBlockBuffer::AllocateEmpty failed", mName);
1315 return nullptr;
1316 }
1317 c2buffer->setRange(0, 0);
1318 return c2buffer;
1319 } else {
1320 return ConstGraphicBlockBuffer::Allocate(
1321 mFormat,
1322 buffer,
1323 [lbp = mLocalBufferPool](size_t capacity) {
1324 return lbp->newBuffer(capacity);
1325 });
1326 }
1327}
1328
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001329std::function<sp<Codec2Buffer>()> RawGraphicOutputBuffers::getAlloc() {
1330 return [format = mFormat, lbp = mLocalBufferPool]{
1331 return ConstGraphicBlockBuffer::AllocateEmpty(
1332 format,
1333 [lbp](size_t capacity) {
1334 return lbp->newBuffer(capacity);
1335 });
1336 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001337}
1338
1339} // namespace android