1 /*
2 * Copyright 2018, 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 #ifdef __LP64__
18 #define OMX_ANDROID_COMPILE_AS_32BIT_ON_64BIT_PLATFORMS
19 #endif
20
21 //#define LOG_NDEBUG 0
22 #define LOG_TAG "C2OMXNode"
23 #include <log/log.h>
24
25 #include <C2AllocatorGralloc.h>
26 #include <C2BlockInternal.h>
27 #include <C2Component.h>
28 #include <C2PlatformSupport.h>
29
30 #include <OMX_Component.h>
31 #include <OMX_Index.h>
32 #include <OMX_IndexExt.h>
33
34 #include <android/fdsan.h>
35 #include <media/stagefright/omx/OMXUtils.h>
36 #include <media/stagefright/MediaErrors.h>
37 #include <ui/Fence.h>
38 #include <ui/GraphicBuffer.h>
39 #include <utils/Thread.h>
40
41 #include "C2OMXNode.h"
42
43 namespace android {
44
45 namespace {
46
47 class Buffer2D : public C2Buffer {
48 public:
Buffer2D(C2ConstGraphicBlock block)49 explicit Buffer2D(C2ConstGraphicBlock block) : C2Buffer({ block }) {}
50 };
51
52 } // namespace
53
54 class C2OMXNode::QueueThread : public Thread {
55 public:
QueueThread()56 QueueThread() : Thread(false) {}
57 ~QueueThread() override = default;
queue(const std::shared_ptr<Codec2Client::Component> & comp,int fenceFd,std::unique_ptr<C2Work> && work,android::base::unique_fd && fd0,android::base::unique_fd && fd1)58 void queue(
59 const std::shared_ptr<Codec2Client::Component> &comp,
60 int fenceFd,
61 std::unique_ptr<C2Work> &&work,
62 android::base::unique_fd &&fd0,
63 android::base::unique_fd &&fd1) {
64 Mutexed<Jobs>::Locked jobs(mJobs);
65 auto it = jobs->queues.try_emplace(comp, comp).first;
66 it->second.workList.emplace_back(
67 std::move(work), fenceFd, std::move(fd0), std::move(fd1));
68 jobs->cond.broadcast();
69 }
70
71 protected:
threadLoop()72 bool threadLoop() override {
73 constexpr nsecs_t kIntervalNs = nsecs_t(10) * 1000 * 1000; // 10ms
74 constexpr nsecs_t kWaitNs = kIntervalNs * 2;
75 for (int i = 0; i < 2; ++i) {
76 Mutexed<Jobs>::Locked jobs(mJobs);
77 nsecs_t nowNs = systemTime();
78 bool queued = false;
79 for (auto it = jobs->queues.begin(); it != jobs->queues.end(); ) {
80 Queue &queue = it->second;
81 if (queue.workList.empty()
82 || (queue.lastQueuedTimestampNs != 0 &&
83 nowNs - queue.lastQueuedTimestampNs < kIntervalNs)) {
84 ++it;
85 continue;
86 }
87 std::shared_ptr<Codec2Client::Component> comp = queue.component.lock();
88 if (!comp) {
89 it = jobs->queues.erase(it);
90 continue;
91 }
92 std::list<std::unique_ptr<C2Work>> items;
93 std::vector<int> fenceFds;
94 std::vector<android::base::unique_fd> uniqueFds;
95 while (!queue.workList.empty()) {
96 items.push_back(std::move(queue.workList.front().work));
97 fenceFds.push_back(queue.workList.front().fenceFd);
98 uniqueFds.push_back(std::move(queue.workList.front().fd0));
99 uniqueFds.push_back(std::move(queue.workList.front().fd1));
100 queue.workList.pop_front();
101 }
102
103 jobs.unlock();
104 for (int fenceFd : fenceFds) {
105 sp<Fence> fence(new Fence(fenceFd));
106 fence->waitForever(LOG_TAG);
107 }
108 queue.lastQueuedTimestampNs = nowNs;
109 comp->queue(&items);
110 for (android::base::unique_fd &ufd : uniqueFds) {
111 (void)ufd.release();
112 }
113 jobs.lock();
114
115 it = jobs->queues.upper_bound(comp);
116 queued = true;
117 }
118 if (queued) {
119 return true;
120 }
121 if (i == 0) {
122 jobs.waitForConditionRelative(jobs->cond, kWaitNs);
123 }
124 }
125 return true;
126 }
127
128 private:
129 struct WorkFence {
WorkFenceandroid::C2OMXNode::QueueThread::WorkFence130 WorkFence(std::unique_ptr<C2Work> &&w, int fd) : work(std::move(w)), fenceFd(fd) {}
131
WorkFenceandroid::C2OMXNode::QueueThread::WorkFence132 WorkFence(
133 std::unique_ptr<C2Work> &&w,
134 int fd,
135 android::base::unique_fd &&uniqueFd0,
136 android::base::unique_fd &&uniqueFd1)
137 : work(std::move(w)),
138 fenceFd(fd),
139 fd0(std::move(uniqueFd0)),
140 fd1(std::move(uniqueFd1)) {}
141
142 std::unique_ptr<C2Work> work;
143 int fenceFd;
144 android::base::unique_fd fd0;
145 android::base::unique_fd fd1;
146 };
147 struct Queue {
Queueandroid::C2OMXNode::QueueThread::Queue148 Queue(const std::shared_ptr<Codec2Client::Component> &comp)
149 : component(comp), lastQueuedTimestampNs(0) {}
150 Queue(const Queue &) = delete;
151 Queue &operator =(const Queue &) = delete;
152
153 std::weak_ptr<Codec2Client::Component> component;
154 std::list<WorkFence> workList;
155 nsecs_t lastQueuedTimestampNs;
156 };
157 struct Jobs {
158 std::map<std::weak_ptr<Codec2Client::Component>,
159 Queue,
160 std::owner_less<std::weak_ptr<Codec2Client::Component>>> queues;
161 Condition cond;
162 };
163 Mutexed<Jobs> mJobs;
164 };
165
C2OMXNode(const std::shared_ptr<Codec2Client::Component> & comp)166 C2OMXNode::C2OMXNode(const std::shared_ptr<Codec2Client::Component> &comp)
167 : mComp(comp), mFrameIndex(0), mWidth(0), mHeight(0), mUsage(0),
168 mAdjustTimestampGapUs(0), mFirstInputFrame(true),
169 mQueueThread(new QueueThread) {
170 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ALWAYS);
171 mQueueThread->run("C2OMXNode", PRIORITY_AUDIO);
172 }
173
freeNode()174 status_t C2OMXNode::freeNode() {
175 mComp.reset();
176 android_fdsan_set_error_level(ANDROID_FDSAN_ERROR_LEVEL_WARN_ONCE);
177 return mQueueThread->requestExitAndWait();
178 }
179
sendCommand(OMX_COMMANDTYPE cmd,OMX_S32 param)180 status_t C2OMXNode::sendCommand(OMX_COMMANDTYPE cmd, OMX_S32 param) {
181 if (cmd == OMX_CommandStateSet && param == OMX_StateLoaded) {
182 // Reset first input frame so if C2OMXNode is recycled, the timestamp does not become
183 // negative. This is a workaround for HW codecs that do not handle timestamp rollover.
184 mFirstInputFrame = true;
185 }
186 return ERROR_UNSUPPORTED;
187 }
188
getParameter(OMX_INDEXTYPE index,void * params,size_t size)189 status_t C2OMXNode::getParameter(OMX_INDEXTYPE index, void *params, size_t size) {
190 status_t err = ERROR_UNSUPPORTED;
191 switch ((uint32_t)index) {
192 case OMX_IndexParamConsumerUsageBits: {
193 OMX_U32 *usage = (OMX_U32 *)params;
194 *usage = mUsage;
195 err = OK;
196 break;
197 }
198 case OMX_IndexParamPortDefinition: {
199 if (size < sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) {
200 return BAD_VALUE;
201 }
202 OMX_PARAM_PORTDEFINITIONTYPE *pDef = (OMX_PARAM_PORTDEFINITIONTYPE *)params;
203 // TODO: read these from intf()
204 pDef->nBufferCountActual = 16;
205 pDef->eDomain = OMX_PortDomainVideo;
206 pDef->format.video.nFrameWidth = mWidth;
207 pDef->format.video.nFrameHeight = mHeight;
208 err = OK;
209 break;
210 }
211 default:
212 break;
213 }
214 return err;
215 }
216
setParameter(OMX_INDEXTYPE index,const void * params,size_t size)217 status_t C2OMXNode::setParameter(OMX_INDEXTYPE index, const void *params, size_t size) {
218 if (params == NULL) {
219 return BAD_VALUE;
220 }
221 switch ((uint32_t)index) {
222 case OMX_IndexParamMaxFrameDurationForBitrateControl:
223 // handle max/fixed frame duration control
224 if (size != sizeof(OMX_PARAM_U32TYPE)) {
225 return BAD_VALUE;
226 }
227 // The incoming number is an int32_t contained in OMX_U32.
228 mAdjustTimestampGapUs = (int32_t)((OMX_PARAM_U32TYPE*)params)->nU32;
229 return OK;
230
231 case OMX_IndexParamConsumerUsageBits:
232 if (size != sizeof(OMX_U32)) {
233 return BAD_VALUE;
234 }
235 mUsage = *((OMX_U32 *)params);
236 return OK;
237 }
238 return ERROR_UNSUPPORTED;
239 }
240
getConfig(OMX_INDEXTYPE index,void * config,size_t size)241 status_t C2OMXNode::getConfig(OMX_INDEXTYPE index, void *config, size_t size) {
242 (void)index;
243 (void)config;
244 (void)size;
245 return ERROR_UNSUPPORTED;
246 }
247
setConfig(OMX_INDEXTYPE index,const void * config,size_t size)248 status_t C2OMXNode::setConfig(OMX_INDEXTYPE index, const void *config, size_t size) {
249 (void)index;
250 (void)config;
251 (void)size;
252 return ERROR_UNSUPPORTED;
253 }
254
setPortMode(OMX_U32 portIndex,IOMX::PortMode mode)255 status_t C2OMXNode::setPortMode(OMX_U32 portIndex, IOMX::PortMode mode) {
256 (void)portIndex;
257 (void)mode;
258 return ERROR_UNSUPPORTED;
259 }
260
prepareForAdaptivePlayback(OMX_U32 portIndex,OMX_BOOL enable,OMX_U32 maxFrameWidth,OMX_U32 maxFrameHeight)261 status_t C2OMXNode::prepareForAdaptivePlayback(
262 OMX_U32 portIndex, OMX_BOOL enable,
263 OMX_U32 maxFrameWidth, OMX_U32 maxFrameHeight) {
264 (void)portIndex;
265 (void)enable;
266 (void)maxFrameWidth;
267 (void)maxFrameHeight;
268 return ERROR_UNSUPPORTED;
269 }
270
configureVideoTunnelMode(OMX_U32 portIndex,OMX_BOOL tunneled,OMX_U32 audioHwSync,native_handle_t ** sidebandHandle)271 status_t C2OMXNode::configureVideoTunnelMode(
272 OMX_U32 portIndex, OMX_BOOL tunneled,
273 OMX_U32 audioHwSync, native_handle_t **sidebandHandle) {
274 (void)portIndex;
275 (void)tunneled;
276 (void)audioHwSync;
277 *sidebandHandle = nullptr;
278 return ERROR_UNSUPPORTED;
279 }
280
getGraphicBufferUsage(OMX_U32 portIndex,OMX_U32 * usage)281 status_t C2OMXNode::getGraphicBufferUsage(OMX_U32 portIndex, OMX_U32* usage) {
282 (void)portIndex;
283 *usage = 0;
284 return ERROR_UNSUPPORTED;
285 }
286
setInputSurface(const sp<IOMXBufferSource> & bufferSource)287 status_t C2OMXNode::setInputSurface(const sp<IOMXBufferSource> &bufferSource) {
288 c2_status_t err = GetCodec2PlatformAllocatorStore()->fetchAllocator(
289 C2PlatformAllocatorStore::GRALLOC,
290 &mAllocator);
291 if (err != OK) {
292 return UNKNOWN_ERROR;
293 }
294 mBufferSource = bufferSource;
295 return OK;
296 }
297
allocateSecureBuffer(OMX_U32 portIndex,size_t size,buffer_id * buffer,void ** bufferData,sp<NativeHandle> * nativeHandle)298 status_t C2OMXNode::allocateSecureBuffer(
299 OMX_U32 portIndex, size_t size, buffer_id *buffer,
300 void **bufferData, sp<NativeHandle> *nativeHandle) {
301 (void)portIndex;
302 (void)size;
303 (void)nativeHandle;
304 *buffer = 0;
305 *bufferData = nullptr;
306 return ERROR_UNSUPPORTED;
307 }
308
useBuffer(OMX_U32 portIndex,const OMXBuffer & omxBuf,buffer_id * buffer)309 status_t C2OMXNode::useBuffer(
310 OMX_U32 portIndex, const OMXBuffer &omxBuf, buffer_id *buffer) {
311 (void)portIndex;
312 (void)omxBuf;
313 *buffer = 0;
314 return ERROR_UNSUPPORTED;
315 }
316
freeBuffer(OMX_U32 portIndex,buffer_id buffer)317 status_t C2OMXNode::freeBuffer(OMX_U32 portIndex, buffer_id buffer) {
318 (void)portIndex;
319 (void)buffer;
320 return ERROR_UNSUPPORTED;
321 }
322
fillBuffer(buffer_id buffer,const OMXBuffer & omxBuf,int fenceFd)323 status_t C2OMXNode::fillBuffer(
324 buffer_id buffer, const OMXBuffer &omxBuf, int fenceFd) {
325 (void)buffer;
326 (void)omxBuf;
327 (void)fenceFd;
328 return ERROR_UNSUPPORTED;
329 }
330
emptyBuffer(buffer_id buffer,const OMXBuffer & omxBuf,OMX_U32 flags,OMX_TICKS timestamp,int fenceFd)331 status_t C2OMXNode::emptyBuffer(
332 buffer_id buffer, const OMXBuffer &omxBuf,
333 OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
334 std::shared_ptr<Codec2Client::Component> comp = mComp.lock();
335 if (!comp) {
336 return NO_INIT;
337 }
338
339 uint32_t c2Flags = (flags & OMX_BUFFERFLAG_EOS)
340 ? C2FrameData::FLAG_END_OF_STREAM : 0;
341 std::shared_ptr<C2GraphicBlock> block;
342
343 android::base::unique_fd fd0, fd1;
344 C2Handle *handle = nullptr;
345 if (omxBuf.mBufferType == OMXBuffer::kBufferTypeANWBuffer
346 && omxBuf.mGraphicBuffer != nullptr) {
347 std::shared_ptr<C2GraphicAllocation> alloc;
348 handle = WrapNativeCodec2GrallocHandle(
349 omxBuf.mGraphicBuffer->handle,
350 omxBuf.mGraphicBuffer->width,
351 omxBuf.mGraphicBuffer->height,
352 omxBuf.mGraphicBuffer->format,
353 omxBuf.mGraphicBuffer->usage,
354 omxBuf.mGraphicBuffer->stride);
355 if (handle != nullptr) {
356 // unique_fd takes ownership of the fds, we'll get warning if these
357 // fds get closed by somebody else. Onwership will be released before
358 // we return, so that the fds get closed as usually when this function
359 // goes out of scope (when both items and block are gone).
360 native_handle_t *nativeHandle = reinterpret_cast<native_handle_t*>(handle);
361 fd0.reset(nativeHandle->numFds > 0 ? nativeHandle->data[0] : -1);
362 fd1.reset(nativeHandle->numFds > 1 ? nativeHandle->data[1] : -1);
363 }
364 c2_status_t err = mAllocator->priorGraphicAllocation(handle, &alloc);
365 if (err != OK) {
366 (void)fd0.release();
367 (void)fd1.release();
368 return UNKNOWN_ERROR;
369 }
370 block = _C2BlockFactory::CreateGraphicBlock(alloc);
371 } else if (!(flags & OMX_BUFFERFLAG_EOS)) {
372 return BAD_VALUE;
373 }
374
375 std::unique_ptr<C2Work> work(new C2Work);
376 work->input.flags = (C2FrameData::flags_t)c2Flags;
377 work->input.ordinal.timestamp = timestamp;
378
379 // WORKAROUND: adjust timestamp based on gapUs
380 {
381 work->input.ordinal.customOrdinal = timestamp; // save input timestamp
382 if (mFirstInputFrame) {
383 // grab timestamps on first frame
384 mPrevInputTimestamp = timestamp;
385 mPrevCodecTimestamp = timestamp;
386 mFirstInputFrame = false;
387 } else if (mAdjustTimestampGapUs > 0) {
388 work->input.ordinal.timestamp =
389 mPrevCodecTimestamp
390 + c2_min((timestamp - mPrevInputTimestamp).peek(), mAdjustTimestampGapUs);
391 } else if (mAdjustTimestampGapUs < 0) {
392 work->input.ordinal.timestamp = mPrevCodecTimestamp - mAdjustTimestampGapUs;
393 }
394 mPrevInputTimestamp = work->input.ordinal.customOrdinal;
395 mPrevCodecTimestamp = work->input.ordinal.timestamp;
396 ALOGV("adjusting %lld to %lld (gap=%lld)",
397 work->input.ordinal.customOrdinal.peekll(),
398 work->input.ordinal.timestamp.peekll(),
399 (long long)mAdjustTimestampGapUs);
400 }
401
402 work->input.ordinal.frameIndex = mFrameIndex++;
403 work->input.buffers.clear();
404 if (block) {
405 std::shared_ptr<C2Buffer> c2Buffer(
406 new Buffer2D(block->share(
407 C2Rect(block->width(), block->height()), ::C2Fence())));
408 work->input.buffers.push_back(c2Buffer);
409 }
410 work->worklets.clear();
411 work->worklets.emplace_back(new C2Worklet);
412 mBufferIdsInUse.lock()->emplace(work->input.ordinal.frameIndex.peeku(), buffer);
413 mQueueThread->queue(comp, fenceFd, std::move(work), std::move(fd0), std::move(fd1));
414
415 return OK;
416 }
417
getExtensionIndex(const char * parameterName,OMX_INDEXTYPE * index)418 status_t C2OMXNode::getExtensionIndex(
419 const char *parameterName, OMX_INDEXTYPE *index) {
420 (void)parameterName;
421 *index = OMX_IndexMax;
422 return ERROR_UNSUPPORTED;
423 }
424
dispatchMessage(const omx_message & msg)425 status_t C2OMXNode::dispatchMessage(const omx_message& msg) {
426 if (msg.type != omx_message::EVENT) {
427 return ERROR_UNSUPPORTED;
428 }
429 if (msg.u.event_data.event != OMX_EventDataSpaceChanged) {
430 return ERROR_UNSUPPORTED;
431 }
432 android_dataspace dataSpace = (android_dataspace)msg.u.event_data.data1;
433 uint32_t pixelFormat = msg.u.event_data.data3;
434
435 // TODO: set dataspace on component to see if it impacts color aspects
436 ALOGD("dataspace changed to %#x pixel format: %#x", dataSpace, pixelFormat);
437 return OK;
438 }
439
getSource()440 sp<IOMXBufferSource> C2OMXNode::getSource() {
441 return mBufferSource;
442 }
443
setFrameSize(uint32_t width,uint32_t height)444 void C2OMXNode::setFrameSize(uint32_t width, uint32_t height) {
445 mWidth = width;
446 mHeight = height;
447 }
448
onInputBufferDone(c2_cntr64_t index)449 void C2OMXNode::onInputBufferDone(c2_cntr64_t index) {
450 if (!mBufferSource) {
451 ALOGD("Buffer source not set (index=%llu)", index.peekull());
452 return;
453 }
454
455 int32_t bufferId = 0;
456 {
457 decltype(mBufferIdsInUse)::Locked bufferIds(mBufferIdsInUse);
458 auto it = bufferIds->find(index.peeku());
459 if (it == bufferIds->end()) {
460 ALOGV("Untracked input index %llu (maybe already removed)", index.peekull());
461 return;
462 }
463 bufferId = it->second;
464 (void)bufferIds->erase(it);
465 }
466 (void)mBufferSource->onInputBufferEmptied(bufferId, -1);
467 }
468
469 } // namespace android
470