blob: ba440744e926f6509253c84b38e357ab3b39f51d [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"
Wonsik Kimd79ee1f2020-08-27 17:41:56 -070030#include "Codec2Mapper.h"
Wonsik Kim469c8342019-04-11 16:46:09 -070031
32namespace android {
33
34namespace {
35
36sp<GraphicBlockBuffer> AllocateGraphicBuffer(
37 const std::shared_ptr<C2BlockPool> &pool,
38 const sp<AMessage> &format,
39 uint32_t pixelFormat,
40 const C2MemoryUsage &usage,
41 const std::shared_ptr<LocalBufferPool> &localBufferPool) {
42 int32_t width, height;
43 if (!format->findInt32("width", &width) || !format->findInt32("height", &height)) {
44 ALOGD("format lacks width or height");
45 return nullptr;
46 }
47
48 std::shared_ptr<C2GraphicBlock> block;
49 c2_status_t err = pool->fetchGraphicBlock(
50 width, height, pixelFormat, usage, &block);
51 if (err != C2_OK) {
52 ALOGD("fetch graphic block failed: %d", err);
53 return nullptr;
54 }
55
56 return GraphicBlockBuffer::Allocate(
57 format,
58 block,
59 [localBufferPool](size_t capacity) {
60 return localBufferPool->newBuffer(capacity);
61 });
62}
63
64} // namespace
65
66// CCodecBuffers
67
68void CCodecBuffers::setFormat(const sp<AMessage> &format) {
69 CHECK(format != nullptr);
70 mFormat = format;
71}
72
73sp<AMessage> CCodecBuffers::dupFormat() {
74 return mFormat != nullptr ? mFormat->dup() : nullptr;
75}
76
77void CCodecBuffers::handleImageData(const sp<Codec2Buffer> &buffer) {
78 sp<ABuffer> imageDataCandidate = buffer->getImageData();
79 if (imageDataCandidate == nullptr) {
Wonsik Kim4a3c0462021-03-09 15:45:05 -080080 if (mFormatWithImageData) {
81 // We previously sent the format with image data, so use the same format.
82 buffer->setFormat(mFormatWithImageData);
83 }
Wonsik Kim469c8342019-04-11 16:46:09 -070084 return;
85 }
Wonsik Kim4a3c0462021-03-09 15:45:05 -080086 if (!mLastImageData
87 || imageDataCandidate->size() != mLastImageData->size()
88 || memcmp(imageDataCandidate->data(),
89 mLastImageData->data(),
90 mLastImageData->size()) != 0) {
Wonsik Kim469c8342019-04-11 16:46:09 -070091 ALOGD("[%s] updating image-data", mName);
Wonsik Kim4a3c0462021-03-09 15:45:05 -080092 mFormatWithImageData = dupFormat();
93 mLastImageData = imageDataCandidate;
94 mFormatWithImageData->setBuffer("image-data", imageDataCandidate);
Wonsik Kim469c8342019-04-11 16:46:09 -070095 MediaImage2 *img = (MediaImage2*)imageDataCandidate->data();
96 if (img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
97 int32_t stride = img->mPlane[0].mRowInc;
Wonsik Kim4a3c0462021-03-09 15:45:05 -080098 mFormatWithImageData->setInt32(KEY_STRIDE, stride);
Wonsik Kim469c8342019-04-11 16:46:09 -070099 ALOGD("[%s] updating stride = %d", mName, stride);
100 if (img->mNumPlanes > 1 && stride > 0) {
Taehwan Kimfd9b8092020-09-17 12:26:40 +0900101 int64_t offsetDelta =
102 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
103 int32_t vstride = int32_t(offsetDelta / stride);
Wonsik Kim4a3c0462021-03-09 15:45:05 -0800104 mFormatWithImageData->setInt32(KEY_SLICE_HEIGHT, vstride);
Wonsik Kim469c8342019-04-11 16:46:09 -0700105 ALOGD("[%s] updating vstride = %d", mName, vstride);
Wonsik Kim2eb06312020-12-03 11:07:58 -0800106 buffer->setRange(
107 img->mPlane[0].mOffset,
108 buffer->size() - img->mPlane[0].mOffset);
Wonsik Kim469c8342019-04-11 16:46:09 -0700109 }
110 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700111 }
Wonsik Kim4a3c0462021-03-09 15:45:05 -0800112 buffer->setFormat(mFormatWithImageData);
Wonsik Kim469c8342019-04-11 16:46:09 -0700113}
114
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700115// InputBuffers
116
117sp<Codec2Buffer> InputBuffers::cloneAndReleaseBuffer(const sp<MediaCodecBuffer> &buffer) {
118 sp<Codec2Buffer> copy = createNewBuffer();
119 if (copy == nullptr) {
120 return nullptr;
121 }
122 std::shared_ptr<C2Buffer> c2buffer;
123 if (!releaseBuffer(buffer, &c2buffer, true)) {
124 return nullptr;
125 }
126 if (!copy->canCopy(c2buffer)) {
127 return nullptr;
128 }
129 if (!copy->copy(c2buffer)) {
130 return nullptr;
131 }
132 return copy;
133}
134
Wonsik Kim469c8342019-04-11 16:46:09 -0700135// OutputBuffers
136
Wonsik Kim41d83432020-04-27 16:40:49 -0700137OutputBuffers::OutputBuffers(const char *componentName, const char *name)
138 : CCodecBuffers(componentName, name) { }
139
140OutputBuffers::~OutputBuffers() = default;
141
Wonsik Kim469c8342019-04-11 16:46:09 -0700142void OutputBuffers::initSkipCutBuffer(
143 int32_t delay, int32_t padding, int32_t sampleRate, int32_t channelCount) {
144 CHECK(mSkipCutBuffer == nullptr);
145 mDelay = delay;
146 mPadding = padding;
147 mSampleRate = sampleRate;
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700148 mChannelCount = channelCount;
149 setSkipCutBuffer(delay, padding);
Wonsik Kim469c8342019-04-11 16:46:09 -0700150}
151
152void OutputBuffers::updateSkipCutBuffer(int32_t sampleRate, int32_t channelCount) {
153 if (mSkipCutBuffer == nullptr) {
154 return;
155 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700156 if (mSampleRate == sampleRate && mChannelCount == channelCount) {
157 return;
158 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700159 int32_t delay = mDelay;
160 int32_t padding = mPadding;
161 if (sampleRate != mSampleRate) {
162 delay = ((int64_t)delay * sampleRate) / mSampleRate;
163 padding = ((int64_t)padding * sampleRate) / mSampleRate;
164 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700165 mSampleRate = sampleRate;
166 mChannelCount = channelCount;
167 setSkipCutBuffer(delay, padding);
Wonsik Kim469c8342019-04-11 16:46:09 -0700168}
169
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800170void OutputBuffers::updateSkipCutBuffer(const sp<AMessage> &format) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700171 AString mediaType;
172 if (format->findString(KEY_MIME, &mediaType)
173 && mediaType == MIMETYPE_AUDIO_RAW) {
174 int32_t channelCount;
175 int32_t sampleRate;
176 if (format->findInt32(KEY_CHANNEL_COUNT, &channelCount)
177 && format->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
178 updateSkipCutBuffer(sampleRate, channelCount);
179 }
180 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700181}
182
Wonsik Kim469c8342019-04-11 16:46:09 -0700183void OutputBuffers::submit(const sp<MediaCodecBuffer> &buffer) {
184 if (mSkipCutBuffer != nullptr) {
185 mSkipCutBuffer->submit(buffer);
186 }
187}
188
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700189void OutputBuffers::setSkipCutBuffer(int32_t skip, int32_t cut) {
Wonsik Kim469c8342019-04-11 16:46:09 -0700190 if (mSkipCutBuffer != nullptr) {
191 size_t prevSize = mSkipCutBuffer->size();
192 if (prevSize != 0u) {
193 ALOGD("[%s] Replacing SkipCutBuffer holding %zu bytes", mName, prevSize);
194 }
195 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700196 mSkipCutBuffer = new SkipCutBuffer(skip, cut, mChannelCount);
Wonsik Kim469c8342019-04-11 16:46:09 -0700197}
198
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700199void OutputBuffers::clearStash() {
200 mPending.clear();
201 mReorderStash.clear();
202 mDepth = 0;
203 mKey = C2Config::ORDINAL;
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700204}
205
206void OutputBuffers::flushStash() {
207 for (StashEntry& e : mPending) {
208 e.notify = false;
209 }
210 for (StashEntry& e : mReorderStash) {
211 e.notify = false;
212 }
213}
214
215uint32_t OutputBuffers::getReorderDepth() const {
216 return mDepth;
217}
218
219void OutputBuffers::setReorderDepth(uint32_t depth) {
220 mPending.splice(mPending.end(), mReorderStash);
221 mDepth = depth;
222}
223
224void OutputBuffers::setReorderKey(C2Config::ordinal_key_t key) {
225 mPending.splice(mPending.end(), mReorderStash);
226 mKey = key;
227}
228
229void OutputBuffers::pushToStash(
230 const std::shared_ptr<C2Buffer>& buffer,
231 bool notify,
232 int64_t timestamp,
233 int32_t flags,
234 const sp<AMessage>& format,
235 const C2WorkOrdinalStruct& ordinal) {
236 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
237 if (!buffer && eos) {
238 // TRICKY: we may be violating ordering of the stash here. Because we
239 // don't expect any more emplace() calls after this, the ordering should
240 // not matter.
241 mReorderStash.emplace_back(
242 buffer, notify, timestamp, flags, format, ordinal);
243 } else {
244 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
245 auto it = mReorderStash.begin();
246 for (; it != mReorderStash.end(); ++it) {
247 if (less(ordinal, it->ordinal)) {
248 break;
249 }
250 }
251 mReorderStash.emplace(it,
252 buffer, notify, timestamp, flags, format, ordinal);
253 if (eos) {
254 mReorderStash.back().flags =
255 mReorderStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
256 }
257 }
258 while (!mReorderStash.empty() && mReorderStash.size() > mDepth) {
259 mPending.push_back(mReorderStash.front());
260 mReorderStash.pop_front();
261 }
262 ALOGV("[%s] %s: pushToStash -- pending size = %zu", mName, __func__, mPending.size());
263}
264
265OutputBuffers::BufferAction OutputBuffers::popFromStashAndRegister(
266 std::shared_ptr<C2Buffer>* c2Buffer,
267 size_t* index,
268 sp<MediaCodecBuffer>* outBuffer) {
269 if (mPending.empty()) {
270 return SKIP;
271 }
272
273 // Retrieve the first entry.
274 StashEntry &entry = mPending.front();
275
276 *c2Buffer = entry.buffer;
277 sp<AMessage> outputFormat = entry.format;
278
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800279 if (entry.notify && mFormat != outputFormat) {
280 updateSkipCutBuffer(outputFormat);
Wonsik Kim4a3c0462021-03-09 15:45:05 -0800281 // Trigger image data processing to the new format
282 mLastImageData.clear();
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800283 ALOGV("[%s] popFromStashAndRegister: output format reference changed: %p -> %p",
284 mName, mFormat.get(), outputFormat.get());
Wonsik Kim4a3c0462021-03-09 15:45:05 -0800285 ALOGD("[%s] popFromStashAndRegister: at %lldus, output format changed to %s",
286 mName, (long long)entry.timestamp, outputFormat->debugString().c_str());
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800287 setFormat(outputFormat);
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700288 }
289
290 // Flushing mReorderStash because no other buffers should come after output
291 // EOS.
292 if (entry.flags & MediaCodec::BUFFER_FLAG_EOS) {
293 // Flush reorder stash
294 setReorderDepth(0);
295 }
296
297 if (!entry.notify) {
298 mPending.pop_front();
299 return DISCARD;
300 }
301
302 // Try to register the buffer.
303 status_t err = registerBuffer(*c2Buffer, index, outBuffer);
304 if (err != OK) {
305 if (err != WOULD_BLOCK) {
306 return REALLOCATE;
307 }
308 return RETRY;
309 }
310
311 // Append information from the front stash entry to outBuffer.
312 (*outBuffer)->meta()->setInt64("timeUs", entry.timestamp);
313 (*outBuffer)->meta()->setInt32("flags", entry.flags);
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900314 (*outBuffer)->meta()->setInt64("frameIndex", entry.ordinal.frameIndex.peekll());
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700315 ALOGV("[%s] popFromStashAndRegister: "
316 "out buffer index = %zu [%p] => %p + %zu (%lld)",
317 mName, *index, outBuffer->get(),
318 (*outBuffer)->data(), (*outBuffer)->size(),
319 (long long)entry.timestamp);
320
321 // The front entry of mPending will be removed now that the registration
322 // succeeded.
323 mPending.pop_front();
324 return NOTIFY_CLIENT;
325}
326
327bool OutputBuffers::popPending(StashEntry *entry) {
328 if (mPending.empty()) {
329 return false;
330 }
331 *entry = mPending.front();
332 mPending.pop_front();
333 return true;
334}
335
336void OutputBuffers::deferPending(const OutputBuffers::StashEntry &entry) {
337 mPending.push_front(entry);
338}
339
340bool OutputBuffers::hasPending() const {
341 return !mPending.empty();
342}
343
344bool OutputBuffers::less(
345 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) const {
346 switch (mKey) {
347 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
348 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
349 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
350 default:
351 ALOGD("Unrecognized key; default to timestamp");
352 return o1.frameIndex < o2.frameIndex;
353 }
354}
355
Wonsik Kim469c8342019-04-11 16:46:09 -0700356// LocalBufferPool
357
Wonsik Kim41d83432020-04-27 16:40:49 -0700358constexpr size_t kInitialPoolCapacity = kMaxLinearBufferSize;
359constexpr size_t kMaxPoolCapacity = kMaxLinearBufferSize * 32;
360
361std::shared_ptr<LocalBufferPool> LocalBufferPool::Create() {
362 return std::shared_ptr<LocalBufferPool>(new LocalBufferPool(kInitialPoolCapacity));
Wonsik Kim469c8342019-04-11 16:46:09 -0700363}
364
365sp<ABuffer> LocalBufferPool::newBuffer(size_t capacity) {
366 Mutex::Autolock lock(mMutex);
367 auto it = std::find_if(
368 mPool.begin(), mPool.end(),
369 [capacity](const std::vector<uint8_t> &vec) {
370 return vec.capacity() >= capacity;
371 });
372 if (it != mPool.end()) {
373 sp<ABuffer> buffer = new VectorBuffer(std::move(*it), shared_from_this());
374 mPool.erase(it);
375 return buffer;
376 }
377 if (mUsedSize + capacity > mPoolCapacity) {
378 while (!mPool.empty()) {
379 mUsedSize -= mPool.back().capacity();
380 mPool.pop_back();
381 }
Wonsik Kim41d83432020-04-27 16:40:49 -0700382 while (mUsedSize + capacity > mPoolCapacity && mPoolCapacity * 2 <= kMaxPoolCapacity) {
383 ALOGD("Increasing local buffer pool capacity from %zu to %zu",
384 mPoolCapacity, mPoolCapacity * 2);
385 mPoolCapacity *= 2;
386 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700387 if (mUsedSize + capacity > mPoolCapacity) {
388 ALOGD("mUsedSize = %zu, capacity = %zu, mPoolCapacity = %zu",
389 mUsedSize, capacity, mPoolCapacity);
390 return nullptr;
391 }
392 }
393 std::vector<uint8_t> vec(capacity);
394 mUsedSize += vec.capacity();
395 return new VectorBuffer(std::move(vec), shared_from_this());
396}
397
398LocalBufferPool::VectorBuffer::VectorBuffer(
399 std::vector<uint8_t> &&vec, const std::shared_ptr<LocalBufferPool> &pool)
400 : ABuffer(vec.data(), vec.capacity()),
401 mVec(std::move(vec)),
402 mPool(pool) {
403}
404
405LocalBufferPool::VectorBuffer::~VectorBuffer() {
406 std::shared_ptr<LocalBufferPool> pool = mPool.lock();
407 if (pool) {
408 // If pool is alive, return the vector back to the pool so that
409 // it can be recycled.
410 pool->returnVector(std::move(mVec));
411 }
412}
413
414void LocalBufferPool::returnVector(std::vector<uint8_t> &&vec) {
415 Mutex::Autolock lock(mMutex);
416 mPool.push_front(std::move(vec));
417}
418
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700419// FlexBuffersImpl
420
Wonsik Kim469c8342019-04-11 16:46:09 -0700421size_t FlexBuffersImpl::assignSlot(const sp<Codec2Buffer> &buffer) {
422 for (size_t i = 0; i < mBuffers.size(); ++i) {
423 if (mBuffers[i].clientBuffer == nullptr
424 && mBuffers[i].compBuffer.expired()) {
425 mBuffers[i].clientBuffer = buffer;
426 return i;
427 }
428 }
429 mBuffers.push_back({ buffer, std::weak_ptr<C2Buffer>() });
430 return mBuffers.size() - 1;
431}
432
Wonsik Kim469c8342019-04-11 16:46:09 -0700433bool FlexBuffersImpl::releaseSlot(
434 const sp<MediaCodecBuffer> &buffer,
435 std::shared_ptr<C2Buffer> *c2buffer,
436 bool release) {
437 sp<Codec2Buffer> clientBuffer;
438 size_t index = mBuffers.size();
439 for (size_t i = 0; i < mBuffers.size(); ++i) {
440 if (mBuffers[i].clientBuffer == buffer) {
441 clientBuffer = mBuffers[i].clientBuffer;
442 if (release) {
443 mBuffers[i].clientBuffer.clear();
444 }
445 index = i;
446 break;
447 }
448 }
449 if (clientBuffer == nullptr) {
450 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
451 return false;
452 }
453 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
454 if (!result) {
455 result = clientBuffer->asC2Buffer();
Wonsik Kimf9b32122020-04-02 11:30:17 -0700456 clientBuffer->clearC2BufferRefs();
Wonsik Kim469c8342019-04-11 16:46:09 -0700457 mBuffers[index].compBuffer = result;
458 }
459 if (c2buffer) {
460 *c2buffer = result;
461 }
462 return true;
463}
464
465bool FlexBuffersImpl::expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
466 for (size_t i = 0; i < mBuffers.size(); ++i) {
467 std::shared_ptr<C2Buffer> compBuffer =
468 mBuffers[i].compBuffer.lock();
469 if (!compBuffer || compBuffer != c2buffer) {
470 continue;
471 }
472 mBuffers[i].compBuffer.reset();
473 ALOGV("[%s] codec released buffer #%zu", mName, i);
474 return true;
475 }
476 ALOGV("[%s] codec released an unknown buffer", mName);
477 return false;
478}
479
480void FlexBuffersImpl::flush() {
481 ALOGV("[%s] buffers are flushed %zu", mName, mBuffers.size());
482 mBuffers.clear();
483}
484
Wonsik Kim0487b782020-10-28 11:45:50 -0700485size_t FlexBuffersImpl::numActiveSlots() const {
Wonsik Kim469c8342019-04-11 16:46:09 -0700486 return std::count_if(
487 mBuffers.begin(), mBuffers.end(),
488 [](const Entry &entry) {
Wonsik Kim0487b782020-10-28 11:45:50 -0700489 return (entry.clientBuffer != nullptr
490 || !entry.compBuffer.expired());
Wonsik Kim469c8342019-04-11 16:46:09 -0700491 });
492}
493
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700494size_t FlexBuffersImpl::numComponentBuffers() const {
495 return std::count_if(
496 mBuffers.begin(), mBuffers.end(),
497 [](const Entry &entry) {
498 return !entry.compBuffer.expired();
499 });
500}
501
Wonsik Kim469c8342019-04-11 16:46:09 -0700502// BuffersArrayImpl
503
504void BuffersArrayImpl::initialize(
505 const FlexBuffersImpl &impl,
506 size_t minSize,
507 std::function<sp<Codec2Buffer>()> allocate) {
508 mImplName = impl.mImplName + "[N]";
509 mName = mImplName.c_str();
510 for (size_t i = 0; i < impl.mBuffers.size(); ++i) {
511 sp<Codec2Buffer> clientBuffer = impl.mBuffers[i].clientBuffer;
512 bool ownedByClient = (clientBuffer != nullptr);
513 if (!ownedByClient) {
514 clientBuffer = allocate();
515 }
516 mBuffers.push_back({ clientBuffer, impl.mBuffers[i].compBuffer, ownedByClient });
517 }
518 ALOGV("[%s] converted %zu buffers to array mode of %zu", mName, mBuffers.size(), minSize);
519 for (size_t i = impl.mBuffers.size(); i < minSize; ++i) {
520 mBuffers.push_back({ allocate(), std::weak_ptr<C2Buffer>(), false });
521 }
522}
523
524status_t BuffersArrayImpl::grabBuffer(
525 size_t *index,
526 sp<Codec2Buffer> *buffer,
527 std::function<bool(const sp<Codec2Buffer> &)> match) {
528 // allBuffersDontMatch remains true if all buffers are available but
529 // match() returns false for every buffer.
530 bool allBuffersDontMatch = true;
531 for (size_t i = 0; i < mBuffers.size(); ++i) {
532 if (!mBuffers[i].ownedByClient && mBuffers[i].compBuffer.expired()) {
533 if (match(mBuffers[i].clientBuffer)) {
534 mBuffers[i].ownedByClient = true;
535 *buffer = mBuffers[i].clientBuffer;
536 (*buffer)->meta()->clear();
537 (*buffer)->setRange(0, (*buffer)->capacity());
538 *index = i;
539 return OK;
540 }
541 } else {
542 allBuffersDontMatch = false;
543 }
544 }
545 return allBuffersDontMatch ? NO_MEMORY : WOULD_BLOCK;
546}
547
548bool BuffersArrayImpl::returnBuffer(
549 const sp<MediaCodecBuffer> &buffer,
550 std::shared_ptr<C2Buffer> *c2buffer,
551 bool release) {
552 sp<Codec2Buffer> clientBuffer;
553 size_t index = mBuffers.size();
554 for (size_t i = 0; i < mBuffers.size(); ++i) {
555 if (mBuffers[i].clientBuffer == buffer) {
556 if (!mBuffers[i].ownedByClient) {
557 ALOGD("[%s] Client returned a buffer it does not own according to our record: %zu",
558 mName, i);
559 }
560 clientBuffer = mBuffers[i].clientBuffer;
561 if (release) {
562 mBuffers[i].ownedByClient = false;
563 }
564 index = i;
565 break;
566 }
567 }
568 if (clientBuffer == nullptr) {
569 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
570 return false;
571 }
572 ALOGV("[%s] %s: matching buffer found (index=%zu)", mName, __func__, index);
573 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
574 if (!result) {
575 result = clientBuffer->asC2Buffer();
Wonsik Kimf9b32122020-04-02 11:30:17 -0700576 clientBuffer->clearC2BufferRefs();
Wonsik Kim469c8342019-04-11 16:46:09 -0700577 mBuffers[index].compBuffer = result;
578 }
579 if (c2buffer) {
580 *c2buffer = result;
581 }
582 return true;
583}
584
585bool BuffersArrayImpl::expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
586 for (size_t i = 0; i < mBuffers.size(); ++i) {
587 std::shared_ptr<C2Buffer> compBuffer =
588 mBuffers[i].compBuffer.lock();
589 if (!compBuffer) {
590 continue;
591 }
592 if (c2buffer == compBuffer) {
593 if (mBuffers[i].ownedByClient) {
594 // This should not happen.
595 ALOGD("[%s] codec released a buffer owned by client "
596 "(index %zu)", mName, i);
597 }
598 mBuffers[i].compBuffer.reset();
599 ALOGV("[%s] codec released buffer #%zu(array mode)", mName, i);
600 return true;
601 }
602 }
603 ALOGV("[%s] codec released an unknown buffer (array mode)", mName);
604 return false;
605}
606
607void BuffersArrayImpl::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
608 array->clear();
609 for (const Entry &entry : mBuffers) {
610 array->push(entry.clientBuffer);
611 }
612}
613
614void BuffersArrayImpl::flush() {
615 for (Entry &entry : mBuffers) {
616 entry.ownedByClient = false;
617 }
618}
619
620void BuffersArrayImpl::realloc(std::function<sp<Codec2Buffer>()> alloc) {
621 size_t size = mBuffers.size();
622 mBuffers.clear();
623 for (size_t i = 0; i < size; ++i) {
624 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
625 }
626}
627
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700628void BuffersArrayImpl::grow(
629 size_t newSize, std::function<sp<Codec2Buffer>()> alloc) {
630 CHECK_LT(mBuffers.size(), newSize);
631 while (mBuffers.size() < newSize) {
632 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
633 }
634}
635
Wonsik Kim0487b782020-10-28 11:45:50 -0700636size_t BuffersArrayImpl::numActiveSlots() const {
Wonsik Kim469c8342019-04-11 16:46:09 -0700637 return std::count_if(
638 mBuffers.begin(), mBuffers.end(),
639 [](const Entry &entry) {
Wonsik Kim0487b782020-10-28 11:45:50 -0700640 return entry.ownedByClient || !entry.compBuffer.expired();
Wonsik Kim469c8342019-04-11 16:46:09 -0700641 });
642}
643
Wonsik Kima39882b2019-06-20 16:13:56 -0700644size_t BuffersArrayImpl::arraySize() const {
645 return mBuffers.size();
646}
647
Wonsik Kim469c8342019-04-11 16:46:09 -0700648// InputBuffersArray
649
650void InputBuffersArray::initialize(
651 const FlexBuffersImpl &impl,
652 size_t minSize,
653 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700654 mAllocate = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -0700655 mImpl.initialize(impl, minSize, allocate);
656}
657
658void InputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
659 mImpl.getArray(array);
660}
661
662bool InputBuffersArray::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
663 sp<Codec2Buffer> c2Buffer;
664 status_t err = mImpl.grabBuffer(index, &c2Buffer);
665 if (err == OK) {
666 c2Buffer->setFormat(mFormat);
667 handleImageData(c2Buffer);
668 *buffer = c2Buffer;
669 return true;
670 }
671 return false;
672}
673
674bool InputBuffersArray::releaseBuffer(
675 const sp<MediaCodecBuffer> &buffer,
676 std::shared_ptr<C2Buffer> *c2buffer,
677 bool release) {
678 return mImpl.returnBuffer(buffer, c2buffer, release);
679}
680
681bool InputBuffersArray::expireComponentBuffer(
682 const std::shared_ptr<C2Buffer> &c2buffer) {
683 return mImpl.expireComponentBuffer(c2buffer);
684}
685
686void InputBuffersArray::flush() {
687 mImpl.flush();
688}
689
Wonsik Kim0487b782020-10-28 11:45:50 -0700690size_t InputBuffersArray::numActiveSlots() const {
691 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700692}
693
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700694sp<Codec2Buffer> InputBuffersArray::createNewBuffer() {
695 return mAllocate();
696}
697
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800698// SlotInputBuffers
699
700bool SlotInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
701 sp<Codec2Buffer> newBuffer = createNewBuffer();
702 *index = mImpl.assignSlot(newBuffer);
703 *buffer = newBuffer;
704 return true;
705}
706
707bool SlotInputBuffers::releaseBuffer(
708 const sp<MediaCodecBuffer> &buffer,
709 std::shared_ptr<C2Buffer> *c2buffer,
710 bool release) {
711 return mImpl.releaseSlot(buffer, c2buffer, release);
712}
713
714bool SlotInputBuffers::expireComponentBuffer(
715 const std::shared_ptr<C2Buffer> &c2buffer) {
716 return mImpl.expireComponentBuffer(c2buffer);
717}
718
719void SlotInputBuffers::flush() {
720 mImpl.flush();
721}
722
723std::unique_ptr<InputBuffers> SlotInputBuffers::toArrayMode(size_t) {
724 TRESPASS("Array mode should not be called at non-legacy mode");
725 return nullptr;
726}
727
Wonsik Kim0487b782020-10-28 11:45:50 -0700728size_t SlotInputBuffers::numActiveSlots() const {
729 return mImpl.numActiveSlots();
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800730}
731
732sp<Codec2Buffer> SlotInputBuffers::createNewBuffer() {
733 return new DummyContainerBuffer{mFormat, nullptr};
734}
735
Wonsik Kim469c8342019-04-11 16:46:09 -0700736// LinearInputBuffers
737
738bool LinearInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700739 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700740 if (newBuffer == nullptr) {
741 return false;
742 }
743 *index = mImpl.assignSlot(newBuffer);
744 *buffer = newBuffer;
745 return true;
746}
747
748bool LinearInputBuffers::releaseBuffer(
749 const sp<MediaCodecBuffer> &buffer,
750 std::shared_ptr<C2Buffer> *c2buffer,
751 bool release) {
752 return mImpl.releaseSlot(buffer, c2buffer, release);
753}
754
755bool LinearInputBuffers::expireComponentBuffer(
756 const std::shared_ptr<C2Buffer> &c2buffer) {
757 return mImpl.expireComponentBuffer(c2buffer);
758}
759
760void LinearInputBuffers::flush() {
761 // This is no-op by default unless we're in array mode where we need to keep
762 // track of the flushed work.
763 mImpl.flush();
764}
765
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700766std::unique_ptr<InputBuffers> LinearInputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -0700767 std::unique_ptr<InputBuffersArray> array(
768 new InputBuffersArray(mComponentName.c_str(), "1D-Input[N]"));
769 array->setPool(mPool);
770 array->setFormat(mFormat);
771 array->initialize(
772 mImpl,
773 size,
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700774 [pool = mPool, format = mFormat] () -> sp<Codec2Buffer> {
775 return Alloc(pool, format);
776 });
Wonsik Kim469c8342019-04-11 16:46:09 -0700777 return std::move(array);
778}
779
Wonsik Kim0487b782020-10-28 11:45:50 -0700780size_t LinearInputBuffers::numActiveSlots() const {
781 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700782}
783
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700784// static
785sp<Codec2Buffer> LinearInputBuffers::Alloc(
786 const std::shared_ptr<C2BlockPool> &pool, const sp<AMessage> &format) {
787 int32_t capacity = kLinearBufferSize;
788 (void)format->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
789 if ((size_t)capacity > kMaxLinearBufferSize) {
790 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
791 capacity = kMaxLinearBufferSize;
792 }
793
794 // TODO: read usage from intf
Wonsik Kim469c8342019-04-11 16:46:09 -0700795 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
796 std::shared_ptr<C2LinearBlock> block;
797
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700798 c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block);
Wonsik Kim469c8342019-04-11 16:46:09 -0700799 if (err != C2_OK) {
800 return nullptr;
801 }
802
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700803 return LinearBlockBuffer::Allocate(format, block);
804}
805
806sp<Codec2Buffer> LinearInputBuffers::createNewBuffer() {
807 return Alloc(mPool, mFormat);
Wonsik Kim469c8342019-04-11 16:46:09 -0700808}
809
810// EncryptedLinearInputBuffers
811
812EncryptedLinearInputBuffers::EncryptedLinearInputBuffers(
813 bool secure,
814 const sp<MemoryDealer> &dealer,
815 const sp<ICrypto> &crypto,
816 int32_t heapSeqNum,
817 size_t capacity,
818 size_t numInputSlots,
819 const char *componentName, const char *name)
820 : LinearInputBuffers(componentName, name),
821 mUsage({0, 0}),
822 mDealer(dealer),
823 mCrypto(crypto),
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700824 mMemoryVector(new std::vector<Entry>){
Wonsik Kim469c8342019-04-11 16:46:09 -0700825 if (secure) {
826 mUsage = { C2MemoryUsage::READ_PROTECTED, 0 };
827 } else {
828 mUsage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
829 }
830 for (size_t i = 0; i < numInputSlots; ++i) {
831 sp<IMemory> memory = mDealer->allocate(capacity);
832 if (memory == nullptr) {
833 ALOGD("[%s] Failed to allocate memory from dealer: only %zu slots allocated",
834 mName, i);
835 break;
836 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700837 mMemoryVector->push_back({std::weak_ptr<C2LinearBlock>(), memory, heapSeqNum});
Wonsik Kim469c8342019-04-11 16:46:09 -0700838 }
839}
840
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700841std::unique_ptr<InputBuffers> EncryptedLinearInputBuffers::toArrayMode(size_t size) {
842 std::unique_ptr<InputBuffersArray> array(
843 new InputBuffersArray(mComponentName.c_str(), "1D-EncryptedInput[N]"));
844 array->setPool(mPool);
845 array->setFormat(mFormat);
846 array->initialize(
847 mImpl,
848 size,
849 [pool = mPool,
850 format = mFormat,
851 usage = mUsage,
852 memoryVector = mMemoryVector] () -> sp<Codec2Buffer> {
853 return Alloc(pool, format, usage, memoryVector);
854 });
855 return std::move(array);
856}
857
858
859// static
860sp<Codec2Buffer> EncryptedLinearInputBuffers::Alloc(
861 const std::shared_ptr<C2BlockPool> &pool,
862 const sp<AMessage> &format,
863 C2MemoryUsage usage,
864 const std::shared_ptr<std::vector<EncryptedLinearInputBuffers::Entry>> &memoryVector) {
865 int32_t capacity = kLinearBufferSize;
866 (void)format->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
867 if ((size_t)capacity > kMaxLinearBufferSize) {
868 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
869 capacity = kMaxLinearBufferSize;
870 }
871
Wonsik Kim469c8342019-04-11 16:46:09 -0700872 sp<IMemory> memory;
873 size_t slot = 0;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700874 int32_t heapSeqNum = -1;
875 for (; slot < memoryVector->size(); ++slot) {
876 if (memoryVector->at(slot).block.expired()) {
877 memory = memoryVector->at(slot).memory;
878 heapSeqNum = memoryVector->at(slot).heapSeqNum;
Wonsik Kim469c8342019-04-11 16:46:09 -0700879 break;
880 }
881 }
882 if (memory == nullptr) {
883 return nullptr;
884 }
885
886 std::shared_ptr<C2LinearBlock> block;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700887 c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block);
Wonsik Kim469c8342019-04-11 16:46:09 -0700888 if (err != C2_OK || block == nullptr) {
889 return nullptr;
890 }
891
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700892 memoryVector->at(slot).block = block;
893 return new EncryptedLinearBlockBuffer(format, block, memory, heapSeqNum);
894}
895
896sp<Codec2Buffer> EncryptedLinearInputBuffers::createNewBuffer() {
897 // TODO: android_2020
898 return nullptr;
Wonsik Kim469c8342019-04-11 16:46:09 -0700899}
900
901// GraphicMetadataInputBuffers
902
903GraphicMetadataInputBuffers::GraphicMetadataInputBuffers(
904 const char *componentName, const char *name)
905 : InputBuffers(componentName, name),
906 mImpl(mName),
907 mStore(GetCodec2PlatformAllocatorStore()) { }
908
909bool GraphicMetadataInputBuffers::requestNewBuffer(
910 size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700911 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700912 if (newBuffer == nullptr) {
913 return false;
914 }
915 *index = mImpl.assignSlot(newBuffer);
916 *buffer = newBuffer;
917 return true;
918}
919
920bool GraphicMetadataInputBuffers::releaseBuffer(
921 const sp<MediaCodecBuffer> &buffer,
922 std::shared_ptr<C2Buffer> *c2buffer,
923 bool release) {
924 return mImpl.releaseSlot(buffer, c2buffer, release);
925}
926
927bool GraphicMetadataInputBuffers::expireComponentBuffer(
928 const std::shared_ptr<C2Buffer> &c2buffer) {
929 return mImpl.expireComponentBuffer(c2buffer);
930}
931
932void GraphicMetadataInputBuffers::flush() {
933 // This is no-op by default unless we're in array mode where we need to keep
934 // track of the flushed work.
935}
936
937std::unique_ptr<InputBuffers> GraphicMetadataInputBuffers::toArrayMode(
938 size_t size) {
939 std::shared_ptr<C2Allocator> alloc;
940 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
941 if (err != C2_OK) {
942 return nullptr;
943 }
944 std::unique_ptr<InputBuffersArray> array(
945 new InputBuffersArray(mComponentName.c_str(), "2D-MetaInput[N]"));
946 array->setPool(mPool);
947 array->setFormat(mFormat);
948 array->initialize(
949 mImpl,
950 size,
951 [format = mFormat, alloc]() -> sp<Codec2Buffer> {
952 return new GraphicMetadataBuffer(format, alloc);
953 });
954 return std::move(array);
955}
956
Wonsik Kim0487b782020-10-28 11:45:50 -0700957size_t GraphicMetadataInputBuffers::numActiveSlots() const {
958 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700959}
960
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700961sp<Codec2Buffer> GraphicMetadataInputBuffers::createNewBuffer() {
962 std::shared_ptr<C2Allocator> alloc;
963 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
964 if (err != C2_OK) {
965 return nullptr;
966 }
967 return new GraphicMetadataBuffer(mFormat, alloc);
968}
969
Wonsik Kim469c8342019-04-11 16:46:09 -0700970// GraphicInputBuffers
971
972GraphicInputBuffers::GraphicInputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -0700973 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -0700974 : InputBuffers(componentName, name),
975 mImpl(mName),
Wonsik Kim41d83432020-04-27 16:40:49 -0700976 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -0700977
978bool GraphicInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700979 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700980 if (newBuffer == nullptr) {
981 return false;
982 }
983 *index = mImpl.assignSlot(newBuffer);
984 handleImageData(newBuffer);
985 *buffer = newBuffer;
986 return true;
987}
988
989bool GraphicInputBuffers::releaseBuffer(
990 const sp<MediaCodecBuffer> &buffer,
991 std::shared_ptr<C2Buffer> *c2buffer,
992 bool release) {
993 return mImpl.releaseSlot(buffer, c2buffer, release);
994}
995
996bool GraphicInputBuffers::expireComponentBuffer(
997 const std::shared_ptr<C2Buffer> &c2buffer) {
998 return mImpl.expireComponentBuffer(c2buffer);
999}
1000
1001void GraphicInputBuffers::flush() {
1002 // This is no-op by default unless we're in array mode where we need to keep
1003 // track of the flushed work.
1004}
1005
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001006static uint32_t extractPixelFormat(const sp<AMessage> &format) {
1007 int32_t frameworkColorFormat = 0;
1008 if (!format->findInt32("android._color-format", &frameworkColorFormat)) {
1009 return PIXEL_FORMAT_UNKNOWN;
1010 }
1011 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1012 if (C2Mapper::mapPixelFormatFrameworkToCodec(frameworkColorFormat, &pixelFormat)) {
1013 return pixelFormat;
1014 }
1015 return PIXEL_FORMAT_UNKNOWN;
1016}
1017
Wonsik Kim469c8342019-04-11 16:46:09 -07001018std::unique_ptr<InputBuffers> GraphicInputBuffers::toArrayMode(size_t size) {
1019 std::unique_ptr<InputBuffersArray> array(
1020 new InputBuffersArray(mComponentName.c_str(), "2D-BB-Input[N]"));
1021 array->setPool(mPool);
1022 array->setFormat(mFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001023 uint32_t pixelFormat = extractPixelFormat(mFormat);
Wonsik Kim469c8342019-04-11 16:46:09 -07001024 array->initialize(
1025 mImpl,
1026 size,
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001027 [pool = mPool, format = mFormat, lbp = mLocalBufferPool, pixelFormat]()
1028 -> sp<Codec2Buffer> {
Wonsik Kim469c8342019-04-11 16:46:09 -07001029 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1030 return AllocateGraphicBuffer(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001031 pool, format, pixelFormat, usage, lbp);
Wonsik Kim469c8342019-04-11 16:46:09 -07001032 });
1033 return std::move(array);
1034}
1035
Wonsik Kim0487b782020-10-28 11:45:50 -07001036size_t GraphicInputBuffers::numActiveSlots() const {
1037 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001038}
1039
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001040sp<Codec2Buffer> GraphicInputBuffers::createNewBuffer() {
1041 // TODO: read usage from intf
1042 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1043 return AllocateGraphicBuffer(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001044 mPool, mFormat, extractPixelFormat(mFormat), usage, mLocalBufferPool);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001045}
1046
Wonsik Kim469c8342019-04-11 16:46:09 -07001047// OutputBuffersArray
1048
1049void OutputBuffersArray::initialize(
1050 const FlexBuffersImpl &impl,
1051 size_t minSize,
1052 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001053 mAlloc = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -07001054 mImpl.initialize(impl, minSize, allocate);
1055}
1056
1057status_t OutputBuffersArray::registerBuffer(
1058 const std::shared_ptr<C2Buffer> &buffer,
1059 size_t *index,
1060 sp<MediaCodecBuffer> *clientBuffer) {
1061 sp<Codec2Buffer> c2Buffer;
1062 status_t err = mImpl.grabBuffer(
1063 index,
1064 &c2Buffer,
1065 [buffer](const sp<Codec2Buffer> &clientBuffer) {
1066 return clientBuffer->canCopy(buffer);
1067 });
1068 if (err == WOULD_BLOCK) {
1069 ALOGV("[%s] buffers temporarily not available", mName);
1070 return err;
1071 } else if (err != OK) {
1072 ALOGD("[%s] grabBuffer failed: %d", mName, err);
1073 return err;
1074 }
1075 c2Buffer->setFormat(mFormat);
1076 if (!c2Buffer->copy(buffer)) {
1077 ALOGD("[%s] copy buffer failed", mName);
1078 return WOULD_BLOCK;
1079 }
1080 submit(c2Buffer);
1081 handleImageData(c2Buffer);
1082 *clientBuffer = c2Buffer;
1083 ALOGV("[%s] grabbed buffer %zu", mName, *index);
1084 return OK;
1085}
1086
1087status_t OutputBuffersArray::registerCsd(
1088 const C2StreamInitDataInfo::output *csd,
1089 size_t *index,
1090 sp<MediaCodecBuffer> *clientBuffer) {
1091 sp<Codec2Buffer> c2Buffer;
1092 status_t err = mImpl.grabBuffer(
1093 index,
1094 &c2Buffer,
1095 [csd](const sp<Codec2Buffer> &clientBuffer) {
1096 return clientBuffer->base() != nullptr
1097 && clientBuffer->capacity() >= csd->flexCount();
1098 });
1099 if (err != OK) {
1100 return err;
1101 }
1102 memcpy(c2Buffer->base(), csd->m.value, csd->flexCount());
1103 c2Buffer->setRange(0, csd->flexCount());
1104 c2Buffer->setFormat(mFormat);
1105 *clientBuffer = c2Buffer;
1106 return OK;
1107}
1108
1109bool OutputBuffersArray::releaseBuffer(
1110 const sp<MediaCodecBuffer> &buffer, std::shared_ptr<C2Buffer> *c2buffer) {
1111 return mImpl.returnBuffer(buffer, c2buffer, true);
1112}
1113
1114void OutputBuffersArray::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1115 (void)flushedWork;
1116 mImpl.flush();
1117 if (mSkipCutBuffer != nullptr) {
1118 mSkipCutBuffer->clear();
1119 }
1120}
1121
1122void OutputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
1123 mImpl.getArray(array);
1124}
1125
Wonsik Kim0487b782020-10-28 11:45:50 -07001126size_t OutputBuffersArray::numActiveSlots() const {
1127 return mImpl.numActiveSlots();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001128}
1129
Wonsik Kim469c8342019-04-11 16:46:09 -07001130void OutputBuffersArray::realloc(const std::shared_ptr<C2Buffer> &c2buffer) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001131 switch (c2buffer->data().type()) {
1132 case C2BufferData::LINEAR: {
1133 uint32_t size = kLinearBufferSize;
Nick Desaulniersd09eaea2019-10-07 20:19:39 -07001134 const std::vector<C2ConstLinearBlock> &linear_blocks = c2buffer->data().linearBlocks();
1135 const uint32_t block_size = linear_blocks.front().size();
1136 if (block_size < kMaxLinearBufferSize / 2) {
1137 size = block_size * 2;
Wonsik Kim469c8342019-04-11 16:46:09 -07001138 } else {
1139 size = kMaxLinearBufferSize;
1140 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001141 mAlloc = [format = mFormat, size] {
Wonsik Kim469c8342019-04-11 16:46:09 -07001142 return new LocalLinearBuffer(format, new ABuffer(size));
1143 };
Wonsik Kima39882b2019-06-20 16:13:56 -07001144 ALOGD("[%s] reallocating with linear buffer of size %u", mName, size);
Wonsik Kim469c8342019-04-11 16:46:09 -07001145 break;
1146 }
1147
Wonsik Kima39882b2019-06-20 16:13:56 -07001148 case C2BufferData::GRAPHIC: {
1149 // This is only called for RawGraphicOutputBuffers.
1150 mAlloc = [format = mFormat,
Wonsik Kim41d83432020-04-27 16:40:49 -07001151 lbp = LocalBufferPool::Create()] {
Wonsik Kima39882b2019-06-20 16:13:56 -07001152 return ConstGraphicBlockBuffer::AllocateEmpty(
1153 format,
1154 [lbp](size_t capacity) {
1155 return lbp->newBuffer(capacity);
1156 });
1157 };
1158 ALOGD("[%s] reallocating with graphic buffer: format = %s",
1159 mName, mFormat->debugString().c_str());
1160 break;
1161 }
Wonsik Kim469c8342019-04-11 16:46:09 -07001162
1163 case C2BufferData::INVALID: [[fallthrough]];
1164 case C2BufferData::LINEAR_CHUNKS: [[fallthrough]];
1165 case C2BufferData::GRAPHIC_CHUNKS: [[fallthrough]];
1166 default:
1167 ALOGD("Unsupported type: %d", (int)c2buffer->data().type());
1168 return;
1169 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001170 mImpl.realloc(mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001171}
1172
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001173void OutputBuffersArray::grow(size_t newSize) {
1174 mImpl.grow(newSize, mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001175}
1176
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001177void OutputBuffersArray::transferFrom(OutputBuffers* source) {
1178 mFormat = source->mFormat;
1179 mSkipCutBuffer = source->mSkipCutBuffer;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001180 mPending = std::move(source->mPending);
1181 mReorderStash = std::move(source->mReorderStash);
1182 mDepth = source->mDepth;
1183 mKey = source->mKey;
1184}
1185
Wonsik Kim469c8342019-04-11 16:46:09 -07001186// FlexOutputBuffers
1187
1188status_t FlexOutputBuffers::registerBuffer(
1189 const std::shared_ptr<C2Buffer> &buffer,
1190 size_t *index,
1191 sp<MediaCodecBuffer> *clientBuffer) {
1192 sp<Codec2Buffer> newBuffer = wrap(buffer);
1193 if (newBuffer == nullptr) {
1194 return NO_MEMORY;
1195 }
1196 newBuffer->setFormat(mFormat);
1197 *index = mImpl.assignSlot(newBuffer);
1198 handleImageData(newBuffer);
1199 *clientBuffer = newBuffer;
1200 ALOGV("[%s] registered buffer %zu", mName, *index);
1201 return OK;
1202}
1203
1204status_t FlexOutputBuffers::registerCsd(
1205 const C2StreamInitDataInfo::output *csd,
1206 size_t *index,
1207 sp<MediaCodecBuffer> *clientBuffer) {
1208 sp<Codec2Buffer> newBuffer = new LocalLinearBuffer(
1209 mFormat, ABuffer::CreateAsCopy(csd->m.value, csd->flexCount()));
1210 *index = mImpl.assignSlot(newBuffer);
1211 *clientBuffer = newBuffer;
1212 return OK;
1213}
1214
1215bool FlexOutputBuffers::releaseBuffer(
1216 const sp<MediaCodecBuffer> &buffer,
1217 std::shared_ptr<C2Buffer> *c2buffer) {
1218 return mImpl.releaseSlot(buffer, c2buffer, true);
1219}
1220
1221void FlexOutputBuffers::flush(
1222 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1223 (void) flushedWork;
1224 // This is no-op by default unless we're in array mode where we need to keep
1225 // track of the flushed work.
1226}
1227
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001228std::unique_ptr<OutputBuffersArray> FlexOutputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001229 std::unique_ptr<OutputBuffersArray> array(new OutputBuffersArray(mComponentName.c_str()));
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001230 array->transferFrom(this);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001231 std::function<sp<Codec2Buffer>()> alloc = getAlloc();
1232 array->initialize(mImpl, size, alloc);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001233 return array;
Wonsik Kim469c8342019-04-11 16:46:09 -07001234}
1235
Wonsik Kim0487b782020-10-28 11:45:50 -07001236size_t FlexOutputBuffers::numActiveSlots() const {
1237 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001238}
1239
1240// LinearOutputBuffers
1241
1242void LinearOutputBuffers::flush(
1243 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1244 if (mSkipCutBuffer != nullptr) {
1245 mSkipCutBuffer->clear();
1246 }
1247 FlexOutputBuffers::flush(flushedWork);
1248}
1249
1250sp<Codec2Buffer> LinearOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1251 if (buffer == nullptr) {
1252 ALOGV("[%s] using a dummy buffer", mName);
1253 return new LocalLinearBuffer(mFormat, new ABuffer(0));
1254 }
1255 if (buffer->data().type() != C2BufferData::LINEAR) {
1256 ALOGV("[%s] non-linear buffer %d", mName, buffer->data().type());
1257 // We expect linear output buffers from the component.
1258 return nullptr;
1259 }
1260 if (buffer->data().linearBlocks().size() != 1u) {
1261 ALOGV("[%s] no linear buffers", mName);
1262 // We expect one and only one linear block from the component.
1263 return nullptr;
1264 }
1265 sp<Codec2Buffer> clientBuffer = ConstLinearBlockBuffer::Allocate(mFormat, buffer);
1266 if (clientBuffer == nullptr) {
1267 ALOGD("[%s] ConstLinearBlockBuffer::Allocate failed", mName);
1268 return nullptr;
1269 }
1270 submit(clientBuffer);
1271 return clientBuffer;
1272}
1273
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001274std::function<sp<Codec2Buffer>()> LinearOutputBuffers::getAlloc() {
1275 return [format = mFormat]{
1276 // TODO: proper max output size
1277 return new LocalLinearBuffer(format, new ABuffer(kLinearBufferSize));
1278 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001279}
1280
1281// GraphicOutputBuffers
1282
1283sp<Codec2Buffer> GraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1284 return new DummyContainerBuffer(mFormat, buffer);
1285}
1286
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001287std::function<sp<Codec2Buffer>()> GraphicOutputBuffers::getAlloc() {
1288 return [format = mFormat]{
1289 return new DummyContainerBuffer(format);
1290 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001291}
1292
1293// RawGraphicOutputBuffers
1294
1295RawGraphicOutputBuffers::RawGraphicOutputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -07001296 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -07001297 : FlexOutputBuffers(componentName, name),
Wonsik Kim41d83432020-04-27 16:40:49 -07001298 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -07001299
1300sp<Codec2Buffer> RawGraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1301 if (buffer == nullptr) {
1302 sp<Codec2Buffer> c2buffer = ConstGraphicBlockBuffer::AllocateEmpty(
1303 mFormat,
1304 [lbp = mLocalBufferPool](size_t capacity) {
1305 return lbp->newBuffer(capacity);
1306 });
1307 if (c2buffer == nullptr) {
1308 ALOGD("[%s] ConstGraphicBlockBuffer::AllocateEmpty failed", mName);
1309 return nullptr;
1310 }
1311 c2buffer->setRange(0, 0);
1312 return c2buffer;
1313 } else {
1314 return ConstGraphicBlockBuffer::Allocate(
1315 mFormat,
1316 buffer,
1317 [lbp = mLocalBufferPool](size_t capacity) {
1318 return lbp->newBuffer(capacity);
1319 });
1320 }
1321}
1322
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001323std::function<sp<Codec2Buffer>()> RawGraphicOutputBuffers::getAlloc() {
1324 return [format = mFormat, lbp = mLocalBufferPool]{
1325 return ConstGraphicBlockBuffer::AllocateEmpty(
1326 format,
1327 [lbp](size_t capacity) {
1328 return lbp->newBuffer(capacity);
1329 });
1330 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001331}
1332
1333} // namespace android