/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2020, Google Inc.
 *
 * Image Processing Algorithm proxy for ipu3
 *
 * This file is auto-generated. Do not edit.
 */

#include <libcamera/ipa/ipu3_ipa_proxy.h>

#include <memory>
#include <string>
#include <vector>

#include <libcamera/ipa/ipa_module_info.h>
#include <libcamera/ipa/ipu3_ipa_interface.h>
#include <libcamera/ipa/ipu3_ipa_serializer.h>

#include <libcamera/base/log.h>
#include <libcamera/base/thread.h>

#include "libcamera/internal/control_serializer.h"
#include "libcamera/internal/ipa_data_serializer.h"
#include "libcamera/internal/ipa_module.h"
#include "libcamera/internal/ipa_proxy.h"
#include "libcamera/internal/ipc_pipe.h"
#include "libcamera/internal/ipc_pipe_unixsocket.h"
#include "libcamera/internal/ipc_unixsocket.h"
#include "libcamera/internal/process.h"

namespace libcamera {

LOG_DECLARE_CATEGORY(IPAProxy)

namespace ipa {

namespace ipu3 {


IPAProxyIPU3Threaded::IPAProxyIPU3Threaded(IPAModule *ipam, const CameraManager &cm)
	: IPAProxyIPU3(ipam, cm), thread_("IPAProxyIPU3")
{
	LOG(IPAProxy, Debug)
		<< "initializing ipu3 proxy in thread: loading IPA from "
		<< ipam->path();

	if (!ipam->load())
		return;

	IPAInterface *ipai = ipam->createInterface();
	if (!ipai) {
		LOG(IPAProxy, Error)
			<< "Failed to create IPA context for " << ipam->path();
		return;
	}

	ipa_ = std::unique_ptr<IPAIPU3Interface>(static_cast<IPAIPU3Interface *>(ipai));
	proxy_.setIPA(ipa_.get());


	ipa_->setSensorControls.connect(this, &IPAProxyIPU3Threaded::setSensorControlsHandler);
	ipa_->paramsComputed.connect(this, &IPAProxyIPU3Threaded::paramsComputedHandler);
	ipa_->metadataReady.connect(this, &IPAProxyIPU3Threaded::metadataReadyHandler);

	valid_ = true;
}

IPAProxyIPU3Threaded::~IPAProxyIPU3Threaded() = default;


int32_t IPAProxyIPU3Threaded::init(
	const IPASettings &settings,
	const IPACameraSensorInfo &sensorInfo,
	const ControlInfoMap &sensorControls,
	ControlInfoMap *ipaControls)
{
	int32_t _ret = ipa_->init(settings, sensorInfo, sensorControls, ipaControls);

	proxy_.moveToThread(&thread_);

	return _ret;
}

int32_t IPAProxyIPU3Threaded::start()
{
	state_ = ProxyRunning;
	thread_.start();

	return proxy_.invokeMethod(&ThreadProxy::start, ConnectionTypeBlocking);
}

void IPAProxyIPU3Threaded::stop()
{
	ASSERT(state_ != ProxyStopping);
	if (state_ != ProxyRunning)
		return;

	state_ = ProxyStopping;

	proxy_.invokeMethod(&ThreadProxy::stop, ConnectionTypeBlocking);

	thread_.exit();
	thread_.wait();

	Thread::current()->dispatchMessages(Message::Type::InvokeMessage, this);

	state_ = ProxyStopped;
}

int32_t IPAProxyIPU3Threaded::configure(
	const IPAConfigInfo &configInfo,
	ControlInfoMap *ipaControls)
{
	return ipa_->configure(configInfo, ipaControls);

}

void IPAProxyIPU3Threaded::mapBuffers(
	const std::vector<libcamera::IPABuffer> &buffers)
{
	return ipa_->mapBuffers(buffers);

}

void IPAProxyIPU3Threaded::unmapBuffers(
	const std::vector<uint32_t> &ids)
{
	return ipa_->unmapBuffers(ids);

}

void IPAProxyIPU3Threaded::queueRequest(
	const uint32_t frame,
	const ControlList &controls)
{
	ASSERT(state_ == ProxyRunning);
	proxy_.invokeMethod(&ThreadProxy::queueRequest, ConnectionTypeQueued, frame, controls);
}

void IPAProxyIPU3Threaded::computeParams(
	const uint32_t frame,
	const uint32_t bufferId)
{
	ASSERT(state_ == ProxyRunning);
	proxy_.invokeMethod(&ThreadProxy::computeParams, ConnectionTypeQueued, frame, bufferId);
}

void IPAProxyIPU3Threaded::processStats(
	const uint32_t frame,
	const int64_t frameTimestamp,
	const uint32_t bufferId,
	const ControlList &sensorControls)
{
	ASSERT(state_ == ProxyRunning);
	proxy_.invokeMethod(&ThreadProxy::processStats, ConnectionTypeQueued, frame, frameTimestamp, bufferId, sensorControls);
}



void IPAProxyIPU3Threaded::setSensorControlsHandler(
	const uint32_t frame,
	const ControlList &sensorControls,
	const ControlList &lensControls)
{
	ASSERT(state_ != ProxyStopped);
	setSensorControls.emit(frame, sensorControls, lensControls);
}

void IPAProxyIPU3Threaded::paramsComputedHandler(
	const uint32_t frame)
{
	ASSERT(state_ != ProxyStopped);
	paramsComputed.emit(frame);
}

void IPAProxyIPU3Threaded::metadataReadyHandler(
	const uint32_t frame,
	const ControlList &metadata)
{
	ASSERT(state_ != ProxyStopped);
	metadataReady.emit(frame, metadata);
}


/* ========================================================================== */

IPAProxyIPU3Isolated::IPAProxyIPU3Isolated(IPAModule *ipam, const CameraManager &cm)
	: IPAProxyIPU3(ipam, cm),
	  controlSerializer_(ControlSerializer::Role::Proxy), seq_(0)
{
	LOG(IPAProxy, Debug)
		<< "initializing ipu3 proxy in isolation: loading IPA from "
		<< ipam->path();

	const std::string proxyWorkerPath = resolvePath("ipu3_ipa_proxy");
	if (proxyWorkerPath.empty()) {
		LOG(IPAProxy, Error) << "Failed to get proxy worker path";
		return;
	}

	auto ipc = std::make_unique<IPCPipeUnixSocket>(ipam->path().c_str(),
						       proxyWorkerPath.c_str());
	if (!ipc->isConnected()) {
		LOG(IPAProxy, Error) << "Failed to create IPCPipe";
		return;
	}

	ipc->recv.connect(this, &IPAProxyIPU3Isolated::recvMessage);

	ipc_ = std::move(ipc);
	valid_ = true;
}

IPAProxyIPU3Isolated::~IPAProxyIPU3Isolated()
{
	if (ipc_) {
		IPCMessage::Header header =
			{ static_cast<uint32_t>(_IPU3Cmd::Exit), seq_++ };
		IPCMessage msg(header);
		ipc_->sendAsync(msg);
	}
}


int32_t IPAProxyIPU3Isolated::init(
	const IPASettings &settings,
	const IPACameraSensorInfo &sensorInfo,
	const ControlInfoMap &sensorControls,
	ControlInfoMap *ipaControls)
{
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::Init), seq_++ };
	IPCMessage _ipcInputBuf(_header);
	IPCMessage _ipcOutputBuf;


	std::vector<uint8_t> settingsBuf;
	std::tie(settingsBuf, std::ignore) =
		IPADataSerializer<libcamera::IPASettings>::serialize(settings);
	std::vector<uint8_t> sensorInfoBuf;
	std::tie(sensorInfoBuf, std::ignore) =
		IPADataSerializer<libcamera::IPACameraSensorInfo>::serialize(sensorInfo);
	std::vector<uint8_t> sensorControlsBuf;
	std::tie(sensorControlsBuf, std::ignore) =
		IPADataSerializer<libcamera::ControlInfoMap>::serialize(sensorControls, &controlSerializer_);
	appendPOD<uint32_t>(_ipcInputBuf.data(), settingsBuf.size());
	appendPOD<uint32_t>(_ipcInputBuf.data(), sensorInfoBuf.size());
	appendPOD<uint32_t>(_ipcInputBuf.data(), sensorControlsBuf.size());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), settingsBuf.begin(), settingsBuf.end());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), sensorInfoBuf.begin(), sensorInfoBuf.end());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), sensorControlsBuf.begin(), sensorControlsBuf.end());


	int _ret = ipc_->sendSync(_ipcInputBuf, &_ipcOutputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call init: " << _ret;
		return static_cast<int32_t>(_ret);
	}

	int32_t _retValue = IPADataSerializer<int32_t>::deserialize(_ipcOutputBuf.data(), 0);



	const size_t ipaControlsStart = 4;


	if (ipaControls) {
                *ipaControls =
                IPADataSerializer<libcamera::ControlInfoMap>::deserialize(
                	_ipcOutputBuf.data().cbegin() + ipaControlsStart,
                	_ipcOutputBuf.data().cend(),
                	&controlSerializer_);
	}


	return _retValue;

}


int32_t IPAProxyIPU3Isolated::start()
{
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::Start), seq_++ };
	IPCMessage _ipcInputBuf(_header);
	IPCMessage _ipcOutputBuf;




	int _ret = ipc_->sendSync(_ipcInputBuf, &_ipcOutputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call start: " << _ret;
		return static_cast<int32_t>(_ret);
	}

	int32_t _retValue = IPADataSerializer<int32_t>::deserialize(_ipcOutputBuf.data(), 0);






	return _retValue;

}


void IPAProxyIPU3Isolated::stop()
{
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::Stop), seq_++ };
	IPCMessage _ipcInputBuf(_header);




	int _ret = ipc_->sendSync(_ipcInputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call stop: " << _ret;
		return;
	}
}


int32_t IPAProxyIPU3Isolated::configure(
	const IPAConfigInfo &configInfo,
	ControlInfoMap *ipaControls)
{
	controlSerializer_.reset();
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::Configure), seq_++ };
	IPCMessage _ipcInputBuf(_header);
	IPCMessage _ipcOutputBuf;


	std::vector<uint8_t> configInfoBuf;
	std::tie(configInfoBuf, std::ignore) =
		IPADataSerializer<ipa::ipu3::IPAConfigInfo>::serialize(configInfo, &controlSerializer_);
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), configInfoBuf.begin(), configInfoBuf.end());


	int _ret = ipc_->sendSync(_ipcInputBuf, &_ipcOutputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call configure: " << _ret;
		return static_cast<int32_t>(_ret);
	}

	int32_t _retValue = IPADataSerializer<int32_t>::deserialize(_ipcOutputBuf.data(), 0);



	const size_t ipaControlsStart = 4;


	if (ipaControls) {
                *ipaControls =
                IPADataSerializer<libcamera::ControlInfoMap>::deserialize(
                	_ipcOutputBuf.data().cbegin() + ipaControlsStart,
                	_ipcOutputBuf.data().cend(),
                	&controlSerializer_);
	}


	return _retValue;

}


void IPAProxyIPU3Isolated::mapBuffers(
	const std::vector<libcamera::IPABuffer> &buffers)
{
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::MapBuffers), seq_++ };
	IPCMessage _ipcInputBuf(_header);


	std::vector<uint8_t> buffersBuf;
	std::vector<SharedFD> buffersFds;
	std::tie(buffersBuf, buffersFds) =
		IPADataSerializer<std::vector<libcamera::IPABuffer>>::serialize(buffers);
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), buffersBuf.begin(), buffersBuf.end());
	_ipcInputBuf.fds().insert(_ipcInputBuf.fds().end(), buffersFds.begin(), buffersFds.end());


	int _ret = ipc_->sendSync(_ipcInputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call mapBuffers: " << _ret;
		return;
	}
}


void IPAProxyIPU3Isolated::unmapBuffers(
	const std::vector<uint32_t> &ids)
{
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::UnmapBuffers), seq_++ };
	IPCMessage _ipcInputBuf(_header);


	std::vector<uint8_t> idsBuf;
	std::tie(idsBuf, std::ignore) =
		IPADataSerializer<std::vector<uint32_t>>::serialize(ids);
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), idsBuf.begin(), idsBuf.end());


	int _ret = ipc_->sendSync(_ipcInputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call unmapBuffers: " << _ret;
		return;
	}
}


void IPAProxyIPU3Isolated::queueRequest(
	const uint32_t frame,
	const ControlList &controls)
{
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::QueueRequest), seq_++ };
	IPCMessage _ipcInputBuf(_header);


	std::vector<uint8_t> frameBuf;
	std::tie(frameBuf, std::ignore) =
		IPADataSerializer<uint32_t>::serialize(frame);
	std::vector<uint8_t> controlsBuf;
	std::tie(controlsBuf, std::ignore) =
		IPADataSerializer<libcamera::ControlList>::serialize(controls, &controlSerializer_);
	appendPOD<uint32_t>(_ipcInputBuf.data(), frameBuf.size());
	appendPOD<uint32_t>(_ipcInputBuf.data(), controlsBuf.size());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), frameBuf.begin(), frameBuf.end());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), controlsBuf.begin(), controlsBuf.end());


	int _ret = ipc_->sendAsync(_ipcInputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call queueRequest: " << _ret;
		return;
	}
}


void IPAProxyIPU3Isolated::computeParams(
	const uint32_t frame,
	const uint32_t bufferId)
{
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::ComputeParams), seq_++ };
	IPCMessage _ipcInputBuf(_header);


	std::vector<uint8_t> frameBuf;
	std::tie(frameBuf, std::ignore) =
		IPADataSerializer<uint32_t>::serialize(frame);
	std::vector<uint8_t> bufferIdBuf;
	std::tie(bufferIdBuf, std::ignore) =
		IPADataSerializer<uint32_t>::serialize(bufferId);
	appendPOD<uint32_t>(_ipcInputBuf.data(), frameBuf.size());
	appendPOD<uint32_t>(_ipcInputBuf.data(), bufferIdBuf.size());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), frameBuf.begin(), frameBuf.end());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), bufferIdBuf.begin(), bufferIdBuf.end());


	int _ret = ipc_->sendAsync(_ipcInputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call computeParams: " << _ret;
		return;
	}
}


void IPAProxyIPU3Isolated::processStats(
	const uint32_t frame,
	const int64_t frameTimestamp,
	const uint32_t bufferId,
	const ControlList &sensorControls)
{
	IPCMessage::Header _header = { static_cast<uint32_t>(_IPU3Cmd::ProcessStats), seq_++ };
	IPCMessage _ipcInputBuf(_header);


	std::vector<uint8_t> frameBuf;
	std::tie(frameBuf, std::ignore) =
		IPADataSerializer<uint32_t>::serialize(frame);
	std::vector<uint8_t> frameTimestampBuf;
	std::tie(frameTimestampBuf, std::ignore) =
		IPADataSerializer<int64_t>::serialize(frameTimestamp);
	std::vector<uint8_t> bufferIdBuf;
	std::tie(bufferIdBuf, std::ignore) =
		IPADataSerializer<uint32_t>::serialize(bufferId);
	std::vector<uint8_t> sensorControlsBuf;
	std::tie(sensorControlsBuf, std::ignore) =
		IPADataSerializer<libcamera::ControlList>::serialize(sensorControls, &controlSerializer_);
	appendPOD<uint32_t>(_ipcInputBuf.data(), frameBuf.size());
	appendPOD<uint32_t>(_ipcInputBuf.data(), frameTimestampBuf.size());
	appendPOD<uint32_t>(_ipcInputBuf.data(), bufferIdBuf.size());
	appendPOD<uint32_t>(_ipcInputBuf.data(), sensorControlsBuf.size());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), frameBuf.begin(), frameBuf.end());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), frameTimestampBuf.begin(), frameTimestampBuf.end());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), bufferIdBuf.begin(), bufferIdBuf.end());
	_ipcInputBuf.data().insert(_ipcInputBuf.data().end(), sensorControlsBuf.begin(), sensorControlsBuf.end());


	int _ret = ipc_->sendAsync(_ipcInputBuf);
	if (_ret < 0) {
		LOG(IPAProxy, Error) << "Failed to call processStats: " << _ret;
		return;
	}
}



void IPAProxyIPU3Isolated::recvMessage(const IPCMessage &data)
{
	size_t dataSize = data.data().size();
	_IPU3EventCmd _cmd = static_cast<_IPU3EventCmd>(data.header().cmd);

	switch (_cmd) {
	case _IPU3EventCmd::SetSensorControls: {
		setSensorControlsHandler(data.data().cbegin(), dataSize, data.fds());
		break;
	}
	case _IPU3EventCmd::ParamsComputed: {
		paramsComputedHandler(data.data().cbegin(), dataSize, data.fds());
		break;
	}
	case _IPU3EventCmd::MetadataReady: {
		metadataReadyHandler(data.data().cbegin(), dataSize, data.fds());
		break;
	}
	default:
		LOG(IPAProxy, Error) << "Unknown command " << static_cast<uint32_t>(_cmd);
	}
}


void IPAProxyIPU3Isolated::setSensorControlsHandler(
	[[maybe_unused]] std::vector<uint8_t>::const_iterator data,
	[[maybe_unused]] size_t dataSize,
	[[maybe_unused]] const std::vector<SharedFD> &fds)
{

	[[maybe_unused]] const size_t frameBufSize = readPOD<uint32_t>(data, 0, data + dataSize);
	[[maybe_unused]] const size_t sensorControlsBufSize = readPOD<uint32_t>(data, 4, data + dataSize);
	[[maybe_unused]] const size_t lensControlsBufSize = readPOD<uint32_t>(data, 8, data + dataSize);

	const size_t frameStart = 12;
	const size_t sensorControlsStart = frameStart + frameBufSize;
	const size_t lensControlsStart = sensorControlsStart + sensorControlsBufSize;


	uint32_t frame =
        IPADataSerializer<uint32_t>::deserialize(
        	data + frameStart,
        	data + frameStart + frameBufSize);

	ControlList sensorControls =
        IPADataSerializer<libcamera::ControlList>::deserialize(
        	data + sensorControlsStart,
        	data + sensorControlsStart + sensorControlsBufSize,
        	&controlSerializer_);

	ControlList lensControls =
        IPADataSerializer<libcamera::ControlList>::deserialize(
        	data + lensControlsStart,
        	data + lensControlsStart + lensControlsBufSize,
        	&controlSerializer_);

	setSensorControls.emit(frame, sensorControls, lensControls);
}

void IPAProxyIPU3Isolated::paramsComputedHandler(
	[[maybe_unused]] std::vector<uint8_t>::const_iterator data,
	[[maybe_unused]] size_t dataSize,
	[[maybe_unused]] const std::vector<SharedFD> &fds)
{


	const size_t frameStart = 0;


	uint32_t frame =
        IPADataSerializer<uint32_t>::deserialize(
        	data + frameStart,
        	data + dataSize);

	paramsComputed.emit(frame);
}

void IPAProxyIPU3Isolated::metadataReadyHandler(
	[[maybe_unused]] std::vector<uint8_t>::const_iterator data,
	[[maybe_unused]] size_t dataSize,
	[[maybe_unused]] const std::vector<SharedFD> &fds)
{

	[[maybe_unused]] const size_t frameBufSize = readPOD<uint32_t>(data, 0, data + dataSize);
	[[maybe_unused]] const size_t metadataBufSize = readPOD<uint32_t>(data, 4, data + dataSize);

	const size_t frameStart = 8;
	const size_t metadataStart = frameStart + frameBufSize;


	uint32_t frame =
        IPADataSerializer<uint32_t>::deserialize(
        	data + frameStart,
        	data + frameStart + frameBufSize);

	ControlList metadata =
        IPADataSerializer<libcamera::ControlList>::deserialize(
        	data + metadataStart,
        	data + metadataStart + metadataBufSize,
        	&controlSerializer_);

	metadataReady.emit(frame, metadata);
}


} /* namespace ipu3 */

} /* namespace ipa */

} /* namespace libcamera */