/**
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "../includes/omxUtils.h"
#define TIMESTAMP_MICROSECONDS 0x00010001
#define OUT_BUFFER_COUNT 8
#define EMPTY_BUFFER_DONE_CALLBACK_TIMEOUT_SEC 30
extern int numCallbackEmptyBufferDone;
sp<IAllocator> mAllocator = IAllocator::getService("ashmem");
int allocateHidlPortBuffers(OMX_U32 portIndex, Vector<Buffer> *buffers) {
    buffers->clear();
    OMX_PARAM_PORTDEFINITIONTYPE def;
    int err = omxUtilsGetParameter(portIndex, &def);
    omxExitOnError(err);
    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
        Buffer buffer;
        buffer.mFlags = 0;
        bool success;
        auto transStatus = mAllocator->allocate(def.nBufferSize,
                                                [&success, &buffer](
                                                        bool s,
                                                        hidl_memory const& m) {
                                                    success = s;
                                                    buffer.mHidlMemory = m;
                                                });
        omxExitOnError(!transStatus.isOk());
        omxExitOnError(!success);
        omxUtilsUseBuffer(portIndex, buffer.mHidlMemory, &buffer.mID);
        buffers->push(buffer);
    }
    return OK;
}
int main() {
    /* Initialize OMX for the specified codec                                 */
    status_t ret = omxUtilsInit((char *) "OMX.google.h263.decoder");
    omxExitOnError(ret);
    int allCallbacksReceivedEmptyBufferDone = 0;
    /* Get OMX input port parameters                                          */
    OMX_PARAM_PORTDEFINITIONTYPE *params =
            (OMX_PARAM_PORTDEFINITIONTYPE *) malloc(
                    sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
    memset(params, 0, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
    omxUtilsGetParameter(OMX_UTILS_IP_PORT, params);
    /* Prepare input port buffers                                             */
    int inBufferCnt = params->nBufferCountActual;
    std::unique_ptr<IOMX::buffer_id[]> inBufferId(new IOMX::buffer_id[inBufferCnt]);
    /* Get OMX output port parameters                                         */
    memset(params, 0, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
    omxUtilsGetParameter(OMX_UTILS_OP_PORT, params);
    params->nBufferCountActual = OUT_BUFFER_COUNT;
    omxUtilsSetParameter(OMX_UTILS_OP_PORT, params);
    /* Prepare output port buffers                                            */
    int outBufferCnt = params->nBufferCountActual;
    std::unique_ptr<IOMX::buffer_id[]> outBufferId(new IOMX::buffer_id[outBufferCnt]);
    Vector<Buffer> inputBuffers, outputBuffers;
    /* Register input buffers with OMX component                              */
    allocateHidlPortBuffers(OMX_UTILS_IP_PORT, &inputBuffers);
    for (int i = 0; i < inBufferCnt; i++) {
        inBufferId[i] = inputBuffers[i].mID;
    }
    /* Register output buffers with OMX component                             */
    allocateHidlPortBuffers(OMX_UTILS_OP_PORT, &outputBuffers);
    for (int i = 0; i < outBufferCnt; i++) {
        outBufferId[i] = outputBuffers[i].mID;
    }
    /* Do OMX State change to Idle                                            */
    omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateIdle);
    /* Do OMX State change to Executing                                       */
    omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateExecuting);
    OMX_U32 flags = OMX_BUFFERFLAG_EOS;
    int64_t timeUs = TIMESTAMP_MICROSECONDS;
    for (int i = 0; i < inBufferCnt; i++) {
        omxUtilsEmptyBuffer(inBufferId[i], OMXBuffer::sPreset, flags, timeUs,
                            -1);
    }
    for (int i = 0; i < outBufferCnt; i++) {
        omxUtilsFillBuffer(outBufferId[i], OMXBuffer::sPreset, -1);
    }
    /* Do OMX State change to Idle                                            */
    omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateIdle);
    time_t currentTime = time(NULL);
    time_t waitTimeInSeconds = EMPTY_BUFFER_DONE_CALLBACK_TIMEOUT_SEC;
    time_t endTime = currentTime + waitTimeInSeconds;
    while (currentTime < endTime) {
        if (numCallbackEmptyBufferDone == inBufferCnt) {
            allCallbacksReceivedEmptyBufferDone = 1;
            break;
        }
        currentTime = time(NULL);
    }
    if (!allCallbacksReceivedEmptyBufferDone) {
        ALOGE("Exiting the app");
        exit (EXIT_FAILURE);
    }
    /* Do OMX State change to Loaded                                          */
    omxUtilsSendCommand(OMX_CommandStateSet, OMX_StateLoaded);
    /* Free input and output buffers                                          */
    for (int i = 0; i < inBufferCnt; i++) {
        omxUtilsFreeBuffer(OMX_UTILS_IP_PORT, inBufferId[i]);
    }
    for (int i = 0; i < outBufferCnt; i++) {
        omxUtilsFreeBuffer(OMX_UTILS_OP_PORT, outBufferId[i]);
    }
    /* Free OMX resources                                                     */
    omxUtilsFreeNode();
    return EXIT_SUCCESS;
}
