/*
 * Copyright 2024 Rockchip Electronics Co. LTD
 *
 * 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.
 *
 */
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif /* End of #ifdef __cplusplus */

#include <stdio.h>
#include <unistd.h>
#include "sample_comm.h"
#include "sample_comm_aov.h"

#define AENC_BUF_SIZE 720

static uint8_t mp3Mute[AENC_BUF_SIZE] = {
    0xff, 0xf3, 0xe8, 0xc4, 0x00, 0x00, 0x00, 0x01, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

int SAMPLE_COMM_MuxerInit(SAMPLE_MPI_MUXER_S **pstMuxer, SAMPLE_VENC_CTX_S *pVenc) {
	if (!pVenc) {
		RK_LOGE("venc point is NULL");
		return RK_FAILURE;
	}

	(*pstMuxer) = (SAMPLE_MPI_MUXER_S *)malloc(sizeof(SAMPLE_MPI_MUXER_S));
	if (!(*pstMuxer)) {
		RK_LOGE("malloc pstMuxer failed");
		return RK_FAILURE;
	}

	SAMPLE_MPI_MUXER_S *pstTmpMuxer = (SAMPLE_MPI_MUXER_S *)(*pstMuxer);
	memset(pstTmpMuxer, 0, sizeof(SAMPLE_MPI_MUXER_S));

	pstTmpMuxer->pBuffer = (char *)malloc(AOV_STREAM_SIZE_WRITE_TO_SDCARD);
	if (!pstTmpMuxer->pBuffer) {
		RK_LOGE("malloc muxer data falied");
		return -1;
	}

	memset(pstTmpMuxer->pBuffer, 0, AOV_STREAM_SIZE_WRITE_TO_SDCARD);
	// set stVideoParam
	pstTmpMuxer->stVideoParam.level = 52;
	pstTmpMuxer->stVideoParam.width = pVenc->u32Width;
	pstTmpMuxer->stVideoParam.height = pVenc->u32Height;
	pstTmpMuxer->stVideoParam.bit_rate = pVenc->u32BitRate;
	pstTmpMuxer->stVideoParam.frame_rate_den = 1;
	pstTmpMuxer->stVideoParam.frame_rate_num = pVenc->u32Fps;

	if (pVenc->enCodecType == RK_CODEC_TYPE_H264) {
		memcpy(pstTmpMuxer->stVideoParam.codec, "H.264", strlen("H.264"));
		pstTmpMuxer->stVideoParam.profile = 100;
	} else if (pVenc->enCodecType == RK_CODEC_TYPE_H265) {
		memcpy(pstTmpMuxer->stVideoParam.codec, "H.265", strlen("H.265"));
	}

	memcpy(pstTmpMuxer->stVideoParam.format, "NV12", strlen("NV12"));

	pstTmpMuxer->stAudioParam.channels = 1;
	pstTmpMuxer->stAudioParam.sample_rate = 16000;
	pstTmpMuxer->stAudioParam.frame_size = 1152;
	const char *format = "S16";
	memcpy(pstTmpMuxer->stAudioParam.format, format, strlen(format));
	const char *codec = "MP3";
	if (codec)
		memcpy(pstTmpMuxer->stAudioParam.codec, codec, strlen(codec));

	return 0;
}

int SAMPLE_COMM_MuxerDeinit(SAMPLE_MPI_MUXER_S **pstMuxer) {
	if (*pstMuxer) {
		if ((*pstMuxer)->pBuffer) {
			free((*pstMuxer)->pBuffer);
			(*pstMuxer)->pBuffer = NULL;
		}

		free(*pstMuxer);
		(*pstMuxer) = NULL;
	}

	return 0;
}

static bool validate_muxer(SAMPLE_MPI_MUXER_S *pstMuxer, RK_U32 u32Len) {
	if (!pstMuxer) {
		RK_LOGE("error: pstMuxer(%p) is NULL", pstMuxer);
		return false;
	}
	if (pstMuxer->s32VideoDataSize + pstMuxer->s32AudioDataSize + u32Len >=
	    AOV_STREAM_SIZE_WRITE_TO_SDCARD) {
		RK_LOGE("error: cache buffer is not enough!");
		return false;
	}
	if (pstMuxer->s32AudioFrmCnt >= AUDIOFRAMECNT) {
		RK_LOGE("error: audio count(%d) > max count(%d)", pstMuxer->s32AudioFrmCnt,
		        AUDIOFRAMECNT);
		return false;
	}
	if (pstMuxer->s32VideoFrmCnt >= VIDEOFRAMECNT) {
		RK_LOGE("error: video count(%d) > max count(%d)", pstMuxer->s32VideoFrmCnt,
		        VIDEOFRAMECNT);
		return false;
	}
	return true;
}

void SAMPLE_COMM_MuxerVFrame(SAMPLE_MPI_MUXER_S *pstMuxer, RK_U32 u32Len, RK_U64 u64PTS,
                             RK_S32 s32KeyFrame, void *pData) {
	if (!validate_muxer(pstMuxer, u32Len)) {
		RK_LOGE("validate_muxer failed");
		return;
	}
	memcpy(pstMuxer->pBuffer + pstMuxer->s32VideoDataSize, pData, u32Len);

	pstMuxer->astVideoStream[pstMuxer->s32VideoFrmCnt].pData =
	    pstMuxer->pBuffer + pstMuxer->s32VideoDataSize;
	pstMuxer->astVideoStream[pstMuxer->s32VideoFrmCnt].u32Len = u32Len;
	pstMuxer->astVideoStream[pstMuxer->s32VideoFrmCnt].u64PTS = u64PTS;
	pstMuxer->astVideoStream[pstMuxer->s32VideoFrmCnt].s32KeyFrame = s32KeyFrame;
	pstMuxer->s32VideoFrmCnt++;
	pstMuxer->s32VideoDataSize += u32Len;
	pstMuxer->u64VSrcPts = u64PTS;
	return;
}

void SAMPLE_COMM_MuxerAFrame(SAMPLE_MPI_MUXER_S *pstMuxer, RK_U32 u32Len, RK_U64 u64PTS,
                             void *pData) {
	if (!validate_muxer(pstMuxer, u32Len)) {
		RK_LOGE("validate_muxer failed");
		return;
	}

	memcpy(pstMuxer->pBuffer - pstMuxer->s32AudioDataSize - u32Len +
	           AOV_STREAM_SIZE_WRITE_TO_SDCARD,
	       pData, u32Len);
	// if (pstMuxer->u64ASrcPts)
	//  	u64PTS = pstMuxer->u64ASrcPts;

	pstMuxer->astAudioStream[pstMuxer->s32AudioFrmCnt].pData =
	    pstMuxer->pBuffer - pstMuxer->s32AudioDataSize - u32Len +
	    AOV_STREAM_SIZE_WRITE_TO_SDCARD;
	pstMuxer->astAudioStream[pstMuxer->s32AudioFrmCnt].u32Len = u32Len;
	pstMuxer->astAudioStream[pstMuxer->s32AudioFrmCnt].u64PTS = u64PTS;
	pstMuxer->astAudioStream[pstMuxer->s32AudioFrmCnt].u32MuteCnt = 0;
	pstMuxer->s32AudioFrmCnt++;
	pstMuxer->s32AudioDataSize += u32Len;
	pstMuxer->u64ASrcPts = u64PTS + AENC_MUTE_DURATION;
	return;
}

void SAMPLE_COMM_MuxerMuteAFrame(SAMPLE_MPI_MUXER_S *pstMuxer) {
	RK_S32 mute_frame_cnt = 0;
	if (!validate_muxer(pstMuxer, 0)) {
		RK_LOGE("validate_muxer failed");
		return;
	}

	if (!pstMuxer->u64ASrcPts) {
		RK_LOGD("u64ASrcPts is 0, skip save mute frame");
		return;
	}

	if (pstMuxer->u64VSrcPts >= pstMuxer->u64ASrcPts) {
		mute_frame_cnt =
		    (pstMuxer->u64VSrcPts - pstMuxer->u64ASrcPts) / AENC_MUTE_DURATION +
		    1; // At least one mute frame
		pstMuxer->astAudioStream[pstMuxer->s32AudioFrmCnt].pData = mp3Mute;
		pstMuxer->astAudioStream[pstMuxer->s32AudioFrmCnt].u32Len = AENC_BUF_SIZE;
		pstMuxer->astAudioStream[pstMuxer->s32AudioFrmCnt].u64PTS = pstMuxer->u64ASrcPts;
		pstMuxer->astAudioStream[pstMuxer->s32AudioFrmCnt].u32MuteCnt = mute_frame_cnt;
		pstMuxer->u64ASrcPts += AENC_MUTE_DURATION * mute_frame_cnt;
		pstMuxer->s32AudioFrmCnt++;
	}

	return;
}

int SAMPLE_COMM_MuxerWrite(SAMPLE_MPI_MUXER_S *pstMuxer) {
	RK_U64 vPts = 0, aPts = 0, dPts = 0;
	RK_S32 aCnt = 0, vCnt = 0, err = 0;
	if (!pstMuxer) {
		RK_LOGE("error: pstMuxer(%p) is NULL", pstMuxer);
		return RK_FAILURE;
	}
	for (vCnt = 0; vCnt < pstMuxer->s32VideoFrmCnt; vCnt++) {
		vPts = pstMuxer->astVideoStream[vCnt].u64PTS;
		while (aCnt < pstMuxer->s32AudioFrmCnt && vCnt > 0) {
			aPts = pstMuxer->astAudioStream[aCnt].u64PTS;
			if (aPts >= vPts)
				break;
			while (1) {
				err = rkmuxer_write_audio_frame(0, pstMuxer->astAudioStream[aCnt].pData,
				                                pstMuxer->astAudioStream[aCnt].u32Len,
				                                aPts);

				if (err)
					RK_LOGE("rkmuxer_write_audio_frame %d failed. PTS %llu, len %d, %s",
					        aCnt, aPts, pstMuxer->astAudioStream[aCnt].u32Len,
					        pstMuxer->astAudioStream[aCnt].pData == (char *)mp3Mute
					            ? "mute frame"
					            : "normal frame");
				// else
				// 	RK_LOGD("rkmuxer_write_audio_frame %d success. PTS %llu, len %d, %s"
				// 			, aCnt, aPts, pstMuxer->astAudioStream[aCnt].u32Len
				// 			, pstMuxer->astAudioStream[aCnt].pData == (char *)mp3Mute ?
				// "mute frame" : "normal frame");

				if (pstMuxer->astAudioStream[aCnt].u32MuteCnt > 0) {
					pstMuxer->astAudioStream[aCnt].u32MuteCnt--;
					aPts += AENC_MUTE_DURATION;
				} else
					break;
			}
			aCnt++;
		}

		err = rkmuxer_write_video_frame(0, pstMuxer->astVideoStream[vCnt].pData,
		                                pstMuxer->astVideoStream[vCnt].u32Len,
		                                pstMuxer->astVideoStream[vCnt].u64PTS,
		                                pstMuxer->astVideoStream[vCnt].s32KeyFrame);
		if (err)
			RK_LOGE("rkmuxer_write_video_frame %d failed, PTS %llu, len %d, key_frame %d",
			        vCnt, pstMuxer->astVideoStream[vCnt].u64PTS,
			        pstMuxer->astVideoStream[vCnt].u32Len,
			        pstMuxer->astVideoStream[vCnt].s32KeyFrame);
		// else
		// 	RK_LOGD("rkmuxer_write_video_frame %d success, PTS %llu, len %d, key_frame %d"
		// 			, vCnt, pstMuxer->astVideoStream[vCnt].u64PTS
		// 			, pstMuxer->astVideoStream[vCnt].u32Len,
		// pstMuxer->astVideoStream[vCnt].s32KeyFrame);
	}

	RK_LOGI("rkmuxer write done, video frame cnt %d, audio frame cnt %d",
	        pstMuxer->s32VideoFrmCnt, pstMuxer->s32AudioFrmCnt);
	pstMuxer->s32AudioFrmCnt = 0;
	pstMuxer->s32AudioDataSize = 0;
	memset(pstMuxer->astAudioStream, 0, sizeof(pstMuxer->astAudioStream));
	pstMuxer->s32VideoFrmCnt = 0;
	pstMuxer->s32VideoDataSize = 0;
	memset(pstMuxer->astVideoStream, 0, sizeof(pstMuxer->astVideoStream));
	return RK_SUCCESS;
}

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* End of #ifdef __cplusplus */
