/**
 * 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 "../includes/common.h"
#include "../includes/memutils.h"
#include <dlfcn.h>
#include <host_src/eas_types.h>
#include <lib_src/eas_wtengine.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#define MEM_ALIGNMENT 16
#define PHASE_INCREMENT 555555

typedef void (*fp_WT_Process_Voice)(S_WT_VOICE *, S_WT_INT_FRAME *);
char enable_selective_overload = ENABLE_NONE;
void *libHandle = NULL;
void *phaseAccumPtr = NULL;

void exit_Handler(void) {
  if (phaseAccumPtr) {
    free(phaseAccumPtr);
  }
  if (libHandle) {
    dlclose(libHandle);
  }
}

int main() {
  atexit(exit_Handler);
  libHandle = dlopen("libsonivox.so", RTLD_NOW | RTLD_LOCAL);
  FAIL_CHECK(libHandle);
  fp_WT_Process_Voice functionWTProcessVoice =
      (fp_WT_Process_Voice)dlsym(libHandle, "WT_ProcessVoice");
  FAIL_CHECK(functionWTProcessVoice);

  S_WT_VOICE pWTVoice = {};
  enable_selective_overload = ENABLE_MEMALIGN_CHECK;
  pWTVoice.phaseAccum = (EAS_U32)memalign(MEM_ALIGNMENT, sizeof(EAS_I16));
  FAIL_CHECK((void *)pWTVoice.phaseAccum);
  phaseAccumPtr = ((void *)pWTVoice.phaseAccum);
  enable_selective_overload = ENABLE_FREE_CHECK | ENABLE_REALLOC_CHECK;
  pWTVoice.loopEnd = pWTVoice.phaseAccum;
  pWTVoice.loopStart = pWTVoice.phaseAccum;

  S_WT_INT_FRAME pWTIntFrame = {};
  pWTIntFrame.frame.phaseIncrement = PHASE_INCREMENT;
  EAS_PCM pAudioBuffer;
  EAS_I32 pMixBuffer;
  pWTIntFrame.pAudioBuffer = &pAudioBuffer;
  pWTIntFrame.pMixBuffer = &pMixBuffer;
  pWTIntFrame.numSamples = 1;

  functionWTProcessVoice(&pWTVoice, &pWTIntFrame);

  return EXIT_SUCCESS;
}
