// SPDX-FileCopyrightText: © 2025 Allegro DVT <github-ip@allegrodvt.com>
// SPDX-License-Identifier: MIT

#if __linux__

#include "DriverDataConversions.h"
#include <string.h>

#include "lib_rtos/types.h"

static void write(struct al5_params* msg, void* data, int32_t size)
{
  memcpy(msg->opaque + (msg->size / 4), data, size);
  msg->size += ((size + 3) / 4) * 4;
}

void setChannelParam(struct al5_params* msg, AL_TMemDesc* pMDChParam, AL_TMemDesc* pEP1)
{
  uint32_t uMcuVirtAddr;
  static_assert(2 * sizeof(uMcuVirtAddr) <= sizeof(msg->opaque), "Driver channel_param struct is too small");
  msg->size = 0;

  uMcuVirtAddr = (pMDChParam->uPhysicalAddr & 0x7FFFFFFF) + DCACHE_OFFSET;
  write(msg, &uMcuVirtAddr, sizeof(uMcuVirtAddr));

  if(pEP1)
    uMcuVirtAddr = (pEP1->uPhysicalAddr & 0x7FFFFFFF) + DCACHE_OFFSET;
  else
    uMcuVirtAddr = 0;
  write(msg, &uMcuVirtAddr, sizeof(uMcuVirtAddr));
}

static void setPicParam(struct al5_params* msg, AL_TEncInfo* encInfo, AL_TEncRequestInfo* reqInfo)
{
  static_assert(sizeof(*encInfo) + sizeof(*reqInfo) <= sizeof(msg->opaque), "Driver struct is too small for AL_TEncInfo & AL_TEncRequestInfo");
  msg->size = 0;
  write(msg, encInfo, sizeof(*encInfo));

  write(msg, &reqInfo->eReqOptions, sizeof(reqInfo->eReqOptions));

  if(reqInfo->eReqOptions & AL_OPT_SCENE_CHANGE)
    write(msg, &reqInfo->uSceneChangeDelay, sizeof(reqInfo->uSceneChangeDelay));

  if(reqInfo->eReqOptions & AL_OPT_UPDATE_RC_GOP_PARAMS)
  {
    write(msg, &reqInfo->smartParams.rc, sizeof(reqInfo->smartParams.rc));
    write(msg, &reqInfo->smartParams.gop, sizeof(reqInfo->smartParams.gop));
  }

  if(reqInfo->eReqOptions & AL_OPT_SET_QP)
    write(msg, &reqInfo->smartParams.iQPSet, sizeof(reqInfo->smartParams.iQPSet));

  if(reqInfo->eReqOptions & AL_OPT_SET_INPUT_RESOLUTION)
    write(msg, &reqInfo->dynResParams, sizeof(reqInfo->dynResParams));

  if(reqInfo->eReqOptions & AL_OPT_SET_LF_MODE)
    write(msg, &reqInfo->smartParams.uLFMode, sizeof(reqInfo->smartParams.uLFMode));

  if(reqInfo->eReqOptions & AL_OPT_SET_LF_OFFSETS)
  {
    write(msg, &reqInfo->smartParams.iLFBetaOffset, sizeof(reqInfo->smartParams.iLFBetaOffset));
    write(msg, &reqInfo->smartParams.iLFTcOffset, sizeof(reqInfo->smartParams.iLFTcOffset));
  }
}

static void setBuffersAddrs(struct al5_params* msg, AL_TEncPicBufAddrs* pBuffersAddrs)
{
  static_assert(sizeof(*pBuffersAddrs) <= sizeof(msg->opaque), "Driver struct is too small for AL_TEncPicBufAddrs");
  msg->size = 0;
  write(msg, pBuffersAddrs, sizeof(*pBuffersAddrs));
}

void setEncodeMsg(struct al5_encode_msg* msg, AL_TEncInfo* encInfo, AL_TEncRequestInfo* reqInfo, AL_TEncPicBufAddrs* pBuffersAddrs)
{
  setPicParam(&msg->params, encInfo, reqInfo);
  setBuffersAddrs(&msg->addresses, pBuffersAddrs);
}

#endif
