blob: a3b188edb66849e74f1c881e1d12d0ce4159e15c [file] [log] [blame]
Wonsik Kim469c8342019-04-11 16:46:09 -07001/*
2 * Copyright 2019, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CCodecBuffers"
19#include <utils/Log.h>
20
21#include <C2PlatformSupport.h>
22
23#include <media/stagefright/foundation/ADebug.h>
Pawin Vongmasa9b906982020-04-11 05:07:15 -070024#include <media/stagefright/MediaCodec.h>
Wonsik Kim469c8342019-04-11 16:46:09 -070025#include <media/stagefright/MediaCodecConstants.h>
Wonsik Kim155d5cb2019-10-09 12:49:49 -070026#include <media/stagefright/SkipCutBuffer.h>
Wonsik Kim41d83432020-04-27 16:40:49 -070027#include <mediadrm/ICrypto.h>
Wonsik Kim469c8342019-04-11 16:46:09 -070028
29#include "CCodecBuffers.h"
30
31namespace android {
32
33namespace {
34
35sp<GraphicBlockBuffer> AllocateGraphicBuffer(
36 const std::shared_ptr<C2BlockPool> &pool,
37 const sp<AMessage> &format,
38 uint32_t pixelFormat,
39 const C2MemoryUsage &usage,
40 const std::shared_ptr<LocalBufferPool> &localBufferPool) {
41 int32_t width, height;
42 if (!format->findInt32("width", &width) || !format->findInt32("height", &height)) {
43 ALOGD("format lacks width or height");
44 return nullptr;
45 }
46
47 std::shared_ptr<C2GraphicBlock> block;
48 c2_status_t err = pool->fetchGraphicBlock(
49 width, height, pixelFormat, usage, &block);
50 if (err != C2_OK) {
51 ALOGD("fetch graphic block failed: %d", err);
52 return nullptr;
53 }
54
55 return GraphicBlockBuffer::Allocate(
56 format,
57 block,
58 [localBufferPool](size_t capacity) {
59 return localBufferPool->newBuffer(capacity);
60 });
61}
62
63} // namespace
64
65// CCodecBuffers
66
67void CCodecBuffers::setFormat(const sp<AMessage> &format) {
68 CHECK(format != nullptr);
69 mFormat = format;
70}
71
72sp<AMessage> CCodecBuffers::dupFormat() {
73 return mFormat != nullptr ? mFormat->dup() : nullptr;
74}
75
76void CCodecBuffers::handleImageData(const sp<Codec2Buffer> &buffer) {
77 sp<ABuffer> imageDataCandidate = buffer->getImageData();
78 if (imageDataCandidate == nullptr) {
79 return;
80 }
81 sp<ABuffer> imageData;
82 if (!mFormat->findBuffer("image-data", &imageData)
83 || imageDataCandidate->size() != imageData->size()
84 || memcmp(imageDataCandidate->data(), imageData->data(), imageData->size()) != 0) {
85 ALOGD("[%s] updating image-data", mName);
86 sp<AMessage> newFormat = dupFormat();
87 newFormat->setBuffer("image-data", imageDataCandidate);
88 MediaImage2 *img = (MediaImage2*)imageDataCandidate->data();
89 if (img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
90 int32_t stride = img->mPlane[0].mRowInc;
91 newFormat->setInt32(KEY_STRIDE, stride);
92 ALOGD("[%s] updating stride = %d", mName, stride);
93 if (img->mNumPlanes > 1 && stride > 0) {
Taehwan Kimfd9b8092020-09-17 12:26:40 +090094 int64_t offsetDelta =
95 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
96 int32_t vstride = int32_t(offsetDelta / stride);
Wonsik Kim469c8342019-04-11 16:46:09 -070097 newFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
98 ALOGD("[%s] updating vstride = %d", mName, vstride);
Wonsik Kim2eb06312020-12-03 11:07:58 -080099 buffer->setRange(
100 img->mPlane[0].mOffset,
101 buffer->size() - img->mPlane[0].mOffset);
Wonsik Kim469c8342019-04-11 16:46:09 -0700102 }
103 }
104 setFormat(newFormat);
105 buffer->setFormat(newFormat);
106 }
107}
108
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700109// InputBuffers
110
111sp<Codec2Buffer> InputBuffers::cloneAndReleaseBuffer(const sp<MediaCodecBuffer> &buffer) {
112 sp<Codec2Buffer> copy = createNewBuffer();
113 if (copy == nullptr) {
114 return nullptr;
115 }
116 std::shared_ptr<C2Buffer> c2buffer;
117 if (!releaseBuffer(buffer, &c2buffer, true)) {
118 return nullptr;
119 }
120 if (!copy->canCopy(c2buffer)) {
121 return nullptr;
122 }
123 if (!copy->copy(c2buffer)) {
124 return nullptr;
125 }
126 return copy;
127}
128
Wonsik Kim469c8342019-04-11 16:46:09 -0700129// OutputBuffers
130
Wonsik Kim41d83432020-04-27 16:40:49 -0700131OutputBuffers::OutputBuffers(const char *componentName, const char *name)
132 : CCodecBuffers(componentName, name) { }
133
134OutputBuffers::~OutputBuffers() = default;
135
Wonsik Kim469c8342019-04-11 16:46:09 -0700136void OutputBuffers::initSkipCutBuffer(
137 int32_t delay, int32_t padding, int32_t sampleRate, int32_t channelCount) {
138 CHECK(mSkipCutBuffer == nullptr);
139 mDelay = delay;
140 mPadding = padding;
141 mSampleRate = sampleRate;
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700142 mChannelCount = channelCount;
143 setSkipCutBuffer(delay, padding);
Wonsik Kim469c8342019-04-11 16:46:09 -0700144}
145
146void OutputBuffers::updateSkipCutBuffer(int32_t sampleRate, int32_t channelCount) {
147 if (mSkipCutBuffer == nullptr) {
148 return;
149 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700150 if (mSampleRate == sampleRate && mChannelCount == channelCount) {
151 return;
152 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700153 int32_t delay = mDelay;
154 int32_t padding = mPadding;
155 if (sampleRate != mSampleRate) {
156 delay = ((int64_t)delay * sampleRate) / mSampleRate;
157 padding = ((int64_t)padding * sampleRate) / mSampleRate;
158 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700159 mSampleRate = sampleRate;
160 mChannelCount = channelCount;
161 setSkipCutBuffer(delay, padding);
Wonsik Kim469c8342019-04-11 16:46:09 -0700162}
163
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800164void OutputBuffers::updateSkipCutBuffer(const sp<AMessage> &format) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700165 AString mediaType;
166 if (format->findString(KEY_MIME, &mediaType)
167 && mediaType == MIMETYPE_AUDIO_RAW) {
168 int32_t channelCount;
169 int32_t sampleRate;
170 if (format->findInt32(KEY_CHANNEL_COUNT, &channelCount)
171 && format->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
172 updateSkipCutBuffer(sampleRate, channelCount);
173 }
174 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700175}
176
Wonsik Kim469c8342019-04-11 16:46:09 -0700177void OutputBuffers::submit(const sp<MediaCodecBuffer> &buffer) {
178 if (mSkipCutBuffer != nullptr) {
179 mSkipCutBuffer->submit(buffer);
180 }
181}
182
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700183void OutputBuffers::setSkipCutBuffer(int32_t skip, int32_t cut) {
Wonsik Kim469c8342019-04-11 16:46:09 -0700184 if (mSkipCutBuffer != nullptr) {
185 size_t prevSize = mSkipCutBuffer->size();
186 if (prevSize != 0u) {
187 ALOGD("[%s] Replacing SkipCutBuffer holding %zu bytes", mName, prevSize);
188 }
189 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700190 mSkipCutBuffer = new SkipCutBuffer(skip, cut, mChannelCount);
Wonsik Kim469c8342019-04-11 16:46:09 -0700191}
192
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700193void OutputBuffers::clearStash() {
194 mPending.clear();
195 mReorderStash.clear();
196 mDepth = 0;
197 mKey = C2Config::ORDINAL;
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700198}
199
200void OutputBuffers::flushStash() {
201 for (StashEntry& e : mPending) {
202 e.notify = false;
203 }
204 for (StashEntry& e : mReorderStash) {
205 e.notify = false;
206 }
207}
208
209uint32_t OutputBuffers::getReorderDepth() const {
210 return mDepth;
211}
212
213void OutputBuffers::setReorderDepth(uint32_t depth) {
214 mPending.splice(mPending.end(), mReorderStash);
215 mDepth = depth;
216}
217
218void OutputBuffers::setReorderKey(C2Config::ordinal_key_t key) {
219 mPending.splice(mPending.end(), mReorderStash);
220 mKey = key;
221}
222
223void OutputBuffers::pushToStash(
224 const std::shared_ptr<C2Buffer>& buffer,
225 bool notify,
226 int64_t timestamp,
227 int32_t flags,
228 const sp<AMessage>& format,
229 const C2WorkOrdinalStruct& ordinal) {
230 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
231 if (!buffer && eos) {
232 // TRICKY: we may be violating ordering of the stash here. Because we
233 // don't expect any more emplace() calls after this, the ordering should
234 // not matter.
235 mReorderStash.emplace_back(
236 buffer, notify, timestamp, flags, format, ordinal);
237 } else {
238 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
239 auto it = mReorderStash.begin();
240 for (; it != mReorderStash.end(); ++it) {
241 if (less(ordinal, it->ordinal)) {
242 break;
243 }
244 }
245 mReorderStash.emplace(it,
246 buffer, notify, timestamp, flags, format, ordinal);
247 if (eos) {
248 mReorderStash.back().flags =
249 mReorderStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
250 }
251 }
252 while (!mReorderStash.empty() && mReorderStash.size() > mDepth) {
253 mPending.push_back(mReorderStash.front());
254 mReorderStash.pop_front();
255 }
256 ALOGV("[%s] %s: pushToStash -- pending size = %zu", mName, __func__, mPending.size());
257}
258
259OutputBuffers::BufferAction OutputBuffers::popFromStashAndRegister(
260 std::shared_ptr<C2Buffer>* c2Buffer,
261 size_t* index,
262 sp<MediaCodecBuffer>* outBuffer) {
263 if (mPending.empty()) {
264 return SKIP;
265 }
266
267 // Retrieve the first entry.
268 StashEntry &entry = mPending.front();
269
270 *c2Buffer = entry.buffer;
271 sp<AMessage> outputFormat = entry.format;
272
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800273 if (entry.notify && mFormat != outputFormat) {
274 updateSkipCutBuffer(outputFormat);
275 sp<ABuffer> imageData;
276 if (mFormat->findBuffer("image-data", &imageData)) {
277 outputFormat->setBuffer("image-data", imageData);
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700278 }
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800279 int32_t stride;
280 if (mFormat->findInt32(KEY_STRIDE, &stride)) {
281 outputFormat->setInt32(KEY_STRIDE, stride);
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700282 }
Wonsik Kim3b4349a2020-11-10 11:54:15 -0800283 int32_t sliceHeight;
284 if (mFormat->findInt32(KEY_SLICE_HEIGHT, &sliceHeight)) {
285 outputFormat->setInt32(KEY_SLICE_HEIGHT, sliceHeight);
286 }
287 ALOGV("[%s] popFromStashAndRegister: output format reference changed: %p -> %p",
288 mName, mFormat.get(), outputFormat.get());
289 ALOGD("[%s] popFromStashAndRegister: output format changed to %s",
290 mName, outputFormat->debugString().c_str());
291 setFormat(outputFormat);
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700292 }
293
294 // Flushing mReorderStash because no other buffers should come after output
295 // EOS.
296 if (entry.flags & MediaCodec::BUFFER_FLAG_EOS) {
297 // Flush reorder stash
298 setReorderDepth(0);
299 }
300
301 if (!entry.notify) {
302 mPending.pop_front();
303 return DISCARD;
304 }
305
306 // Try to register the buffer.
307 status_t err = registerBuffer(*c2Buffer, index, outBuffer);
308 if (err != OK) {
309 if (err != WOULD_BLOCK) {
310 return REALLOCATE;
311 }
312 return RETRY;
313 }
314
315 // Append information from the front stash entry to outBuffer.
316 (*outBuffer)->meta()->setInt64("timeUs", entry.timestamp);
317 (*outBuffer)->meta()->setInt32("flags", entry.flags);
Byeongjo Park2eef13e2020-06-12 17:24:21 +0900318 (*outBuffer)->meta()->setInt64("frameIndex", entry.ordinal.frameIndex.peekll());
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700319 ALOGV("[%s] popFromStashAndRegister: "
320 "out buffer index = %zu [%p] => %p + %zu (%lld)",
321 mName, *index, outBuffer->get(),
322 (*outBuffer)->data(), (*outBuffer)->size(),
323 (long long)entry.timestamp);
324
325 // The front entry of mPending will be removed now that the registration
326 // succeeded.
327 mPending.pop_front();
328 return NOTIFY_CLIENT;
329}
330
331bool OutputBuffers::popPending(StashEntry *entry) {
332 if (mPending.empty()) {
333 return false;
334 }
335 *entry = mPending.front();
336 mPending.pop_front();
337 return true;
338}
339
340void OutputBuffers::deferPending(const OutputBuffers::StashEntry &entry) {
341 mPending.push_front(entry);
342}
343
344bool OutputBuffers::hasPending() const {
345 return !mPending.empty();
346}
347
348bool OutputBuffers::less(
349 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) const {
350 switch (mKey) {
351 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
352 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
353 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
354 default:
355 ALOGD("Unrecognized key; default to timestamp");
356 return o1.frameIndex < o2.frameIndex;
357 }
358}
359
Wonsik Kim469c8342019-04-11 16:46:09 -0700360// LocalBufferPool
361
Wonsik Kim41d83432020-04-27 16:40:49 -0700362constexpr size_t kInitialPoolCapacity = kMaxLinearBufferSize;
363constexpr size_t kMaxPoolCapacity = kMaxLinearBufferSize * 32;
364
365std::shared_ptr<LocalBufferPool> LocalBufferPool::Create() {
366 return std::shared_ptr<LocalBufferPool>(new LocalBufferPool(kInitialPoolCapacity));
Wonsik Kim469c8342019-04-11 16:46:09 -0700367}
368
369sp<ABuffer> LocalBufferPool::newBuffer(size_t capacity) {
370 Mutex::Autolock lock(mMutex);
371 auto it = std::find_if(
372 mPool.begin(), mPool.end(),
373 [capacity](const std::vector<uint8_t> &vec) {
374 return vec.capacity() >= capacity;
375 });
376 if (it != mPool.end()) {
377 sp<ABuffer> buffer = new VectorBuffer(std::move(*it), shared_from_this());
378 mPool.erase(it);
379 return buffer;
380 }
381 if (mUsedSize + capacity > mPoolCapacity) {
382 while (!mPool.empty()) {
383 mUsedSize -= mPool.back().capacity();
384 mPool.pop_back();
385 }
Wonsik Kim41d83432020-04-27 16:40:49 -0700386 while (mUsedSize + capacity > mPoolCapacity && mPoolCapacity * 2 <= kMaxPoolCapacity) {
387 ALOGD("Increasing local buffer pool capacity from %zu to %zu",
388 mPoolCapacity, mPoolCapacity * 2);
389 mPoolCapacity *= 2;
390 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700391 if (mUsedSize + capacity > mPoolCapacity) {
392 ALOGD("mUsedSize = %zu, capacity = %zu, mPoolCapacity = %zu",
393 mUsedSize, capacity, mPoolCapacity);
394 return nullptr;
395 }
396 }
397 std::vector<uint8_t> vec(capacity);
398 mUsedSize += vec.capacity();
399 return new VectorBuffer(std::move(vec), shared_from_this());
400}
401
402LocalBufferPool::VectorBuffer::VectorBuffer(
403 std::vector<uint8_t> &&vec, const std::shared_ptr<LocalBufferPool> &pool)
404 : ABuffer(vec.data(), vec.capacity()),
405 mVec(std::move(vec)),
406 mPool(pool) {
407}
408
409LocalBufferPool::VectorBuffer::~VectorBuffer() {
410 std::shared_ptr<LocalBufferPool> pool = mPool.lock();
411 if (pool) {
412 // If pool is alive, return the vector back to the pool so that
413 // it can be recycled.
414 pool->returnVector(std::move(mVec));
415 }
416}
417
418void LocalBufferPool::returnVector(std::vector<uint8_t> &&vec) {
419 Mutex::Autolock lock(mMutex);
420 mPool.push_front(std::move(vec));
421}
422
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700423// FlexBuffersImpl
424
Wonsik Kim469c8342019-04-11 16:46:09 -0700425size_t FlexBuffersImpl::assignSlot(const sp<Codec2Buffer> &buffer) {
426 for (size_t i = 0; i < mBuffers.size(); ++i) {
427 if (mBuffers[i].clientBuffer == nullptr
428 && mBuffers[i].compBuffer.expired()) {
429 mBuffers[i].clientBuffer = buffer;
430 return i;
431 }
432 }
433 mBuffers.push_back({ buffer, std::weak_ptr<C2Buffer>() });
434 return mBuffers.size() - 1;
435}
436
Wonsik Kim469c8342019-04-11 16:46:09 -0700437bool FlexBuffersImpl::releaseSlot(
438 const sp<MediaCodecBuffer> &buffer,
439 std::shared_ptr<C2Buffer> *c2buffer,
440 bool release) {
441 sp<Codec2Buffer> clientBuffer;
442 size_t index = mBuffers.size();
443 for (size_t i = 0; i < mBuffers.size(); ++i) {
444 if (mBuffers[i].clientBuffer == buffer) {
445 clientBuffer = mBuffers[i].clientBuffer;
446 if (release) {
447 mBuffers[i].clientBuffer.clear();
448 }
449 index = i;
450 break;
451 }
452 }
453 if (clientBuffer == nullptr) {
454 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
455 return false;
456 }
457 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
458 if (!result) {
459 result = clientBuffer->asC2Buffer();
Wonsik Kimf9b32122020-04-02 11:30:17 -0700460 clientBuffer->clearC2BufferRefs();
Wonsik Kim469c8342019-04-11 16:46:09 -0700461 mBuffers[index].compBuffer = result;
462 }
463 if (c2buffer) {
464 *c2buffer = result;
465 }
466 return true;
467}
468
469bool FlexBuffersImpl::expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
470 for (size_t i = 0; i < mBuffers.size(); ++i) {
471 std::shared_ptr<C2Buffer> compBuffer =
472 mBuffers[i].compBuffer.lock();
473 if (!compBuffer || compBuffer != c2buffer) {
474 continue;
475 }
476 mBuffers[i].compBuffer.reset();
477 ALOGV("[%s] codec released buffer #%zu", mName, i);
478 return true;
479 }
480 ALOGV("[%s] codec released an unknown buffer", mName);
481 return false;
482}
483
484void FlexBuffersImpl::flush() {
485 ALOGV("[%s] buffers are flushed %zu", mName, mBuffers.size());
486 mBuffers.clear();
487}
488
Wonsik Kim0487b782020-10-28 11:45:50 -0700489size_t FlexBuffersImpl::numActiveSlots() const {
Wonsik Kim469c8342019-04-11 16:46:09 -0700490 return std::count_if(
491 mBuffers.begin(), mBuffers.end(),
492 [](const Entry &entry) {
Wonsik Kim0487b782020-10-28 11:45:50 -0700493 return (entry.clientBuffer != nullptr
494 || !entry.compBuffer.expired());
Wonsik Kim469c8342019-04-11 16:46:09 -0700495 });
496}
497
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700498size_t FlexBuffersImpl::numComponentBuffers() const {
499 return std::count_if(
500 mBuffers.begin(), mBuffers.end(),
501 [](const Entry &entry) {
502 return !entry.compBuffer.expired();
503 });
504}
505
Wonsik Kim469c8342019-04-11 16:46:09 -0700506// BuffersArrayImpl
507
508void BuffersArrayImpl::initialize(
509 const FlexBuffersImpl &impl,
510 size_t minSize,
511 std::function<sp<Codec2Buffer>()> allocate) {
512 mImplName = impl.mImplName + "[N]";
513 mName = mImplName.c_str();
514 for (size_t i = 0; i < impl.mBuffers.size(); ++i) {
515 sp<Codec2Buffer> clientBuffer = impl.mBuffers[i].clientBuffer;
516 bool ownedByClient = (clientBuffer != nullptr);
517 if (!ownedByClient) {
518 clientBuffer = allocate();
519 }
520 mBuffers.push_back({ clientBuffer, impl.mBuffers[i].compBuffer, ownedByClient });
521 }
522 ALOGV("[%s] converted %zu buffers to array mode of %zu", mName, mBuffers.size(), minSize);
523 for (size_t i = impl.mBuffers.size(); i < minSize; ++i) {
524 mBuffers.push_back({ allocate(), std::weak_ptr<C2Buffer>(), false });
525 }
526}
527
528status_t BuffersArrayImpl::grabBuffer(
529 size_t *index,
530 sp<Codec2Buffer> *buffer,
531 std::function<bool(const sp<Codec2Buffer> &)> match) {
532 // allBuffersDontMatch remains true if all buffers are available but
533 // match() returns false for every buffer.
534 bool allBuffersDontMatch = true;
535 for (size_t i = 0; i < mBuffers.size(); ++i) {
536 if (!mBuffers[i].ownedByClient && mBuffers[i].compBuffer.expired()) {
537 if (match(mBuffers[i].clientBuffer)) {
538 mBuffers[i].ownedByClient = true;
539 *buffer = mBuffers[i].clientBuffer;
540 (*buffer)->meta()->clear();
541 (*buffer)->setRange(0, (*buffer)->capacity());
542 *index = i;
543 return OK;
544 }
545 } else {
546 allBuffersDontMatch = false;
547 }
548 }
549 return allBuffersDontMatch ? NO_MEMORY : WOULD_BLOCK;
550}
551
552bool BuffersArrayImpl::returnBuffer(
553 const sp<MediaCodecBuffer> &buffer,
554 std::shared_ptr<C2Buffer> *c2buffer,
555 bool release) {
556 sp<Codec2Buffer> clientBuffer;
557 size_t index = mBuffers.size();
558 for (size_t i = 0; i < mBuffers.size(); ++i) {
559 if (mBuffers[i].clientBuffer == buffer) {
560 if (!mBuffers[i].ownedByClient) {
561 ALOGD("[%s] Client returned a buffer it does not own according to our record: %zu",
562 mName, i);
563 }
564 clientBuffer = mBuffers[i].clientBuffer;
565 if (release) {
566 mBuffers[i].ownedByClient = false;
567 }
568 index = i;
569 break;
570 }
571 }
572 if (clientBuffer == nullptr) {
573 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
574 return false;
575 }
576 ALOGV("[%s] %s: matching buffer found (index=%zu)", mName, __func__, index);
577 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
578 if (!result) {
579 result = clientBuffer->asC2Buffer();
Wonsik Kimf9b32122020-04-02 11:30:17 -0700580 clientBuffer->clearC2BufferRefs();
Wonsik Kim469c8342019-04-11 16:46:09 -0700581 mBuffers[index].compBuffer = result;
582 }
583 if (c2buffer) {
584 *c2buffer = result;
585 }
586 return true;
587}
588
589bool BuffersArrayImpl::expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
590 for (size_t i = 0; i < mBuffers.size(); ++i) {
591 std::shared_ptr<C2Buffer> compBuffer =
592 mBuffers[i].compBuffer.lock();
593 if (!compBuffer) {
594 continue;
595 }
596 if (c2buffer == compBuffer) {
597 if (mBuffers[i].ownedByClient) {
598 // This should not happen.
599 ALOGD("[%s] codec released a buffer owned by client "
600 "(index %zu)", mName, i);
601 }
602 mBuffers[i].compBuffer.reset();
603 ALOGV("[%s] codec released buffer #%zu(array mode)", mName, i);
604 return true;
605 }
606 }
607 ALOGV("[%s] codec released an unknown buffer (array mode)", mName);
608 return false;
609}
610
611void BuffersArrayImpl::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
612 array->clear();
613 for (const Entry &entry : mBuffers) {
614 array->push(entry.clientBuffer);
615 }
616}
617
618void BuffersArrayImpl::flush() {
619 for (Entry &entry : mBuffers) {
620 entry.ownedByClient = false;
621 }
622}
623
624void BuffersArrayImpl::realloc(std::function<sp<Codec2Buffer>()> alloc) {
625 size_t size = mBuffers.size();
626 mBuffers.clear();
627 for (size_t i = 0; i < size; ++i) {
628 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
629 }
630}
631
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700632void BuffersArrayImpl::grow(
633 size_t newSize, std::function<sp<Codec2Buffer>()> alloc) {
634 CHECK_LT(mBuffers.size(), newSize);
635 while (mBuffers.size() < newSize) {
636 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
637 }
638}
639
Wonsik Kim0487b782020-10-28 11:45:50 -0700640size_t BuffersArrayImpl::numActiveSlots() const {
Wonsik Kim469c8342019-04-11 16:46:09 -0700641 return std::count_if(
642 mBuffers.begin(), mBuffers.end(),
643 [](const Entry &entry) {
Wonsik Kim0487b782020-10-28 11:45:50 -0700644 return entry.ownedByClient || !entry.compBuffer.expired();
Wonsik Kim469c8342019-04-11 16:46:09 -0700645 });
646}
647
Wonsik Kima39882b2019-06-20 16:13:56 -0700648size_t BuffersArrayImpl::arraySize() const {
649 return mBuffers.size();
650}
651
Wonsik Kim469c8342019-04-11 16:46:09 -0700652// InputBuffersArray
653
654void InputBuffersArray::initialize(
655 const FlexBuffersImpl &impl,
656 size_t minSize,
657 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700658 mAllocate = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -0700659 mImpl.initialize(impl, minSize, allocate);
660}
661
662void InputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
663 mImpl.getArray(array);
664}
665
666bool InputBuffersArray::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
667 sp<Codec2Buffer> c2Buffer;
668 status_t err = mImpl.grabBuffer(index, &c2Buffer);
669 if (err == OK) {
670 c2Buffer->setFormat(mFormat);
671 handleImageData(c2Buffer);
672 *buffer = c2Buffer;
673 return true;
674 }
675 return false;
676}
677
678bool InputBuffersArray::releaseBuffer(
679 const sp<MediaCodecBuffer> &buffer,
680 std::shared_ptr<C2Buffer> *c2buffer,
681 bool release) {
682 return mImpl.returnBuffer(buffer, c2buffer, release);
683}
684
685bool InputBuffersArray::expireComponentBuffer(
686 const std::shared_ptr<C2Buffer> &c2buffer) {
687 return mImpl.expireComponentBuffer(c2buffer);
688}
689
690void InputBuffersArray::flush() {
691 mImpl.flush();
692}
693
Wonsik Kim0487b782020-10-28 11:45:50 -0700694size_t InputBuffersArray::numActiveSlots() const {
695 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700696}
697
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700698sp<Codec2Buffer> InputBuffersArray::createNewBuffer() {
699 return mAllocate();
700}
701
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800702// SlotInputBuffers
703
704bool SlotInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
705 sp<Codec2Buffer> newBuffer = createNewBuffer();
706 *index = mImpl.assignSlot(newBuffer);
707 *buffer = newBuffer;
708 return true;
709}
710
711bool SlotInputBuffers::releaseBuffer(
712 const sp<MediaCodecBuffer> &buffer,
713 std::shared_ptr<C2Buffer> *c2buffer,
714 bool release) {
715 return mImpl.releaseSlot(buffer, c2buffer, release);
716}
717
718bool SlotInputBuffers::expireComponentBuffer(
719 const std::shared_ptr<C2Buffer> &c2buffer) {
720 return mImpl.expireComponentBuffer(c2buffer);
721}
722
723void SlotInputBuffers::flush() {
724 mImpl.flush();
725}
726
727std::unique_ptr<InputBuffers> SlotInputBuffers::toArrayMode(size_t) {
728 TRESPASS("Array mode should not be called at non-legacy mode");
729 return nullptr;
730}
731
Wonsik Kim0487b782020-10-28 11:45:50 -0700732size_t SlotInputBuffers::numActiveSlots() const {
733 return mImpl.numActiveSlots();
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800734}
735
736sp<Codec2Buffer> SlotInputBuffers::createNewBuffer() {
737 return new DummyContainerBuffer{mFormat, nullptr};
738}
739
Wonsik Kim469c8342019-04-11 16:46:09 -0700740// LinearInputBuffers
741
742bool LinearInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700743 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700744 if (newBuffer == nullptr) {
745 return false;
746 }
747 *index = mImpl.assignSlot(newBuffer);
748 *buffer = newBuffer;
749 return true;
750}
751
752bool LinearInputBuffers::releaseBuffer(
753 const sp<MediaCodecBuffer> &buffer,
754 std::shared_ptr<C2Buffer> *c2buffer,
755 bool release) {
756 return mImpl.releaseSlot(buffer, c2buffer, release);
757}
758
759bool LinearInputBuffers::expireComponentBuffer(
760 const std::shared_ptr<C2Buffer> &c2buffer) {
761 return mImpl.expireComponentBuffer(c2buffer);
762}
763
764void LinearInputBuffers::flush() {
765 // This is no-op by default unless we're in array mode where we need to keep
766 // track of the flushed work.
767 mImpl.flush();
768}
769
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700770std::unique_ptr<InputBuffers> LinearInputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -0700771 std::unique_ptr<InputBuffersArray> array(
772 new InputBuffersArray(mComponentName.c_str(), "1D-Input[N]"));
773 array->setPool(mPool);
774 array->setFormat(mFormat);
775 array->initialize(
776 mImpl,
777 size,
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700778 [pool = mPool, format = mFormat] () -> sp<Codec2Buffer> {
779 return Alloc(pool, format);
780 });
Wonsik Kim469c8342019-04-11 16:46:09 -0700781 return std::move(array);
782}
783
Wonsik Kim0487b782020-10-28 11:45:50 -0700784size_t LinearInputBuffers::numActiveSlots() const {
785 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700786}
787
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700788// static
789sp<Codec2Buffer> LinearInputBuffers::Alloc(
790 const std::shared_ptr<C2BlockPool> &pool, const sp<AMessage> &format) {
791 int32_t capacity = kLinearBufferSize;
792 (void)format->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
793 if ((size_t)capacity > kMaxLinearBufferSize) {
794 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
795 capacity = kMaxLinearBufferSize;
796 }
797
Wonsik Kim666604a2020-05-14 16:57:49 -0700798 int64_t usageValue = 0;
799 (void)format->findInt64("android._C2MemoryUsage", &usageValue);
800 C2MemoryUsage usage{usageValue | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE};
Wonsik Kim469c8342019-04-11 16:46:09 -0700801 std::shared_ptr<C2LinearBlock> block;
802
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700803 c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block);
Wonsik Kim469c8342019-04-11 16:46:09 -0700804 if (err != C2_OK) {
805 return nullptr;
806 }
807
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700808 return LinearBlockBuffer::Allocate(format, block);
809}
810
811sp<Codec2Buffer> LinearInputBuffers::createNewBuffer() {
812 return Alloc(mPool, mFormat);
Wonsik Kim469c8342019-04-11 16:46:09 -0700813}
814
815// EncryptedLinearInputBuffers
816
817EncryptedLinearInputBuffers::EncryptedLinearInputBuffers(
818 bool secure,
819 const sp<MemoryDealer> &dealer,
820 const sp<ICrypto> &crypto,
821 int32_t heapSeqNum,
822 size_t capacity,
823 size_t numInputSlots,
824 const char *componentName, const char *name)
825 : LinearInputBuffers(componentName, name),
826 mUsage({0, 0}),
827 mDealer(dealer),
828 mCrypto(crypto),
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700829 mMemoryVector(new std::vector<Entry>){
Wonsik Kim469c8342019-04-11 16:46:09 -0700830 if (secure) {
831 mUsage = { C2MemoryUsage::READ_PROTECTED, 0 };
832 } else {
833 mUsage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
834 }
835 for (size_t i = 0; i < numInputSlots; ++i) {
836 sp<IMemory> memory = mDealer->allocate(capacity);
837 if (memory == nullptr) {
838 ALOGD("[%s] Failed to allocate memory from dealer: only %zu slots allocated",
839 mName, i);
840 break;
841 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700842 mMemoryVector->push_back({std::weak_ptr<C2LinearBlock>(), memory, heapSeqNum});
Wonsik Kim469c8342019-04-11 16:46:09 -0700843 }
844}
845
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700846std::unique_ptr<InputBuffers> EncryptedLinearInputBuffers::toArrayMode(size_t size) {
847 std::unique_ptr<InputBuffersArray> array(
848 new InputBuffersArray(mComponentName.c_str(), "1D-EncryptedInput[N]"));
849 array->setPool(mPool);
850 array->setFormat(mFormat);
851 array->initialize(
852 mImpl,
853 size,
854 [pool = mPool,
855 format = mFormat,
856 usage = mUsage,
857 memoryVector = mMemoryVector] () -> sp<Codec2Buffer> {
858 return Alloc(pool, format, usage, memoryVector);
859 });
860 return std::move(array);
861}
862
863
864// static
865sp<Codec2Buffer> EncryptedLinearInputBuffers::Alloc(
866 const std::shared_ptr<C2BlockPool> &pool,
867 const sp<AMessage> &format,
868 C2MemoryUsage usage,
869 const std::shared_ptr<std::vector<EncryptedLinearInputBuffers::Entry>> &memoryVector) {
870 int32_t capacity = kLinearBufferSize;
871 (void)format->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
872 if ((size_t)capacity > kMaxLinearBufferSize) {
873 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
874 capacity = kMaxLinearBufferSize;
875 }
876
Wonsik Kim469c8342019-04-11 16:46:09 -0700877 sp<IMemory> memory;
878 size_t slot = 0;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700879 int32_t heapSeqNum = -1;
880 for (; slot < memoryVector->size(); ++slot) {
881 if (memoryVector->at(slot).block.expired()) {
882 memory = memoryVector->at(slot).memory;
883 heapSeqNum = memoryVector->at(slot).heapSeqNum;
Wonsik Kim469c8342019-04-11 16:46:09 -0700884 break;
885 }
886 }
887 if (memory == nullptr) {
888 return nullptr;
889 }
890
891 std::shared_ptr<C2LinearBlock> block;
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700892 c2_status_t err = pool->fetchLinearBlock(capacity, usage, &block);
Wonsik Kim469c8342019-04-11 16:46:09 -0700893 if (err != C2_OK || block == nullptr) {
894 return nullptr;
895 }
896
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700897 memoryVector->at(slot).block = block;
898 return new EncryptedLinearBlockBuffer(format, block, memory, heapSeqNum);
899}
900
901sp<Codec2Buffer> EncryptedLinearInputBuffers::createNewBuffer() {
902 // TODO: android_2020
903 return nullptr;
Wonsik Kim469c8342019-04-11 16:46:09 -0700904}
905
906// GraphicMetadataInputBuffers
907
908GraphicMetadataInputBuffers::GraphicMetadataInputBuffers(
909 const char *componentName, const char *name)
910 : InputBuffers(componentName, name),
911 mImpl(mName),
912 mStore(GetCodec2PlatformAllocatorStore()) { }
913
914bool GraphicMetadataInputBuffers::requestNewBuffer(
915 size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700916 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700917 if (newBuffer == nullptr) {
918 return false;
919 }
920 *index = mImpl.assignSlot(newBuffer);
921 *buffer = newBuffer;
922 return true;
923}
924
925bool GraphicMetadataInputBuffers::releaseBuffer(
926 const sp<MediaCodecBuffer> &buffer,
927 std::shared_ptr<C2Buffer> *c2buffer,
928 bool release) {
929 return mImpl.releaseSlot(buffer, c2buffer, release);
930}
931
932bool GraphicMetadataInputBuffers::expireComponentBuffer(
933 const std::shared_ptr<C2Buffer> &c2buffer) {
934 return mImpl.expireComponentBuffer(c2buffer);
935}
936
937void GraphicMetadataInputBuffers::flush() {
938 // This is no-op by default unless we're in array mode where we need to keep
939 // track of the flushed work.
940}
941
942std::unique_ptr<InputBuffers> GraphicMetadataInputBuffers::toArrayMode(
943 size_t size) {
944 std::shared_ptr<C2Allocator> alloc;
945 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
946 if (err != C2_OK) {
947 return nullptr;
948 }
949 std::unique_ptr<InputBuffersArray> array(
950 new InputBuffersArray(mComponentName.c_str(), "2D-MetaInput[N]"));
951 array->setPool(mPool);
952 array->setFormat(mFormat);
953 array->initialize(
954 mImpl,
955 size,
956 [format = mFormat, alloc]() -> sp<Codec2Buffer> {
957 return new GraphicMetadataBuffer(format, alloc);
958 });
959 return std::move(array);
960}
961
Wonsik Kim0487b782020-10-28 11:45:50 -0700962size_t GraphicMetadataInputBuffers::numActiveSlots() const {
963 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700964}
965
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700966sp<Codec2Buffer> GraphicMetadataInputBuffers::createNewBuffer() {
967 std::shared_ptr<C2Allocator> alloc;
968 c2_status_t err = mStore->fetchAllocator(mPool->getAllocatorId(), &alloc);
969 if (err != C2_OK) {
970 return nullptr;
971 }
972 return new GraphicMetadataBuffer(mFormat, alloc);
973}
974
Wonsik Kim469c8342019-04-11 16:46:09 -0700975// GraphicInputBuffers
976
977GraphicInputBuffers::GraphicInputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -0700978 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -0700979 : InputBuffers(componentName, name),
980 mImpl(mName),
Wonsik Kim41d83432020-04-27 16:40:49 -0700981 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -0700982
983bool GraphicInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700984 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700985 if (newBuffer == nullptr) {
986 return false;
987 }
988 *index = mImpl.assignSlot(newBuffer);
989 handleImageData(newBuffer);
990 *buffer = newBuffer;
991 return true;
992}
993
994bool GraphicInputBuffers::releaseBuffer(
995 const sp<MediaCodecBuffer> &buffer,
996 std::shared_ptr<C2Buffer> *c2buffer,
997 bool release) {
998 return mImpl.releaseSlot(buffer, c2buffer, release);
999}
1000
1001bool GraphicInputBuffers::expireComponentBuffer(
1002 const std::shared_ptr<C2Buffer> &c2buffer) {
1003 return mImpl.expireComponentBuffer(c2buffer);
1004}
1005
1006void GraphicInputBuffers::flush() {
1007 // This is no-op by default unless we're in array mode where we need to keep
1008 // track of the flushed work.
1009}
1010
1011std::unique_ptr<InputBuffers> GraphicInputBuffers::toArrayMode(size_t size) {
1012 std::unique_ptr<InputBuffersArray> array(
1013 new InputBuffersArray(mComponentName.c_str(), "2D-BB-Input[N]"));
1014 array->setPool(mPool);
1015 array->setFormat(mFormat);
1016 array->initialize(
1017 mImpl,
1018 size,
1019 [pool = mPool, format = mFormat, lbp = mLocalBufferPool]() -> sp<Codec2Buffer> {
1020 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1021 return AllocateGraphicBuffer(
1022 pool, format, HAL_PIXEL_FORMAT_YV12, usage, lbp);
1023 });
1024 return std::move(array);
1025}
1026
Wonsik Kim0487b782020-10-28 11:45:50 -07001027size_t GraphicInputBuffers::numActiveSlots() const {
1028 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001029}
1030
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001031sp<Codec2Buffer> GraphicInputBuffers::createNewBuffer() {
Wonsik Kim666604a2020-05-14 16:57:49 -07001032 int64_t usageValue = 0;
1033 (void)mFormat->findInt64("android._C2MemoryUsage", &usageValue);
1034 C2MemoryUsage usage{usageValue | C2MemoryUsage::CPU_READ | C2MemoryUsage::CPU_WRITE};
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001035 return AllocateGraphicBuffer(
1036 mPool, mFormat, HAL_PIXEL_FORMAT_YV12, usage, mLocalBufferPool);
1037}
1038
Wonsik Kim469c8342019-04-11 16:46:09 -07001039// OutputBuffersArray
1040
1041void OutputBuffersArray::initialize(
1042 const FlexBuffersImpl &impl,
1043 size_t minSize,
1044 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001045 mAlloc = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -07001046 mImpl.initialize(impl, minSize, allocate);
1047}
1048
1049status_t OutputBuffersArray::registerBuffer(
1050 const std::shared_ptr<C2Buffer> &buffer,
1051 size_t *index,
1052 sp<MediaCodecBuffer> *clientBuffer) {
1053 sp<Codec2Buffer> c2Buffer;
1054 status_t err = mImpl.grabBuffer(
1055 index,
1056 &c2Buffer,
1057 [buffer](const sp<Codec2Buffer> &clientBuffer) {
1058 return clientBuffer->canCopy(buffer);
1059 });
1060 if (err == WOULD_BLOCK) {
1061 ALOGV("[%s] buffers temporarily not available", mName);
1062 return err;
1063 } else if (err != OK) {
1064 ALOGD("[%s] grabBuffer failed: %d", mName, err);
1065 return err;
1066 }
1067 c2Buffer->setFormat(mFormat);
1068 if (!c2Buffer->copy(buffer)) {
1069 ALOGD("[%s] copy buffer failed", mName);
1070 return WOULD_BLOCK;
1071 }
1072 submit(c2Buffer);
1073 handleImageData(c2Buffer);
1074 *clientBuffer = c2Buffer;
1075 ALOGV("[%s] grabbed buffer %zu", mName, *index);
1076 return OK;
1077}
1078
1079status_t OutputBuffersArray::registerCsd(
1080 const C2StreamInitDataInfo::output *csd,
1081 size_t *index,
1082 sp<MediaCodecBuffer> *clientBuffer) {
1083 sp<Codec2Buffer> c2Buffer;
1084 status_t err = mImpl.grabBuffer(
1085 index,
1086 &c2Buffer,
1087 [csd](const sp<Codec2Buffer> &clientBuffer) {
1088 return clientBuffer->base() != nullptr
1089 && clientBuffer->capacity() >= csd->flexCount();
1090 });
1091 if (err != OK) {
1092 return err;
1093 }
1094 memcpy(c2Buffer->base(), csd->m.value, csd->flexCount());
1095 c2Buffer->setRange(0, csd->flexCount());
1096 c2Buffer->setFormat(mFormat);
1097 *clientBuffer = c2Buffer;
1098 return OK;
1099}
1100
1101bool OutputBuffersArray::releaseBuffer(
1102 const sp<MediaCodecBuffer> &buffer, std::shared_ptr<C2Buffer> *c2buffer) {
1103 return mImpl.returnBuffer(buffer, c2buffer, true);
1104}
1105
1106void OutputBuffersArray::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1107 (void)flushedWork;
1108 mImpl.flush();
1109 if (mSkipCutBuffer != nullptr) {
1110 mSkipCutBuffer->clear();
1111 }
1112}
1113
1114void OutputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
1115 mImpl.getArray(array);
1116}
1117
Wonsik Kim0487b782020-10-28 11:45:50 -07001118size_t OutputBuffersArray::numActiveSlots() const {
1119 return mImpl.numActiveSlots();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001120}
1121
Wonsik Kim469c8342019-04-11 16:46:09 -07001122void OutputBuffersArray::realloc(const std::shared_ptr<C2Buffer> &c2buffer) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001123 switch (c2buffer->data().type()) {
1124 case C2BufferData::LINEAR: {
1125 uint32_t size = kLinearBufferSize;
Nick Desaulniersd09eaea2019-10-07 20:19:39 -07001126 const std::vector<C2ConstLinearBlock> &linear_blocks = c2buffer->data().linearBlocks();
1127 const uint32_t block_size = linear_blocks.front().size();
1128 if (block_size < kMaxLinearBufferSize / 2) {
1129 size = block_size * 2;
Wonsik Kim469c8342019-04-11 16:46:09 -07001130 } else {
1131 size = kMaxLinearBufferSize;
1132 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001133 mAlloc = [format = mFormat, size] {
Wonsik Kim469c8342019-04-11 16:46:09 -07001134 return new LocalLinearBuffer(format, new ABuffer(size));
1135 };
Wonsik Kima39882b2019-06-20 16:13:56 -07001136 ALOGD("[%s] reallocating with linear buffer of size %u", mName, size);
Wonsik Kim469c8342019-04-11 16:46:09 -07001137 break;
1138 }
1139
Wonsik Kima39882b2019-06-20 16:13:56 -07001140 case C2BufferData::GRAPHIC: {
1141 // This is only called for RawGraphicOutputBuffers.
1142 mAlloc = [format = mFormat,
Wonsik Kim41d83432020-04-27 16:40:49 -07001143 lbp = LocalBufferPool::Create()] {
Wonsik Kima39882b2019-06-20 16:13:56 -07001144 return ConstGraphicBlockBuffer::AllocateEmpty(
1145 format,
1146 [lbp](size_t capacity) {
1147 return lbp->newBuffer(capacity);
1148 });
1149 };
1150 ALOGD("[%s] reallocating with graphic buffer: format = %s",
1151 mName, mFormat->debugString().c_str());
1152 break;
1153 }
Wonsik Kim469c8342019-04-11 16:46:09 -07001154
1155 case C2BufferData::INVALID: [[fallthrough]];
1156 case C2BufferData::LINEAR_CHUNKS: [[fallthrough]];
1157 case C2BufferData::GRAPHIC_CHUNKS: [[fallthrough]];
1158 default:
1159 ALOGD("Unsupported type: %d", (int)c2buffer->data().type());
1160 return;
1161 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001162 mImpl.realloc(mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001163}
1164
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001165void OutputBuffersArray::grow(size_t newSize) {
1166 mImpl.grow(newSize, mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001167}
1168
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001169void OutputBuffersArray::transferFrom(OutputBuffers* source) {
1170 mFormat = source->mFormat;
1171 mSkipCutBuffer = source->mSkipCutBuffer;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001172 mPending = std::move(source->mPending);
1173 mReorderStash = std::move(source->mReorderStash);
1174 mDepth = source->mDepth;
1175 mKey = source->mKey;
1176}
1177
Wonsik Kim469c8342019-04-11 16:46:09 -07001178// FlexOutputBuffers
1179
1180status_t FlexOutputBuffers::registerBuffer(
1181 const std::shared_ptr<C2Buffer> &buffer,
1182 size_t *index,
1183 sp<MediaCodecBuffer> *clientBuffer) {
1184 sp<Codec2Buffer> newBuffer = wrap(buffer);
1185 if (newBuffer == nullptr) {
1186 return NO_MEMORY;
1187 }
1188 newBuffer->setFormat(mFormat);
1189 *index = mImpl.assignSlot(newBuffer);
1190 handleImageData(newBuffer);
1191 *clientBuffer = newBuffer;
1192 ALOGV("[%s] registered buffer %zu", mName, *index);
1193 return OK;
1194}
1195
1196status_t FlexOutputBuffers::registerCsd(
1197 const C2StreamInitDataInfo::output *csd,
1198 size_t *index,
1199 sp<MediaCodecBuffer> *clientBuffer) {
1200 sp<Codec2Buffer> newBuffer = new LocalLinearBuffer(
1201 mFormat, ABuffer::CreateAsCopy(csd->m.value, csd->flexCount()));
1202 *index = mImpl.assignSlot(newBuffer);
1203 *clientBuffer = newBuffer;
1204 return OK;
1205}
1206
1207bool FlexOutputBuffers::releaseBuffer(
1208 const sp<MediaCodecBuffer> &buffer,
1209 std::shared_ptr<C2Buffer> *c2buffer) {
1210 return mImpl.releaseSlot(buffer, c2buffer, true);
1211}
1212
1213void FlexOutputBuffers::flush(
1214 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1215 (void) flushedWork;
1216 // This is no-op by default unless we're in array mode where we need to keep
1217 // track of the flushed work.
1218}
1219
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001220std::unique_ptr<OutputBuffersArray> FlexOutputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001221 std::unique_ptr<OutputBuffersArray> array(new OutputBuffersArray(mComponentName.c_str()));
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001222 array->transferFrom(this);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001223 std::function<sp<Codec2Buffer>()> alloc = getAlloc();
1224 array->initialize(mImpl, size, alloc);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001225 return array;
Wonsik Kim469c8342019-04-11 16:46:09 -07001226}
1227
Wonsik Kim0487b782020-10-28 11:45:50 -07001228size_t FlexOutputBuffers::numActiveSlots() const {
1229 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001230}
1231
1232// LinearOutputBuffers
1233
1234void LinearOutputBuffers::flush(
1235 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1236 if (mSkipCutBuffer != nullptr) {
1237 mSkipCutBuffer->clear();
1238 }
1239 FlexOutputBuffers::flush(flushedWork);
1240}
1241
1242sp<Codec2Buffer> LinearOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1243 if (buffer == nullptr) {
1244 ALOGV("[%s] using a dummy buffer", mName);
1245 return new LocalLinearBuffer(mFormat, new ABuffer(0));
1246 }
1247 if (buffer->data().type() != C2BufferData::LINEAR) {
1248 ALOGV("[%s] non-linear buffer %d", mName, buffer->data().type());
1249 // We expect linear output buffers from the component.
1250 return nullptr;
1251 }
1252 if (buffer->data().linearBlocks().size() != 1u) {
1253 ALOGV("[%s] no linear buffers", mName);
1254 // We expect one and only one linear block from the component.
1255 return nullptr;
1256 }
1257 sp<Codec2Buffer> clientBuffer = ConstLinearBlockBuffer::Allocate(mFormat, buffer);
1258 if (clientBuffer == nullptr) {
1259 ALOGD("[%s] ConstLinearBlockBuffer::Allocate failed", mName);
1260 return nullptr;
1261 }
1262 submit(clientBuffer);
1263 return clientBuffer;
1264}
1265
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001266std::function<sp<Codec2Buffer>()> LinearOutputBuffers::getAlloc() {
1267 return [format = mFormat]{
1268 // TODO: proper max output size
1269 return new LocalLinearBuffer(format, new ABuffer(kLinearBufferSize));
1270 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001271}
1272
1273// GraphicOutputBuffers
1274
1275sp<Codec2Buffer> GraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1276 return new DummyContainerBuffer(mFormat, buffer);
1277}
1278
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001279std::function<sp<Codec2Buffer>()> GraphicOutputBuffers::getAlloc() {
1280 return [format = mFormat]{
1281 return new DummyContainerBuffer(format);
1282 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001283}
1284
1285// RawGraphicOutputBuffers
1286
1287RawGraphicOutputBuffers::RawGraphicOutputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -07001288 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -07001289 : FlexOutputBuffers(componentName, name),
Wonsik Kim41d83432020-04-27 16:40:49 -07001290 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -07001291
1292sp<Codec2Buffer> RawGraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1293 if (buffer == nullptr) {
1294 sp<Codec2Buffer> c2buffer = ConstGraphicBlockBuffer::AllocateEmpty(
1295 mFormat,
1296 [lbp = mLocalBufferPool](size_t capacity) {
1297 return lbp->newBuffer(capacity);
1298 });
1299 if (c2buffer == nullptr) {
1300 ALOGD("[%s] ConstGraphicBlockBuffer::AllocateEmpty failed", mName);
1301 return nullptr;
1302 }
1303 c2buffer->setRange(0, 0);
1304 return c2buffer;
1305 } else {
1306 return ConstGraphicBlockBuffer::Allocate(
1307 mFormat,
1308 buffer,
1309 [lbp = mLocalBufferPool](size_t capacity) {
1310 return lbp->newBuffer(capacity);
1311 });
1312 }
1313}
1314
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001315std::function<sp<Codec2Buffer>()> RawGraphicOutputBuffers::getAlloc() {
1316 return [format = mFormat, lbp = mLocalBufferPool]{
1317 return ConstGraphicBlockBuffer::AllocateEmpty(
1318 format,
1319 [lbp](size_t capacity) {
1320 return lbp->newBuffer(capacity);
1321 });
1322 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001323}
1324
1325} // namespace android