blob: 6825dc2cf3ee3e7a8a24afd62d74d5df0bd6951d [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) {
80 return;
81 }
82 sp<ABuffer> imageData;
83 if (!mFormat->findBuffer("image-data", &imageData)
84 || imageDataCandidate->size() != imageData->size()
85 || memcmp(imageDataCandidate->data(), imageData->data(), imageData->size()) != 0) {
86 ALOGD("[%s] updating image-data", mName);
87 sp<AMessage> newFormat = dupFormat();
88 newFormat->setBuffer("image-data", imageDataCandidate);
89 MediaImage2 *img = (MediaImage2*)imageDataCandidate->data();
90 if (img->mNumPlanes > 0 && img->mType != img->MEDIA_IMAGE_TYPE_UNKNOWN) {
91 int32_t stride = img->mPlane[0].mRowInc;
92 newFormat->setInt32(KEY_STRIDE, stride);
93 ALOGD("[%s] updating stride = %d", mName, stride);
94 if (img->mNumPlanes > 1 && stride > 0) {
Taehwan Kimfd9b8092020-09-17 12:26:40 +090095 int64_t offsetDelta =
96 (int64_t)img->mPlane[1].mOffset - (int64_t)img->mPlane[0].mOffset;
97 int32_t vstride = int32_t(offsetDelta / stride);
Wonsik Kim469c8342019-04-11 16:46:09 -070098 newFormat->setInt32(KEY_SLICE_HEIGHT, vstride);
99 ALOGD("[%s] updating vstride = %d", mName, vstride);
Wonsik Kim2eb06312020-12-03 11:07:58 -0800100 buffer->setRange(
101 img->mPlane[0].mOffset,
102 buffer->size() - img->mPlane[0].mOffset);
Wonsik Kim469c8342019-04-11 16:46:09 -0700103 }
104 }
105 setFormat(newFormat);
106 buffer->setFormat(newFormat);
107 }
108}
109
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700110// InputBuffers
111
112sp<Codec2Buffer> InputBuffers::cloneAndReleaseBuffer(const sp<MediaCodecBuffer> &buffer) {
113 sp<Codec2Buffer> copy = createNewBuffer();
114 if (copy == nullptr) {
115 return nullptr;
116 }
117 std::shared_ptr<C2Buffer> c2buffer;
118 if (!releaseBuffer(buffer, &c2buffer, true)) {
119 return nullptr;
120 }
121 if (!copy->canCopy(c2buffer)) {
122 return nullptr;
123 }
124 if (!copy->copy(c2buffer)) {
125 return nullptr;
126 }
127 return copy;
128}
129
Wonsik Kim469c8342019-04-11 16:46:09 -0700130// OutputBuffers
131
Wonsik Kim41d83432020-04-27 16:40:49 -0700132OutputBuffers::OutputBuffers(const char *componentName, const char *name)
133 : CCodecBuffers(componentName, name) { }
134
135OutputBuffers::~OutputBuffers() = default;
136
Wonsik Kim469c8342019-04-11 16:46:09 -0700137void OutputBuffers::initSkipCutBuffer(
138 int32_t delay, int32_t padding, int32_t sampleRate, int32_t channelCount) {
139 CHECK(mSkipCutBuffer == nullptr);
140 mDelay = delay;
141 mPadding = padding;
142 mSampleRate = sampleRate;
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700143 mChannelCount = channelCount;
144 setSkipCutBuffer(delay, padding);
Wonsik Kim469c8342019-04-11 16:46:09 -0700145}
146
147void OutputBuffers::updateSkipCutBuffer(int32_t sampleRate, int32_t channelCount) {
148 if (mSkipCutBuffer == nullptr) {
149 return;
150 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700151 if (mSampleRate == sampleRate && mChannelCount == channelCount) {
152 return;
153 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700154 int32_t delay = mDelay;
155 int32_t padding = mPadding;
156 if (sampleRate != mSampleRate) {
157 delay = ((int64_t)delay * sampleRate) / mSampleRate;
158 padding = ((int64_t)padding * sampleRate) / mSampleRate;
159 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700160 mSampleRate = sampleRate;
161 mChannelCount = channelCount;
162 setSkipCutBuffer(delay, padding);
Wonsik Kim469c8342019-04-11 16:46:09 -0700163}
164
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800165void OutputBuffers::updateSkipCutBuffer(const sp<AMessage> &format) {
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700166 AString mediaType;
167 if (format->findString(KEY_MIME, &mediaType)
168 && mediaType == MIMETYPE_AUDIO_RAW) {
169 int32_t channelCount;
170 int32_t sampleRate;
171 if (format->findInt32(KEY_CHANNEL_COUNT, &channelCount)
172 && format->findInt32(KEY_SAMPLE_RATE, &sampleRate)) {
173 updateSkipCutBuffer(sampleRate, channelCount);
174 }
175 }
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700176}
177
Wonsik Kim469c8342019-04-11 16:46:09 -0700178void OutputBuffers::submit(const sp<MediaCodecBuffer> &buffer) {
179 if (mSkipCutBuffer != nullptr) {
180 mSkipCutBuffer->submit(buffer);
181 }
182}
183
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700184void OutputBuffers::setSkipCutBuffer(int32_t skip, int32_t cut) {
Wonsik Kim469c8342019-04-11 16:46:09 -0700185 if (mSkipCutBuffer != nullptr) {
186 size_t prevSize = mSkipCutBuffer->size();
187 if (prevSize != 0u) {
188 ALOGD("[%s] Replacing SkipCutBuffer holding %zu bytes", mName, prevSize);
189 }
190 }
Wonsik Kim40b0b1d2020-03-25 15:47:35 -0700191 mSkipCutBuffer = new SkipCutBuffer(skip, cut, mChannelCount);
Wonsik Kim469c8342019-04-11 16:46:09 -0700192}
193
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700194void OutputBuffers::clearStash() {
195 mPending.clear();
196 mReorderStash.clear();
197 mDepth = 0;
198 mKey = C2Config::ORDINAL;
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700199}
200
201void OutputBuffers::flushStash() {
202 for (StashEntry& e : mPending) {
203 e.notify = false;
204 }
205 for (StashEntry& e : mReorderStash) {
206 e.notify = false;
207 }
208}
209
210uint32_t OutputBuffers::getReorderDepth() const {
211 return mDepth;
212}
213
214void OutputBuffers::setReorderDepth(uint32_t depth) {
215 mPending.splice(mPending.end(), mReorderStash);
216 mDepth = depth;
217}
218
219void OutputBuffers::setReorderKey(C2Config::ordinal_key_t key) {
220 mPending.splice(mPending.end(), mReorderStash);
221 mKey = key;
222}
223
224void OutputBuffers::pushToStash(
225 const std::shared_ptr<C2Buffer>& buffer,
226 bool notify,
227 int64_t timestamp,
228 int32_t flags,
229 const sp<AMessage>& format,
230 const C2WorkOrdinalStruct& ordinal) {
231 bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
232 if (!buffer && eos) {
233 // TRICKY: we may be violating ordering of the stash here. Because we
234 // don't expect any more emplace() calls after this, the ordering should
235 // not matter.
236 mReorderStash.emplace_back(
237 buffer, notify, timestamp, flags, format, ordinal);
238 } else {
239 flags = flags & ~MediaCodec::BUFFER_FLAG_EOS;
240 auto it = mReorderStash.begin();
241 for (; it != mReorderStash.end(); ++it) {
242 if (less(ordinal, it->ordinal)) {
243 break;
244 }
245 }
246 mReorderStash.emplace(it,
247 buffer, notify, timestamp, flags, format, ordinal);
248 if (eos) {
249 mReorderStash.back().flags =
250 mReorderStash.back().flags | MediaCodec::BUFFER_FLAG_EOS;
251 }
252 }
253 while (!mReorderStash.empty() && mReorderStash.size() > mDepth) {
254 mPending.push_back(mReorderStash.front());
255 mReorderStash.pop_front();
256 }
257 ALOGV("[%s] %s: pushToStash -- pending size = %zu", mName, __func__, mPending.size());
258}
259
260OutputBuffers::BufferAction OutputBuffers::popFromStashAndRegister(
261 std::shared_ptr<C2Buffer>* c2Buffer,
262 size_t* index,
263 sp<MediaCodecBuffer>* outBuffer) {
264 if (mPending.empty()) {
265 return SKIP;
266 }
267
268 // Retrieve the first entry.
269 StashEntry &entry = mPending.front();
270
271 *c2Buffer = entry.buffer;
272 sp<AMessage> outputFormat = entry.format;
273
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800274 if (entry.notify && mFormat != outputFormat) {
275 updateSkipCutBuffer(outputFormat);
276 sp<ABuffer> imageData;
277 if (mFormat->findBuffer("image-data", &imageData)) {
278 outputFormat->setBuffer("image-data", imageData);
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700279 }
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800280 int32_t stride;
281 if (mFormat->findInt32(KEY_STRIDE, &stride)) {
282 outputFormat->setInt32(KEY_STRIDE, stride);
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700283 }
Wonsik Kim970bf0b2020-11-10 11:54:15 -0800284 int32_t sliceHeight;
285 if (mFormat->findInt32(KEY_SLICE_HEIGHT, &sliceHeight)) {
286 outputFormat->setInt32(KEY_SLICE_HEIGHT, sliceHeight);
287 }
288 ALOGV("[%s] popFromStashAndRegister: output format reference changed: %p -> %p",
289 mName, mFormat.get(), outputFormat.get());
290 ALOGD("[%s] popFromStashAndRegister: output format changed to %s",
291 mName, outputFormat->debugString().c_str());
292 setFormat(outputFormat);
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700293 }
294
295 // Flushing mReorderStash because no other buffers should come after output
296 // EOS.
297 if (entry.flags & MediaCodec::BUFFER_FLAG_EOS) {
298 // Flush reorder stash
299 setReorderDepth(0);
300 }
301
302 if (!entry.notify) {
303 mPending.pop_front();
304 return DISCARD;
305 }
306
307 // Try to register the buffer.
308 status_t err = registerBuffer(*c2Buffer, index, outBuffer);
309 if (err != OK) {
310 if (err != WOULD_BLOCK) {
311 return REALLOCATE;
312 }
313 return RETRY;
314 }
315
316 // Append information from the front stash entry to outBuffer.
317 (*outBuffer)->meta()->setInt64("timeUs", entry.timestamp);
318 (*outBuffer)->meta()->setInt32("flags", entry.flags);
Byeongjo Park25c3a3d2020-06-12 17:24:21 +0900319 (*outBuffer)->meta()->setInt64("frameIndex", entry.ordinal.frameIndex.peekll());
Pawin Vongmasa9b906982020-04-11 05:07:15 -0700320 ALOGV("[%s] popFromStashAndRegister: "
321 "out buffer index = %zu [%p] => %p + %zu (%lld)",
322 mName, *index, outBuffer->get(),
323 (*outBuffer)->data(), (*outBuffer)->size(),
324 (long long)entry.timestamp);
325
326 // The front entry of mPending will be removed now that the registration
327 // succeeded.
328 mPending.pop_front();
329 return NOTIFY_CLIENT;
330}
331
332bool OutputBuffers::popPending(StashEntry *entry) {
333 if (mPending.empty()) {
334 return false;
335 }
336 *entry = mPending.front();
337 mPending.pop_front();
338 return true;
339}
340
341void OutputBuffers::deferPending(const OutputBuffers::StashEntry &entry) {
342 mPending.push_front(entry);
343}
344
345bool OutputBuffers::hasPending() const {
346 return !mPending.empty();
347}
348
349bool OutputBuffers::less(
350 const C2WorkOrdinalStruct &o1, const C2WorkOrdinalStruct &o2) const {
351 switch (mKey) {
352 case C2Config::ORDINAL: return o1.frameIndex < o2.frameIndex;
353 case C2Config::TIMESTAMP: return o1.timestamp < o2.timestamp;
354 case C2Config::CUSTOM: return o1.customOrdinal < o2.customOrdinal;
355 default:
356 ALOGD("Unrecognized key; default to timestamp");
357 return o1.frameIndex < o2.frameIndex;
358 }
359}
360
Wonsik Kim469c8342019-04-11 16:46:09 -0700361// LocalBufferPool
362
Wonsik Kim41d83432020-04-27 16:40:49 -0700363constexpr size_t kInitialPoolCapacity = kMaxLinearBufferSize;
364constexpr size_t kMaxPoolCapacity = kMaxLinearBufferSize * 32;
365
366std::shared_ptr<LocalBufferPool> LocalBufferPool::Create() {
367 return std::shared_ptr<LocalBufferPool>(new LocalBufferPool(kInitialPoolCapacity));
Wonsik Kim469c8342019-04-11 16:46:09 -0700368}
369
370sp<ABuffer> LocalBufferPool::newBuffer(size_t capacity) {
371 Mutex::Autolock lock(mMutex);
372 auto it = std::find_if(
373 mPool.begin(), mPool.end(),
374 [capacity](const std::vector<uint8_t> &vec) {
375 return vec.capacity() >= capacity;
376 });
377 if (it != mPool.end()) {
378 sp<ABuffer> buffer = new VectorBuffer(std::move(*it), shared_from_this());
379 mPool.erase(it);
380 return buffer;
381 }
382 if (mUsedSize + capacity > mPoolCapacity) {
383 while (!mPool.empty()) {
384 mUsedSize -= mPool.back().capacity();
385 mPool.pop_back();
386 }
Wonsik Kim41d83432020-04-27 16:40:49 -0700387 while (mUsedSize + capacity > mPoolCapacity && mPoolCapacity * 2 <= kMaxPoolCapacity) {
388 ALOGD("Increasing local buffer pool capacity from %zu to %zu",
389 mPoolCapacity, mPoolCapacity * 2);
390 mPoolCapacity *= 2;
391 }
Wonsik Kim469c8342019-04-11 16:46:09 -0700392 if (mUsedSize + capacity > mPoolCapacity) {
393 ALOGD("mUsedSize = %zu, capacity = %zu, mPoolCapacity = %zu",
394 mUsedSize, capacity, mPoolCapacity);
395 return nullptr;
396 }
397 }
398 std::vector<uint8_t> vec(capacity);
399 mUsedSize += vec.capacity();
400 return new VectorBuffer(std::move(vec), shared_from_this());
401}
402
403LocalBufferPool::VectorBuffer::VectorBuffer(
404 std::vector<uint8_t> &&vec, const std::shared_ptr<LocalBufferPool> &pool)
405 : ABuffer(vec.data(), vec.capacity()),
406 mVec(std::move(vec)),
407 mPool(pool) {
408}
409
410LocalBufferPool::VectorBuffer::~VectorBuffer() {
411 std::shared_ptr<LocalBufferPool> pool = mPool.lock();
412 if (pool) {
413 // If pool is alive, return the vector back to the pool so that
414 // it can be recycled.
415 pool->returnVector(std::move(mVec));
416 }
417}
418
419void LocalBufferPool::returnVector(std::vector<uint8_t> &&vec) {
420 Mutex::Autolock lock(mMutex);
421 mPool.push_front(std::move(vec));
422}
423
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700424// FlexBuffersImpl
425
Wonsik Kim469c8342019-04-11 16:46:09 -0700426size_t FlexBuffersImpl::assignSlot(const sp<Codec2Buffer> &buffer) {
427 for (size_t i = 0; i < mBuffers.size(); ++i) {
428 if (mBuffers[i].clientBuffer == nullptr
429 && mBuffers[i].compBuffer.expired()) {
430 mBuffers[i].clientBuffer = buffer;
431 return i;
432 }
433 }
434 mBuffers.push_back({ buffer, std::weak_ptr<C2Buffer>() });
435 return mBuffers.size() - 1;
436}
437
Wonsik Kim469c8342019-04-11 16:46:09 -0700438bool FlexBuffersImpl::releaseSlot(
439 const sp<MediaCodecBuffer> &buffer,
440 std::shared_ptr<C2Buffer> *c2buffer,
441 bool release) {
442 sp<Codec2Buffer> clientBuffer;
443 size_t index = mBuffers.size();
444 for (size_t i = 0; i < mBuffers.size(); ++i) {
445 if (mBuffers[i].clientBuffer == buffer) {
446 clientBuffer = mBuffers[i].clientBuffer;
447 if (release) {
448 mBuffers[i].clientBuffer.clear();
449 }
450 index = i;
451 break;
452 }
453 }
454 if (clientBuffer == nullptr) {
455 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
456 return false;
457 }
458 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
459 if (!result) {
460 result = clientBuffer->asC2Buffer();
Wonsik Kimf9b32122020-04-02 11:30:17 -0700461 clientBuffer->clearC2BufferRefs();
Wonsik Kim469c8342019-04-11 16:46:09 -0700462 mBuffers[index].compBuffer = result;
463 }
464 if (c2buffer) {
465 *c2buffer = result;
466 }
467 return true;
468}
469
470bool FlexBuffersImpl::expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
471 for (size_t i = 0; i < mBuffers.size(); ++i) {
472 std::shared_ptr<C2Buffer> compBuffer =
473 mBuffers[i].compBuffer.lock();
474 if (!compBuffer || compBuffer != c2buffer) {
475 continue;
476 }
477 mBuffers[i].compBuffer.reset();
478 ALOGV("[%s] codec released buffer #%zu", mName, i);
479 return true;
480 }
481 ALOGV("[%s] codec released an unknown buffer", mName);
482 return false;
483}
484
485void FlexBuffersImpl::flush() {
486 ALOGV("[%s] buffers are flushed %zu", mName, mBuffers.size());
487 mBuffers.clear();
488}
489
Wonsik Kim0487b782020-10-28 11:45:50 -0700490size_t FlexBuffersImpl::numActiveSlots() const {
Wonsik Kim469c8342019-04-11 16:46:09 -0700491 return std::count_if(
492 mBuffers.begin(), mBuffers.end(),
493 [](const Entry &entry) {
Wonsik Kim0487b782020-10-28 11:45:50 -0700494 return (entry.clientBuffer != nullptr
495 || !entry.compBuffer.expired());
Wonsik Kim469c8342019-04-11 16:46:09 -0700496 });
497}
498
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700499size_t FlexBuffersImpl::numComponentBuffers() const {
500 return std::count_if(
501 mBuffers.begin(), mBuffers.end(),
502 [](const Entry &entry) {
503 return !entry.compBuffer.expired();
504 });
505}
506
Wonsik Kim469c8342019-04-11 16:46:09 -0700507// BuffersArrayImpl
508
509void BuffersArrayImpl::initialize(
510 const FlexBuffersImpl &impl,
511 size_t minSize,
512 std::function<sp<Codec2Buffer>()> allocate) {
513 mImplName = impl.mImplName + "[N]";
514 mName = mImplName.c_str();
515 for (size_t i = 0; i < impl.mBuffers.size(); ++i) {
516 sp<Codec2Buffer> clientBuffer = impl.mBuffers[i].clientBuffer;
517 bool ownedByClient = (clientBuffer != nullptr);
518 if (!ownedByClient) {
519 clientBuffer = allocate();
520 }
521 mBuffers.push_back({ clientBuffer, impl.mBuffers[i].compBuffer, ownedByClient });
522 }
523 ALOGV("[%s] converted %zu buffers to array mode of %zu", mName, mBuffers.size(), minSize);
524 for (size_t i = impl.mBuffers.size(); i < minSize; ++i) {
525 mBuffers.push_back({ allocate(), std::weak_ptr<C2Buffer>(), false });
526 }
527}
528
529status_t BuffersArrayImpl::grabBuffer(
530 size_t *index,
531 sp<Codec2Buffer> *buffer,
532 std::function<bool(const sp<Codec2Buffer> &)> match) {
533 // allBuffersDontMatch remains true if all buffers are available but
534 // match() returns false for every buffer.
535 bool allBuffersDontMatch = true;
536 for (size_t i = 0; i < mBuffers.size(); ++i) {
537 if (!mBuffers[i].ownedByClient && mBuffers[i].compBuffer.expired()) {
538 if (match(mBuffers[i].clientBuffer)) {
539 mBuffers[i].ownedByClient = true;
540 *buffer = mBuffers[i].clientBuffer;
541 (*buffer)->meta()->clear();
542 (*buffer)->setRange(0, (*buffer)->capacity());
543 *index = i;
544 return OK;
545 }
546 } else {
547 allBuffersDontMatch = false;
548 }
549 }
550 return allBuffersDontMatch ? NO_MEMORY : WOULD_BLOCK;
551}
552
553bool BuffersArrayImpl::returnBuffer(
554 const sp<MediaCodecBuffer> &buffer,
555 std::shared_ptr<C2Buffer> *c2buffer,
556 bool release) {
557 sp<Codec2Buffer> clientBuffer;
558 size_t index = mBuffers.size();
559 for (size_t i = 0; i < mBuffers.size(); ++i) {
560 if (mBuffers[i].clientBuffer == buffer) {
561 if (!mBuffers[i].ownedByClient) {
562 ALOGD("[%s] Client returned a buffer it does not own according to our record: %zu",
563 mName, i);
564 }
565 clientBuffer = mBuffers[i].clientBuffer;
566 if (release) {
567 mBuffers[i].ownedByClient = false;
568 }
569 index = i;
570 break;
571 }
572 }
573 if (clientBuffer == nullptr) {
574 ALOGV("[%s] %s: No matching buffer found", mName, __func__);
575 return false;
576 }
577 ALOGV("[%s] %s: matching buffer found (index=%zu)", mName, __func__, index);
578 std::shared_ptr<C2Buffer> result = mBuffers[index].compBuffer.lock();
579 if (!result) {
580 result = clientBuffer->asC2Buffer();
Wonsik Kimf9b32122020-04-02 11:30:17 -0700581 clientBuffer->clearC2BufferRefs();
Wonsik Kim469c8342019-04-11 16:46:09 -0700582 mBuffers[index].compBuffer = result;
583 }
584 if (c2buffer) {
585 *c2buffer = result;
586 }
587 return true;
588}
589
590bool BuffersArrayImpl::expireComponentBuffer(const std::shared_ptr<C2Buffer> &c2buffer) {
591 for (size_t i = 0; i < mBuffers.size(); ++i) {
592 std::shared_ptr<C2Buffer> compBuffer =
593 mBuffers[i].compBuffer.lock();
594 if (!compBuffer) {
595 continue;
596 }
597 if (c2buffer == compBuffer) {
598 if (mBuffers[i].ownedByClient) {
599 // This should not happen.
600 ALOGD("[%s] codec released a buffer owned by client "
601 "(index %zu)", mName, i);
602 }
603 mBuffers[i].compBuffer.reset();
604 ALOGV("[%s] codec released buffer #%zu(array mode)", mName, i);
605 return true;
606 }
607 }
608 ALOGV("[%s] codec released an unknown buffer (array mode)", mName);
609 return false;
610}
611
612void BuffersArrayImpl::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
613 array->clear();
614 for (const Entry &entry : mBuffers) {
615 array->push(entry.clientBuffer);
616 }
617}
618
619void BuffersArrayImpl::flush() {
620 for (Entry &entry : mBuffers) {
621 entry.ownedByClient = false;
622 }
623}
624
625void BuffersArrayImpl::realloc(std::function<sp<Codec2Buffer>()> alloc) {
626 size_t size = mBuffers.size();
627 mBuffers.clear();
628 for (size_t i = 0; i < size; ++i) {
629 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
630 }
631}
632
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700633void BuffersArrayImpl::grow(
634 size_t newSize, std::function<sp<Codec2Buffer>()> alloc) {
635 CHECK_LT(mBuffers.size(), newSize);
636 while (mBuffers.size() < newSize) {
637 mBuffers.push_back({ alloc(), std::weak_ptr<C2Buffer>(), false });
638 }
639}
640
Wonsik Kim0487b782020-10-28 11:45:50 -0700641size_t BuffersArrayImpl::numActiveSlots() const {
Wonsik Kim469c8342019-04-11 16:46:09 -0700642 return std::count_if(
643 mBuffers.begin(), mBuffers.end(),
644 [](const Entry &entry) {
Wonsik Kim0487b782020-10-28 11:45:50 -0700645 return entry.ownedByClient || !entry.compBuffer.expired();
Wonsik Kim469c8342019-04-11 16:46:09 -0700646 });
647}
648
Wonsik Kima39882b2019-06-20 16:13:56 -0700649size_t BuffersArrayImpl::arraySize() const {
650 return mBuffers.size();
651}
652
Wonsik Kim469c8342019-04-11 16:46:09 -0700653// InputBuffersArray
654
655void InputBuffersArray::initialize(
656 const FlexBuffersImpl &impl,
657 size_t minSize,
658 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700659 mAllocate = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -0700660 mImpl.initialize(impl, minSize, allocate);
661}
662
663void InputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
664 mImpl.getArray(array);
665}
666
667bool InputBuffersArray::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
668 sp<Codec2Buffer> c2Buffer;
669 status_t err = mImpl.grabBuffer(index, &c2Buffer);
670 if (err == OK) {
671 c2Buffer->setFormat(mFormat);
672 handleImageData(c2Buffer);
673 *buffer = c2Buffer;
674 return true;
675 }
676 return false;
677}
678
679bool InputBuffersArray::releaseBuffer(
680 const sp<MediaCodecBuffer> &buffer,
681 std::shared_ptr<C2Buffer> *c2buffer,
682 bool release) {
683 return mImpl.returnBuffer(buffer, c2buffer, release);
684}
685
686bool InputBuffersArray::expireComponentBuffer(
687 const std::shared_ptr<C2Buffer> &c2buffer) {
688 return mImpl.expireComponentBuffer(c2buffer);
689}
690
691void InputBuffersArray::flush() {
692 mImpl.flush();
693}
694
Wonsik Kim0487b782020-10-28 11:45:50 -0700695size_t InputBuffersArray::numActiveSlots() const {
696 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700697}
698
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700699sp<Codec2Buffer> InputBuffersArray::createNewBuffer() {
700 return mAllocate();
701}
702
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800703// SlotInputBuffers
704
705bool SlotInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
706 sp<Codec2Buffer> newBuffer = createNewBuffer();
707 *index = mImpl.assignSlot(newBuffer);
708 *buffer = newBuffer;
709 return true;
710}
711
712bool SlotInputBuffers::releaseBuffer(
713 const sp<MediaCodecBuffer> &buffer,
714 std::shared_ptr<C2Buffer> *c2buffer,
715 bool release) {
716 return mImpl.releaseSlot(buffer, c2buffer, release);
717}
718
719bool SlotInputBuffers::expireComponentBuffer(
720 const std::shared_ptr<C2Buffer> &c2buffer) {
721 return mImpl.expireComponentBuffer(c2buffer);
722}
723
724void SlotInputBuffers::flush() {
725 mImpl.flush();
726}
727
728std::unique_ptr<InputBuffers> SlotInputBuffers::toArrayMode(size_t) {
729 TRESPASS("Array mode should not be called at non-legacy mode");
730 return nullptr;
731}
732
Wonsik Kim0487b782020-10-28 11:45:50 -0700733size_t SlotInputBuffers::numActiveSlots() const {
734 return mImpl.numActiveSlots();
Wonsik Kimfb7a7672019-12-27 17:13:33 -0800735}
736
737sp<Codec2Buffer> SlotInputBuffers::createNewBuffer() {
738 return new DummyContainerBuffer{mFormat, nullptr};
739}
740
Wonsik Kim469c8342019-04-11 16:46:09 -0700741// LinearInputBuffers
742
743bool LinearInputBuffers::requestNewBuffer(size_t *index, sp<MediaCodecBuffer> *buffer) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700744 sp<Codec2Buffer> newBuffer = createNewBuffer();
Wonsik Kim469c8342019-04-11 16:46:09 -0700745 if (newBuffer == nullptr) {
746 return false;
747 }
748 *index = mImpl.assignSlot(newBuffer);
749 *buffer = newBuffer;
750 return true;
751}
752
753bool LinearInputBuffers::releaseBuffer(
754 const sp<MediaCodecBuffer> &buffer,
755 std::shared_ptr<C2Buffer> *c2buffer,
756 bool release) {
757 return mImpl.releaseSlot(buffer, c2buffer, release);
758}
759
760bool LinearInputBuffers::expireComponentBuffer(
761 const std::shared_ptr<C2Buffer> &c2buffer) {
762 return mImpl.expireComponentBuffer(c2buffer);
763}
764
765void LinearInputBuffers::flush() {
766 // This is no-op by default unless we're in array mode where we need to keep
767 // track of the flushed work.
768 mImpl.flush();
769}
770
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700771std::unique_ptr<InputBuffers> LinearInputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -0700772 std::unique_ptr<InputBuffersArray> array(
773 new InputBuffersArray(mComponentName.c_str(), "1D-Input[N]"));
774 array->setPool(mPool);
775 array->setFormat(mFormat);
776 array->initialize(
777 mImpl,
778 size,
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700779 [pool = mPool, format = mFormat] () -> sp<Codec2Buffer> {
780 return Alloc(pool, format);
781 });
Wonsik Kim469c8342019-04-11 16:46:09 -0700782 return std::move(array);
783}
784
Wonsik Kim0487b782020-10-28 11:45:50 -0700785size_t LinearInputBuffers::numActiveSlots() const {
786 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -0700787}
788
Wonsik Kim5ecf3832019-04-18 10:28:58 -0700789// static
790sp<Codec2Buffer> LinearInputBuffers::Alloc(
791 const std::shared_ptr<C2BlockPool> &pool, const sp<AMessage> &format) {
792 int32_t capacity = kLinearBufferSize;
793 (void)format->findInt32(KEY_MAX_INPUT_SIZE, &capacity);
794 if ((size_t)capacity > kMaxLinearBufferSize) {
795 ALOGD("client requested %d, capped to %zu", capacity, kMaxLinearBufferSize);
796 capacity = kMaxLinearBufferSize;
797 }
798
799 // TODO: read usage from intf
Wonsik Kim469c8342019-04-11 16:46:09 -0700800 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
801 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
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001011static uint32_t extractPixelFormat(const sp<AMessage> &format) {
1012 int32_t frameworkColorFormat = 0;
1013 if (!format->findInt32("android._color-format", &frameworkColorFormat)) {
1014 return PIXEL_FORMAT_UNKNOWN;
1015 }
1016 uint32_t pixelFormat = PIXEL_FORMAT_UNKNOWN;
1017 if (C2Mapper::mapPixelFormatFrameworkToCodec(frameworkColorFormat, &pixelFormat)) {
1018 return pixelFormat;
1019 }
1020 return PIXEL_FORMAT_UNKNOWN;
1021}
1022
Wonsik Kim469c8342019-04-11 16:46:09 -07001023std::unique_ptr<InputBuffers> GraphicInputBuffers::toArrayMode(size_t size) {
1024 std::unique_ptr<InputBuffersArray> array(
1025 new InputBuffersArray(mComponentName.c_str(), "2D-BB-Input[N]"));
1026 array->setPool(mPool);
1027 array->setFormat(mFormat);
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001028 uint32_t pixelFormat = extractPixelFormat(mFormat);
Wonsik Kim469c8342019-04-11 16:46:09 -07001029 array->initialize(
1030 mImpl,
1031 size,
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001032 [pool = mPool, format = mFormat, lbp = mLocalBufferPool, pixelFormat]()
1033 -> sp<Codec2Buffer> {
Wonsik Kim469c8342019-04-11 16:46:09 -07001034 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1035 return AllocateGraphicBuffer(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001036 pool, format, pixelFormat, usage, lbp);
Wonsik Kim469c8342019-04-11 16:46:09 -07001037 });
1038 return std::move(array);
1039}
1040
Wonsik Kim0487b782020-10-28 11:45:50 -07001041size_t GraphicInputBuffers::numActiveSlots() const {
1042 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001043}
1044
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001045sp<Codec2Buffer> GraphicInputBuffers::createNewBuffer() {
1046 // TODO: read usage from intf
1047 C2MemoryUsage usage = { C2MemoryUsage::CPU_READ, C2MemoryUsage::CPU_WRITE };
1048 return AllocateGraphicBuffer(
Wonsik Kimd79ee1f2020-08-27 17:41:56 -07001049 mPool, mFormat, extractPixelFormat(mFormat), usage, mLocalBufferPool);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001050}
1051
Wonsik Kim469c8342019-04-11 16:46:09 -07001052// OutputBuffersArray
1053
1054void OutputBuffersArray::initialize(
1055 const FlexBuffersImpl &impl,
1056 size_t minSize,
1057 std::function<sp<Codec2Buffer>()> allocate) {
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001058 mAlloc = allocate;
Wonsik Kim469c8342019-04-11 16:46:09 -07001059 mImpl.initialize(impl, minSize, allocate);
1060}
1061
1062status_t OutputBuffersArray::registerBuffer(
1063 const std::shared_ptr<C2Buffer> &buffer,
1064 size_t *index,
1065 sp<MediaCodecBuffer> *clientBuffer) {
1066 sp<Codec2Buffer> c2Buffer;
1067 status_t err = mImpl.grabBuffer(
1068 index,
1069 &c2Buffer,
1070 [buffer](const sp<Codec2Buffer> &clientBuffer) {
1071 return clientBuffer->canCopy(buffer);
1072 });
1073 if (err == WOULD_BLOCK) {
1074 ALOGV("[%s] buffers temporarily not available", mName);
1075 return err;
1076 } else if (err != OK) {
1077 ALOGD("[%s] grabBuffer failed: %d", mName, err);
1078 return err;
1079 }
1080 c2Buffer->setFormat(mFormat);
1081 if (!c2Buffer->copy(buffer)) {
1082 ALOGD("[%s] copy buffer failed", mName);
1083 return WOULD_BLOCK;
1084 }
1085 submit(c2Buffer);
1086 handleImageData(c2Buffer);
1087 *clientBuffer = c2Buffer;
1088 ALOGV("[%s] grabbed buffer %zu", mName, *index);
1089 return OK;
1090}
1091
1092status_t OutputBuffersArray::registerCsd(
1093 const C2StreamInitDataInfo::output *csd,
1094 size_t *index,
1095 sp<MediaCodecBuffer> *clientBuffer) {
1096 sp<Codec2Buffer> c2Buffer;
1097 status_t err = mImpl.grabBuffer(
1098 index,
1099 &c2Buffer,
1100 [csd](const sp<Codec2Buffer> &clientBuffer) {
1101 return clientBuffer->base() != nullptr
1102 && clientBuffer->capacity() >= csd->flexCount();
1103 });
1104 if (err != OK) {
1105 return err;
1106 }
1107 memcpy(c2Buffer->base(), csd->m.value, csd->flexCount());
1108 c2Buffer->setRange(0, csd->flexCount());
1109 c2Buffer->setFormat(mFormat);
1110 *clientBuffer = c2Buffer;
1111 return OK;
1112}
1113
1114bool OutputBuffersArray::releaseBuffer(
1115 const sp<MediaCodecBuffer> &buffer, std::shared_ptr<C2Buffer> *c2buffer) {
1116 return mImpl.returnBuffer(buffer, c2buffer, true);
1117}
1118
1119void OutputBuffersArray::flush(const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1120 (void)flushedWork;
1121 mImpl.flush();
1122 if (mSkipCutBuffer != nullptr) {
1123 mSkipCutBuffer->clear();
1124 }
1125}
1126
1127void OutputBuffersArray::getArray(Vector<sp<MediaCodecBuffer>> *array) const {
1128 mImpl.getArray(array);
1129}
1130
Wonsik Kim0487b782020-10-28 11:45:50 -07001131size_t OutputBuffersArray::numActiveSlots() const {
1132 return mImpl.numActiveSlots();
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001133}
1134
Wonsik Kim469c8342019-04-11 16:46:09 -07001135void OutputBuffersArray::realloc(const std::shared_ptr<C2Buffer> &c2buffer) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001136 switch (c2buffer->data().type()) {
1137 case C2BufferData::LINEAR: {
1138 uint32_t size = kLinearBufferSize;
Nick Desaulniersd09eaea2019-10-07 20:19:39 -07001139 const std::vector<C2ConstLinearBlock> &linear_blocks = c2buffer->data().linearBlocks();
1140 const uint32_t block_size = linear_blocks.front().size();
1141 if (block_size < kMaxLinearBufferSize / 2) {
1142 size = block_size * 2;
Wonsik Kim469c8342019-04-11 16:46:09 -07001143 } else {
1144 size = kMaxLinearBufferSize;
1145 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001146 mAlloc = [format = mFormat, size] {
Wonsik Kim469c8342019-04-11 16:46:09 -07001147 return new LocalLinearBuffer(format, new ABuffer(size));
1148 };
Wonsik Kima39882b2019-06-20 16:13:56 -07001149 ALOGD("[%s] reallocating with linear buffer of size %u", mName, size);
Wonsik Kim469c8342019-04-11 16:46:09 -07001150 break;
1151 }
1152
Wonsik Kima39882b2019-06-20 16:13:56 -07001153 case C2BufferData::GRAPHIC: {
1154 // This is only called for RawGraphicOutputBuffers.
1155 mAlloc = [format = mFormat,
Wonsik Kim41d83432020-04-27 16:40:49 -07001156 lbp = LocalBufferPool::Create()] {
Wonsik Kima39882b2019-06-20 16:13:56 -07001157 return ConstGraphicBlockBuffer::AllocateEmpty(
1158 format,
1159 [lbp](size_t capacity) {
1160 return lbp->newBuffer(capacity);
1161 });
1162 };
1163 ALOGD("[%s] reallocating with graphic buffer: format = %s",
1164 mName, mFormat->debugString().c_str());
1165 break;
1166 }
Wonsik Kim469c8342019-04-11 16:46:09 -07001167
1168 case C2BufferData::INVALID: [[fallthrough]];
1169 case C2BufferData::LINEAR_CHUNKS: [[fallthrough]];
1170 case C2BufferData::GRAPHIC_CHUNKS: [[fallthrough]];
1171 default:
1172 ALOGD("Unsupported type: %d", (int)c2buffer->data().type());
1173 return;
1174 }
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001175 mImpl.realloc(mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001176}
1177
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001178void OutputBuffersArray::grow(size_t newSize) {
1179 mImpl.grow(newSize, mAlloc);
Wonsik Kim469c8342019-04-11 16:46:09 -07001180}
1181
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001182void OutputBuffersArray::transferFrom(OutputBuffers* source) {
1183 mFormat = source->mFormat;
1184 mSkipCutBuffer = source->mSkipCutBuffer;
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001185 mPending = std::move(source->mPending);
1186 mReorderStash = std::move(source->mReorderStash);
1187 mDepth = source->mDepth;
1188 mKey = source->mKey;
1189}
1190
Wonsik Kim469c8342019-04-11 16:46:09 -07001191// FlexOutputBuffers
1192
1193status_t FlexOutputBuffers::registerBuffer(
1194 const std::shared_ptr<C2Buffer> &buffer,
1195 size_t *index,
1196 sp<MediaCodecBuffer> *clientBuffer) {
1197 sp<Codec2Buffer> newBuffer = wrap(buffer);
1198 if (newBuffer == nullptr) {
1199 return NO_MEMORY;
1200 }
1201 newBuffer->setFormat(mFormat);
1202 *index = mImpl.assignSlot(newBuffer);
1203 handleImageData(newBuffer);
1204 *clientBuffer = newBuffer;
1205 ALOGV("[%s] registered buffer %zu", mName, *index);
1206 return OK;
1207}
1208
1209status_t FlexOutputBuffers::registerCsd(
1210 const C2StreamInitDataInfo::output *csd,
1211 size_t *index,
1212 sp<MediaCodecBuffer> *clientBuffer) {
1213 sp<Codec2Buffer> newBuffer = new LocalLinearBuffer(
1214 mFormat, ABuffer::CreateAsCopy(csd->m.value, csd->flexCount()));
1215 *index = mImpl.assignSlot(newBuffer);
1216 *clientBuffer = newBuffer;
1217 return OK;
1218}
1219
1220bool FlexOutputBuffers::releaseBuffer(
1221 const sp<MediaCodecBuffer> &buffer,
1222 std::shared_ptr<C2Buffer> *c2buffer) {
1223 return mImpl.releaseSlot(buffer, c2buffer, true);
1224}
1225
1226void FlexOutputBuffers::flush(
1227 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1228 (void) flushedWork;
1229 // This is no-op by default unless we're in array mode where we need to keep
1230 // track of the flushed work.
1231}
1232
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001233std::unique_ptr<OutputBuffersArray> FlexOutputBuffers::toArrayMode(size_t size) {
Wonsik Kim469c8342019-04-11 16:46:09 -07001234 std::unique_ptr<OutputBuffersArray> array(new OutputBuffersArray(mComponentName.c_str()));
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001235 array->transferFrom(this);
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001236 std::function<sp<Codec2Buffer>()> alloc = getAlloc();
1237 array->initialize(mImpl, size, alloc);
Pawin Vongmasa9b906982020-04-11 05:07:15 -07001238 return array;
Wonsik Kim469c8342019-04-11 16:46:09 -07001239}
1240
Wonsik Kim0487b782020-10-28 11:45:50 -07001241size_t FlexOutputBuffers::numActiveSlots() const {
1242 return mImpl.numActiveSlots();
Wonsik Kim469c8342019-04-11 16:46:09 -07001243}
1244
1245// LinearOutputBuffers
1246
1247void LinearOutputBuffers::flush(
1248 const std::list<std::unique_ptr<C2Work>> &flushedWork) {
1249 if (mSkipCutBuffer != nullptr) {
1250 mSkipCutBuffer->clear();
1251 }
1252 FlexOutputBuffers::flush(flushedWork);
1253}
1254
1255sp<Codec2Buffer> LinearOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1256 if (buffer == nullptr) {
1257 ALOGV("[%s] using a dummy buffer", mName);
1258 return new LocalLinearBuffer(mFormat, new ABuffer(0));
1259 }
1260 if (buffer->data().type() != C2BufferData::LINEAR) {
1261 ALOGV("[%s] non-linear buffer %d", mName, buffer->data().type());
1262 // We expect linear output buffers from the component.
1263 return nullptr;
1264 }
1265 if (buffer->data().linearBlocks().size() != 1u) {
1266 ALOGV("[%s] no linear buffers", mName);
1267 // We expect one and only one linear block from the component.
1268 return nullptr;
1269 }
1270 sp<Codec2Buffer> clientBuffer = ConstLinearBlockBuffer::Allocate(mFormat, buffer);
1271 if (clientBuffer == nullptr) {
1272 ALOGD("[%s] ConstLinearBlockBuffer::Allocate failed", mName);
1273 return nullptr;
1274 }
1275 submit(clientBuffer);
1276 return clientBuffer;
1277}
1278
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001279std::function<sp<Codec2Buffer>()> LinearOutputBuffers::getAlloc() {
1280 return [format = mFormat]{
1281 // TODO: proper max output size
1282 return new LocalLinearBuffer(format, new ABuffer(kLinearBufferSize));
1283 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001284}
1285
1286// GraphicOutputBuffers
1287
1288sp<Codec2Buffer> GraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1289 return new DummyContainerBuffer(mFormat, buffer);
1290}
1291
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001292std::function<sp<Codec2Buffer>()> GraphicOutputBuffers::getAlloc() {
1293 return [format = mFormat]{
1294 return new DummyContainerBuffer(format);
1295 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001296}
1297
1298// RawGraphicOutputBuffers
1299
1300RawGraphicOutputBuffers::RawGraphicOutputBuffers(
Wonsik Kim41d83432020-04-27 16:40:49 -07001301 const char *componentName, const char *name)
Wonsik Kim469c8342019-04-11 16:46:09 -07001302 : FlexOutputBuffers(componentName, name),
Wonsik Kim41d83432020-04-27 16:40:49 -07001303 mLocalBufferPool(LocalBufferPool::Create()) { }
Wonsik Kim469c8342019-04-11 16:46:09 -07001304
1305sp<Codec2Buffer> RawGraphicOutputBuffers::wrap(const std::shared_ptr<C2Buffer> &buffer) {
1306 if (buffer == nullptr) {
1307 sp<Codec2Buffer> c2buffer = ConstGraphicBlockBuffer::AllocateEmpty(
1308 mFormat,
1309 [lbp = mLocalBufferPool](size_t capacity) {
1310 return lbp->newBuffer(capacity);
1311 });
1312 if (c2buffer == nullptr) {
1313 ALOGD("[%s] ConstGraphicBlockBuffer::AllocateEmpty failed", mName);
1314 return nullptr;
1315 }
1316 c2buffer->setRange(0, 0);
1317 return c2buffer;
1318 } else {
1319 return ConstGraphicBlockBuffer::Allocate(
1320 mFormat,
1321 buffer,
1322 [lbp = mLocalBufferPool](size_t capacity) {
1323 return lbp->newBuffer(capacity);
1324 });
1325 }
1326}
1327
Wonsik Kim5ecf3832019-04-18 10:28:58 -07001328std::function<sp<Codec2Buffer>()> RawGraphicOutputBuffers::getAlloc() {
1329 return [format = mFormat, lbp = mLocalBufferPool]{
1330 return ConstGraphicBlockBuffer::AllocateEmpty(
1331 format,
1332 [lbp](size_t capacity) {
1333 return lbp->newBuffer(capacity);
1334 });
1335 };
Wonsik Kim469c8342019-04-11 16:46:09 -07001336}
1337
1338} // namespace android