/**
 * Copyright (C) 2022 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 <dlfcn.h>

#include "../includes/common.h"

#define private public
#include <media/stagefright/rtsp/AAVCAssembler.h>

using namespace android;

bool isOverloadingEnabled = false;

bool isTestInProgress = false;

struct sigaction newAction, oldAction;

static void *(*realMalloc)(size_t) = nullptr;

void *malloc(size_t size) {
    if (!realMalloc) {
        realMalloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
        if (!realMalloc) {
            return nullptr;
        }
    }
    if (isOverloadingEnabled && (size == 0)) {
        size_t pageSize = sysconf(_SC_PAGE_SIZE);
        void *ptr = memalign(pageSize, pageSize);
        mprotect(ptr, pageSize, PROT_NONE);
        return ptr;
    }
    return realMalloc(size);
}

void sigsegv_handler(int signum, siginfo_t *info, void *context) {
    if (isTestInProgress && info->si_signo == SIGSEGV) {
        (*oldAction.sa_sigaction)(signum, info, context);
        return;
    }
    _exit(EXIT_FAILURE);
}

int main() {
    sigemptyset(&newAction.sa_mask);
    newAction.sa_flags = SA_SIGINFO;
    newAction.sa_sigaction = sigsegv_handler;
    sigaction(SIGSEGV, &newAction, &oldAction);

    sp<ABuffer> buffer(new ABuffer(16));
    FAIL_CHECK(buffer != nullptr);

    sp<AMessage> meta = buffer->meta();
    FAIL_CHECK(meta != nullptr);

    uint32_t rtpTime = 16;
    meta->setInt32("rtp-time", rtpTime);

    AAVCAssembler *assembler = new AAVCAssembler(meta);
    FAIL_CHECK(assembler != nullptr);

    isOverloadingEnabled = true;
    sp<ABuffer> zeroSizedBuffer(new ABuffer(0));
    isOverloadingEnabled = false;

    isTestInProgress = true;
    assembler->checkSpsUpdated(zeroSizedBuffer);
    isTestInProgress = false;

    return EXIT_SUCCESS;
}
