/*****************************************************************************
Copyright(c) 2005 Analog Devices, Inc.  All Rights Reserved. This software is 
proprietary and confidential to Analog Devices, Inc. and its licensors.
******************************************************************************

$RCSfile: jpeg_encode.c,v $
$Revision: 1.1 $
$Date: 2007/05/22 18:37:51 $

Project:	BlackfinSDK (JPEG-MJPEG)
Title:		JPEG encode
Author(s):	ku, bmk
Revised by: 

Description:
			High level JPEG encoding functions

References:
			None

******************************************************************************
Tab Setting:			4

Target Processor:		ADSP-BF5xx
Target Tools Revision:	ADSP VisualDSP++ v4.5
******************************************************************************

Modification History:
====================
$Log: jpeg_encode.c,v $
Revision 1.1  2007/05/22 18:37:51  gstephan
Creating VDSP 5.00 release folder.  Created from the head copy of
VDSP 4.50 release folder.

Revision 1.6  2006/11/10 07:18:59  bmk
merged BF533 & BF561 apps
Fixed BF561 caches issue

Revision 1.5  2006/11/03 07:12:15  bmk
SDK 2.0  files - Initial Entry

*****************************************************************************/

#include <jpeg_mjpeg_system.h>		// JPEG-MJPEG System includes

#include <adi_usbio_blackfin.h>		// USB I/O functions for Blackfin
#include <string.h>					// string header
#include <math.h>
#include <cycle_count.h> 			// for basic cycle counting

// codec APIs
#include <JPEG_api_encoder.h>
#include <JPEG_BitsBuffer.h>
#include <IMG_common.h>
#include <JPEG_memalloc.h>
#include <jpeg_mjpeg_err.h>

// local prototype
int JPEG_encode(char* input_file);

// encoder settings (valid only for the JPEG encoder in this file) 
// Width, Heigth and Quality Factor can be set through the specification file
static unsigned int			QualityFactor 	 	=  40;		// Input Desired Quality Factor
static unsigned int			Threshold 		 	=   0;
static unsigned int			EncodingMode	 	=  SEQUENTIAL;

/*********************************************************************

    Function:       do_JPEG_Encode

    Description:    File Handling for JPEG Encoding

*********************************************************************/	
section("sdram0_bank1_nocache")
int do_JPEG_Encode(void)
{
	char  current_input_file_name[MAX_FILE_NAME_LEN+4];
	static char current_path[MAX_PATH_NAME_LEN];
	static char temp_path[MAX_PATH_NAME_LEN];

	FILE *fp_jpg_dir;			// file pointer to list file

	int next_file = 1;	// let next file value not be a null
	char key;
	
	int return_code = CODEC_SUCCESS;	
	
	printf("Blackfin(r) Multimedia Starter Kit - JPEG Encoder\n");
	printf("(c) 2006 Analog Devices Inc.\n\n");

	// Reset Video codecs
	ResetVideoCodecs();
		
	if (File_Settings == PROMPT_FOR_FILE_SETTINGS) 
	{
	    printf("Enter directory path to store JPEG file(s): ");
	    fflush(stdout);
	    scanf ("%s", current_path);
	    strcat(current_path,"\\");
	    printf("Name this JPEG file as: ");
	    fflush(stdout);
	    scanf ("%s", current_input_file_name);
	}   
	else if (File_Settings == GET_FILE_SETTINGS_FROM_TXT_FILE) 
	{
  		// Open JPEG list-and-specification file
  		strcpy(current_path, SPEC_DIR);  	
  		fp_jpg_dir = fopen( strcat(current_path, JPEG_SPEC_FILE), "r" );
 		if (fp_jpg_dir == NULL)
		{
			fprintf( fperr, "Error: could not read specification file\n" );
			return CODEC_FILE_ERROR;
		}
		    
		printf("\nReading list of JPEG files and parameters from '%s'\n", JPEG_SPEC_FILE);

		// loop through all the files in the list-file
		// Get first File name from directory file
		next_file = fscanf(fp_jpg_dir, "%s %d %d %d", current_input_file_name, &JPEGImageWidth, &JPEGImageHeight, &QualityFactor);
	}

	// Format a JPEG image buffer as ITU656 frame
	if (VideoMode == ITU656_PAL)
		// Format as PAL frame
		adi_video_FrameFormat ((char *)pITU656Frames[0],PAL_IL);
	else // VideoMode must be ITU656_NTSC
		// Format as NTSC frame
		adi_video_FrameFormat ((char *)pITU656Frames[0],NTSC_IL);

	// continue till end of list or user selects to quit
	while((next_file != EOF) && (next_file != (int)NULL))
	{
		if (File_Settings == PROMPT_FOR_FILE_SETTINGS) 
		{
		    printf("\n");
	    	printf("Desired Image Size (Width) : ");
	    	fflush(stdout);
	    	scanf ("%d", &JPEGImageWidth);
	    	printf("Desired Image Size (Height): ");
	    	fflush(stdout);	    	
	    	scanf ("%d", &JPEGImageHeight);
	    	printf("Desired Quality factor     : ");
	    	fflush(stdout);
	    	scanf ("%d", &QualityFactor);	    	
	    	key = getchar();	// clear the final character (\n) in the input buffer
		}
		
		// delimit image sizes to valid values
		// minimum image size must be 16 x 16 pixels
		// maximum can be size of input resolution (720 x 486 for NTSC, 720 x 576 for PAL)
		if (JPEGImageWidth < 0x10)
			JPEGImageWidth = 0x10;
		else if (JPEGImageWidth > ITU_PIXEL_PER_LINE)
			JPEGImageWidth = ITU_PIXEL_PER_LINE;

		if (JPEGImageHeight < 0x10)
			JPEGImageHeight = 0x10;
		else if (JPEGImageHeight > ActiveFrameLines)
			JPEGImageHeight = ActiveFrameLines;	

		// Quality factor should be between 1 and 100
		if (QualityFactor < 1)
			QualityFactor = 1;
		else if (QualityFactor > 100)
			QualityFactor = 100;	
			
		// Sizes should be multiples of 16
		JPEGImageWidth  &= ~0xf;				
		JPEGImageHeight &= ~0xf;	

		// clear out video frame (black screen)
		if (VideoMode == ITU656_PAL)
			// Fill the Video out frame with background color
			adi_video_FrameFill ((char *)pITU656Frames[0],PAL_IL,JPEGImageBackground);
		else // VideoMode must be ITU656_NTSC
			// Fill the Video out frame with background color
			adi_video_FrameFill ((char *)pITU656Frames[0],NTSC_IL,JPEGImageBackground);

		// Install video decoder (ADV7183)
		InstallVideoDecoder();	    	
  		// Setup MDMA for ITU656 to YUV conversion
 		SetupMDMA_YUV_ITU656();
 					
#ifdef ADI_MMSK_EXTRA_INFO		// Extra debug information		
		if (File_Settings == GET_FILE_SETTINGS_FROM_TXT_FILE)
		{
			// print actual parameters
			printf("\nImage size to capture   = %d x %d pixels\n", JPEGImageWidth, JPEGImageHeight);
			printf("Encoding Quality Factor = %d \n", QualityFactor);
		}
#endif

		if (File_Settings == PROMPT_FOR_FILE_SETTINGS) 
		{
			// build the next input file name in tempstring
	    	strcpy (temp_path,current_path);
			strcat(temp_path, current_input_file_name);			
		}   
		else if (File_Settings == GET_FILE_SETTINGS_FROM_TXT_FILE) 
		{
			// build the next input file name in tempstring
			strcpy(temp_path, ROOT_DIR);
			strcat(strcat(temp_path, IMAGE_DIR_JPEG), current_input_file_name);
		}
	
		// encode the JPEG file
		if ((return_code = JPEG_encode(temp_path)) != CODEC_SUCCESS)
		{
			if (return_code != CODEC_FILE_ERROR)		// if it was a file error, try next file in the list
				break;			// error! Abort loop
		}
		
		// Wait for Key stroke to go to next file
		printf("\nHit 'Return' key to go to next file or 'q' to quit: ");
		fflush(stdout);
		while (key = getchar())
		{
			if ( (key == 'q') || (key == 'Q') )
				next_file = EOF;
			else if (key == '\n')
				break;
		}

		// check for end of file
		if((next_file != EOF) && (next_file != (int)NULL))
		{
		    				
			if (File_Settings == PROMPT_FOR_FILE_SETTINGS) 
			{
		    	printf("\nName this JPEG file as: ");
		    	fflush(stdout);
	    		scanf ("%s", current_input_file_name);
			}   
			else if (File_Settings == GET_FILE_SETTINGS_FROM_TXT_FILE) 
			{
				// Get Next File name from directory file
				next_file = fscanf(fp_jpg_dir, "%s %d %d %d", current_input_file_name, &JPEGImageWidth, &JPEGImageHeight, &QualityFactor);				
			}
		}
		// free up Video and DMA resources	
		// Free MDMA stream used for ITU656 to YUV conversion
		FreeMDMA_YUV_ITU656 ();		
		// Close Video Decoder (ADV7183)
		ezErrorCheck(adi_dev_Close(ADV7183DeviceHandle));			
	}

	if(return_code)
		fprintf(fperr, "\n!!! JPEG Encoding Failed !!!\n");
		
	if (File_Settings == GET_FILE_SETTINGS_FROM_TXT_FILE)
	{
	    printf("Reached end of list\n");
		// close the list file
		fclose( fp_jpg_dir );
	}

  	return return_code;
}

/*********************************************************************

    Function:       JPEG_encode

    Description:    Encodes a ITU656 frame to JPEG image 
    				(by interacting with JPEG Encode library)

*********************************************************************/	
section("sdram0_bank1_cache")
int JPEG_encode(char* input_file)
{
	tJpegEncoder	   			*lBaseJpegEnc = NULL;
	tJpegParam		   			lImageEncParam = { 0 };
	uint8	        			*lOutputBuffer;       	// Image output buffer	
	MemObjHandle      			*StreamBuffer_Obj;
	uint8			  			*StreamBuffer = NULL;
	FILE			   			*OutputFile = NULL;		// Image output file	
	uint32			 			NumBytes = 0;
    int32 				    	lResult = 0;

#ifdef ADI_MMSK_EXTRA_INFO		// macto to enable extra debug information
	// cycle counting
	static cycle_t              start_count;
	static cycle_t              final_count;
#endif
	
    // Get the address of YUV output buffer
	lOutputBuffer = (uint8*)pYUVBufs[0];
	
	printf("\npress and release button %s on EZ-kit to capture a frame\n",JPEG_MJPEG_REC_BUTTON_ID);
					
	// wait for button to be pressed
	while(!ezIsButtonPushed(JPEG_MJPEG_RECORD_BUTTON));
	// wait for button to be released
	while(ezIsButtonPushed(JPEG_MJPEG_RECORD_BUTTON));
	
	// Get the input video mode & update the video parameters
	UpdateInputVideoMode();
	// Submit Video Input buffer for JPEG encoding (only one ITU656 frame buffer will be used)
	SubmitVideoInBufs ();
	
	// wait until a video frame is captured		
	VideoFrameCompletedFlag = FALSE;	
	while(VideoFrameCompletedFlag != TRUE)
		asm("nop;");	
	VideoFrameCompletedFlag = FALSE;	
	    	
	// Initialise ITU656 to YUV conversion parameters
 	// Source Descriptor start address - Video (ITU656) buffer(s)
 	pSrcDescStartAddr	= pITU656Frames[0];
 	// Destination Descriptor start buffer - YUV buffer(s)
 	pDestDescStartAddr	= pYUVBufs[0];

	// check interleave format
	if (JPEGFrameFormat == 1)
	{
	    // Image will be encoded in YUV420 format
	    // initialise MDMA descriptors for ITU656 to YUV420 conversion
	    SetupMDMA_ITU656toYUV420 ();
	}
			
	// Kick off the DMA transfer (build YUV buffer from ITU656 frame)
	FrameReady = FALSE;	
	KickOffMDMA_YUV_ITU656();		
	// wait until YUV frame is ready
	while(!FrameReady)
		asm("nop;");

	// now we have the YUV buffers filled with an image
	// Configure JPEG encoder
	// set the desired input image width
	lResult = JPEG_Param_CONFIG(&lImageEncParam, JPEG_FRAME_WIDTH, JPEGImageWidth);
	if(lResult != E_SUCCESS)	JPEG_ProcessErrorCode(lResult, "JPEG_Param_CONFIG");
    // set the desired input image height
	lResult = JPEG_Param_CONFIG(&lImageEncParam, JPEG_FRAME_HEIGHT, JPEGImageHeight);
	if(lResult != E_SUCCESS)	JPEG_ProcessErrorCode(lResult, "JPEG_Param_CONFIG");
    // set the desired Quality factor
	lResult = JPEG_Param_CONFIG(&lImageEncParam, JPEG_QUALITYFACTOR, QualityFactor);
	if(lResult != E_SUCCESS)	JPEG_ProcessErrorCode(lResult, "JPEG_Param_CONFIG");
	// set the desired encoding mode
	lResult = JPEG_Param_CONFIG(&lImageEncParam, JPEG_ENCODINGMODE, EncodingMode);
	if(lResult != E_SUCCESS)	JPEG_ProcessErrorCode(lResult, "JPEG_Param_CONFIG");
	// set the desired threshold
	lResult = JPEG_Param_CONFIG(&lImageEncParam, JPEG_THRESHOLD, Threshold);
	if(lResult != E_SUCCESS)	JPEG_ProcessErrorCode(lResult, "JPEG_Param_CONFIG");
	// set the desired image frame format
	lResult = JPEG_Param_CONFIG(&lImageEncParam, JPEG_IMAGEFORMAT, JPEGFrameFormat);
	if(lResult != E_SUCCESS)    JPEG_ProcessErrorCode(lResult, "JPEG_Param_CONFIG");
	
	// allocate the output streambuffer
	StreamBuffer_Obj = JPEG_MemAlloc_NEW(3 * JPEGImageWidth * JPEGImageHeight,1,MEM_TYPE_DATA);
	if(StreamBuffer_Obj == NULL)
	{
		fprintf(fperr, "Memory allocation for StreamBuffer failed.\n");
		return CODEC_MEMORY_ALLOCATION_ERROR;	
	}
	
	// Get address of the output stream buffer
	StreamBuffer = (uint8*)JPEG_MemAlloc_ADDRESS(StreamBuffer_Obj);

	// pass input buffer address
	lResult = JPEG_Param_CONFIG(&lImageEncParam, JPEG_POINTER_INPUT, (int)lOutputBuffer);
	if(lResult != E_SUCCESS)	JPEG_ProcessErrorCode(lResult, "JPEG_Param_CONFIG");

    // pass output buffer address 
	lResult = JPEG_Param_CONFIG(&lImageEncParam, JPEG_POINTER_OUTPUT, (int)StreamBuffer);
	if(lResult != E_SUCCESS)	JPEG_ProcessErrorCode(lResult, "JPEG_Param_CONFIG");

	// Create Instance of JPEG Encoder
	lBaseJpegEnc = JPEG_Encoder_NEW(&lImageEncParam);
	// check if the encoder instance creation was a success
	if(lBaseJpegEnc == NULL)
	{
		fprintf(fperr, "Encoder creation failed\n");
		// free the memory
		JPEG_MemAlloc_DELETE(StreamBuffer_Obj);
		return CODEC_MEMORY_ALLOCATION_ERROR;
	}

#ifdef ADI_MMSK_EXTRA_INFO		// macro to enable extra debug information    	
	START_CYCLE_COUNT(start_count)	// begin counting time
#endif

	// Encode the YUV frame to JPEG image
	lResult = JPEG_EncodeImage(lBaseJpegEnc, &NumBytes);	
	
#ifdef ADI_MMSK_EXTRA_INFO		// Extra debug information
	STOP_CYCLE_COUNT(final_count,start_count)	// stop counting
#endif // ADI_MMSK_EXTRA_INFO	

	// process the encode image result
	if (lResult != E_SUCCESS)
	{
	    JPEG_ProcessErrorCode(lResult, "JPEG_EncodeImage");
	    fprintf(fperr, "!!! JPEG Encoding process failed!!!\n");
		// free the memory
		JPEG_MemAlloc_DELETE(StreamBuffer_Obj);		
		// Delete Encoder instance
		JPEG_Encoder_DELETE(lBaseJpegEnc);
		return CODEC_ALGORITHM_ERROR;
	}
		
#ifdef ADI_MMSK_EXTRA_INFO		// Extra debug information
	printf("\nTook %lu cycles to encode this image, ",final_count);
	printf("Equivalent to %lu cyles/pixel\n", final_count/((JPEGImageWidth) * (JPEGImageHeight)));
#endif // ADI_MMSK_EXTRA_INFO
	
	// Delete Encoder instance
	JPEG_Encoder_DELETE(lBaseJpegEnc);

	// check for file extension. add file extension if user didn't provide it
	if ((strstr(input_file, ".jpg") == NULL) &&	(strstr(input_file, ".JPG") == NULL))
		strcat(input_file,".jpg");	// add file extension	
		
	printf("\nWriting result to Output file: %s\n", input_file);
		
	// write result to output file
	OutputFile = fopen(input_file,"wb");
	if (OutputFile==NULL)
	{
		fprintf(fperr, "Error while opening the output file: %s \n", input_file);
		return CODEC_FILE_ERROR;
	}
	// Check video mode
	if (VideoMode == ITU656_PAL)
	    printf ("\nCaptured an ITU656 PAL video frame\n");	
	else // video mode must be ITU656_NTSC
	    printf ("\nCaptured an ITU656 NTSC video frame\n");

#ifdef ADI_MMSK_EXTRA_INFO		// macro to enable extra debug information    	
	printf("\nSending encoded file to Host via USB\n");	
	START_CYCLE_COUNT(start_count)	// begin counting time
#endif

	// Store bitstream in file
	fwrite(StreamBuffer, 1, NumBytes, OutputFile);
	
#ifdef ADI_MMSK_EXTRA_INFO		// Extra debug information
	STOP_CYCLE_COUNT(final_count,start_count)	// stop counting
#endif // ADI_MMSK_EXTRA_INFO	
	
	// Free and destory used resources
	// close output file
	fclose(OutputFile);	
	
#ifdef ADI_MMSK_EXTRA_INFO		// Extra debug information	
	printf("Took %lu cycles",final_count);	
	printf(" to write %d bytes\n\n",NumBytes);	
#endif // ADI_MMSK_EXTRA_INFO	    
			
	// free the memory
	JPEG_MemAlloc_DELETE(StreamBuffer_Obj);  

	printf("***  JPEG Conversion successful ***\n");
	
  	return CODEC_SUCCESS;
}

/*****/
