blob: e7207a5897c2c6c5d58166043883e89d97dd54a3 [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 Kim3b4349a2020-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 Kim3b4349a2020-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 Kim3b4349a2020-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 Kim3b4349a2020-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 Park2eef13e2020-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
Wonsik Kim666604a2020-05-14 16:57:49 -0700794 int64_t usageValue = 0;
795 (void)format->findInt64("android._C2MemoryUsage", &usageValue);
796 C2MemoryUsage usage{usageValue | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE};
Wonsik Kim469c8342019-04-11 16:46:09 -0700797 std::shared_ptr<C2LinearBlock> block;
798
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700799 c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block);
Wonsik Kim469c8342019-04-11 16:46:09 -0700800 if (err != C2_OK) {
801 return nullptr;
802 }
803
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700804 return LinearBlockBuffer::Allocate(format, block);
805}
806
807sp<Codec2Buffer> LinearInputBuffers::createNewBuffer() {
808 return Alloc(mPool, mFormat);
Wonsik Kim469c8342019-04-11 16:46:09 -0700809}
810
811// EncryptedLinearInputBuffers
812
813EncryptedLinearInputBuffers::EncryptedLinearInputBuffers(
814 bool secure,
815 const sp<MemoryDealer> &dealer,
816 const sp<ICrypto> &crypto,
817 int32_t heapSeqNum,
818 size_t capacity,
819 size_t numInputSlots,
820 const char *componentName, const char *name)
821 : LinearInputBuffers(componentName, name),
822 mUsage({0, 0}),
823 mDealer(dealer),
824 mCrypto(crypto),
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700825 mMemoryVector(new std::vector<Entry>){
Wonsik Kim469c8342019-04-11 16:46:09 -0700826 if (secure) {
827 mUsage = { C2MemoryUsage::READ_PROTECTED, 0 };
828 } else {
829 mUsage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
830 }
831 for (size_t i = 0; i < numInputSlots; ++i) {
832 sp<IMemory> memory = mDealer->allocate(capacity);
833 if (memory == nullptr) {
834 ALOGD("[%s] Failed to allocate memory from dealer: only %zu slots allocated",
835 mName, i);
836 break;
837 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700838 mMemoryVector->push_back({std::weak_ptr<C2LinearBlock>(), memory, heapSeqNum});
Wonsik Kim469c8342019-04-11 16:46:09 -0700839 }
840}
841
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700842std::unique_ptr<InputBuffers> EncryptedLinearInputBuffers::toArrayMode(size_t size) {
843 std::unique_ptr<InputBuffersArray> array(
844 new InputBuffersArray(mComponentName.c_str(), "1D-EncryptedInput[N]"));
845 array->setPool(mPool);
846 array->setFormat(mFormat);
847 array->initialize(
848 mImpl,
849 size,
850 [pool = mPool,
851 format = mFormat,
852 usage = mUsage,
853 memoryVector = mMemoryVector] () -> sp<Codec2Buffer> {
854 return Alloc(pool, format, usage, memoryVector);
855 });
856 return std::move(array);
857}
858
859
860// static
861sp<Codec2Buffer> EncryptedLinearInputBuffers::Alloc(
862 const std::shared_ptr<C2BlockPool> &pool,
863 const sp<AMessage> &format,
864 C2MemoryUsage usage,
865 const std::shared_ptr<std::vector<EncryptedLinearInputBuffers::Entry>> &memoryVector) {
866 int32_t capacity = kLinearBufferSize;
867 (void)format->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
868 if ((size_t)capacity > kMaxLinearBufferSize) {
869 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
870 capacity = kMaxLinearBufferSize;
871 }
872
Wonsik Kim469c8342019-04-11 16:46:09 -0700873 sp<IMemory> memory;
874 size_t slot = 0;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700875 int32_t heapSeqNum = -1;
876 for (; slot < memoryVector->size(); ++slot) {
877 if (memoryVector->at(slot).block.expired()) {
878 memory = memoryVector->at(slot).memory;
879 heapSeqNum = memoryVector->at(slot).heapSeqNum;
Wonsik Kim469c8342019-04-11 16:46:09 -0700880 break;
881 }
882 }
883 if (memory == nullptr) {
884 return nullptr;
885 }
886
887 std::shared_ptr<C2LinearBlock> block;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700888 c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block);
Wonsik Kim469c8342019-04-11 16:46:09 -0700889 if (err != C2_OK || block == nullptr) {
890 return nullptr;
891 }
892
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700893 memoryVector->at(slot).block = block;
894 return new EncryptedLinearBlockBuffer(format, block, memory, heapSeqNum);
895}
896
897sp<Codec2Buffer> EncryptedLinearInputBuffers::createNewBuffer() {
898 // TODO: android_2020
899 return nullptr;
Wonsik Kim469c8342019-04-11 16:46:09 -0700900}
901
902// GraphicMetadataInputBuffers
903
904GraphicMetadataInputBuffers::GraphicMetadataInputBuffers(
905 const char *componentName, const char *name)
906 : InputBuffers(componentName, name),
907 mImpl(mName),
908 mStore(GetCodec2PlatformAllocatorStore()) { }
909
910bool GraphicMetadataInputBuffers::requestNewBuffer(
911 size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700912 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700913 if (newBuffer == nullptr) {
914 return false;
915 }
916 *index = mImpl.assignSlot(newBuffer);
917 *buffer = newBuffer;
918 return true;
919}
920
921bool GraphicMetadataInputBuffers::releaseBuffer(
922 const sp<MediaCodecBuffer> &buffer,
923 std::shared_ptr<C2Buffer> *c2buffer,
924 bool release) {
925 return mImpl.releaseSlot(buffer, c2buffer, release);
926}
927
928bool GraphicMetadataInputBuffers::expireComponentBuffer(
929 const std::shared_ptr<C2Buffer> &c2buffer) {
930 return mImpl.expireComponentBuffer(c2buffer);
931}
932
933void GraphicMetadataInputBuffers::flush() {
934 // This is no-op by default unless we're in array mode where we need to keep
935 // track of the flushed work.
936}
937
938std::unique_ptr<InputBuffers> GraphicMetadataInputBuffers::toArrayMode(
939 size_t size) {
940 std::shared_ptr<C2Allocator> alloc;
941 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
942 if (err != C2_OK) {
943 return nullptr;
944 }
945 std::unique_ptr<InputBuffersArray> array(
946 new InputBuffersArray(mComponentName.c_str(), "2D-MetaInput[N]"));
947 array->setPool(mPool);
948 array->setFormat(mFormat);
949 array->initialize(
950 mImpl,
951 size,
952 [format = mFormat, alloc]() -> sp<Codec2Buffer> {
953 return new GraphicMetadataBuffer(format, alloc);
954 });
955 return std::move(array);
956}
957
Wonsik Kim0487b782020-10-28 11:45:50 -0700958size_t GraphicMetadataInputBuffers::numActiveSlots() const {
959 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700960}
961
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700962sp<Codec2Buffer> GraphicMetadataInputBuffers::createNewBuffer() {
963 std::shared_ptr<C2Allocator> alloc;
964 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
965 if (err != C2_OK) {
966 return nullptr;
967 }
968 return new GraphicMetadataBuffer(mFormat, alloc);
969}
970
Wonsik Kim469c8342019-04-11 16:46:09 -0700971// GraphicInputBuffers
972
973GraphicInputBuffers::GraphicInputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -0700974 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -0700975 : InputBuffers(componentName, name),
976 mImpl(mName),
Wonsik Kim41d83432020-04-27 16:40:49 -0700977 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -0700978
979bool GraphicInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700980 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700981 if (newBuffer == nullptr) {
982 return false;
983 }
984 *index = mImpl.assignSlot(newBuffer);
985 handleImageData(newBuffer);
986 *buffer = newBuffer;
987 return true;
988}
989
990bool GraphicInputBuffers::releaseBuffer(
991 const sp<MediaCodecBuffer> &buffer,
992 std::shared_ptr<C2Buffer> *c2buffer,
993 bool release) {
994 return mImpl.releaseSlot(buffer, c2buffer, release);
995}
996
997bool GraphicInputBuffers::expireComponentBuffer(
998 const std::shared_ptr<C2Buffer> &c2buffer) {
999 return mImpl.expireComponentBuffer(c2buffer);
1000}
1001
1002void GraphicInputBuffers::flush() {
1003 // This is no-op by default unless we're in array mode where we need to keep
1004 // track of the flushed work.
1005}
1006
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001007static uint32_t extractPixelFormat(const sp<AMessage> &format) {
1008 int32_t frameworkColorFormat = 0;
1009 if (!format->findInt32("android._color-format", &frameworkColorFormat)) {
1010 return PIXEL_FORMAT_UNKNOWN;
1011 }
1012 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1013 if (C2Mapper::mapPixelFormatFrameworkToCodec(frameworkColorFormat, &pixelFormat)) {
1014 return pixelFormat;
1015 }
1016 return PIXEL_FORMAT_UNKNOWN;
1017}
1018
Wonsik Kim469c8342019-04-11 16:46:09 -07001019std::unique_ptr<InputBuffers> GraphicInputBuffers::toArrayMode(size_t size) {
1020 std::unique_ptr<InputBuffersArray> array(
1021 new InputBuffersArray(mComponentName.c_str(), "2D-BB-Input[N]"));
1022 array->setPool(mPool);
1023 array->setFormat(mFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001024 uint32_t pixelFormat = extractPixelFormat(mFormat);
Wonsik Kim469c8342019-04-11 16:46:09 -07001025 array->initialize(
1026 mImpl,
1027 size,
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001028 [pool = mPool, format = mFormat, lbp = mLocalBufferPool, pixelFormat]()
1029 -> sp<Codec2Buffer> {
Wonsik Kim469c8342019-04-11 16:46:09 -07001030 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1031 return AllocateGraphicBuffer(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001032 pool, format, pixelFormat, usage, lbp);
Wonsik Kim469c8342019-04-11 16:46:09 -07001033 });
1034 return std::move(array);
1035}
1036
Wonsik Kim0487b782020-10-28 11:45:50 -07001037size_t GraphicInputBuffers::numActiveSlots() const {
1038 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001039}
1040
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001041sp<Codec2Buffer> GraphicInputBuffers::createNewBuffer() {
Wonsik Kim666604a2020-05-14 16:57:49 -07001042 int64_t usageValue = 0;
1043 (void)mFormat->findInt64("android._C2MemoryUsage", &usageValue);
1044 C2MemoryUsage usage{usageValue | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE};
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001045 return AllocateGraphicBuffer(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001046 mPool, mFormat, extractPixelFormat(mFormat), usage, mLocalBufferPool);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001047}
1048
Wonsik Kim469c8342019-04-11 16:46:09 -07001049// OutputBuffersArray
1050
1051void OutputBuffersArray::initialize(
1052 const FlexBuffersImpl &impl,
1053 size_t minSize,
1054 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001055 mAlloc = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -07001056 mImpl.initialize(impl, minSize, allocate);
1057}
1058
1059status_t OutputBuffersArray::registerBuffer(
1060 const std::shared_ptr<C2Buffer> &buffer,
1061 size_t *index,
1062 sp<MediaCodecBuffer> *clientBuffer) {
1063 sp<Codec2Buffer> c2Buffer;
1064 status_t err = mImpl.grabBuffer(
1065 index,
1066 &c2Buffer,
1067 [buffer](const sp<Codec2Buffer> &clientBuffer) {
1068 return clientBuffer->canCopy(buffer);
1069 });
1070 if (err == WOULD_BLOCK) {
1071 ALOGV("[%s] buffers temporarily not available", mName);
1072 return err;
1073 } else if (err != OK) {
1074 ALOGD("[%s] grabBuffer failed: %d", mName, err);
1075 return err;
1076 }
1077 c2Buffer->setFormat(mFormat);
1078 if (!c2Buffer->copy(buffer)) {
1079 ALOGD("[%s] copy buffer failed", mName);
1080 return WOULD_BLOCK;
1081 }
1082 submit(c2Buffer);
1083 handleImageData(c2Buffer);
1084 *clientBuffer = c2Buffer;
1085 ALOGV("[%s] grabbed buffer %zu", mName, *index);
1086 return OK;
1087}
1088
1089status_t OutputBuffersArray::registerCsd(
1090 const C2StreamInitDataInfo::output *csd,
1091 size_t *index,
1092 sp<MediaCodecBuffer> *clientBuffer) {
1093 sp<Codec2Buffer> c2Buffer;
1094 status_t err = mImpl.grabBuffer(
1095 index,
1096 &c2Buffer,
1097 [csd](const sp<Codec2Buffer> &clientBuffer) {
1098 return clientBuffer->base() != nullptr
1099 && clientBuffer->capacity() >= csd->flexCount();
1100 });
1101 if (err != OK) {
1102 return err;
1103 }
1104 memcpy(c2Buffer->base(), csd->m.value, csd->flexCount());
1105 c2Buffer->setRange(0, csd->flexCount());
1106 c2Buffer->setFormat(mFormat);
1107 *clientBuffer = c2Buffer;
1108 return OK;
1109}
1110
1111bool OutputBuffersArray::releaseBuffer(
1112 const sp<MediaCodecBuffer> &buffer, std::shared_ptr<C2Buffer> *c2buffer) {
1113 return mImpl.returnBuffer(buffer, c2buffer, true);
1114}
1115
1116void OutputBuffersArray::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1117 (void)flushedWork;
1118 mImpl.flush();
1119 if (mSkipCutBuffer != nullptr) {
1120 mSkipCutBuffer->clear();
1121 }
1122}
1123
1124void OutputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
1125 mImpl.getArray(array);
1126}
1127
Wonsik Kim0487b782020-10-28 11:45:50 -07001128size_t OutputBuffersArray::numActiveSlots() const {
1129 return mImpl.numActiveSlots();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001130}
1131
Wonsik Kim469c8342019-04-11 16:46:09 -07001132void OutputBuffersArray::realloc(const std::shared_ptr<C2Buffer> &c2buffer) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001133 switch (c2buffer->data().type()) {
1134 case C2BufferData::LINEAR: {
1135 uint32_t size = kLinearBufferSize;
Nick Desaulniersd09eaea2019-10-07 20:19:39 -07001136 const std::vector<C2ConstLinearBlock> &linear_blocks = c2buffer->data().linearBlocks();
1137 const uint32_t block_size = linear_blocks.front().size();
1138 if (block_size < kMaxLinearBufferSize / 2) {
1139 size = block_size * 2;
Wonsik Kim469c8342019-04-11 16:46:09 -07001140 } else {
1141 size = kMaxLinearBufferSize;
1142 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001143 mAlloc = [format = mFormat, size] {
Wonsik Kim469c8342019-04-11 16:46:09 -07001144 return new LocalLinearBuffer(format, new ABuffer(size));
1145 };
Wonsik Kima39882b2019-06-20 16:13:56 -07001146 ALOGD("[%s] reallocating with linear buffer of size %u", mName, size);
Wonsik Kim469c8342019-04-11 16:46:09 -07001147 break;
1148 }
1149
Wonsik Kima39882b2019-06-20 16:13:56 -07001150 case C2BufferData::GRAPHIC: {
1151 // This is only called for RawGraphicOutputBuffers.
1152 mAlloc = [format = mFormat,
Wonsik Kim41d83432020-04-27 16:40:49 -07001153 lbp = LocalBufferPool::Create()] {
Wonsik Kima39882b2019-06-20 16:13:56 -07001154 return ConstGraphicBlockBuffer::AllocateEmpty(
1155 format,
1156 [lbp](size_t capacity) {
1157 return lbp->newBuffer(capacity);
1158 });
1159 };
1160 ALOGD("[%s] reallocating with graphic buffer: format = %s",
1161 mName, mFormat->debugString().c_str());
1162 break;
1163 }
Wonsik Kim469c8342019-04-11 16:46:09 -07001164
1165 case C2BufferData::INVALID: [[fallthrough]];
1166 case C2BufferData::LINEAR_CHUNKS: [[fallthrough]];
1167 case C2BufferData::GRAPHIC_CHUNKS: [[fallthrough]];
1168 default:
1169 ALOGD("Unsupported type: %d", (int)c2buffer->data().type());
1170 return;
1171 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001172 mImpl.realloc(mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001173}
1174
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001175void OutputBuffersArray::grow(size_t newSize) {
1176 mImpl.grow(newSize, mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001177}
1178
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001179void OutputBuffersArray::transferFrom(OutputBuffers* source) {
1180 mFormat = source->mFormat;
1181 mSkipCutBuffer = source->mSkipCutBuffer;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001182 mPending = std::move(source->mPending);
1183 mReorderStash = std::move(source->mReorderStash);
1184 mDepth = source->mDepth;
1185 mKey = source->mKey;
1186}
1187
Wonsik Kim469c8342019-04-11 16:46:09 -07001188// FlexOutputBuffers
1189
1190status_t FlexOutputBuffers::registerBuffer(
1191 const std::shared_ptr<C2Buffer> &buffer,
1192 size_t *index,
1193 sp<MediaCodecBuffer> *clientBuffer) {
1194 sp<Codec2Buffer> newBuffer = wrap(buffer);
1195 if (newBuffer == nullptr) {
1196 return NO_MEMORY;
1197 }
1198 newBuffer->setFormat(mFormat);
1199 *index = mImpl.assignSlot(newBuffer);
1200 handleImageData(newBuffer);
1201 *clientBuffer = newBuffer;
1202 ALOGV("[%s] registered buffer %zu", mName, *index);
1203 return OK;
1204}
1205
1206status_t FlexOutputBuffers::registerCsd(
1207 const C2StreamInitDataInfo::output *csd,
1208 size_t *index,
1209 sp<MediaCodecBuffer> *clientBuffer) {
1210 sp<Codec2Buffer> newBuffer = new LocalLinearBuffer(
1211 mFormat, ABuffer::CreateAsCopy(csd->m.value, csd->flexCount()));
1212 *index = mImpl.assignSlot(newBuffer);
1213 *clientBuffer = newBuffer;
1214 return OK;
1215}
1216
1217bool FlexOutputBuffers::releaseBuffer(
1218 const sp<MediaCodecBuffer> &buffer,
1219 std::shared_ptr<C2Buffer> *c2buffer) {
1220 return mImpl.releaseSlot(buffer, c2buffer, true);
1221}
1222
1223void FlexOutputBuffers::flush(
1224 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1225 (void) flushedWork;
1226 // This is no-op by default unless we're in array mode where we need to keep
1227 // track of the flushed work.
1228}
1229
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001230std::unique_ptr<OutputBuffersArray> FlexOutputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001231 std::unique_ptr<OutputBuffersArray> array(new OutputBuffersArray(mComponentName.c_str()));
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001232 array->transferFrom(this);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001233 std::function<sp<Codec2Buffer>()> alloc = getAlloc();
1234 array->initialize(mImpl, size, alloc);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001235 return array;
Wonsik Kim469c8342019-04-11 16:46:09 -07001236}
1237
Wonsik Kim0487b782020-10-28 11:45:50 -07001238size_t FlexOutputBuffers::numActiveSlots() const {
1239 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001240}
1241
1242// LinearOutputBuffers
1243
1244void LinearOutputBuffers::flush(
1245 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1246 if (mSkipCutBuffer != nullptr) {
1247 mSkipCutBuffer->clear();
1248 }
1249 FlexOutputBuffers::flush(flushedWork);
1250}
1251
1252sp<Codec2Buffer> LinearOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1253 if (buffer == nullptr) {
1254 ALOGV("[%s] using a dummy buffer", mName);
1255 return new LocalLinearBuffer(mFormat, new ABuffer(0));
1256 }
1257 if (buffer->data().type() != C2BufferData::LINEAR) {
1258 ALOGV("[%s] non-linear buffer %d", mName, buffer->data().type());
1259 // We expect linear output buffers from the component.
1260 return nullptr;
1261 }
1262 if (buffer->data().linearBlocks().size() != 1u) {
1263 ALOGV("[%s] no linear buffers", mName);
1264 // We expect one and only one linear block from the component.
1265 return nullptr;
1266 }
1267 sp<Codec2Buffer> clientBuffer = ConstLinearBlockBuffer::Allocate(mFormat, buffer);
1268 if (clientBuffer == nullptr) {
1269 ALOGD("[%s] ConstLinearBlockBuffer::Allocate failed", mName);
1270 return nullptr;
1271 }
1272 submit(clientBuffer);
1273 return clientBuffer;
1274}
1275
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001276std::function<sp<Codec2Buffer>()> LinearOutputBuffers::getAlloc() {
1277 return [format = mFormat]{
1278 // TODO: proper max output size
1279 return new LocalLinearBuffer(format, new ABuffer(kLinearBufferSize));
1280 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001281}
1282
1283// GraphicOutputBuffers
1284
1285sp<Codec2Buffer> GraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1286 return new DummyContainerBuffer(mFormat, buffer);
1287}
1288
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001289std::function<sp<Codec2Buffer>()> GraphicOutputBuffers::getAlloc() {
1290 return [format = mFormat]{
1291 return new DummyContainerBuffer(format);
1292 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001293}
1294
1295// RawGraphicOutputBuffers
1296
1297RawGraphicOutputBuffers::RawGraphicOutputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -07001298 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -07001299 : FlexOutputBuffers(componentName, name),
Wonsik Kim41d83432020-04-27 16:40:49 -07001300 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -07001301
1302sp<Codec2Buffer> RawGraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1303 if (buffer == nullptr) {
1304 sp<Codec2Buffer> c2buffer = ConstGraphicBlockBuffer::AllocateEmpty(
1305 mFormat,
1306 [lbp = mLocalBufferPool](size_t capacity) {
1307 return lbp->newBuffer(capacity);
1308 });
1309 if (c2buffer == nullptr) {
1310 ALOGD("[%s] ConstGraphicBlockBuffer::AllocateEmpty failed", mName);
1311 return nullptr;
1312 }
1313 c2buffer->setRange(0, 0);
1314 return c2buffer;
1315 } else {
1316 return ConstGraphicBlockBuffer::Allocate(
1317 mFormat,
1318 buffer,
1319 [lbp = mLocalBufferPool](size_t capacity) {
1320 return lbp->newBuffer(capacity);
1321 });
1322 }
1323}
1324
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001325std::function<sp<Codec2Buffer>()> RawGraphicOutputBuffers::getAlloc() {
1326 return [format = mFormat, lbp = mLocalBufferPool]{
1327 return ConstGraphicBlockBuffer::AllocateEmpty(
1328 format,
1329 [lbp](size_t capacity) {
1330 return lbp->newBuffer(capacity);
1331 });
1332 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001333}
1334
1335} // namespace android