Преглед изворни кода

1、在 formal 里增加 ir_RegisterKpCallback(_MAINAPP_KeyPad_FiveKey_Callback) 函数及调用,解决长按按键不响应的问题
2、g_stSettingDefault_Picture 里的第一个数据是 Projection zoom,set 100 means full screen show
3、上传 tools 文件夹里的 mergelmage 文件夹内容备份

robbin пре 2 недеља
родитељ
комит
bbdf500938
35 измењених фајлова са 7977 додато и 3 уклоњено
  1. 121 2
      aps/application/s2tek/formal/main_app_initflow.c
  2. 1 1
      aps/customer/s2tek/sub_customer/s2tek/s2tek/system_setting/formal/app_data_setting.c
  3. 828 0
      tools/mergeImage/generateBin.c
  4. 12 0
      tools/mergeImage/generateBin.h
  5. 280 0
      tools/mergeImage/generateOutput.c
  6. 23 0
      tools/mergeImage/generateOutput.h
  7. 298 0
      tools/mergeImage/generateSave.c
  8. 18 0
      tools/mergeImage/generateSave.h
  9. 23 0
      tools/mergeImage/gpioset.h
  10. 23 0
      tools/mergeImage/init_flash_module.h
  11. 60 0
      tools/mergeImage/irset.h
  12. 95 0
      tools/mergeImage/loadBasicPacket.c
  13. 21 0
      tools/mergeImage/loadBasicPacket.h
  14. 38 0
      tools/mergeImage/makefile
  15. 155 0
      tools/mergeImage/mergeImage.c
  16. 118 0
      tools/mergeImage/mergeImage.cfg
  17. 217 0
      tools/mergeImage/mergeImage.h
  18. 737 0
      tools/mergeImage/mergeToBin.c
  19. 23 0
      tools/mergeImage/mergeToBin.h
  20. 201 0
      tools/mergeImage/mt_aq.c
  21. 11 0
      tools/mergeImage/mt_aq.h
  22. 182 0
      tools/mergeImage/mt_main.c
  23. 729 0
      tools/mergeImage/mt_mt.c
  24. 72 0
      tools/mergeImage/mt_mt.h
  25. 223 0
      tools/mergeImage/mt_pq.c
  26. 12 0
      tools/mergeImage/mt_pq.h
  27. 258 0
      tools/mergeImage/option.h
  28. 171 0
      tools/mergeImage/option_330.c
  29. 726 0
      tools/mergeImage/parseConfig.c
  30. 77 0
      tools/mergeImage/parseConfig.h
  31. 1507 0
      tools/mergeImage/pnlset2bin.c
  32. 199 0
      tools/mergeImage/pnlset2bin.h
  33. 493 0
      tools/mergeImage/sisspi_encrypt.c
  34. BIN
      tools/mergeImage/spi_encrypt.o
  35. 25 0
      tools/mergeImage/types.h

+ 121 - 2
aps/application/s2tek/formal/main_app_initflow.c

@@ -1005,6 +1005,119 @@ void _MAINAPP_Joystick_Callback(UINT32 Key, UINT32 joypadNum)
 }
 #endif
 
+#ifdef CONFIG_KEYPAD_FIVE_KEY_REUSE  //robbin add
+void _MAINAPP_KeyPad_FiveKey_Callback(UINT32 *dMessage)
+{
+	UINT32	dIndex = 0;
+    INT32 dObjectID = 0;
+    sys_app_errorcode_t ret = SYSTEM_APP_SUCCESS;
+    
+    if (MAIN_APP_SUCCESS != MAINAPP_GetActiveSystemAppIndex(&dIndex))
+    {
+        return;
+    }
+
+    if (dIndex == SYS_APP_ATV)
+    {
+        ret = SYSAPP_GOBJ_GetFocusedGUIObject(dIndex, &dObjectID);    
+        printf("!!!!!!!!!!!!!Function=%s,line=%d,ret=%d,*dMessage=%d\n",__FUNCTION__,__LINE__,ret,*dMessage);
+        if (ret == SYSTEM_APP_NO_FOCUSED_GUIOBJ || (ATVApp_IsPopupExist(PLAYBACK_POPUP_MSG_NO_SIGNAL)))//未进入菜单里
+        {
+			if(*dMessage == UI_EVENT_UP)
+				*dMessage = UI_EVENT_VOL_UP;
+			if(*dMessage == UI_EVENT_DOWN)
+				*dMessage = UI_EVENT_VOL_DN;
+
+            switch(*dMessage)
+            {                   
+               case UI_EVENT_KEYPAD_SOURCE: 
+                   *dMessage = UI_EVENT_SOURCE;
+                   break;                
+               case UI_EVENT_KEYPAD_POWER: 
+                   *dMessage = UI_EVENT_POWER;
+                   break;
+               case UI_EVENT_KEYPAD_MENU:
+                   *dMessage = UI_EVENT_MENU;
+                   break;
+               case UI_EVENT_KEYPAD_UP: 
+                   *dMessage = UI_EVENT_VOL_UP;
+                   break;
+               case UI_EVENT_KEYPAD_DOWN: 
+                   *dMessage = UI_EVENT_VOL_DN;
+                   break;
+               case UI_EVENT_KEYPAD_LEFT: 
+                   *dMessage = UI_EVENT_CH_UP;
+                   break;
+               case UI_EVENT_KEYPAD_RIGHT: 
+                   *dMessage = UI_EVENT_CH_DN;
+                   break;                   
+            } 
+        }
+    }
+#ifdef CONFIG_MEDIA_ENABLE	
+    else if (dIndex == SYS_APP_FILE_PLAYER)
+    {
+        ret = SYSAPP_GOBJ_GetFocusedGUIObject(dIndex, &dObjectID);          
+        printf("!!!!!!!!!!!!!Function=%s,line=%d,ret=%d,*dMessage=%d\n",__FUNCTION__,__LINE__,ret,*dMessage);
+        if (ret == SYSTEM_APP_NO_FOCUSED_GUIOBJ)
+        {
+            switch(*dMessage)
+            {
+                case UI_EVENT_KEYPAD_MENU:
+                    *dMessage = UI_EVENT_MENU;
+                    break;
+                case UI_EVENT_KEYPAD_SOURCE: 
+                    *dMessage = UI_EVENT_SOURCE;
+                    break;                 
+                case UI_EVENT_KEYPAD_POWER: 
+                    *dMessage = UI_EVENT_POWER;
+                    break;
+                case UI_EVENT_KEYPAD_UP: 
+                    *dMessage = UI_EVENT_CH_UP;
+                    break;
+                case UI_EVENT_KEYPAD_DOWN: 
+                    *dMessage = UI_EVENT_CH_DN;
+                    break;
+                case UI_EVENT_KEYPAD_LEFT: 
+                    *dMessage = UI_EVENT_VOL_UP;
+                    break;
+                case UI_EVENT_KEYPAD_RIGHT: 
+                    *dMessage = UI_EVENT_VOL_DN;
+                    break;          
+            } 
+        }
+        else if (ret == SYSTEM_APP_SUCCESS)
+        {
+            switch(*dMessage)
+            {
+                case UI_EVENT_KEYPAD_MENU:
+                    *dMessage = UI_EVENT_ENTER;
+                    break;
+                case UI_EVENT_KEYPAD_EXIT: 
+                    *dMessage = UI_EVENT_EXIT;
+                    break;                 
+                case UI_EVENT_KEYPAD_POWER: 
+                    *dMessage = UI_EVENT_POWER;
+                    break;
+                case UI_EVENT_KEYPAD_UP: 
+                    *dMessage = UI_EVENT_CH_UP;
+                    break;
+                case UI_EVENT_KEYPAD_DOWN: 
+                    *dMessage = UI_EVENT_CH_DN;
+                    break;
+                case UI_EVENT_KEYPAD_LEFT: 
+                    *dMessage = UI_EVENT_VOL_UP;
+                    break;
+                case UI_EVENT_KEYPAD_RIGHT: 
+                    *dMessage = UI_EVENT_VOL_DN;
+                    break;   
+            } 
+        }
+    }
+#endif	
+}
+#endif
+
 #ifdef CONFIG_SUPPORT_NET_OTA
 void NET_OTA_Event_Callback(NET_OTA_Event_e event, int param)
 {
@@ -2061,9 +2174,15 @@ static int _MAINAPP_InitSysApp(UINT32* dTotalApp)
 #ifdef CONFIG_AUTO_USB_STORE_IRSEQ
 	AUTO_IF_Initialize(_MAINAPP_Ir_Callback);
 #endif
-#ifdef CONFIG_KEYPAD_SINGLE_REUSE
-	ir_RegisterKpCallback(APP_GetSingleKeyPadEvent);
+
+#if defined(CONFIG_KEYPAD_SINGLE_REUSE)
+//#ifdef CONFIG_SUPPORT_SHOW_KEYPADMENU
+    ir_RegisterKpCallback(APP_GetSingleKeyPadEvent);
+//#endif
+#elif defined (CONFIG_KEYPAD_FIVE_KEY_REUSE)
+    ir_RegisterKpCallback(_MAINAPP_KeyPad_FiveKey_Callback);
 #endif
+
 #ifdef CONFIG_SUPPORT_NES_GAME
 	joystick_init(_MAINAPP_Joystick_Callback);
 #endif

+ 1 - 1
aps/customer/s2tek/sub_customer/s2tek/s2tek/system_setting/formal/app_data_setting.c

@@ -123,7 +123,7 @@ APP_SETTING_Version_t g_stSettingDefault_Version =
 APP_SETTING_Picture_t g_stSettingDefault_Picture =
 {
 #ifdef CONFIG_PROJECTOR_ASPECT
-	75,/*Projectionzoom*/
+	100,/*Projectionzoom*/  //robbin 100-full screen show
 #endif
 	MID_NR_MIDDLE, /* Nosie Reduce */
 	APP_ENVIRONMENT_HOME,/*Environment Select*/

+ 828 - 0
tools/mergeImage/generateBin.c

@@ -0,0 +1,828 @@
+//---------------------------------------------------------------------------
+#include "generateBin.h"
+#include "generateSave.h"
+#include "generateOutput.h"
+#include "drv_spi_sfs.h"
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <fcntl.h>
+
+#ifdef CONFIG_DISABLE_CIKEY_HDCPKEY_SPI_ENCRYPT
+#define HDCP_KEY_SIZE  (588)
+#define HDCP2X_KEY_SIZE  (588)
+#define CIPLUS_KEY_DATA_SIZE  (10240)
+extern void do_spi_decrypt(char *, unsigned int, unsigned int);
+#endif
+//---------------------------------------------------------------------------
+extern bool copyFileToMemory( u8 *memOut, const char *fileName, int maxSize );
+extern void writeToFlashTempFile( const char *fileName, u8 *memOut, u32 memSize );
+extern bool checkFileNameExtension( const char *fileName, const char *wildcard );
+extern int BMP2Bin(char *szFileIn, char *szFileOut);
+extern int JPG2Bin( const char *szFileIn, const char *szFileOut );
+extern int ini2binmem(char* pInFile, char *pOutData, int nBufSize);
+extern int syscmd( const char * format, ... );
+
+//---------------------------------------------------------------------------
+
+#if 0
+static inline bool generateFlashTempFile()
+{
+	int i;
+	for( i = 0; i < MODULE_MAX; i++ )
+	{
+		if( !flashModuleInfo[i].isValid  ) continue;
+		if( !mergeToBinCrossFlash( &flashModuleInfo[i] ) ) return false;
+	}
+
+	if( !mergeToBin_GenerateOption() ) return false;
+	if( !mergeToBin_GenerateUMFDefaultSetting() ) return false;
+#if 0//gaia, remove featrue 2013.04.23
+	if( !mergeToBin_Backup64K() ) return false;
+	if( !mergeToBin_BackupRRT() ) return false;
+#endif
+	return true;
+}
+#endif
+
+static unsigned int get_lzma_uncompressed_size(char *bin_name)
+{
+    int i, fd, ret;
+    unsigned int unpack_size;
+    unsigned char tmp_buf[64];
+    unsigned char offset = 0;
+	 
+    fd = open(bin_name,O_RDONLY);
+    if (fd < 0)
+        return 0;
+    ret = read(fd, tmp_buf, 64);
+    if (ret <= 0) {
+        close(fd);
+        return 0;
+    } else {   
+        close(fd);
+    }
+    
+    unpack_size = 0;
+
+#ifdef CONFIG_SUPPORT_PROJECT_ID
+    /* the header format is: the size of whole panel bin(2bytes) |Reserved byte(1Byte)| panel id(1byte) | Panel Name(38Bytes) | real data of panel bin(rest bytes) */
+    /* for GammaTable, VIPTable, CLUTTable, there will be 42 bytes header */
+    #define HEADER_SIZE (42)
+    char *p = strrchr(bin_name, '/');
+    if (p != NULL && (!strncmp(p+1, "GAMMATABLE.bin", strlen(p+1))
+        || !strncmp(p+1, "VIPTABLE.bin", strlen(p+1))
+        || !strncmp(p+1, "COLORLUT.bin", strlen(p+1))))
+    {
+        offset = HEADER_SIZE;
+    }
+#endif
+    for (i = 0;i < 8; i++) {
+        unpack_size += (tmp_buf[5+i+offset]<<(i*8));
+    }
+
+    return unpack_size; 
+}
+
+static unsigned int get_table_shaodw_size(char *pattern_str)
+{
+    char pattern_buf[128];
+    char cmd_buf[128];
+    FILE *pfile;
+    char *ref_file;
+    char *ref_file1 = "../boot/include/rom_def.h";
+    char *ref_file2 = "../drivers/module_include/drv_spi_flashalloc_internal.h";
+
+    if (!strcmp(pattern_str,"SPI_Custable_ShadowSize"))
+        ref_file = ref_file2;
+    else
+        ref_file = ref_file1;
+    memset(pattern_buf, 0, 128);
+    memset(cmd_buf, 0, 128);
+    sprintf(cmd_buf,"sed -n 's/#define\\s\\+%s\\s\\+\\(\\S\\+\\)/\\1/p' %s",pattern_str,ref_file);
+    pfile = popen(cmd_buf, "r");
+    if (fgets(pattern_buf, 128, pfile) != NULL) {
+        pclose(pfile);
+    } else {
+        return 0;
+    }
+    sprintf(cmd_buf,"python -c 'print %s'",pattern_buf);
+    pfile = popen(cmd_buf, "r");
+    memset(pattern_buf, 0 ,128);
+    if (fgets(pattern_buf, 128, pfile) != NULL) {
+        pclose(pfile);
+        return (unsigned int)atoi(pattern_buf);
+    } else {
+        return 0;
+    }
+     
+}
+
+static void __check_table_shaodw_size(char *bin_name, char *pattern_str)
+{
+    unsigned int unpack_size;
+    unsigned int shaodw_size;
+    char *ref_file;
+    char *ref_file1 = "boot/include/rom_def.h";
+    char *ref_file2 = "drivers/module_include/drv_spi_flashalloc_internal.h";
+
+    if (!strcmp(pattern_str,"SPI_Custable_ShadowSize"))
+        ref_file = ref_file2;
+    else
+        ref_file = ref_file1;
+    
+    shaodw_size = get_table_shaodw_size(pattern_str);
+    unpack_size = get_lzma_uncompressed_size(bin_name);
+    if ( shaodw_size < unpack_size) {
+        printf("\033[31;43m%s error!(real:%d shaodw:%d)\nPlease modify %s\n#define %s\033[0m\n",pattern_str,unpack_size,shaodw_size, ref_file, pattern_str);
+        exit(-1);
+    }
+}
+
+void check_table_shaodw_size(void)
+{
+    int i;
+
+    for (i=0; i < MODULE_MAX; i++) {
+        if (!strncmp(flashModuleInfo[i].moduleName, "Custable", TAG_LENGTH)) {
+            __check_table_shaodw_size(flashModuleInfo[i].tmpBinName, "SPI_Custable_ShadowSize");
+        }
+        if (!strncmp(flashModuleInfo[i].moduleName, "GammaTable", TAG_LENGTH)) {
+            __check_table_shaodw_size(flashModuleInfo[i].tmpBinName, "GammaTable_ShaodwSize");
+        }
+        if (!strncmp(flashModuleInfo[i].moduleName, "VIPTable", TAG_LENGTH)) {
+            __check_table_shaodw_size(flashModuleInfo[i].tmpBinName, "VipTable_ShadowSize");
+        }
+        if (!strncmp(flashModuleInfo[i].moduleName, "CLUPTable", TAG_LENGTH)) {
+            __check_table_shaodw_size(flashModuleInfo[i].tmpBinName, "ColorLUTTable_ShaodwSize");
+        }
+    }
+}
+
+static inline bool generateEncryptFlashBin( const char *tmp, const char *final )
+{
+	if( sisspi_encrypt( tmp, final, true ) )
+	{
+		errMsg( "encrypt failed\n"); return false;
+	}
+
+	return true;
+}
+static bool generateFinalFlashBin( const char *tmp, const char *final, const char *save )
+{
+	bool ret = true;
+	dbgMsg( "[generateFinalFlashBin] %s (%c)\n", final, MI_ENCRYPT_FLASH_BIN ? 'e' : 'd' );
+
+	ret = generateEncryptFlashBin( tmp, FILENAME_ENCRYPTTMP );
+#if 0
+	if( miGenerateOriginalBinFlag ) copyToOutputFolder( save, FILENAME_ENCRYPTTMP );
+#endif
+	rename( MI_ENCRYPT_FLASH_BIN ? FILENAME_ENCRYPTTMP : tmp, final );
+	//removeTempFile( MI_ENCRYPT_FLASH_BIN ? tmp : FILENAME_ENCRYPTTMP );
+	return ret;
+}
+
+#ifdef CONFIG_SUPPORT_FLASH_MODULE_CRC_CHECK
+void CalculatEachModuleCRC(u8 *raw_data, u32 data_size)
+{
+    int module_size;
+    mtab_head_s *flash_head;
+    char *current_ptr;
+    char module_name[TAG_LENGTH+1];
+
+    //calculate bootrom crc
+    current_ptr = (char *)raw_data;
+    module_size = *(u32 *)(current_ptr+8);
+    flash_head = (mtab_head_s *)(raw_data+SPI_OUIBOOTINFO_ADDR);
+    flash_head->crc = memCRC32(current_ptr, module_size);
+    current_ptr += module_size;
+
+    //calculate each module crc
+    do {
+        memset(module_name, '\0', TAG_LENGTH+1);
+        memcpy(module_name, current_ptr, TAG_LENGTH);
+        module_size = *(u32 *)(current_ptr+TAG_LENGTH);
+        flash_head = (mtab_head_s *)current_ptr;
+        flash_head->crc = memCRC32(current_ptr+sizeof(mtab_head_s), module_size-sizeof(mtab_head_s));
+        current_ptr += module_size;
+    }while( strncmp("NVM",module_name,TAG_LENGTH) );
+}
+
+
+void FillEachModuleDataSize(u8 *raw_data, u32 data_size)
+{
+    int i,module_size;
+    mtab_head_s *flash_head;
+    char *current_ptr;
+    struct stat st;
+    char module_name[TAG_LENGTH+1];
+
+    //skip bootrom data size
+    current_ptr = (char *)raw_data;
+    module_size = *(u32 *)(current_ptr+8);
+    current_ptr += module_size;
+
+    //calculate each module crc
+    do {
+        memset(module_name, '\0', TAG_LENGTH+1);
+        memcpy(module_name, current_ptr, TAG_LENGTH);
+        module_size = *(u32 *)(current_ptr+TAG_LENGTH);
+        flash_head = (mtab_head_s *)current_ptr;
+        for (i=0; i < MODULE_MAX; i++)
+            if (!strncmp(flashModuleInfo[i].moduleName, module_name, TAG_LENGTH))
+                break;
+        if ( i < MODULE_MAX) {
+            if ((i != MODULE_END) && (i != MODULE_NVM)){
+                stat(flashModuleInfo[i].tmpBinName, &st);
+                flash_head->data_size = st.st_size;
+            }
+        }
+        current_ptr += module_size;
+    }while( strncmp("NVM",module_name,TAG_LENGTH) );
+}
+
+#endif  //CONFIG_SUPPORT_FLASH_MODULE_CRC_CHECK
+
+#if 0
+bool generateFlashBin()
+{
+	bool ret = true;
+
+	dbgMsg( "\ngenerateFlashBin ==>\n" );
+	if( !mallocFlashTempMem() ) return false;
+	ret = generateFlashTempFile();
+	freeFlashTempMem();
+	if( !ret ) return false;
+
+	ret = generateFinalFlashBin( FILENAME_CODETMP, FILENAME_CODEBIN, miCodeBinName );
+
+#if( CONFIG_DATA_FLASH_SIZE != 0  )
+	if( ret ) ret = generateFinalFlashBin( FILENAME_DATATMP, FILENAME_DATABIN, miDataBinName );
+#endif
+
+    	return ret;
+}
+#endif
+
+#if 0
+#define TAG_LENGTH		12
+typedef struct _mtab_head_s
+{
+	char sys_tag[TAG_LENGTH]; /* write by createRomBin tool */
+ 	unsigned int size;
+
+}mtab_head_s;
+
+#endif
+static void cpy_mtab_head( char* buffer, char* sys_tag, int filesize)
+{
+	mtab_head_s mtab_head;
+	memset(&mtab_head, 0, sizeof(mtab_head_s));
+	strncpy(mtab_head.sys_tag, sys_tag, TAG_LENGTH);
+	mtab_head.size = ROUND_16B_ALIGNMENT(filesize) + sizeof(mtab_head_s);
+	memcpy(buffer, &mtab_head, sizeof(mtab_head_s));
+
+}
+#ifdef CONFIG_SUPPORT_NVM_PRELOAD
+bool sfs_dispatch(u16 id, void* src, void* des, int size)
+{
+	int write_offset =0;
+	u8 sn = 0;
+
+	u8* buff = (void *)malloc(SFS_page_size);	//2013.05.10, buffer for DMA, care alignment
+	if (buff == NULL)
+		return false;
+	
+	oob_st* oob = (oob_st *)(&buff[SFS_data_size]);
+
+	dbgMsg( "sfs_dispatch %d(%d bytes)\n", id, size);
+	while(write_offset < size)
+	{
+		oob->id = id;
+		oob->sn = sn;
+		oob->offset = (write_offset/SFS_data_size);
+		oob->len = ((size % SFS_data_size) == 0)? (size/SFS_data_size): (size/SFS_data_size+1);
+		oob->Magic = SFS_MagicNum;
+		memcpy(buff, (void *)((u32)src+write_offset), SFS_data_size);/*Warning, if remain size < pagesize, other space out of data will unknow */
+		memcpy(des, buff, SFS_page_size);
+		write_offset += SFS_data_size;
+		des += SFS_page_size;
+	}
+	//dbgMsg("<--\n");
+
+	free(buff);
+
+	return true;
+}
+
+
+bool transfer2sfs(u16 id, char* out_filename, char* in_filename)
+{
+	FILE *OutFile, *InFile;
+	char *rbuff,*wbuff,*ptr;
+	size_t result;
+
+	int i,chksum=0x0,infile_size = getFileSize(in_filename);
+
+	if (infile_size <= 0) {
+		return false;
+	}
+
+	InFile = fopen(in_filename,"rb");
+	OutFile = fopen(out_filename,"ab+");
+
+	if(OutFile == NULL || InFile == NULL){
+		fprintf(stderr, "Can't open will write/read file\n");
+		if (InFile) fclose(InFile);
+		if (OutFile) fclose(OutFile);
+		return false;
+	}
+
+	rbuff = (char*) malloc(SFS_Size);
+	if (rbuff == NULL) {
+		fclose(InFile);
+		fclose(OutFile);
+		return false;
+	}
+	memset(rbuff,0,SFS_Size);
+
+	result = fread(rbuff,1,infile_size,InFile);
+	if(result != infile_size){
+		fputs ("Reading error",stderr);
+		fclose(InFile);
+		fclose(OutFile);
+		free(rbuff);
+		return false;
+	}
+
+	wbuff = (char*)malloc(SFS_Size);
+	if (wbuff == NULL) {
+		fclose(InFile);
+		fclose(OutFile);
+		free(rbuff);
+		return false;
+	}
+	memset(wbuff,0,SFS_Size);
+
+	if(id == SPI_KMFSHARE_FLASHID){
+		sfs_dispatch(id, rbuff, wbuff, infile_size);
+		ptr=wbuff;
+		for(i=0;i<infile_size;i++, ptr++){
+			chksum += *ptr;
+		}
+		*ptr=chksum;
+		dbgMsg("chksum 0x%x\n", *ptr);
+		fwrite (wbuff , sizeof(char), (infile_size/SFS_page_size+1)*SFS_page_size, OutFile);
+	}else{
+		#if 1
+		char *tmp = (char*)malloc(SFS_Size);
+		if (tmp == NULL) {
+			fclose(InFile);
+			fclose(OutFile);
+			free(rbuff);
+			free(wbuff);
+			return false;
+		}
+		memset(tmp,0,SFS_Size);
+		//*(char *)tmp = infile_size;
+		memcpy(tmp ,rbuff, infile_size);
+		sfs_dispatch(id, tmp, wbuff, infile_size);
+		fwrite(wbuff , sizeof(char), ((infile_size)/SFS_page_size+1)*SFS_page_size, OutFile);
+		free (tmp);
+		#endif
+	}
+
+	fclose (OutFile);
+	fclose (InFile);
+
+	free (wbuff);
+	free (rbuff);
+
+	return true;
+}
+#endif
+//FlashTableStr FlashTable[MODULE_MAX] = {0};
+//int FlashTableIdx = 0;
+extern u8 *codeTmpMem;
+
+bool MergeBins2Mem(void)
+{
+	int i, fileSize;
+	bool ret = true;
+	//FILE* tmpbin;
+	u32 ACC_Offset = 0x00000000;		//start offset
+	u32 flashSize = CONFIG_CODE_FLASH_SIZE *1024 ;		//flash size
+	float fRealFlashSize = 0;
+	u32 keys_phy_addr = 0;
+	u32 last_module_offset = 0;
+	u32 last_module_size = 0;
+    u32 max_size = 0;
+
+#ifdef CONFIG_SUPPORT_NVM_PRELOAD
+	char sfs_tempfile[] = "sfs/nvm.bin";
+#endif
+#ifdef CONFIG_DISABLE_CIKEY_HDCPKEY_SPI_ENCRYPT
+    char *decrypt_tmp;
+#endif
+    check_table_shaodw_size();
+	if( !mallocFlashTempMem() ) return false;
+
+	/* initial key start offset */
+	#define SIMFS_PHYADDR 	(SPI_SIMFS_FLASHADDR & 0x00ffffff)
+	keys_phy_addr = CONFIG_FLASH_KEYSTORAGE_END_OFFSET + EDID_RELATEADDR;
+
+	/* scan all modules */
+	showMsg( "******* FlashMap *******\nAddress \tSize \tName \tPath\n");
+	for( i = 0; i < MODULE_MAX; i++ )
+	{
+		if( !flashModuleInfo[i].isValid  ) continue;
+		/* fopen input file */
+		fileSize = getFileSize(flashModuleInfo[i].tmpBinName);
+        max_size = flashModuleInfo[i].max_module_size*1024;
+
+        if ((max_size != 0) && (fileSize > max_size)){
+            errMsg("Module %s size(%d) large than max size(%d)\n",flashModuleInfo[i].moduleName, fileSize, max_size);
+            return false;
+        }
+        fileSize = max_size? max_size:fileSize;
+
+		if((i == MODULE_END) || (i == MODULE_NVM))
+			fileSize = 0x7fffffff;
+		if( fileSize < 0 ){
+			#if !DBG_SKIP_NOT_EXIST
+				errMsg( "getFileSize failed (%s)\n", flashModuleInfo[i].tmpBinName );//isAllowSkip?
+				return false;
+			#else
+				errMsg( "file not found, skip (%s)\n", flashModuleInfo[i].tmpBinName );//isAllowSkip?
+				continue;
+			#endif
+		}
+		if(((ACC_Offset + fileSize) > flashSize)
+		    && (i != MODULE_END) && (i != MODULE_NVM)){
+            errMsg("FiashSize is %d, ACC_Offset(0x%x(%d)) + filesize(%d) = %d, Over FlashSize %d B\n",
+                flashSize, ACC_Offset, ACC_Offset, fileSize, ACC_Offset+fileSize, ACC_Offset+fileSize-flashSize);
+            return false;
+		}
+		switch(i){
+		//fix address start here..
+			case MODULE_BOOTROM:	//bootrom @ 0xbc000000..+? byte, No header
+				copyFileToMemory(&codeTmpMem[ACC_Offset], flashModuleInfo[i].tmpBinName, fileSize);
+				showMsg( "0x%08x\t%d\t%s\t%s\n",  ACC_Offset, fileSize, flashModuleInfo[i].moduleName, flashModuleInfo[i].tmpBinName);
+				ACC_Offset += ROUND_16B_ALIGNMENT(fileSize);
+				break;
+			case MODULE_OPTION:	//option @ 0xbc011000..+0x200 & No header
+				dbgMsg( "%d copyFileToMemory %s %d\n",i,  flashModuleInfo[i].tmpBinName, fileSize );
+				copyFileToMemory(&codeTmpMem[SPI_OPTION_DATA_ADDR], (const char*)flashModuleInfo[i].tmpBinName, SPI_OPTION_DATA_SIZE);
+				showMsg( "0x%08x \t%d\t%s\t%s\n",  SPI_OPTION_DATA_ADDR,SPI_OPTION_DATA_SIZE, flashModuleInfo[i].moduleName, flashModuleInfo[i].tmpBinName);
+				break;
+			case MODULE_OUIBOOTINFO:	//oui info @ 0xbc011200..+0x30
+				dbgMsg( "%d copyFileToMemory %s %d\n",i,  flashModuleInfo[i].tmpBinName, fileSize );
+				cpy_mtab_head((char*)&codeTmpMem[SPI_OUIBOOTINFO_ADDR], flashModuleInfo[i].moduleName, fileSize);
+				copyFileToMemory(&codeTmpMem[SPI_OUIBOOTINFO_ADDR+FLASH_HEAD_SIZE], flashModuleInfo[i].tmpBinName, 0x30);
+				showMsg( "0x%08x \t48\t%s\t%s\n",  SPI_OUIBOOTINFO_ADDR, flashModuleInfo[i].moduleName, flashModuleInfo[i].tmpBinName);
+				break;
+			case MODULE_EDID:	//edid @ (NVM - 12K)..+0x380
+			{
+				/* check size first */
+				int tmp =  keys_phy_addr - ACC_Offset;
+				if ( tmp < 0) {
+					printf( "\n\n** ERROR!!! Code Size Overflow (%d bytes)! **\n\n", tmp);
+					return false;
+				}
+				/* extend the module before keys to key offset. */
+				//showMsg( "last_module_offset %x\n", last_module_offset);
+				/* add POOP */
+				mtab_head_s *mtab_head = (mtab_head_s *)(&codeTmpMem[last_module_offset]);
+				last_module_size = mtab_head->size;
+				cpy_mtab_head((char*)&codeTmpMem[last_module_offset + mtab_head->size], "NOOP", 0x10);
+				mtab_head_s *mtab_headS = (mtab_head_s *)(&codeTmpMem[last_module_offset + mtab_head->size ]);
+				mtab_headS->size = (CONFIG_FLASH_KEYSTORAGE_END_OFFSET + EDID_RELATEADDR)-(last_module_offset+last_module_size);
+				showMsg( "=== MainCode Size 0x%08x ===\n\t%s\n",  last_module_offset + mtab_head->size, "NOOP");
+
+				/* copy header */
+				dbgMsg( "%d copyFileToMemory %s %d\n", i,  flashModuleInfo[i].tmpBinName, fileSize );
+				cpy_mtab_head((char*)&codeTmpMem[keys_phy_addr], flashModuleInfo[i].moduleName, EDID_SIZE);
+				copyFileToMemory(&codeTmpMem[keys_phy_addr+FLASH_HEAD_SIZE], flashModuleInfo[i].tmpBinName, EDID_SIZE);
+				showMsg( "0x%08x \t%d\t%s\t%s\n",  keys_phy_addr, fileSize, flashModuleInfo[i].moduleName, flashModuleInfo[i].tmpBinName);
+				keys_phy_addr +=  EDID_SIZE + FLASH_HEAD_SIZE;
+				break;
+			}
+			case MODULE_HDCPKEY:	//hdcp @ (edid_addr)..+0x280
+				dbgMsg( "%d copyFileToMemory %s %d\n",i,  flashModuleInfo[i].tmpBinName, fileSize );
+				cpy_mtab_head((char*)&codeTmpMem[keys_phy_addr], flashModuleInfo[i].moduleName, HDCPKEY_SIZE);
+				copyFileToMemory(&codeTmpMem[keys_phy_addr+FLASH_HEAD_SIZE], flashModuleInfo[i].tmpBinName, HDCPKEY_SIZE);
+#ifdef CONFIG_DISABLE_CIKEY_HDCPKEY_SPI_ENCRYPT
+                decrypt_tmp = malloc(((HDCP_KEY_SIZE+15)>>4)<<4);
+                memcpy((void *)decrypt_tmp, (void *)&codeTmpMem[keys_phy_addr+0x10], HDCP_KEY_SIZE);
+                do_spi_decrypt(decrypt_tmp, (((HDCP_KEY_SIZE+15)>>4)<<4), 0);
+                memcpy((void *)&codeTmpMem[keys_phy_addr+FLASH_HEAD_SIZE], (void *)decrypt_tmp, HDCP_KEY_SIZE);
+                free(decrypt_tmp);
+#endif
+				showMsg( "0x%08x \t%d\t%s\t%s\n",  keys_phy_addr, fileSize, flashModuleInfo[i].moduleName, flashModuleInfo[i].tmpBinName);
+				keys_phy_addr +=  HDCPKEY_SIZE + FLASH_HEAD_SIZE;
+				break;
+#ifdef CONFIG_AUTO_WB
+            case MODULE_WBDATA:
+				dbgMsg( "%d copyFileToMemory %s %d\n",i,  flashModuleInfo[i].tmpBinName, fileSize );
+				cpy_mtab_head((char*)&codeTmpMem[keys_phy_addr], flashModuleInfo[i].moduleName, WBDATA_SIZE);
+				copyFileToMemory(&codeTmpMem[keys_phy_addr+FLASH_HEAD_SIZE], flashModuleInfo[i].tmpBinName, WBDATA_SIZE);
+				showMsg( "0x%08x \t%d\t%s\t%s\n",  keys_phy_addr, fileSize, flashModuleInfo[i].moduleName, flashModuleInfo[i].tmpBinName);
+				keys_phy_addr +=  WBDATA_SIZE + FLASH_HEAD_SIZE;
+				break;
+#endif
+#ifdef CONFIG_SUPPORT_STORE_HDCP2X_TO_FLASH
+ 			case MODULE_HDCP2XKEY:
+				dbgMsg( "%d copyFileToMemory %s %d\n",i,  flashModuleInfo[i].tmpBinName, fileSize );
+				cpy_mtab_head((char*)&codeTmpMem[keys_phy_addr], flashModuleInfo[i].moduleName, HDCP2XKEY_SIZE);
+				copyFileToMemory(&codeTmpMem[keys_phy_addr+FLASH_HEAD_SIZE], flashModuleInfo[i].tmpBinName, HDCP2XKEY_SIZE);
+#ifdef CONFIG_DISABLE_CIKEY_HDCPKEY_SPI_ENCRYPT
+                decrypt_tmp = malloc(((HDCP2X_KEY_SIZE+15)>>4)<<4);
+                memcpy((void *)decrypt_tmp, (void *)&codeTmpMem[keys_phy_addr+0x10], HDCP2X_KEY_SIZE);
+                do_spi_decrypt(decrypt_tmp, (((HDCP2X_KEY_SIZE+15)>>4)<<4), 0);
+                memcpy((void *)&codeTmpMem[keys_phy_addr+FLASH_HEAD_SIZE], (void *)decrypt_tmp, HDCP2X_KEY_SIZE);
+                free(decrypt_tmp);
+#endif
+				showMsg( "0x%08x \t%d\t%s\t%s\n",  keys_phy_addr, fileSize, flashModuleInfo[i].moduleName, flashModuleInfo[i].tmpBinName);
+				keys_phy_addr +=  HDCP2XKEY_SIZE + FLASH_HEAD_SIZE;
+				break;
+#endif
+#ifdef CONFIG_CI_SUPPORT
+			case MODULE_CIKEY:	//hdcp @ (hdcpy_addr)..+? ( max 10740)
+				dbgMsg( "%d copyFileToMemory %s %d\n",i,  flashModuleInfo[i].tmpBinName, fileSize );
+				cpy_mtab_head((char*)&codeTmpMem[keys_phy_addr], flashModuleInfo[i].moduleName, fileSize);
+				copyFileToMemory(&codeTmpMem[keys_phy_addr+FLASH_HEAD_SIZE], flashModuleInfo[i].tmpBinName, fileSize);
+#ifdef CONFIG_DISABLE_CIKEY_HDCPKEY_SPI_ENCRYPT
+                do_spi_decrypt((char *)&codeTmpMem[keys_phy_addr+FLASH_HEAD_SIZE], CIPLUS_KEY_DATA_SIZE, 0);
+#endif
+				showMsg( "0x%08x \t%d\t%s\t%s\n",  keys_phy_addr, fileSize, flashModuleInfo[i].moduleName, flashModuleInfo[i].tmpBinName);
+				keys_phy_addr +=  fileSize + FLASH_HEAD_SIZE;
+				break;
+#endif
+			case MODULE_END:
+			{	//code end, just the last module before NVM
+
+				int the_range_between_end_and_nvm = (SIMFS_PHYADDR-FLASH_HEAD_SIZE)-keys_phy_addr-FLASH_HEAD_SIZE;
+				dbgMsg( "%d copyFileToMemory %s %d\n",i,  flashModuleInfo[i].moduleName, fileSize );
+				ACC_Offset = keys_phy_addr;		//end = keys end..
+				cpy_mtab_head((char*)&codeTmpMem[ACC_Offset], flashModuleInfo[i].moduleName, the_range_between_end_and_nvm);
+				showMsg( "0x%08x \t\t%s\n",  ACC_Offset, flashModuleInfo[i].moduleName);
+				ACC_Offset += ROUND_16B_ALIGNMENT(sizeof(mtab_head_s));
+				break;
+			}
+
+			case MODULE_NVM:
+			{
+#ifdef CONFIG_SUPPORT_NVM_PRELOAD
+                int c;
+                c=system("rm sfs/nvm.bin");
+                for (c = 0; c < gNVMData_count; c++) {
+				    if (!transfer2sfs( gNVMData[c].id, sfs_tempfile,  gNVMData[c].pathName)){
+					printf( "\nERROR!!! transfer2sfs fail!!!\n");
+					return false;
+				}
+                }
+				int outfile_size = getFileSize(sfs_tempfile);
+				dbgMsg( "%d copyFileToMemory %s %d\n",i,  sfs_tempfile, outfile_size);
+				cpy_mtab_head((char*)&codeTmpMem[SIMFS_PHYADDR-FLASH_HEAD_SIZE], flashModuleInfo[i].moduleName, outfile_size);
+				copyFileToMemory(&codeTmpMem[SIMFS_PHYADDR], sfs_tempfile , outfile_size);
+				showMsg( "0x%08x \t%d\tNVM\t%s\n",  SIMFS_PHYADDR-FLASH_HEAD_SIZE, outfile_size, "sfs/nvm.bin");
+				ACC_Offset = SIMFS_PHYADDR + outfile_size;
+#else
+				cpy_mtab_head((char*)&codeTmpMem[SIMFS_PHYADDR-FLASH_HEAD_SIZE], flashModuleInfo[i].moduleName, 0);
+				ACC_Offset = SIMFS_PHYADDR;
+#endif
+				break;
+			}
+
+		//dynamic address start here..
+			default:
+				last_module_offset = ACC_Offset;
+				cpy_mtab_head((char*)&codeTmpMem[ACC_Offset], flashModuleInfo[i].moduleName, fileSize);
+				ACC_Offset +=	 sizeof(mtab_head_s);
+				copyFileToMemory(&codeTmpMem[ACC_Offset], flashModuleInfo[i].tmpBinName, fileSize);
+				showMsg( "0x%08x \t%d\t%s\t%s\n",  ACC_Offset-sizeof(mtab_head_s), fileSize, flashModuleInfo[i].moduleName, flashModuleInfo[i].fileName);
+				ACC_Offset += ROUND_16B_ALIGNMENT(fileSize);
+				break;
+		}
+	}
+	/* check size */
+	showMsg( "End offset %x\n", ACC_Offset);
+	fRealFlashSize = (float)ACC_Offset / 1024.0 / 1024.0;
+	showMsg( "Real BIN size=%.2fM\n", fRealFlashSize);
+
+	//write to flash temp file
+#ifdef CONFIG_SUPPORT_FLASH_MODULE_CRC_CHECK
+    FillEachModuleDataSize(codeTmpMem, ACC_Offset);
+    CalculatEachModuleCRC(codeTmpMem, ACC_Offset);
+#endif
+
+	writeToFlashTempFile( FILENAME_CODETMP, codeTmpMem, ACC_Offset	);
+	free( codeTmpMem );
+
+	ret = generateFinalFlashBin( FILENAME_CODETMP, FILENAME_CODEBIN, miCodeBinName );
+
+#if( CONFIG_DATA_FLASH_SIZE != 0  )
+	if( ret ) ret = generateFinalFlashBin( FILENAME_DATATMP, FILENAME_DATABIN, miDataBinName );
+#endif
+#ifdef CONFIG_APPEND_NAME_TO_CIKEY_HDCPKEY
+#ifdef CONFIG_CI_SUPPORT
+		removeTempFile(flashModuleInfo[MODULE_CIKEY].tmpBinName);
+#endif
+		removeTempFile(flashModuleInfo[MODULE_HDCPKEY].tmpBinName);
+        #ifdef CONFIG_SUPPORT_STORE_HDCP2X_TO_FLASH
+		removeTempFile(flashModuleInfo[MODULE_HDCP2XKEY].tmpBinName);
+        #endif
+#endif
+    	return ret;
+}
+
+bool transferPnelSet2Bin(char* out_filename, char* pnl_ini_name)
+{
+	#define MAX_PNLSET_SIZE		2048
+	FILE *OutFile;
+	char* buff;
+	int size;
+	
+	buff = malloc(MAX_PNLSET_SIZE);		// max panelset bin file size 2k.
+	if (buff == NULL)
+		return false;
+	
+	size = ini2binmem(pnl_ini_name, buff, MAX_PNLSET_SIZE);
+	//get writed size
+	if(size < 0) {
+		free(buff);
+		return false;
+	}
+	
+	OutFile = fopen(out_filename,"wb");
+	if (OutFile == NULL) {
+		fprintf(stderr, "Can't open will write file\n");
+		free(buff);
+		return false;
+	}
+	
+	fwrite(buff, size, 1, OutFile);
+	fclose(OutFile);
+	free(buff);
+
+	#undef MAX_PNLSET_SIZE
+	return true;
+}
+
+//bool transferLogo2Bin( u8* memOut, NorFlashModuleInfo *info  )
+bool transferLogo2Bin(char* out_filename, char* input_name)
+{
+	int ret = false;
+	showMsg( "[transferLogoFileToMemory] %s\n", input_name );
+	if( checkFileNameExtension( input_name, ".bmp" ) )
+	{
+		ret = BMP2Bin( input_name, FILENAME_LOGOTMP );
+		if( syscmd( "./../tools/lzma460/lzma e %s %s", FILENAME_LOGOTMP, FILENAME_LOGOGZTMP ) )
+		{
+			ret = false;
+		}
+		if( syscmd( "mv %s %s ", FILENAME_LOGOGZTMP, out_filename ) )
+		{
+			ret = false;
+		}
+	}
+	else if( checkFileNameExtension( input_name, ".jpg" ) || \
+             checkFileNameExtension( input_name, ".mp3" ) || \
+             checkFileNameExtension( input_name, ".jpeg" ))
+	{
+		ret = JPG2Bin( input_name, out_filename );
+	}
+	return ret;
+}
+bool transferCustable2GZIPBin(char* out_filename, char* input_name)
+{
+	int ret = true;
+	//char* out_file[30];
+	showMsg( "[transferCustomertable2lzma] %s\n", input_name );
+	if( checkFileNameExtension( input_name, ".bin" ) )
+	{
+
+		if(syscmd("./../tools/lzma460/lzma e %s %s",input_name,FILENAME_CUSTABLEGZTMP))
+		{
+			ret = false;
+		}
+		if( syscmd( "mv %s %s ", FILENAME_CUSTABLEGZTMP, out_filename ) )
+		{
+			ret = false;
+		}
+	}
+	return ret;
+}
+
+bool genTempBinFiles()
+{
+	int i, ret = true;
+#ifdef CONFIG_APPEND_NAME_TO_CIKEY_HDCPKEY
+	int char_read;
+	char buffer[1024];
+	char tempstring[] = "temp";
+	char temp[512];
+	FILE *f_in, *f_out;
+#endif
+	//char outname[32];
+	dbgMsg( "genTempBinFiles..\n" );
+	for( i = 0; i < MODULE_MAX; i++ )
+	{
+		//transfer all ini files
+		if( !flashModuleInfo[i].isValid  )
+			continue;
+#if 0	// if not support Multi-panel bin file
+		//if get PanelSet.ini
+		if( i ==  MODULE_PANELSET ){
+			sprintf(flashModuleInfo[i].tmpBinName, "%s.bin", flashModuleInfo[i].moduleName);
+			ret = transferPnelSet2Bin(flashModuleInfo[i].tmpBinName,  flashModuleInfo[i].fileName);
+		}
+		//if get ExtraPanelSet1.ini
+		else if( i == MODULE_EXTRAPANELSET1 ){
+			sprintf(flashModuleInfo[i].tmpBinName, "%s.bin", flashModuleInfo[i].moduleName);
+			ret = transferPnelSet2Bin(flashModuleInfo[i].tmpBinName,  flashModuleInfo[i].fileName);
+		}
+		//if get ExtraPanelSet2.ini
+		else if( i == MODULE_EXTRAPANELSET2 ){
+			sprintf(flashModuleInfo[i].tmpBinName, "%s.bin", flashModuleInfo[i].moduleName);
+			ret = transferPnelSet2Bin(flashModuleInfo[i].tmpBinName,  flashModuleInfo[i].fileName);
+		}
+		//if get ExtraPanelSet3.ini
+		else if( i == MODULE_EXTRAPANELSET3 ){
+			sprintf(flashModuleInfo[i].tmpBinName, "%s.bin", flashModuleInfo[i].moduleName);
+			ret = transferPnelSet2Bin(flashModuleInfo[i].tmpBinName,  flashModuleInfo[i].fileName);
+		}
+		//Logo
+		else if( i ==  MODULE_LOGO ){
+#endif
+		#if 0
+		else if( i ==  MODULE_OPTION){
+			sprintf(flashModuleInfo[i].tmpBinName, "%s.bin", flashModuleInfo[i].moduleName);
+			if( !mergeToBin_GenerateOption(flashModuleInfo[i].tmpBinName) )
+				return false;
+		}
+		#endif
+		else if( i ==  MODULE_CUSTABLE){
+			sprintf(flashModuleInfo[i].tmpBinName, "%s.bin", flashModuleInfo[i].moduleName);
+			if( !transferCustable2GZIPBin(flashModuleInfo[i].tmpBinName,  flashModuleInfo[i].fileName) )
+				return false;
+		}
+#ifdef CONFIG_APPEND_NAME_TO_CIKEY_HDCPKEY
+		else if(0||
+                #ifdef CONFIG_CI_SUPPORT
+                ( i ==  MODULE_CIKEY ) || 
+                #endif
+                ( i ==  MODULE_HDCPKEY)||
+                #ifdef CONFIG_SUPPORT_STORE_HDCP2X_TO_FLASH
+                ( i ==  MODULE_HDCP2XKEY)||
+                #endif
+                0){
+				strcpy(temp, flashModuleInfo[i].fileName);
+				strcat(temp , tempstring);
+				f_in = fopen (flashModuleInfo[i].fileName, "rb");
+				if(f_in == NULL)
+				{
+					showMsg( "\nCan not find module binfile: %s\n", flashModuleInfo[i].fileName);
+					return false;
+				}
+				f_out = fopen (temp, "wb");
+				if (f_out == NULL) 
+				{
+					fclose(f_in);
+					return false;
+				}
+				while(!feof(f_in)) {
+				   	char_read=fread(buffer, 1, 32, f_in);
+				    fwrite(buffer,1, char_read, f_out);
+				}
+				fseek(f_out, 0, SEEK_END);
+				fwrite(flashModuleInfo[i].eachfileName, 1, (int)32, f_out);
+				fclose(f_in);
+				fclose(f_out);
+
+				sprintf(flashModuleInfo[i].tmpBinName, "%s", temp);
+		}
+#endif
+		else{
+			//just copy fileName to tmpBinName
+
+			if(checkFileNameExtension( flashModuleInfo[i].fileName, ".jpg" ) || \
+               checkFileNameExtension( flashModuleInfo[i].fileName, ".mp3" ) || \
+               checkFileNameExtension( flashModuleInfo[i].fileName, ".jpeg" ) || \
+               checkFileNameExtension( flashModuleInfo[i].fileName, ".bmp" ) ){
+				showMsg( "use %s %s\n", flashModuleInfo[i].moduleName, flashModuleInfo[i].fileName );
+				sprintf(flashModuleInfo[i].tmpBinName, "%s.bin", flashModuleInfo[i].moduleName);
+				ret = transferLogo2Bin(flashModuleInfo[i].tmpBinName,  flashModuleInfo[i].fileName);
+			}else{	//bmp or jpeg
+			showMsg( "use %s\n", flashModuleInfo[i].fileName );
+					snprintf(flashModuleInfo[i].tmpBinName, sizeof(flashModuleInfo[i].tmpBinName), "%s", flashModuleInfo[i].fileName);
+			}
+		}
+	}
+#if 0	//todo
+	if( !mergeToBin_GenerateUMFDefaultSetting() ) return false;
+#endif
+	/**/
+    	return ret;
+}
+
+

+ 12 - 0
tools/mergeImage/generateBin.h

@@ -0,0 +1,12 @@
+//-------------------------------------------------------------------------------
+// generateBin
+//-------------------------------------------------------------------------------
+#ifndef _GENERATEBIN_H_
+#define _GENERATEBIN_H_
+//-------------------------------------------------------------------------------
+#include "mergeToBin.h"
+#include "stdio.h"
+//-------------------------------------------------------------------------------
+bool generateFlashBin();
+//-------------------------------------------------------------------------------
+#endif

+ 280 - 0
tools/mergeImage/generateOutput.c

@@ -0,0 +1,280 @@
+//-------------------------------------------------------------------------------
+#include "generateOutput.h"
+//-------------------------------------------------------------------------------
+#include "generateSave.h"
+#include "generateBin.h"
+#include "parseConfig.h"
+#include "loadBasicPacket.h"
+//-------------------------------------------------------------------------------
+#include <dirent.h>
+#include<sys/types.h>
+#include<sys/stat.h>
+//-------------------------------------------------------------------------------
+extern bool generateSaveInfo(void);
+extern bool genTempBinFiles();
+extern bool MergeBins2Mem(void);
+
+//-------------------------------------------------------------------------------
+
+void removeTempFile( const char *fileName )
+{
+	if( (fileName == NULL) || (!strlen(fileName)) ) return;
+	if( miDeleteTempFileFlag ) remove( fileName );
+}
+
+//---------------------------------------------------------------------------
+
+static inline bool checkOutputIsLocalFolder()
+{
+	if( strlen(miOutputPathName) == 0 )
+	{
+		strcpy( miOutputPathName, PATHNAME_OUTPUT );
+		errMsg( "miOutputPathName = NULL!\n");  
+		return true;
+	}
+
+	if( strlen(miOutputPathName) == 1 )
+	{
+		if( miOutputPathName[0] == '.'  ) return true;
+	}
+
+	return false;
+}
+
+static inline void deleteContextOfOutputFolder()
+{
+	char tempName[FILENAME_SIZE];
+	DIR *dir = opendir( miOutputPathName );
+	if( dir == NULL ) return;
+	
+	struct dirent * ptr;
+	while( (ptr = readdir(dir)) != NULL )
+	{
+		if( ptr->d_name[0] == '.' ) continue;
+		snprintf( tempName, sizeof(tempName), "%s/%s", miOutputPathName, ptr->d_name );
+		remove( tempName );
+	} 
+	closedir(dir);
+}
+
+static inline bool chmodOutputFolder()
+{
+	DIR *dir;
+	char tempName[FILENAME_SIZE];
+
+	if( checkOutputIsLocalFolder() ) return true;
+	
+	dir = opendir( miOutputPathName );
+	if( dir == NULL ) return false;
+
+	struct dirent * ptr;
+	while( (ptr = readdir(dir)) != NULL )
+	{
+		if( ptr->d_name[0] == '.' ) continue;
+		snprintf( tempName, sizeof(tempName), "%s/%s", miOutputPathName, ptr->d_name );
+		chmod( tempName,  0777 );
+	} 
+	closedir(dir);
+	return true;
+}
+
+static inline void createOutputFolder()
+{
+	if( checkOutputIsLocalFolder() ) return;
+	deleteContextOfOutputFolder();
+	mkdir( miOutputPathName, 0777 );
+	chmod( miOutputPathName, 0777 );
+}
+
+bool copyToOutputFolder( const char *targetName, const char *srcName  )
+{
+	char saveFullyName[FILENAME_SIZE];
+	snprintf( saveFullyName, sizeof(saveFullyName), "%s/%s", miOutputPathName, targetName );	
+	dbgMsg( "[copyToOutputFolder] %s\n", saveFullyName );	
+	return copyFile( saveFullyName, srcName, 0 );	
+}
+
+//-------------------------------------------------------------------------------
+
+void stuff_File_with_zero(FILE *fpIn, u32 size)
+{
+	int i =0, buffer = 0;
+	for(i=0; i < size; i++)
+		fwrite( &buffer, 1, 1, fpIn );
+	
+}
+bool copyFileContent( FILE *fpOut, const char *sourceFileName, u32 cpySize )
+{
+	FILE *fpIn;
+	int i, readSize, fileSize;
+	u8 readBuf[TMP_BUFFER_SIZE] = {0};	
+
+	fileSize = getFileSize( sourceFileName );
+	if( fileSize == 0 )
+	{
+		errMsg( "FileSize (%s) is zero!\n", sourceFileName );
+		return false;
+	}
+	
+	if( (cpySize != 0) && ( cpySize <= fileSize ) )  fileSize = cpySize;
+	fpIn = fopen( sourceFileName, "rb" );
+	if( fpIn == NULL )
+	{
+		errMsg( "File (%s) is not exist\n", sourceFileName );
+		return false;
+	}
+
+	for( i = 0; i < fileSize; i+= TMP_BUFFER_SIZE )
+	{
+		readSize = fread( readBuf, 1, TMP_BUFFER_SIZE, fpIn );
+        	if( readSize < 0 )
+        	{
+            		errMsg( "fread (%s)\n", sourceFileName ); 
+			return false;
+        	} 
+		fwrite( readBuf, 1, readSize, fpOut );
+	}
+
+	fclose( fpIn );
+	return true;
+}
+bool copyFile( const char *targetName, const char *sourceName, u32 cpySize )
+{
+	bool ret;
+	FILE *fpOut = fopen( targetName, "wb" );
+
+	if( fpOut == NULL )
+	{
+		errMsg( "Create writable file failed (%s)\n", targetName );
+		return false;
+	}
+	
+	ret = copyFileContent( fpOut, sourceName, cpySize );
+	fclose( fpOut );
+	//dbgMsg( "copyFile %d\n", ret );
+	return ret;
+}
+
+//-------------------------------------------------------------------------------
+#if 0
+static inline bool stripFlashBin()
+{
+	bool ret;
+	u32 codeValidSize, dataValidSize;
+
+	dbgMsg( "\nstripFlashBin ==>\n" );
+	
+	ret = calculateImageValidSize( &codeValidSize, &dataValidSize );
+	dbgMsg( "FlashValidSize: Code=%dKB, Data=%dKB\n", codeValidSize, dataValidSize );
+
+	codeValidSize *= 1024;
+	dataValidSize *= 1024;
+	
+	if( ret ) ret = copyFile( FILENAME_CODEVALID, FILENAME_CODEBIN, codeValidSize );
+	if( ret && dataValidSize ) ret = copyFile( FILENAME_DATAVALID, FILENAME_DATABIN, dataValidSize );
+#if 0
+	removeTempFile( FILENAME_CODEBIN );
+	removeTempFile( FILENAME_DATABIN );	
+#endif
+	return ret;
+}
+#endif
+//-------------------------------------------------------------------------------
+
+static inline void clearTemporaryFlies()
+{
+	//removeTempFile( FILENAME_CODEVALID );
+	//removeTempFile( FILENAME_DATAVALID );
+	removeTempFile( FILENAME_PACKETSAVE );
+	//removeTempFile( FILENAME_PACKETIMAGE );
+	removeTempFile( FILENAME_CODEBIN );
+	//removeTempFile( FILENAME_BINWITHINFO );
+	//if( isLoadBasicPacket() ) freeBasicPacket();
+
+#if MI_COPY_MERGE_SOURCE
+	//removeTempFile(flashModuleInfo[MODULE_BOOTROM].tmpBinName);
+	//removeTempFile(flashModuleInfo[MODULE_AUDIOROM].tmpBinName);	
+#endif
+}
+#if 0
+static inline bool generatePacketBin( const char *targetName )
+{
+	bool ret = true;
+	dbgMsg( "\ngeneratePacketBin ==>\n" ); 
+
+	FILE *fpOut = fopen( FILENAME_PACKETIMAGE, "wb" );
+	if( fpOut == NULL ) return false;
+
+	if( ret ) ret = copyFileContent( fpOut, FILENAME_PACKETSAVE, 0 );
+	fseek( fpOut, SAVEINFO_SIZE, SEEK_SET );
+	
+	if( ret ) ret = copyFileContent( fpOut, FILENAME_CODEVALID, 0 );
+
+#if( CONFIG_DATA_FLASH_SIZE != 0  )
+	if( ret ) ret = copyFileContent( fpOut, FILENAME_DATAVALID, 0 );
+#endif
+	
+	fclose( fpOut );
+	copyToOutputFolder( targetName, FILENAME_PACKETIMAGE );
+	
+	return ret;
+}
+#endif
+static inline bool generateBinwithInfo( const char *targetName )
+{
+	bool ret = true;
+	int _SaveFile_size;
+	dbgMsg( "\ngenerateBinwithInfo ==>\n" ); 
+
+	FILE *fpOut = fopen( targetName, "wb" );
+	if( fpOut == NULL ) return false;
+
+	if( ret ) ret = copyFileContent( fpOut, FILENAME_CODEBIN, 0 );
+
+	//size will be KB alignment,
+	if( ret ) ret = copyFileContent( fpOut, FILENAME_PACKETSAVE, 0 );
+	//get _SaveFile_size (4 byte alignment)
+	_SaveFile_size = ROUND_UP(getFileSize(FILENAME_PACKETSAVE),4)*4;
+	stuff_File_with_zero(fpOut, _SaveFile_size- getFileSize(FILENAME_PACKETSAVE));
+	//write .save size to last word
+	_SaveFile_size = _SaveFile_size+sizeof(_SaveFile_size);	//add _SaveFile_size itself
+	fwrite( &_SaveFile_size, sizeof(_SaveFile_size), 1, fpOut );
+	fclose( fpOut );
+	//copyToOutputFolder( targetName, FILENAME_BINWITHINFO );
+	
+	return ret;
+}
+
+bool mergeImageMain()
+{
+	bool ret = true;
+	createOutputFolder();
+	//transfer ini to bins
+	if( ret ) ret = genTempBinFiles();
+#if 0
+	if( ret ) ret = generateFlashBin();
+#else
+	if( ret ) ret = MergeBins2Mem();	//just a test
+#endif
+#if 0
+	if( miGenerateOriginalBinFlag && ret ) ret = generateBinSaveInfo();
+#endif
+
+	if( miGeneratePacketFlag ) 
+	{
+	//	if( ret ) ret = stripFlashBin();
+		if( ret ) ret = generateSaveInfo();
+		//if( ret ) ret = generatePacketBin( miPacketName );
+		//append .save to bin file end
+		if( ret ) ret = generateBinwithInfo( miBinWithInfo );
+	}
+
+	clearTemporaryFlies();
+	//chmodOutputFolder();
+	return ret;
+}
+
+
+
+
+

+ 23 - 0
tools/mergeImage/generateOutput.h

@@ -0,0 +1,23 @@
+//-------------------------------------------------------------------------------
+// generateOutput
+//-------------------------------------------------------------------------------
+#ifndef _GENERATEOUTPUT_H_
+#define _GENERATEOUTPUT_H_
+//-------------------------------------------------------------------------------
+#include "mergeImage.h"
+//-------------------------------------------------------------------------------
+bool mergeImageMain();
+bool copyToOutputFolder( const char *targetName, const char *srcName  );
+bool copyFile( const char *targetName, const char *sourceName, u32 cpySize );
+bool copyFileContent( FILE *fpOut, const char *sourceFileName, u32 cpySize );
+void removeTempFile( const char *fileName );
+void stuff_File_with_zero(FILE *fpIn, u32 size);
+
+
+//-------------------------------------------------------------------------------
+#endif
+
+
+
+
+

+ 298 - 0
tools/mergeImage/generateSave.c

@@ -0,0 +1,298 @@
+//---------------------------------------------------------------------------
+#include "generateSave.h"
+//---------------------------------------------------------------------------
+#include "parseConfig.h"
+#include "generateOutput.h"
+//---------------------------------------------------------------------------
+// calculate CheckSum
+//---------------------------------------------------------------------------
+
+#if 0
+
+static inline u32 calculateMemoyCheckSum( u8 *mem, u32 size )
+{
+	int i; u32 checkSum = 0;
+	for( i = 0; i < size; i++ ) checkSum += mem[i];
+	return checkSum;
+}
+
+u32 calculateFileCheckSum( const char *fileName, u32 fileSizeKB )
+{
+	FILE *fp; int i;
+	u32 checkSum = 0;
+	u32 fileSize = fileSizeKB * 1024;
+	u8 readBuf[TMP_BUFFER_SIZE] = {0};
+
+	fp = fopen( fileName, "rb" );
+	for( i = 0; i < fileSize; i+= TMP_BUFFER_SIZE )
+	{
+		if( fread( readBuf, 1, TMP_BUFFER_SIZE, fp ) <= 0 ) break;
+		checkSum += calculateMemoyCheckSum( readBuf, TMP_BUFFER_SIZE );
+	}
+	fclose( fp );
+
+    	return checkSum;
+}
+#endif
+
+//---------------------------------------------------------------------------
+// calculate CRC32
+//---------------------------------------------------------------------------
+
+unsigned int crcTable[256] = {
+0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
+0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
+0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
+0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
+0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
+0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
+0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
+0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
+0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106,
+0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
+0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
+0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
+0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
+0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
+0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA,
+0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
+0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
+0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84,
+0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
+0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
+0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,
+0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
+0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
+0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28,
+0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
+0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
+0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
+0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
+0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
+0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
+0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
+0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
+0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
+};
+
+static inline u32 memCRC32_separate(u8 *pData, int len, u32 finalCrc )
+{
+	int i;
+	for(i=0; i<len; i++)
+	{
+		u32 c = (unsigned int)pData[i];
+        	finalCrc = ((finalCrc>>8) & 0x00FFFFFF) ^ crcTable[ (finalCrc^c) & 0xFF ];
+	}
+
+	return finalCrc;
+}
+
+unsigned int memCRC32(char *pData, int len)
+{
+    unsigned int crc;
+    int i;
+    unsigned int c;
+
+    crc = 0xFFFFFFFF;
+    for(i=0; i<len; i++)
+    {
+        c = (unsigned int)pData[i];
+        crc = ((crc>>8) & 0x00FFFFFF) ^ crcTable[ (crc^c) & 0xFF ];
+    }
+    return( crc^0xFFFFFFFF );
+}
+
+
+#if 0
+u32 calculateFileCRC32( const char *fileName, u32 fileSizeKB )
+{
+	FILE *fp; int i;
+	u32 crc = 0xFFFFFFFF;
+	u8 readBuf[TMP_BUFFER_SIZE] = {0};
+	u32 fileSize = fileSizeKB * 1024;
+
+	dbgMsg( "calculateFileCRC32: %s, %d KB\n", fileName, fileSizeKB );
+
+	fp = fopen( fileName, "rb" );
+	for( i = 0; i < fileSize; i+= TMP_BUFFER_SIZE )
+	{
+		if( fread( readBuf, 1, TMP_BUFFER_SIZE, fp ) <= 0 ) break;
+		crc = memCRC32_separate( readBuf, TMP_BUFFER_SIZE, crc );
+	}
+	fclose( fp );
+
+	return( crc^0xFFFFFFFF );
+}
+#else
+u32 calculateFileCRC32( const char *fileName)
+{
+	FILE *fp; int i;
+	u32 crc = 0xFFFFFFFF;
+	u8 readBuf[TMP_BUFFER_SIZE] = {0};
+	int read_size = 0;
+	u32 fileSize = getFileSize(fileName);
+
+	dbgMsg( "calculateFileCRC32: %s\n", fileName);
+
+	fp = fopen( fileName, "rb" );
+	for( i = 0; i < fileSize; i+= TMP_BUFFER_SIZE )
+	{
+		read_size = fread( readBuf, 1, TMP_BUFFER_SIZE, fp );
+		if(read_size <=0)
+			break;
+		crc = memCRC32_separate( readBuf, read_size, crc );
+	}
+	fclose( fp );
+
+	return( crc^0xFFFFFFFF );
+}
+
+#endif
+//---------------------------------------------------------------------------
+
+static inline void writeInfo_CodeFlash( FILE *fp, u32 codeCRC )
+{
+	fprintf( fp, "[CODE]\n");
+	fprintf( fp, "#codecrccheck\n");
+	fprintf( fp, "0x%08x\n", codeCRC );
+	//fprintf( fp, "#codevalidsize\n");
+	//fprintf( fp, "0x%08x\n", validSizeKB*1024 );
+	fprintf( fp, "\n" );
+}
+
+static inline void writeInfo_DataFlash( FILE *fp, u32 dataCRC )
+{
+	fprintf( fp, "[DATA]\n");
+	fprintf( fp, "#datacrccheck\n");
+	fprintf( fp, "0x%08x\n", dataCRC );
+	//fprintf( fp, "#datavalidsize\n");
+	//fprintf( fp, "0x%08x\n", validSizeKB*1024 );
+	fprintf( fp, "\n" );
+}
+
+static inline void writeInfo_Model( FILE *fp, u32 blockId, const char *protectId, const char *timestamp )
+{
+	fprintf( fp, "[MODEL]\n");
+	fprintf( fp, "#blockID\n");
+	fprintf( fp, "%d\n", blockId );
+	fprintf( fp, "#projectID\n");
+	fprintf( fp, "%s\n", protectId );
+	fprintf( fp, "#timestamp\n");
+	fprintf( fp, "%s\n", timestamp );
+	fprintf( fp, "\n" );
+}
+
+static inline void writeInfo_Protected( FILE *fp, const char *module )
+{
+	fprintf( fp, "#module\n");
+	fprintf( fp, "%s\n", module );
+	fprintf( fp, "\n" );
+}
+
+static inline void writeInfo_End( FILE *fp )
+{
+	fprintf( fp, "#END\n" );
+}
+
+static inline bool generateInfo_Protected( FILE *fpOut, NorFlashModuleInfo *info )
+{
+	int i;
+	for( i = 0; i < MODULE_MAX; i++ )
+	{
+		if( !info[i].isProtected ) continue;
+		writeInfo_Protected( fpOut, info[i].moduleName );
+
+	//	if( (info[i].flashAddr2) && (info[i].flashSize2) )
+	//		writeInfo_Protected( fpOut, info[i].moduleName, info[i].flashAddr2, info[i].flashSize2 );
+	}
+
+	return true;
+}
+#if 0
+static inline bool getTimeStamp( const char *fileName, char *timeStamp )
+{
+	FILE *fpIn = fopen( fileName, "rt" );
+    	if( fpIn == NULL )
+  	{
+  		showMsg( "TimeStamp (%s) not found!\n", fileName );
+		strcpy( timeStamp, "0" );
+		return false;
+  	}
+
+	timeStamp = fgetLine( timeStamp, TMP_BUFFER_SIZE, fpIn );
+	if( timeStamp != NULL ) dbgMsg( "=>TimeStamp: %s\n", timeStamp );
+	fclose( fpIn ); return (timeStamp != NULL);
+}
+#endif
+bool generateSaveInfo(void)
+{
+	FILE *fp;
+	//char timeStamp[TMP_BUFFER_SIZE];
+	dbgMsg( "\ngenerateSaveInfo ==> %s\n", FILENAME_CODEBIN );
+	u32 codeCRC = calculateFileCRC32(FILENAME_CODEBIN);
+
+	//getTimeStamp( FILENAME_TIMESTAMP, timeStamp );
+
+
+	fp = fopen( FILENAME_PACKETSAVE, "wt" );
+	if( fp == NULL ) return false;
+
+	writeInfo_CodeFlash( fp, codeCRC );
+	//writeInfo_Model( fp, 0, "MON-SIS330", timeStamp );
+	generateInfo_Protected( fp, flashModuleInfo );
+
+	writeInfo_End( fp );
+	fclose( fp );
+	return true;
+}
+#if 0
+bool generatePacketSaveInfo()
+{
+	u32 codeCRC, dataCRC = 0;
+	u32 codeValidSizeKB, dataValidSizeKB;
+
+	if( !calculateImageValidSize( &codeValidSizeKB, &dataValidSizeKB ) ) return false;
+
+	codeCRC = calculateFileCRC32( FILENAME_CODEVALID, codeValidSizeKB );
+
+#if( CONFIG_DATA_FLASH_SIZE != 0  )
+	dataCRC = calculateFileCRC32( FILENAME_DATAVALID, dataValidSizeKB );
+#endif
+
+	return generateSaveInfo( FILENAME_PACKETSAVE, codeCRC, dataCRC );
+}
+
+bool generateBinSaveInfo()
+{
+	bool ret;
+	u32 codeCRC, dataCRC = 0;
+
+	codeCRC = calculateFileCRC32( FILENAME_CODEBIN, CONFIG_CODE_FLASH_SIZE );
+
+#if( CONFIG_DATA_FLASH_SIZE != 0  )
+	dataCRC = calculateFileCRC32( FILENAME_DATABIN, CONFIG_DATA_FLASH_SIZE );
+#endif
+
+	ret = generateSaveInfo( FILENAME_SAVEINFO, codeCRC, dataCRC );
+	if( ret )
+	{
+		copyToOutputFolder( miSaveInfoName, FILENAME_SAVEINFO );
+		removeTempFile( FILENAME_SAVEINFO );
+	}
+	return ret;
+}
+#endif
+
+
+
+

+ 18 - 0
tools/mergeImage/generateSave.h

@@ -0,0 +1,18 @@
+//-------------------------------------------------------------------------------
+// generate SAVE
+//-------------------------------------------------------------------------------
+#ifndef _GENERATESAVE_H_
+#define _GENERATESAVE_H_
+//-------------------------------------------------------------------------------
+#include "mergeToBin.h"
+//-------------------------------------------------------------------------------
+bool generatePacketSaveInfo();
+bool generateBinSaveInfo();
+unsigned int memCRC32(char *pData, int len);
+
+//-------------------------------------------------------------------------------
+#endif
+
+
+
+

+ 23 - 0
tools/mergeImage/gpioset.h

@@ -0,0 +1,23 @@
+typedef struct _ADJUST_GPIO {
+	unsigned char	GPIO[256];
+}ADJUST_GPIO, *PADJUST_GPIO;
+
+typedef struct _ADJUST_GPIO_ITEM { //
+	unsigned char	pGPIOData[256];	//0x7f8~0x8f7   struct ADJUST_GPIO will copy there     
+}ADJUST_GPIO_ITEM, *PADJUST_GPIO_ITEM;
+
+typedef struct _GPIO_FORMAT {
+	unsigned char	index;			// 0~63
+	unsigned char	AuxEnalbe;		// Enable GPIO function 0:disable; 1:enable
+	unsigned char	AuxMode;		// 0: output; 1: input; 2: open drain
+	unsigned char	AuxValue;		// 0:low; 1:high
+	unsigned char	AInternalPU;	// 0:disable/1:enable pull high 
+	unsigned char	AInternalPD;	// 0:disable/1:enable pull low 
+	unsigned char	MainEnalbe;		// Enable GPIO function 0:disable; 1:enable
+	unsigned char	MainMode;		// 0: output; 1: input; 2: open drain
+	unsigned char	MainValue;		// 0:low; 1:high
+	unsigned char	MInternalPU;	// 0:disable/1:enable pull high 
+	unsigned char	MInternalPD;	// 0:disable/1:enable pull low 
+	unsigned char	MDELAY_TIME;
+}GPIO_FORMAT, *PGPIO_FORMAT;
+

+ 23 - 0
tools/mergeImage/init_flash_module.h

@@ -0,0 +1,23 @@
+/* This file is auto generated by ./tools/gen_flash_layout.py, don't modify~~ */
+
+static inline void initNorFlashModuleInfo(void)
+{
+    initFlashModuleInfo( MODULE_BOOTROM, "BootROM", 0, 0);
+    initFlashModuleInfo( MODULE_OPTION, "Option", 0, 0);
+    initFlashModuleInfo( MODULE_OUIBOOTINFO, "OUIBOOTinfo", 0, 0);
+    initFlashModuleInfo( MODULE_KERNEL, "Kernel", 0, 0);
+    initFlashModuleInfo( MODULE_OUIMAININFO, "OUIMAINinfo", 0, 0);
+    initFlashModuleInfo( MODULE_CUSTABLE, "Custable", 0, 0);
+    initFlashModuleInfo( MODULE_DEFPANEL, "DefPanel", 0, 0);
+    initFlashModuleInfo( MODULE_GAMMATABLE, "GammaTable", 0, 0);
+    initFlashModuleInfo( MODULE_VIPTABLE, "VIPTable", 0, 0);
+    initFlashModuleInfo( MODULE_CLUPTABLE, "CLUPTable", 0, 0);
+    initFlashModuleInfo( MODULE_IRCN31661, "IRCN31661", 0, 0);
+    initFlashModuleInfo( MODULE_KEYPAD, "KeyPad", 0, 0);
+    initFlashModuleInfo( MODULE_WBDATA, "WBdata", 0, 0);
+    initFlashModuleInfo( MODULE_EDID, "EDID", 0, 0);
+    initFlashModuleInfo( MODULE_HDCPKEY, "HDCPKey", 0, 0);
+    initFlashModuleInfo( MODULE_END, "END", 0, 0);
+    initFlashModuleInfo( MODULE_NVM, "NVM", 0, 0);
+}
+

+ 60 - 0
tools/mergeImage/irset.h

@@ -0,0 +1,60 @@
+//Data valu is Hex format
+
+#define OP_IR_HP_tpw0			0x0188		// first power key(cmd + address_MSB) CVT_Factory_RC 
+#define OP_IR_HP_tpw1			0xD708		// second power key(cmd + address_MSB) CVT_K_RC
+#define OP_IR_HP_polarity		0x90		// first customer code( address bar_LSB)
+#define OP_IR_HP_type			0xf7		// second customer code( address bar_LSB)
+#define OP_IR_HP_space		0x01
+#define OP_IR_HP_rc5_type		0x00
+#define OP_IR_HP_timeout		0x384
+#define OP_IR_HP_code			0x01
+#define OP_IR_HP_headcount	0x02
+#define OP_IR_HP_len1			0x21
+#define OP_IR_HP_al1			0x08
+#define OP_IR_HP_cl1			0x08
+#define OP_IR_HP_len2			0x00
+#define OP_IR_HP_al2			0x00
+#define OP_IR_HP_cl2			0x00
+#define OP_IR_HP_aoffset1		0x18
+#define OP_IR_HP_coffset1		0x08
+#define OP_IR_HP_aoffset2		0x00
+#define OP_IR_HP_coffset2		0x00
+#define OP_IR_HP_offset00		0x0014406b
+#define OP_IR_HP_offset04		0x01114015
+#define OP_IR_HP_offset08		0x01384000
+// 
+#define OP_IR_SET_00			0x88930324			//0x770	// 0x04
+#define OP_IR_SET_01			0x000f0000
+#define OP_IR_SET_02			0x00000000
+#define OP_IR_SET_03			0x01b001b0			// 0x10
+#define OP_IR_SET_04			0x010e0050
+#define OP_IR_SET_05			0x00430028
+#define OP_IR_SET_06			0x00430028
+#define OP_IR_SET_07			0x00ca0079			// 0x20
+#define OP_IR_SET_08			0x04380288
+#define OP_IR_SET_09			0x021c0144
+#define OP_IR_SET_10			0x00000000
+#define OP_IR_SET_11			0x010e00a2			// 0x30
+#define OP_IR_SET_12			0x00000002
+#define OP_IR_SET_13			0x00000000
+#define OP_IR_SET_14			0x00000000
+#define OP_IR_SET_15			0x00020102			// 0x40
+#define OP_IR_SET_16			0x16022d60
+#define OP_IR_SET_17			0x00000000
+#define OP_IR_SET_18			0x00b02009
+#define OP_IR_SET_19			0x00000000			// 0x50
+#define OP_IR_SET_20			0x00000000
+#define OP_IR_SET_21			0x00000000
+#define OP_IR_SET_22			0x00000003
+#define OP_IR_SET_23			0x906fa25d			// 0x60
+#define OP_IR_SET_24			0x00000000
+#define OP_IR_SET_25			0x00000000
+#define OP_IR_SET_26			0x00000000
+#define OP_IR_SET_27			0x00000000			// 0x70
+#define OP_IR_SET_28			0x00000000
+#define OP_IR_SET_29			0x00000000
+#define OP_IR_SET_30			0x00000000
+#define OP_IR_SET_31			0x00000000			// 0x80
+#define OP_IR_SET_32			0x00000000			//0x7f0
+//-------------        
+

+ 95 - 0
tools/mergeImage/loadBasicPacket.c

@@ -0,0 +1,95 @@
+//-------------------------------------------------------------------------------
+#include "loadBasicPacket.h"
+//-------------------------------------------------------------------------------
+#include "generateSave.h"
+#include "generateBin.h"
+#include "generateOutput.h"
+//-------------------------------------------------------------------------------
+
+bool isLoadBasicPacket( void )
+{
+	return (strlen( miBaseImageName ) != 0);
+}
+
+//-------------------------------------------------------------------------------
+
+void freeBasicPacket( void )
+{
+	removeTempFile( BASEIMAGE_CODEBIN );
+	removeTempFile( BASEIMAGE_SAVE );
+	
+#if( CONFIG_DATA_FLASH_SIZE != 0  )
+	removeTempFile( BASEIMAGE_DATABIN );
+#endif
+}
+
+static inline bool generateDecryptFlashBin( const char *tmp, const char *final )
+{
+	dbgMsg( "[generateDecryptFlashBin]\n" );
+	if( sisspi_encrypt( tmp, final, false ) )
+	{
+		errMsg( "decrypt failed\n"); return false;
+	}
+
+	removeTempFile( tmp );
+	return true;
+}
+
+static inline bool outputFileContent(  const char *targetName, FILE *fpIn, u32 cpySize )
+{
+	FILE *fpOut; int readSize;
+	u8 readBuf[TMP_BUFFER_SIZE] = {0};	
+
+	fpOut = fopen( targetName, "wb" );
+	if( fpOut == NULL )
+	{
+		errMsg( "File (%s) can not create\n", targetName );
+		return false;
+	}
+
+	while( (!feof( fpIn)) && (cpySize) )
+	{
+		readSize = fread( readBuf, 1, MIN(TMP_BUFFER_SIZE,cpySize), fpIn );
+        	if( readSize < 0 ) return true;
+			
+		fwrite( readBuf, 1, readSize, fpOut );
+		cpySize -= readSize;
+	}
+
+	fclose( fpOut );
+	return true;
+}
+
+bool separateBasicPacket()
+{
+	if( !isLoadBasicPacket() ) return true;
+
+	showMsg( "miBasicPacketImage: %s\n", miBaseImageName );
+
+	bool ret = true;
+	FILE *fpIn= fopen( miBaseImageName, "rb" );
+	if( fpIn == NULL ) return false;
+
+	if( ret ) ret = outputFileContent( BASEIMAGE_SAVE, fpIn, SAVEINFO_SIZE );
+	if( ret ) ret = outputFileContent( BASEIMAGE_CODETMP, fpIn, CONFIG_CODE_FLASH_SIZE*1024 );
+	if( ret ) ret = generateDecryptFlashBin( BASEIMAGE_CODETMP, BASEIMAGE_CODEBIN );
+
+#if( CONFIG_DATA_FLASH_SIZE != 0  )
+	if( ret ) ret = outputFileContent( BASEIMAGE_DATATMP, fpIn, CONFIG_DATA_FLASH_SIZE*1024 );
+	if( ret ) ret = generateDecryptFlashBin( BASEIMAGE_DATATMP, BASEIMAGE_DATABIN );
+#endif
+
+	fclose( fpIn );
+	return ret;
+}
+
+//-------------------------------------------------------------------------------
+
+bool loadBasicPacket()
+{
+	if( !separateBasicPacket() ) return false;
+	return true;
+}
+
+
+

+ 21 - 0
tools/mergeImage/loadBasicPacket.h

@@ -0,0 +1,21 @@
+//-------------------------------------------------------------------------------
+// load Basic packet
+//-------------------------------------------------------------------------------
+#ifndef _LOADBASICPACKET_H_
+#define _LOADBASICPACKET_H_
+//-------------------------------------------------------------------------------
+#include "mergeImage.h"
+//-------------------------------------------------------------------------------
+#define BASEIMAGE_SAVE			"bi.save"
+#define BASEIMAGE_CODEBIN		"bi_code.bin"
+#define BASEIMAGE_DATABIN		"bi_data.bin"
+
+#define BASEIMAGE_CODETMP		"bi_code.tmp.bin"
+#define BASEIMAGE_DATATMP		"bi_data.tmp.bin"
+//-------------------------------------------------------------------------------
+bool loadBasicPacket();
+bool isLoadBasicPacket( void );
+void freeBasicPacket();
+//-------------------------------------------------------------------------------
+#endif
+

+ 38 - 0
tools/mergeImage/makefile

@@ -0,0 +1,38 @@
+include ../../Makefile.project
+target = mergeImage
+CC = gcc -m32
+LIB = spi_encrypt.o
+CFLAGS = -O2 -Wall -Werror
+CINCLUDE = -I../../drivers/include/ -I../../drivers/module_include/ -I../../mergedir/option
+
+#ifeq ($(CONFIG_VERSION),release)
+#        CFLAGS += -DRELEASE_VER
+#endif
+
+.PHONY: all clean
+all: mkdir_ojbs $(target)
+
+source += $(wildcard *.c)
+objs := $(source:%.c=objs/%.o)
+
+
+$(target): $(objs)
+	@echo Building $@
+	$(CC) -o $@ $(LDFLAGS) $^ $(LIB)
+
+# one pass sequence
+objs/%.o : %.c
+	@echo Compiling $<
+	@$(CC) $(CFLAGS) $(CINCLUDE) -MMD -c -o $@ $<
+
+
+clean: rmdir_objs
+	@rm -f $(target)
+
+mkdir_ojbs:
+	@if [ ! -d "objs" ] ; then mkdir objs; fi
+
+rmdir_objs:
+	@if [ -d "objs" ]; then rm -rf objs; fi
+
+-include $(source:%.c=objs/%.d)

+ 155 - 0
tools/mergeImage/mergeImage.c

@@ -0,0 +1,155 @@
+//-------------------------------------------------------------------------------
+#include "generateBin.h"
+#include "generateSave.h"
+#include "generateOutput.h"
+#include <dirent.h>
+//-------------------------------------------------------------------------------
+#ifdef _windows_
+#include <cstdlib>
+#endif
+//-------------------------------------------------------------------------------
+
+char miPacketName[FILENAME_SIZE];
+char miCodeBinName[FILENAME_SIZE];
+char miDataBinName[FILENAME_SIZE];
+char miBinWithInfo[FILENAME_SIZE];
+
+char miSaveInfoName[FILENAME_SIZE];
+char miConfigFile[FILENAME_SIZE];
+char miBaseImageName[FILENAME_SIZE];
+char miOutputPathName[FILENAME_SIZE];
+bool miGeneratePacketFlag = MI_DFT_GENERATE_PACKET;
+bool miDeleteTempFileFlag = MI_DFT_DELETE_TEMP_FILE;
+bool miGenerateOriginalBinFlag = MI_DFT_GENERATE_ORI_BIN;
+bool miJudgeDebugVersionFlag = MI_DFT_JUDGE_DBG_VERSION;
+
+//---------------------------------------------------------------------------
+
+#define DEBUG_VERSION_KEYWORD	"_dbg"
+
+#if 0
+#ifdef RELEASE_VER
+	const bool isDebugVersion = false;
+#else
+	const bool isDebugVersion = true;
+#endif
+
+static inline bool checkVersionFormat( const char *fileName )
+{
+	bool foundDebugString = false;
+
+	if( strstr( fileName, DEBUG_VERSION_KEYWORD ) ) foundDebugString  = true;
+	if( foundDebugString == isDebugVersion ) return true;
+
+	dbgMsg( "Check debug/release version failed!\n");
+	return false;
+}
+
+static inline bool searchMatchFile( const char *dirName, const char* searchKey, char* matchFileName, bool judgeDebugVersion )
+{
+	bool found = false;
+	DIR *dir = opendir( dirName );
+	if( dir == NULL ) return false;
+
+	struct dirent * ptr;
+	while( (ptr = readdir(dir)) != NULL )
+	{
+		if( ptr->d_name[0] == '.' ) continue;
+
+		if( strstr( ptr->d_name, searchKey ) )
+		{
+			dbgMsg( "Found match file: %s\n",  ptr->d_name );
+			if( judgeDebugVersion && !checkVersionFormat( ptr->d_name ) ) continue;
+			if( !found ) sprintf( matchFileName, "%s/%s", dirName, ptr->d_name );
+			else showMsg( "\n[WARING] Find another file match search rule: %s!!!!\n\n", ptr->d_name );
+			found = true;
+		}
+	} 
+	closedir(dir);
+	return found;
+}
+#endif
+#if 0
+
+static inline bool copyAudioROM()
+{
+	char searchKey[FILENAME_SIZE]; char fileName[FILENAME_SIZE];
+	NorFlashModuleInfo *moduleInfo = searchModuleInfo( MODULENAME_AUDIOROM );
+	NorFlashModulePathInfo* modulePathInfo = searchModulePathInfo( MODULENAME_AUDIOROM );
+	if( (moduleInfo == NULL) || (modulePathInfo==NULL)  ) return false;
+	if( !moduleInfo->isValid  ) return true;	/* skip AudioROM */
+	
+	sprintf( searchKey, "%dK", ROUND_KB( SPI_AUDIOROM_FLASHSIZE ) );
+	if( !searchMatchFile( modulePathInfo->pathName, searchKey, fileName, false ) )
+	{
+		showMsg( "copyAudioROM failed, directory: %s, searchKey: %s\n", modulePathInfo->pathName, searchKey );
+		return false;
+	}
+
+	showMsg( "copyAudioROM: %s\n", fileName );
+	return copyFile( moduleInfo->fileName, fileName, 0 );
+}
+
+static inline bool copyBootROM()
+{
+	char searchKey[FILENAME_SIZE]; char fileName[FILENAME_SIZE];
+	NorFlashModuleInfo *moduleInfo = &flashModuleInfo[MODULE_BOOTROM];//searchModuleInfo( MODULENAME_BOOTROM );
+	NorFlashModulePathInfo* modulePathInfo = searchModulePathInfo( MODULENAME_BOOTROM );	
+	if( (moduleInfo == NULL) || (modulePathInfo==NULL)  ) return false;
+	if( !moduleInfo->isValid ) return true;	/* skip BootROM */		
+	
+	sprintf( searchKey, "C%dM_D%dM_A%dK", ROUND_KB( CONFIG_CODE_FLASH_SIZE ), 
+		ROUND_KB( CONFIG_DATA_FLASH_SIZE ), ROUND_KB( SPI_AUDIOROM_FLASHSIZE ) );
+
+	if( !searchMatchFile( modulePathInfo->pathName, searchKey, fileName, miJudgeDebugVersionFlag ) )
+	{
+		showMsg( "copyBootROM failed, directory: %s, searchKey: \"%s\" \n", modulePathInfo->pathName, searchKey );
+		return false;
+	}
+
+	showMsg( "copyBootROM: %s\n", fileName );	
+	return copyFile( moduleInfo->fileName, fileName, 0 );
+}
+#endif
+#if 0
+bool copyMergeSource()
+{
+	// TODO: sync AudioROM & BootROM
+#if MI_COPY_MERGE_SOURCE
+	dbgMsg( "\n== copyMergeSource ==\n" );
+
+	if( miJudgeDebugVersionFlag ) 
+	{
+		showMsg( "Enable Judge debug/release Version feature : "
+			"BootROM filename %s include \"%s\" string\n", isDebugVersion ? "must" : "can't", DEBUG_VERSION_KEYWORD );
+	}
+
+	if( !copyBootROM() ) return false;
+ 	if( !copyAudioROM() ) return false;
+#endif
+	
+	return true;
+}
+#endif
+//---------------------------------------------------------------------------
+int main(int argc, char *argv[])
+{
+	bool ret = true;
+	showMsg( "\n**** MergeNorFlashImage ... Version: 2012/11/27 ****\n");
+
+	if( parseProgArg( argc, argv ) )
+	{
+		if(ret) ret = loadNorFlashModuleInfo();
+	//	if(ret) ret = copyMergeSource();
+		if(ret) ret = mergeImageMain();	
+		showMsg( "\n\"%s\" %s!!\n\n", miBinWithInfo, ret ? "Success" : "Failed" );
+	}
+
+#ifdef _windows_
+	system("PAUSE");
+#endif
+
+	return (ret ? 0 : -1);
+}
+
+

+ 118 - 0
tools/mergeImage/mergeImage.cfg

@@ -0,0 +1,118 @@
+# ---------------------------------------------------------------------------------------
+# This file is a sample profile for mergeImage configuration. (Version5)
+# ---------------------------------------------------------------------------------------
+# NOTE:
+# 1. The mergeImage will parse filename as "mergeImage.cfg" by default.
+# 	If you want to select another profile for mergeImage, 
+# 	please define extra config MERGEFEATURE="<filename>" with build-system.
+#
+# 2. The mergeImage will automatically select corresponding BootROM and AudioROM.
+#	Please prepare the search folder as define in @PathName.
+#	And place corresponding files according to the naming rules.
+#
+# => BootROM naming rules: must include keyword <CXM_DXM_AXXXK>
+#	CXM: code-flash size.
+#	DXM: data-flash size.
+#	AXXXK: AudioROM size.
+#	example: brv330_C4M_D2M_A320K_a12.bin
+#
+# => AudioROM naming rules:  must include keyword <XXXK>
+#	XXK: AudioROM size.
+#	example: AudioRom_330_192K_a12.bin
+#
+# ---------------------------------------------------------------------------------------
+
+
+@BasicPacket
+# ---------------------------------------------------------------------------------------
+# Please specify the reference basic pacekt filename.
+# ---------------------------------------------------------------------------------------
+# BasicPacket=./Base/formal_EU_0807.base.packet
+
+@Output
+# ---------------------------------------------------------------------------------------
+# Please specify the output folder or other flags for mergeImage tools. 
+# ---------------------------------------------------------------------------------------
+Folder=./Output/
+judgeDebugVersion=y
+
+@PathName
+# ---------------------------------------------------------------------------------------
+# Please specify the search folder for each module. 
+# If no define or leave blank, then default folder will be "BootROM" and "AudioROM".
+# ---------------------------------------------------------------------------------------
+BootROM=./Formal_330/BootROM
+AudioROM=./Formal_330/AudioROM
+
+@FileName
+# ---------------------------------------------------------------------------------------
+# 1. Please specify the file relative path of each module. 
+#    If you want to keep original value for some module, please leave define blank. 
+#    If you want to fill default value for some module, please remove define line. 
+# 
+# 2. Please make sure following files exist, otherwise mergeImage will failed. 
+# ---------------------------------------------------------------------------------------
+
+ShellROM=./FixedROM/ShellROM.bin
+8051ROM=./Formal_330/8051ROM/P330_8051_a22.bin
+USBROM=./FixedROM/USBROM.bin
+EDID=./Formal_330/EDID.bin
+HDCPKey=./Formal_330/HDCPKey.bin
+MAC=
+CIKey=
+VolumeTable=./Formal_330/VolumeTable.bin
+MemoryMap=./Formal_330/MemMap/[12] 330memmap_SIS_EU_330(128MB)_120611.bin
+Option=./Formal_330/SIS330_A-AMP-formal_option_0503.bin
+PanelSet=./Formal_330/PanelSet/CPT215FA01_Smalllogo_SiS330_0508.ini
+ExtraPanelSet=
+VIPTable=./Formal_330/VIP_Table_330_Formal_ATSC_EU_0627v2_VIPv31[CRC_000D01CB]_SVDv08[CRC_0002C74E].lzma.bin
+GammaTable=./Formal_330/GammaNew_withTag.lzma.bin
+ColorLUTTable=./Formal_330/ColorLUT_Formal_Use_v1.1_CRC[4FF74CB0]_120606.lzma.bin
+Logo=./Formal_330/Logo/SiSLogo.bmp
+JpegROM=./FixedROM/jpegROM_a01.gz.optimal.bin
+MultiTable=dummy.bin
+MT_Flag=dummy.bin
+MT_AudioDrv=dummy.bin
+RRTTable=dummy.bin
+
+# ---------------------------------------------------------------------------------------
+# Please don't change the following file name & don't care whether they exist.
+# Unless you do not want to merge these blocks, then you can remove it or leave blank. 
+# 1. The vmlinux & timestamp will generated by the build-system.
+# 2. The BootROM/AudioROM will selected from corresponding folder.
+# ---------------------------------------------------------------------------------------
+
+BootROM=BootROM.bin
+AudioROM=AudioROM.bin
+Kernel=vmlinux.dsc
+
+@Protected
+# ---------------------------------------------------------------------------------------
+# Please specify the protected or or not for each module. 
+# If leave module's finename define blank, then this module will be forced to protected. 
+# ---------------------------------------------------------------------------------------
+
+ShellROM=n
+8051ROM=n
+BootROM=n
+USBROM=n
+EDID=n
+HDCPKey=y
+MAC=n
+CIKey=y
+VolumeTable=n
+MemoryMap=n
+Option=n
+PanelSet=n
+ExtraPanelSet=n
+VIPTable=n
+GammaTable=n
+ColorLUTTable=n
+Logo=n
+AudioROM=n
+JpegROM=n
+MultiTable=n
+MT_Flag=n
+MT_AudioDrv=n
+RRTTable=n
+Kernel=n

+ 217 - 0
tools/mergeImage/mergeImage.h

@@ -0,0 +1,217 @@
+//-------------------------------------------------------------------------------
+// mergeImage.h
+//-------------------------------------------------------------------------------
+#ifndef _MERGEIMAGE_H_
+#define _MERGEIMAGE_H_
+//-------------------------------------------------------------------------------
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include "types.h"
+
+#ifdef _windows_
+	#include "../sisspi_flashalloc.h"
+#else
+	#include <project.h>
+	#include <drv_spi_flashalloc_external.h>
+	#include <drv_spi_flashalloc_internal.h>
+#endif
+
+//-------------------------------------------------------------------------------
+// Option
+//-------------------------------------------------------------------------------
+
+#define DBG_SHOW_DBG_MSG				0
+#define DBG_SHOW_PARSE_RESULT		0
+#define DBG_SHOW_CONFIG_LINE			0
+#define DBG_SKIP_NOT_EXIST				0
+
+#define MI_ENCRYPT_FLASH_BIN			1
+#define MI_COPY_MERGE_SOURCE			1
+#define MI_DFT_GENERATE_ORI_BIN		1
+#define MI_DFT_GENERATE_PACKET		1
+#define MI_DFT_DELETE_TEMP_FILE		1
+#define MI_DFT_JUDGE_DBG_VERSION		0	/* Now only for BootROM */
+#define MI_PROTECT_INVALID_MODULE		1	/* Customer request */
+
+//-------------------------------------------------------------------------------
+// Buffer & file size
+//-------------------------------------------------------------------------------
+
+#define TMP_BUFFER_SIZE			512
+#define SAVEINFO_SIZE				4096
+#define FILENAME_SIZE				4096
+
+//-------------------------------------------------------------------------------
+// Source name
+//-------------------------------------------------------------------------------
+
+#if 0
+#define FILENAME_SHELLROM			"ShellROM.bin"
+#define FILENAME_8051ROM			"8051ROM.bin"
+#define FILENAME_BOOTROM			"BootROM.bin"
+#define FILENAME_USBROM			"USBROM.bin"
+#define FILENAME_EDID				"EDID.bin"
+#define FILENAME_HDCPKEY			"HDCPKey.bin"
+
+#define FILENAME_MAC				"MAC.bin"
+#define FILENAME_CIKEY				"CIKey.bin"
+#define FILENAME_VOLUMETABLE		"VolumeTable.bin"
+#define FILENAME_MEMORYMAP		"MemMap.bin"
+#define FILENAME_OPTION			"Option.bin"
+#define FILENAME_PANELSET			"PanelSet.bin"
+
+#define FILENAME_VIPTABLE			"VIPTable.bin"
+#define FILENAME_GAMMATABLE		"GammaTable.bin"
+#define FILENAME_COLORLUTTABLE	"ColorLUTTable.bin"
+#define FILENAME_LOGO				"Logo.bin"
+#define FILENAME_AUDIOROM			"AudioROM.bin"
+#define FILENAME_KERNEL			"vmlinux.dsc"
+#endif
+
+#define MERGEFEATURE				"mergeImage.cfg"
+
+#define PATHNAME_BOOTROM			"BootROM"
+#define PATHNAME_AUDIOROM			"AudioROM"
+#define PATHNAME_OUTPUT			"."
+
+#define FILENAME_CODEBIN			"code.bin"
+#define FILENAME_DATABIN			"data.bin"
+#define FILENAME_SAVEINFO			"customer.save"
+
+#define FILENAME_BINWITHINFO		"info.bin"
+
+#define FILENAME_PACKETIMAGE		"update.packet"
+#define FILENAME_PACKETSAVE		"update.save"
+
+#define FILENAME_MENUDFTTMP		"MenuSettingDefault.bin"
+#define FILENAME_PQDFTTMP		"PQSettingDefault.bin"
+#define FILENAME_AQDFTTMP		"AQSettingDefault.bin"
+#define FILENAME_ColorTempDFTTMP		"ColorTempSettingDefault.bin"
+
+#define FILENAME_MULTITABLETMP	"Multitable.bin"
+#define FILENAME_MULTIFLAGTMP	"Flag.bin"
+
+
+#define FILENAME_LOGOTMP			"logo.tmp.bin"
+#define FILENAME_LOGOGZTMP		"logo.tmp.bin.lzma"
+#define FILENAME_CAPLOGOTMP_SIZETAG "CAP_LOGO.tmp.bin.sizetag"
+#define FILENAME_CODETMP			"code.tmp.bin"
+#define FILENAME_DATATMP			"data.tmp.bin"
+#define FILENAME_ENCRYPTTMP		"encrypt.tmp.bin"
+#define FILENAME_CODEVALID			"code.valid.bin"
+#define FILENAME_DATAVALID			"data.valid.bin"
+
+#define FILENAME_MICONFIG			"mergeImage.cfg"
+#define FILENAME_TIMESTAMP		"timestamp_info"
+
+#define FILENAME_CUSTABLEGZTMP		"custable.table.lzma"
+
+#if 0
+#define MODULENAME_SHELLROM			"ShellROM"
+#define MODULENAME_8051ROM			"8051ROM"
+
+
+#define MODULENAME_USBROM			"USBROM"
+#define MODULENAME_EDID				"EDID"
+#define MODULENAME_HDCPKEY			"HDCPKey"
+
+#define MODULENAME_MAC				"MAC"
+#define MODULENAME_CIKEY				"CIKey"
+#define MODULENAME_VOLUMETABLE		"VolumeTable"
+#define MODULENAME_MEMORYMAP		"MemoryMap"
+#define MODULENAME_OPTION				"Option"
+#define MODULENAME_PANELSET			"PanelSet"
+#define MODULENAME_EXTRAPANELSET1		"ExtraPanelSet1"
+#define MODULENAME_EXTRAPANELSET2		"ExtraPanelSet2"
+#define MODULENAME_EXTRAPANELSET3		"ExtraPanelSet3"
+
+
+#define MODULENAME_VIPTABLE			"VIPTable"
+#define MODULENAME_GAMMATABLE		"GammaTable"
+#define MODULENAME_COLORLUTTABLE		"ColorLUTTable"
+#define MODULENAME_LOGO				"Logo"
+
+#define MODULENAME_JPEGROM			"JpegROM"
+#define MODULENAME_KERNEL				"Kernel"
+
+#define MODULENAME_MULTITABLE		"MultiTable"
+#define MODULENAME_MT_FLAG			"MT_Flag"
+#define MODULENAME_MT_AUDIODRV		"MT_AudioDrv"
+#define MODULENAME_RRTTABLE			"RRTTable"
+
+#else
+#define MODULENAME_BOOTROM			"BootROM"
+#define MODULENAME_AUDIOROM			"AudioROM"
+
+#endif
+
+//-------------------------------------------------------------------------------
+// debug / error / normal message
+//-------------------------------------------------------------------------------
+
+#if DBG_SHOW_DBG_MSG
+	#define dbgMsg( args... ) printf( args )
+#else
+	#define dbgMsg( args... )
+#endif
+
+#define errMsg( args... ) do{\
+	printf( "\n[Error] " );\
+	printf( args );\
+	}while(0)
+
+#define showMsg( args... ) printf( args )
+
+
+
+//-------------------------------------------------------------------------------
+// mergeImage global variables
+//-------------------------------------------------------------------------------
+
+extern char miPacketName[FILENAME_SIZE];
+extern char miConfigFile[FILENAME_SIZE];
+extern char miCodeBinName[FILENAME_SIZE];
+extern char miDataBinName[FILENAME_SIZE];
+extern char miBinWithInfo[FILENAME_SIZE];
+extern char miSaveInfoName[FILENAME_SIZE];
+extern char miBaseImageName[FILENAME_SIZE];
+extern char miOutputPathName[FILENAME_SIZE];
+extern bool miGeneratePacketFlag;
+extern bool miDeleteTempFileFlag;
+extern bool miGenerateOriginalBinFlag;
+extern bool miJudgeDebugVersionFlag;
+
+//-------------------------------------------------------------------------------
+// Generate option by #define
+//-------------------------------------------------------------------------------
+#include <Customization.h>
+#include <Customization.h>
+
+int GetOptionData(void );
+extern CUSTIMIZATION_TABLE OptionData;
+//-------------------------------------------------------------------------------
+#define ALIGNMENT( addr, size ) ( addr & ~(size-1)  )
+#define ROUND_UP( dividend, divisor ) ( ( (dividend) + (divisor-1) ) / (divisor) )
+#define ROUND_KB( dividend ) ( ROUND_UP( dividend, 1024 ) )
+#define ROUND_16B_ALIGNMENT( dividend ) ( ROUND_UP( dividend, 16 )*16 )
+#if (SPI_ERASE_SIZE == (4*1024))
+#define ROUND_SFS_ALIGNMENT( dividend ) ( ROUND_UP( dividend, 4*1024 )*4*1024 )
+#else
+#define ROUND_SFS_ALIGNMENT( dividend ) ( ROUND_UP( dividend, 64*1024 )*64*1024 )
+#endif
+
+
+#define ToString(x) #x
+#define MIN( a, b ) 	( (a < b ) ? a : b  )
+#define MAX( a, b ) 	( (a > b ) ? a : b  )
+//-------------------------------------------------------------------------------
+int sisspi_encrypt( const char *inFile, const char *outFile, int encryptMode );
+
+#endif
+
+
+
+
+

+ 737 - 0
tools/mergeImage/mergeToBin.c

@@ -0,0 +1,737 @@
+//-------------------------------------------------------------------------------
+#include "mergeToBin.h"
+#include "loadBasicPacket.h"
+#include "generateOutput.h"
+#include <stdarg.h>
+#include <ctype.h>
+
+//-------------------------------------------------------------------------------
+
+u8 *codeTmpMem = NULL;
+u8 *dataTmpMem = NULL;
+
+//-------------------------------------------------------------------------------
+
+static inline u32 getNorFlashOffset( u32 flashAddr )
+{
+	return flashAddr & 0x00ffffff;
+}
+
+u32 getNorFlashID( u32 flashAddr )
+{
+	flashAddr = flashAddr & 0xff000000;
+	if( flashAddr == SPI_CODEFLASH_BASEADDR ) return 0;
+	else if( flashAddr == SPI_DATAFLASH_BASEADDR )
+	{
+		#if( CONFIG_DATA_FLASH_SIZE != 0  )
+			return 1;
+		#else
+			errMsg( "No support data-flash address (0x%08x)\n", flashAddr ); return 9;
+		#endif
+	}
+	else
+	{
+		errMsg( "This address (0x%08x) is not a flash address.\n", flashAddr);
+		return 9;
+	}
+}
+//-------------------------------------------------------------------------------
+
+static bool moveFileContent( u8 *memOut, FILE *fpIn, int cpySize )
+{
+	int i; int readSize;
+	u8 readBuf[TMP_BUFFER_SIZE] = {0};
+
+	for( i = 0; i < cpySize; i+= TMP_BUFFER_SIZE )
+	{
+		readSize = fread( readBuf, 1, TMP_BUFFER_SIZE, fpIn );
+    	if( readSize < 0 )
+    	{
+    		errMsg( "fread() error\n" ); return false;
+    	}
+
+		memcpy( memOut+i, readBuf, readSize );
+	}
+
+	return true;
+}
+
+bool copyFileToMemory( u8 *memOut, const char *fileName, int maxSize )
+{
+	bool ret;
+	FILE *fpIn;
+
+	int fileSize = getFileSize( fileName );
+	if( fileSize > maxSize )
+	{
+		errMsg( "fileSize(%d) > maxSize(%d) (%s)\n", fileSize, maxSize, fileName);
+        exit(-1);
+		return false;
+	}
+
+	fpIn = fopen( fileName, "rb" );
+	if( fpIn == NULL )
+	{
+		errMsg( "Open file failed (%s)\n", fileName );
+		return false;
+	}
+
+	ret = moveFileContent( memOut, fpIn, fileSize );
+	fclose( fpIn );
+	return ret;
+}
+
+//-------------------------------------------------------------------------------
+
+unsigned char G_FLASH_ENCODE_FFFF_4DW[16] =
+{
+        0xac, 0xea, 0x6b, 0xcf,
+        0xac, 0x59, 0x4d, 0x35,
+        0x28, 0xab, 0x54, 0xe3,
+        0xa5, 0xaa, 0x0b, 0x37,
+};
+
+bool loadBasicImageToFlashTempMem( u8 *memOut, const char *fileName)
+{
+	FILE *fpIn; int fileSize;
+	bool ret;
+
+	if( !isLoadBasicPacket() ) return true;
+	dbgMsg( "[loadBasicImageToFlashTempMem] %s\n", fileName );
+	fileSize = getFileSize( fileName );
+	if( fileSize <= 0 )
+	{
+		errMsg( "[loadBasicImageToFlashTempMem] %s\n", fileName );
+	}
+
+	fpIn = fopen( fileName, "rb" );
+	if( fpIn == NULL ) return false;
+
+	ret = moveFileContent ( memOut, fpIn, fileSize );
+	fclose(fpIn);
+	return ret;
+}
+
+u8* initFlashTempMem( u32 Id, u32 fileSizeKB )
+{
+	int i; u8 *tmpMem;
+    	u32 flashSize = fileSizeKB * 1024; // original is KB
+
+	dbgMsg( "[initFlashTempMem] Flash%d : %dKB\n", Id, fileSizeKB );
+
+	tmpMem = (u8*) malloc( flashSize );
+	if( tmpMem == NULL )
+	{
+		errMsg( " malloc flashTempMem failed!\n" );
+		return NULL;
+	}
+
+	for( i = 0; i < flashSize; i += 16 )
+		memcpy ( tmpMem+i , G_FLASH_ENCODE_FFFF_4DW, 16 );
+
+	return tmpMem;
+}
+
+bool mallocFlashTempMem()
+{
+	codeTmpMem = initFlashTempMem( 0, (CONFIG_CODE_FLASH_SIZE > 8192)?CONFIG_CODE_FLASH_SIZE:8192 );
+	if( codeTmpMem == NULL ) return false;
+	if( !loadBasicImageToFlashTempMem( codeTmpMem, BASEIMAGE_CODEBIN ) ) return false;
+
+#if( CONFIG_DATA_FLASH_SIZE != 0  )
+	dataTmpMem = initFlashTempMem( 1, CONFIG_DATA_FLASH_SIZE );
+	if( dataTmpMem == NULL ) return false;
+	if( !loadBasicImageToFlashTempMem( dataTmpMem, BASEIMAGE_DATABIN ) ) return false;
+#else
+	dataTmpMem = 0;
+#endif
+
+	return true;
+}
+
+#if 0
+static u8* getMergeFlashTempMem( unsigned long flashAddr )
+{
+	u8 *memTmp = NULL;
+	u32 id = getNorFlashID( flashAddr );
+	if( id == 0 ) memTmp = codeTmpMem;
+	else if( id == 1 ) memTmp = dataTmpMem;
+
+	if( memTmp ) memTmp += getNorFlashOffset( flashAddr );
+	return memTmp;
+}
+#endif
+
+void writeToFlashTempFile( const char *fileName, u8 *memOut, u32 memSize )
+{
+	FILE *fp;
+	dbgMsg( "[writeToFlashTempFile] %s\n", fileName );
+	fp = fopen( fileName, "wb" );
+	if (fp == NULL)
+		return;
+	
+	fwrite( memOut, 1, memSize, fp );
+	fclose( fp );
+}
+
+//-------------------------------------------------------------------------------
+
+int getFileSize( const char* fileName )
+{
+	FILE *fp = fopen( fileName, "rb" );
+	if( fp == NULL ) return -1;
+
+    	fseek( fp, 0, SEEK_END );
+    	u32 fileSize = ftell( fp );
+	fclose( fp );
+
+    	return fileSize;
+}
+
+static inline FILE* openMergeSource( const char *fileName, bool isAllowSkip )
+{
+	FILE *fp = fopen( fileName, "rb" );
+	if( fp != NULL ) return fp;
+
+	if( isAllowSkip ) showMsg( "[Skip] File (%s) is not exist!\n", fileName );
+	else errMsg( "openMergeSource failed (%s)\n", fileName );
+
+	return NULL;
+}
+
+static inline int checkMergeSourceSize( const char* sourceFile, int fileSize, int flashSize )
+{
+	if( (flashSize != 0) && (fileSize > flashSize) )
+	{
+		if( flashSize >= 1024 )
+		{
+			flashSize = ROUND_KB(flashSize);
+			fileSize = ROUND_KB(fileSize);
+		}
+
+		errMsg( "File's(%s) size Over flashSize limit!! ( %d > %d )\n", sourceFile, fileSize, flashSize  );
+		return -1;
+	}
+
+	if( fileSize == 0 ) showMsg( "[Skip] File's (%s) size is zero\n", sourceFile );
+	return fileSize;
+}
+
+//-------------------------------------------------------------------------------
+
+typedef struct _MergeInfoOut
+{
+	bool skip;	// for DBG_SKIP_NOT_EXIST or fileSize = 0
+	FILE *fpIn;
+	u8 *memIn;	/* If (fpIn) not point to *.bin */
+	u8 *memOut;
+	u8 *memOut2;
+	int cpySize;
+	int cpySize2;
+} MergeInfoOut;
+
+//-------------------------------------------------------------------------------
+// transfer *.ini to memory
+//-------------------------------------------------------------------------------
+
+#include "pnlset2bin.h"
+
+bool checkFileNameExtension( const char *fileName, const char *wildcard )
+{
+	int i ;
+	bool ret = true;
+	int FileNameLength = strlen(fileName);
+	int WildcardLength = strlen(wildcard);
+	const char *extension = fileName + FileNameLength - WildcardLength;
+
+	if( FileNameLength <= WildcardLength ) ret = false;
+
+	for( i = 0; ret && (i < WildcardLength) ; i++ )
+	{
+		char c = tolower( extension[i] );
+		if( c != wildcard[i] ) ret = false;
+	}
+
+	if( !ret )
+	{
+		dbgMsg( "checkFileNameExtension failed : %s, wildcard: %s\n", fileName, wildcard );
+		return false;
+	}
+
+	return true;
+}
+
+bool transferPanelSetFileToMemory( u8* memOut, NorFlashModuleInfo *info  )
+{
+	int ret = false;
+	u32 flashSize = info->flashSize1 + info->flashSize2;
+
+	if( checkFileNameExtension( info->fileName, ".ini" ) )
+	{
+		showMsg( "[transferPanelSetFileToMemory] %s\n", info->fileName );
+		ret = ini2binmem( info->fileName, (char*) memOut , flashSize);
+		if(ret > 0)
+			ret = true;
+	}
+
+	return ret;
+}
+
+int syscmd( const char * format, ... )
+{
+	char cmd[256];
+	va_list arg;
+	va_start( arg, format );
+	vsprintf( cmd, format, arg );
+    	va_end( arg );
+
+	showMsg("[CMD]: %s \n",cmd);
+	return system(cmd);
+}
+
+int JPG2Bin( const char *szFileIn, const char *szFileOut )
+{
+	bool ret;
+	u32 fileSize = getFileSize( szFileIn );
+
+	FILE *fpOut = fopen( szFileOut, "wb" );
+	if (fpOut == NULL)
+		return 0;
+	fwrite( &fileSize, 1, sizeof(u32), fpOut );
+	ret = copyFileContent( fpOut, szFileIn, fileSize );
+	fclose( fpOut );
+	return ret;
+}
+
+bool transferLogoFileToMemory( u8* memOut, NorFlashModuleInfo *info  )
+{
+	int ret = false;
+	u32 fileSize=0;
+	u32 flashSize = info->flashSize1 + info->flashSize2;
+
+	if( checkFileNameExtension( info->fileName, ".bmp" ) )
+	{
+		showMsg( "[transferLogoFileToMemory] %s\n", info->fileName );
+		ret = BMP2Bin( info->fileName, FILENAME_LOGOTMP );
+		if( syscmd( "gzip %s", FILENAME_LOGOTMP ) ) ret = false;
+	}
+	else if( checkFileNameExtension( info->fileName, ".jpg" ) )
+	{
+		showMsg( "[transferLogoFileToMemory] %s\n", info->fileName );
+		ret = JPG2Bin( info->fileName, FILENAME_LOGOGZTMP );
+	}
+
+	if( ret )
+	{
+		ret = copyFileToMemory( memOut, FILENAME_LOGOGZTMP, flashSize );
+		if( !ret )
+			errMsg( "[transferLogoFileToMemory] Size is too large after transfer!!! ( %d KB > %d KB )\n",  fileSize, flashSize );
+	}
+
+	removeTempFile( FILENAME_LOGOTMP );
+	removeTempFile( FILENAME_LOGOGZTMP );
+	return ret;
+}
+#ifdef CONFIG_MULTITABLE	//2012.11.27 for multiable included, gaia
+int mt_main(char* filename, char* output_mtname, char* output_flagname);
+bool transferMultiTableToMemory( u8* memOut, NorFlashModuleInfo *info  )
+{
+	int ret = false;
+//	char cmd[256];
+	u32 flashSize = info->flashSize1 + info->flashSize2;
+	if( checkFileNameExtension( info->fileName, ".ini" ) )
+	{
+		showMsg( "[transferMultiTableToMemory] %s\n", info->fileName );
+		//sprintf( cmd, "./MULTITABLE/multitable ./%s", info->fileName );
+		//syscmd( cmd );
+		if(mt_main( info->fileName, FILENAME_MULTITABLETMP, FILENAME_MULTIFLAGTMP)==0)
+		{
+			//set MODULENAME_MT_FLAG is valid
+			NorFlashModuleInfo *moduleInfo = searchModuleInfo( MODULENAME_MT_FLAG );
+			moduleInfo->isValid = true;
+			strcpy( moduleInfo->fileName, FILENAME_MULTIFLAGTMP);
+			ret = true;
+		}
+
+	}
+
+	if( ret )
+	{
+		ret = copyFileToMemory( memOut, FILENAME_MULTITABLETMP, flashSize );
+		if( !ret )
+			errMsg( "[transferMultiTableToMemory] Size is too large after transfer!!! (  > %d KB )\n", flashSize );
+	}
+
+	removeTempFile( FILENAME_MULTITABLETMP );
+
+
+	return ret;
+}
+bool copyMultiFlagToMemory( u8* memOut, NorFlashModuleInfo *info  )
+{
+	int ret = false;
+//	char cmd[256];
+	u32 flashSize = info->flashSize1 + info->flashSize2;
+	showMsg( "[copyMultiFlagToMemory] %s\n", info->fileName );
+
+	ret = copyFileToMemory( memOut, FILENAME_MULTIFLAGTMP, flashSize );
+	if( !ret )
+		errMsg( "[transferLogoFileToMemory] Size is too large after transfer!!! (  > %d KB )\n", flashSize );
+
+	removeTempFile( FILENAME_MULTIFLAGTMP );
+
+	return ret;
+}
+
+#endif
+#if 0
+u8* transferFileToMemory ( NorFlashModuleInfo *info )
+{
+	int ret = 0;
+	u32 flashSize = info->flashSize1 + info->flashSize2;
+
+	u8 *mem = malloc( flashSize );
+
+	if( mem == NULL )
+	{
+		errMsg( "[transferFileToMemory] allocate memory failed\n" );
+		return NULL;
+	}
+
+	if( !strcmp( info->moduleName, MODULENAME_PANELSET) )
+	{
+		ret = transferPanelSetFileToMemory( mem, info );
+	}
+	else if( !strcmp( info->moduleName, MODULENAME_EXTRAPANELSET1) )
+	{
+		ret = transferPanelSetFileToMemory( mem, info );
+	}
+	else if( !strcmp( info->moduleName, MODULENAME_EXTRAPANELSET2) )
+	{
+		ret = transferPanelSetFileToMemory( mem, info );
+	}
+	else if( !strcmp( info->moduleName, MODULENAME_EXTRAPANELSET3) )
+	{
+		ret = transferPanelSetFileToMemory( mem, info );
+	}
+	else if( !strcmp( info->moduleName, MODULENAME_LOGO) )
+	{
+		ret = transferLogoFileToMemory( mem, info );
+	}
+#ifdef CONFIG_MULTITABLE//2012.11.27 for multiable included, gaia
+	else if( !strcmp( info->moduleName, MODULENAME_MULTITABLE) )
+	{
+		ret = transferMultiTableToMemory( mem, info );
+	}
+	else if( !strcmp( info->moduleName, MODULENAME_MT_FLAG) )
+	{
+		ret = copyMultiFlagToMemory( mem, info );
+	}
+#endif
+	if( ret == false )
+	{
+		free(mem);
+		mem = NULL;
+		errMsg( "[%s] can't not support this file format: %s",  info->moduleName,  info->fileName );
+	}
+
+	return mem;
+}
+//-------------------------------------------------------------------------------
+#endif
+static inline void releaseMergeInfoOut( MergeInfoOut *out )
+{
+	if( out->fpIn ) fclose( out->fpIn );
+	if( out->memIn ) free( out->memIn );
+}
+
+static inline void showFlashInfo( u32 flashAddr, u32 flashSize )
+{
+	dbgMsg( "   =>[Flash%d] Offset: 0x%08x, Size: %d KB\n",
+		getNorFlashID( flashAddr ) ,getNorFlashOffset( flashAddr ), ROUND_KB( flashSize ) );
+}
+#if 0
+bool getMergeInfo( MergeInfoOut *out, NorFlashModuleInfo *info )
+{
+	bool ret = true;
+	bool isAllowSkip = DBG_SKIP_NOT_EXIST;
+	int fileSize = getFileSize( info->fileName );
+	u32 flashSize = info->flashSize1 + info->flashSize2;
+
+	dbgMsg( "[%s] getMergeInfo\n", info->moduleName );
+	dbgMsg( "   =>FileName: %s (%d KB)\n", info->fileName, ROUND_KB( fileSize ) );
+
+	showFlashInfo( info->flashAddr1, info->flashSize1 );
+	if( info->flashAddr2 ) showFlashInfo( info->flashAddr2, info->flashSize2 );
+	if( !info->isValid ) return false;
+
+	out->skip = false;
+	out->fpIn = NULL;
+	out->memIn = NULL;
+
+	if( checkFileNameExtension( info->fileName, ".bin" ) || checkFileNameExtension( info->fileName, ".dsc" )   )
+	{
+		out->fpIn = openMergeSource( info->fileName, isAllowSkip );
+		if( out->fpIn == NULL )
+		{
+			ret = false;
+			out->skip = isAllowSkip;
+		}
+
+		out->cpySize = checkMergeSourceSize( info->fileName, fileSize, flashSize );
+		if( out->cpySize <= 0 )
+		{
+			ret = false;
+			if( out->cpySize == 0 ) out->skip = true;
+		}
+	}
+	else
+	{
+		out->cpySize = info->flashSize1 + info->flashSize2;
+		out->memIn = transferFileToMemory( info );
+		if( out->memIn == NULL ) ret = false;
+	}
+
+	out->memOut = getMergeFlashTempMem( info->flashAddr1 );
+	if( out->memOut == NULL ) ret = false;
+
+	if( info->flashAddr2)
+	{
+		if( out->cpySize > info->flashSize1 )
+		{
+			out->cpySize2 = out->cpySize - info->flashSize1;
+			out->cpySize = info->flashSize1;
+		}
+
+		out->memOut2 = getMergeFlashTempMem( info->flashAddr2 );
+		if(out->memOut2 == NULL) ret = false;
+	}
+	else
+	{
+		out->cpySize2 = 0;
+		out->memOut2 = NULL;
+	}
+
+	if( out->skip ) ret = true;
+	if( !ret ) releaseMergeInfoOut( out );
+	return ret;
+}
+#endif
+#if 0
+bool mergeToBinCrossFlash( NorFlashModuleInfo *moduleInfo )
+{
+	bool ret = true;
+	MergeInfoOut infoOut;
+
+	ret = getMergeInfo( &infoOut, moduleInfo );
+	if( !ret ) return false;
+
+	if( !infoOut.skip )
+	{
+		if( infoOut.memIn != NULL )
+		{
+			memcpy( infoOut.memOut, infoOut.memIn, infoOut.cpySize );
+			memcpy(  infoOut.memOut2, infoOut.memIn + infoOut.cpySize, infoOut.cpySize2 );
+		}
+		else
+		{
+			ret = moveFileContent( infoOut.memOut, infoOut.fpIn, infoOut.cpySize );
+			if( ret && infoOut.cpySize2 ) ret = moveFileContent( infoOut.memOut2, infoOut.fpIn, infoOut.cpySize2 );
+		}
+	}
+
+	releaseMergeInfoOut( &infoOut );
+	return ret;
+}
+#endif
+//-------------------------------------------------------------------------------
+#if 0
+bool calculateImageValidSize( u32 *codeValidSizeKB, u32 *dataValidSizeKB )
+{
+	int action = 0;
+	bool ret = true;
+	MergeInfoOut infoOut;
+	NorFlashModuleInfo *moduleInfo = &flashModuleInfo[MODULE_KERNEL];//searchModuleInfo(MODULE_KERNEL);
+	if( moduleInfo == NULL ) return false;
+
+	if( SPI_IS_WITH_NANDFLASH ) /* don't do that for Nand-flash case ... */
+	{
+		*codeValidSizeKB = CONFIG_CODE_FLASH_SIZE;
+		*dataValidSizeKB = CONFIG_DATA_FLASH_SIZE;
+		return true;
+	}
+
+/*
+	action = 0 : Effective flash size. ( Specified kernel module reference file)
+	action = 1 : totally flash size without kernel. ( kernel content is protected or reference invalid file )
+	action = 2 : basic image's flash size. ( kernel module will refer to basic image. )
+*/
+
+	if( moduleInfo->isProtected ) action = 1;
+	else if( !moduleInfo->isValid ) action =  isLoadBasicPacket() ? 2 : 1;
+
+	if( action )
+	{
+		u32 removeKernelSize;
+		dbgMsg( "calculateImageValidSize: skip Kernel\n");
+
+		removeKernelSize= ROUND_KB( moduleInfo->flashAddr1 - SPI_CODEFLASH_BASEADDR );
+		if( action == 2 )
+		{
+			int basicDataImageSize = ROUND_KB( getFileSize(BASEIMAGE_DATABIN) );
+			*codeValidSizeKB = ROUND_KB( getFileSize(BASEIMAGE_CODEBIN) );
+			*dataValidSizeKB = ( basicDataImageSize > 0 ) ? basicDataImageSize : 0;
+ 		}
+		else if( action == 1 )
+		{
+			*codeValidSizeKB = removeKernelSize;
+			*dataValidSizeKB = 0;
+		}
+
+		if( *codeValidSizeKB <= removeKernelSize  ) moduleInfo->isProtected = true;
+		return true;
+	}
+
+	ret = getMergeInfo( &infoOut, moduleInfo );
+	if( !ret ) return false;
+
+	if( infoOut.cpySize2 )
+	{
+		*codeValidSizeKB = CONFIG_CODE_FLASH_SIZE;
+		*dataValidSizeKB = ROUND_KB( infoOut.cpySize2 );
+	}
+	else
+	{
+		*codeValidSizeKB = ROUND_KB( moduleInfo->flashAddr1 + infoOut.cpySize - SPI_CODEFLASH_BASEADDR );
+		*dataValidSizeKB = 0;
+	}
+
+	releaseMergeInfoOut( &infoOut );
+	return true;
+}
+#endif
+
+//-------------------------------------------------------------------------------
+
+#define BACKUP_CHECK_MAGIC	(0xA110C001)
+#define BACKUP_MAGIC_LENGTH	(4)
+#if 0	//gaia, remove featrue 2013.04.23
+
+bool mergeToBin_Backup64K()
+{
+	u8 *memOut; u8 *memIn;
+	u32 magicNumber = BACKUP_CHECK_MAGIC;
+	u32 sourceFlashAddr = SPI_MEMALLOCINFO_FLASHADDR;
+	u32 targetFlashAddr = SPI_MEMALLOCBACKUP_FLASHADDR;
+
+	dbgMsg( "[CreateBackup64K] 0x%08x => 0x%08x\n", sourceFlashAddr, targetFlashAddr );
+
+	memIn = getMergeFlashTempMem( sourceFlashAddr );
+	memOut = getMergeFlashTempMem( targetFlashAddr );
+	if( (memIn == NULL) || (memOut == NULL) ) return false;
+
+	memcpy( memIn+0xfffc, &magicNumber, BACKUP_MAGIC_LENGTH );
+	memcpy( memOut, memIn, 64*1024 );
+	return true;
+}
+
+
+bool mergeToBin_BackupRRT()
+{
+#if( SPI_RRTTABLE2_FLASHSIZE != 0 )
+	u8 *memOut; u8 *memIn;
+	u32 sourceFlashAddr = ALIGNMENT( SPI_RRTTABLE_FLASHADDR, 64*1024 );
+	u32 targetFlashAddr = SPI_RRTTABLE2_FLASHADDR;
+
+	dbgMsg( "[CreateBackupRRT] 0x%08x => 0x%08x\n", sourceFlashAddr, targetFlashAddr );
+	memIn = getMergeFlashTempMem( sourceFlashAddr );
+	memOut = getMergeFlashTempMem( targetFlashAddr );
+	if( (memIn == NULL) || (memOut == NULL) ) return false;
+
+	memcpy( memOut, memIn, SPI_RRTTABLE2_FLASHSIZE );
+#endif
+
+	return true;
+}
+#endif
+//-------------------------------------------------------------------------------
+
+bool mergeToBin_GenerateOption(char *output_name)
+{
+#if defined(OP_IRCommandType)
+
+	u32 memSize = sizeof(CUSTIMIZATION_TABLE);
+	//u8 *memIn = (u8*) &OptionData;
+	//u8 *memOut = getMergeFlashTempMem( SPI_OPTIONDATA_FLASHADDR );
+
+	showMsg( "[GenerateOption] \n" );
+	#if 0
+	if( SPI_OPTIONDATA_FLASHSIZE < memSize )
+	{
+		errMsg( "Option (%x Bytes) > %x Bytes\n", memSize, SPI_OPTIONDATA_FLASHSIZE); return false;
+	}
+	#endif
+	if( GetOptionData() != 0 )	// generate OptionData content
+	{
+		errMsg( "GetOptionData  failed\n"); return false;
+	}
+	FILE *fpOut = fopen( output_name, "wb" );
+	fwrite( &OptionData, 1, memSize, fpOut );
+	fclose( fpOut );
+	//memcpy( memOut, memIn, memSize );
+#endif
+
+	return true;
+}
+
+//-------------------------------------------------------------------------------
+
+bool mergeToBin_GenerateUMFDefaultSetting()
+{
+	bool ret = true;
+
+#if defined(CONFIG_UMFSWMERGE)
+	u8 *memOut1 = getMergeFlashTempMem( SPI_MENUDEFAULT_FLASHADDR );
+
+	syscmd( "./umfSWMergeAP" );
+
+	// TODO: parsing multiTable data, and write it to memory
+
+	if( ret )
+		ret = copyFileToMemory( memOut1 , FILENAME_MENUDFTTMP, SPI_MENUDEFAULT_FLASHSIZE );
+
+	removeTempFile( FILENAME_MENUDFTTMP );
+
+	#ifndef CONFIG_MULTITABLE
+	/*copy PQ defaul data to flash*/
+	u8 *memOut_PQ_DF = getMergeFlashTempMem(SPI_PICTUREDEFAULT_FLASHADDR);
+
+	if( ret )
+		ret &= copyFileToMemory(memOut_PQ_DF , FILENAME_PQDFTTMP, SPI_PICTUREDEFAULT_FLASHSIZE );
+
+	removeTempFile(FILENAME_PQDFTTMP);
+
+	/*copy AQ defaul data to flash*/
+	u8 *memOut_AQ_DF = getMergeFlashTempMem(SPI_AUDIODEFAULT_FLASHADDR);
+
+	if( ret )
+		ret &= copyFileToMemory(memOut_AQ_DF , FILENAME_AQDFTTMP, SPI_AUDIODEFAULT_FLASHSIZE );
+
+	removeTempFile(FILENAME_AQDFTTMP);
+
+	/*copy Color Temp defaul data to flash*/
+	u8 *memOut_ColorTemp_DF = getMergeFlashTempMem(SPI_COLORTEMP_FLASHADDR);
+
+	if( ret )
+		ret &= copyFileToMemory(memOut_ColorTemp_DF , FILENAME_ColorTempDFTTMP, SPI_COLORTEMPDEFAULT_FLASHSIZE );
+
+	removeTempFile(FILENAME_ColorTempDFTTMP);
+	#endif
+
+#endif
+
+	return ret;
+}
+
+
+

+ 23 - 0
tools/mergeImage/mergeToBin.h

@@ -0,0 +1,23 @@
+//-------------------------------------------------------------------------------
+#ifndef _MERGETOBIN_H_
+#define _MERGETOBIN_H_
+//-------------------------------------------------------------------------------
+#include "mergeImage.h"
+#include "parseConfig.h"
+//-------------------------------------------------------------------------------
+//#define CONFIG_UMFSWMERGE
+//#define CONFIG_MULTITABLE
+
+bool mergeToBinCrossFlash( NorFlashModuleInfo *moduleInfo );
+//bool mergeToBin_Backup64K();
+//bool mergeToBin_BackupRRT();
+bool mergeToBin_GenerateOption();
+bool mergeToBin_GenerateUMFDefaultSetting();
+
+void freeFlashTempMem();
+bool mallocFlashTempMem();
+int getFileSize( const char* fileName );
+
+bool calculateImageValidSize( u32 *codeValidSizeKB, u32 *dataValidSizeKB );
+//-------------------------------------------------------------------------------
+#endif

+ 201 - 0
tools/mergeImage/mt_aq.c

@@ -0,0 +1,201 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <regex.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <string.h>
+
+
+#include "mt_mt.h"
+
+#define LINEMAX 256
+#define AQOSDSETTINGVER_LEN 32
+
+int parseAQ(Item_t *pItem)
+{
+	FILE *fp = NULL;
+	FILE *binfp = NULL;
+	//int retval;
+	//long filelen = 0;
+	char buf[LINEMAX];
+	unsigned char *pOutBuf;
+	//int datasize= 0;
+	int line=0;
+	int retval = 0;
+	int value;
+	int databyte;
+	char AQOSDSetting_ver[AQOSDSETTINGVER_LEN];
+#if WRITEITEMTOFILE
+	char binFileName[256];
+#endif
+
+
+
+
+	pOutBuf = (unsigned char *)malloc(MAXBINSIZE);
+
+	if (pOutBuf == NULL)
+	{
+		fprintf(stderr, "Unable alloc pOutBuf buffer\n");
+		return -1;
+	}
+
+	pItem->pData = pOutBuf;
+	pItem->size = 0;
+
+
+	if (pItem->filepath != NULL && pOutBuf!= NULL)
+	{
+		printf("%s 'open file %s\n", __FUNCTION__, pItem->filepath);
+		fp = fopen(pItem->filepath, "rb");;
+#if WRITEITEMTOFILE
+		strcpy(binFileName, pItem->name);
+		binfp = fopen(strcat(binFileName,".bin"), "wb");
+		if (fp != NULL && binfp != NULL)
+#else
+		if (fp != NULL)
+#endif
+		{
+
+			char *pch;
+			//int reti;
+			//regmatch_t match[2];
+			/* Compile regular expression */
+			//reti = regcomp(&regex, "^ItemFile[ \t]*=[ \t]*\"[a-zA-Z0-9._/\\]*\"[ \t]*", 0);
+			//reti = regcomp(&regex, "^[ \t]*#[.]*", 0);
+			//if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }
+
+			/* Free compiled regular expression if you want to use the regex_t again */
+
+			//fgets (buf , LINEMAX , fp);
+			//line++;
+			if (fgets (buf , LINEMAX , fp) == NULL)
+			{
+				fprintf(stderr, "%s %d fgets error!\n", __FUNCTION__, __LINE__);
+#if WRITEITEMTOFILE
+				fclose(binfp);
+
+#endif				
+				fclose(fp);
+				free(pOutBuf);				
+				return -1;
+			}
+			pch = strtok (buf," @\t\r\n");
+			pch = strtok (NULL, " @\t\r\n");
+			pch = strtok (NULL, " @\t\r\n");
+			if (strlen(pch) <=32)
+			{
+				//fprintf(stderr, "strlen(pch) = %d\n", strlen(pch));
+				memset(AQOSDSetting_ver,0,32);
+				memcpy(AQOSDSetting_ver, pch, strlen(pch));
+				//fwrite(PQOSDSetting_ver, sizeof(char)*AQOSDSETTINGVER_LEN, 1, binfp);
+				writeOutputBuf(AQOSDSetting_ver, sizeof(char)*AQOSDSETTINGVER_LEN, &pOutBuf, binfp);
+				pItem->size += sizeof(char)*AQOSDSETTINGVER_LEN;;
+			}
+			else
+			{
+				//fprintf(stderr, "PQOSDSetting_ver len > AQOSDSETTINGVER_LEN, strip it\n");
+				//fprintf(stderr, "strlen(pch) = %d\n", strlen(pch));
+				memset(AQOSDSetting_ver,0,AQOSDSETTINGVER_LEN);
+				memcpy(AQOSDSetting_ver, pch, AQOSDSETTINGVER_LEN);
+				//fwrite(AQOSDSetting_ver, sizeof(char)*AQOSDSETTINGVER_LEN, 1, binfp);
+				writeOutputBuf(AQOSDSetting_ver, sizeof(char)*AQOSDSETTINGVER_LEN, &pOutBuf, binfp);
+				pItem->size += sizeof(char)*AQOSDSETTINGVER_LEN;
+
+			}
+			line++;
+			//fgets (buf , LINEMAX , fp);
+			//line++;
+
+		    while( fgets (buf , LINEMAX , fp) != NULL )
+			{
+		    	short data_word;
+		    	char data_byte;
+		    	line++;
+				//reti = regexec(&regex, buf, 1, match, 0);
+				//if( !reti ){
+				//	puts("Match");
+				//	printf("==>%s", buf);
+				//}
+				//else if( reti == REG_NOMATCH ){
+				//	puts("No match");
+				//	printf("==>%s", buf);
+				//}
+				//else{
+				//	//regerror(reti, &regex, msgbuf, sizeof(msgbuf));
+				//	fprintf(stderr, "Regex match failed:\n");
+				//}
+				pch = strtok (buf,"@");
+				pch = strtok (NULL, " @\t\r\n");
+				value = atoi(pch);
+				//printf ("%s\n",pch);
+				pch = strtok (NULL, " @\t\r\n");
+				//printf ("%s\n",pch);
+				databyte = atoi(pch);
+
+
+				switch (databyte)
+				{
+					case 1:
+						data_byte = (char) value;
+						//fwrite(&data_byte, sizeof(char), 1, binfp);
+						writeOutputBuf(&data_byte, sizeof(char), &pOutBuf, binfp);
+						pItem->size += sizeof(char);
+						break;
+					case 2:
+						data_word = (short) value;
+						//fwrite(&data_word, sizeof(short), 1, binfp);
+						writeOutputBuf(&data_word, sizeof(short), &pOutBuf, binfp);
+						pItem->size += sizeof(short);
+						break;
+					case 3:
+						data_byte = (char) (value & 0xff);
+						data_word = (short) (value>>8);
+						//fwrite(&data_byte, sizeof(char), 1, binfp);
+						//fwrite(&data_word, sizeof(short), 1, binfp);
+						writeOutputBuf(&data_byte, sizeof(char), &pOutBuf, binfp);
+						writeOutputBuf(&data_word, sizeof(short), &pOutBuf, binfp);
+						pItem->size += sizeof(char)+ sizeof(short);
+						break;
+					case 4:
+						//fwrite(&value, sizeof(int), 1, binfp);
+						writeOutputBuf(&value, sizeof(int), &pOutBuf, binfp);
+						pItem->size += sizeof(int);
+						break;
+				}
+
+			}
+
+		    //regfree(&regex);
+		}
+		else
+		{
+			perror("Can't open file");
+		}
+
+	}
+
+	//for 4 bytes aligment
+	pItem->dummyByteNums = 0;
+	if ((pItem->size % 4) != 0)
+	{
+		pItem->dummyByteNums = 4 - (pItem->size % 4);
+	}
+
+	if (fp != NULL)
+	{
+		fclose(fp);
+	}
+
+
+	if (binfp != NULL)
+	{
+		fflush(binfp);
+		fclose(binfp);
+	}
+	return retval;
+
+}
+

+ 11 - 0
tools/mergeImage/mt_aq.h

@@ -0,0 +1,11 @@
+/*
+ * aq.h
+ *
+ */
+
+#ifndef AQ_H_
+#define AQ_H_
+
+int parseAQ(Item_t *pItem);
+
+#endif /* AQ_H_ */

+ 182 - 0
tools/mergeImage/mt_main.c

@@ -0,0 +1,182 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <regex.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <string.h>
+
+#include "mt_mt.h"
+#include "mt_pq.h"
+
+
+
+int CheckFilename(char *str)
+{
+	int retval = -1;
+	int len;
+	//check filename extension is  .ini
+	if (str != NULL)
+	{
+		len = strlen(str);
+
+		if (len > 4)
+		{
+			if (str[len-4] == '.' && str[len-3] == 'i' &&
+				str[len-2] == 'n' && str[len-1] == 'i')
+			{
+				retval =0;
+			}
+		}
+
+	}
+
+	return retval;
+
+}
+#if 1
+int mt_main(char* filename, char* output_mtname, char* output_flagname)
+{
+
+	int i;
+	int retval = 0;
+	MultiTable_t *pMT = NULL;
+	//char filename[256];
+
+		
+	pMT = ParseMultiTableINI(filename);
+
+	
+	if (pMT != NULL)
+	{
+
+		for (i=0; i<pMT->modelNum; i++)
+		{
+			retval = parseSubTable(pMT->modelList[i]);
+		}
+
+		if (retval == 0)
+		{
+			//strcpy(filename, "Multitable_");
+			//strcat(filename, pMT->defaultModelName);
+			//strcat(filename, ".bin");
+			retval = writeMultiTable(pMT, output_mtname);
+			if (retval == 0)
+			{
+				printf("Create %s done.\n", output_mtname);
+			}
+
+			//strcpy(filename, "Flag_");
+			//strcat(filename, pMT->defaultModelName);
+			//strcat(filename, ".bin");
+
+			retval = writeMultiTableFlag(pMT, output_flagname);
+			if (retval == 0)
+			{
+				printf("Create %s done.\n", output_flagname);
+			}
+			
+		}
+	}
+	else
+	{
+		fprintf(stderr, "Error! Multitable not create!\n");
+	}
+
+	if (pMT != NULL)
+	{
+		ReleaseMultiTable(pMT);
+		free(pMT);
+	}
+
+	return 0;
+}
+
+#else
+int main(int argc, char *argv[])
+{
+
+	int i;
+	int retval;
+	MultiTable_t *pMT = NULL;
+	char filename[256];
+
+
+	if (argc >= 2)
+	{
+
+		if (argc == 2)
+		{
+			strcpy(filename, argv[1]);
+			//printf("%s\n", filename);
+			retval = CheckFilename(filename);
+
+			if (retval ==-1)
+			{
+				printf("wrong file name \"%s\", need ini file.\n", filename);
+				exit(0);
+			}
+		}
+		else
+		{
+			printf("Too may argument!\n");
+			exit(0);
+		}
+			
+	}
+	else
+	{
+		strcpy(filename, "multitable.ini");
+	}
+		
+
+	pMT = ParseMultiTableINI(filename);
+
+	
+	if (pMT != NULL)
+	{
+
+		for (i=0; i<pMT->modelNum; i++)
+		{
+			retval = parseSubTable(pMT->modelList[i]);
+		}
+
+		if (retval == 0)
+		{
+			strcpy(filename, "Multitable_");
+			strcat(filename, pMT->defaultModelName);
+			strcat(filename, ".bin");
+			retval = writeMultiTable(pMT, filename);
+			if (retval == 0)
+			{
+				printf("Create %s done.\n", filename);
+			}
+
+			strcpy(filename, "Flag_");
+			strcat(filename, pMT->defaultModelName);
+			strcat(filename, ".bin");
+
+			retval = writeMultiTableFlag(pMT, filename);
+			if (retval == 0)
+			{
+				printf("Create %s done.\n", filename);
+			}
+			
+		}
+	}
+	else
+	{
+		fprintf(stderr, "Error! Multitable not create!\n");
+	}
+
+	if (pMT != NULL)
+	{
+		ReleaseMultiTable(pMT);
+		free(pMT);
+		pMT = NULL;
+	}
+
+	return 0;
+}
+#endif

+ 729 - 0
tools/mergeImage/mt_mt.c

@@ -0,0 +1,729 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <regex.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <string.h>
+
+
+#include "mt_mt.h"
+#include "mt_aq.h"
+#include "mt_pq.h"
+
+
+//static MultiTable_t *gMT;
+
+static regex_t regex_comment;
+static regex_t regex;
+static unsigned int currLine = 0;
+
+
+void ReleaseSubTableItem(Item_t *pItem)
+{
+	if (pItem != NULL)
+	{
+		if (pItem->filepath != NULL)
+		{
+			free(pItem->filepath);
+			pItem->filepath = NULL;
+		}
+
+		if (pItem->pData != NULL)
+		{
+			free(pItem->pData);
+		}
+
+		memset(pItem, 0, sizeof(Item_t));
+	}
+}
+void ReleaseSubTable(SubTable_t *pSubTable)
+{
+	if (pSubTable != NULL)
+	{
+		int i;
+		for (i=0; i<pSubTable->itemNum; i++)
+		{
+			if(pSubTable->itemList[i] != NULL)
+			{
+				ReleaseSubTableItem(pSubTable->itemList[i]);
+				free(pSubTable->itemList[i]);
+			}
+		}
+		memset(pSubTable, 0, sizeof(SubTable_t));
+	}
+}
+
+
+void ReleaseMultiTable(MultiTable_t *pMT)
+{
+	if (pMT != NULL)
+	{
+		int i;
+		for (i=0; i<pMT->modelNum; i++)
+		{
+			if(pMT->modelList[i] != NULL)
+			{
+				ReleaseSubTable(pMT->modelList[i]);
+				free(pMT->modelList[i]);
+			}
+		}
+		memset(pMT, 0, sizeof(SubTable_t));
+	}
+}
+
+int GetValue(char *buf, char *StringID, char *StringValue)
+{
+	char *pch;
+	int retval = -1;
+	regmatch_t match[2];
+
+	retval = regexec(&regex, buf, 1, match, 0);
+	if( !retval ){
+		//puts("Match");
+		//printf("==>%s", buf);
+	}
+	else if( retval == REG_NOMATCH ){
+		//puts("No match");
+		//printf("==>%s", buf);
+	}
+	else{
+		//regerror(reti, &regex, msgbuf, sizeof(msgbuf));
+		//fprintf(stderr, "Error at %s line %d\n", filename, currLine);
+	}
+
+	pch = strtok (buf," =");
+	if (pch && strcmp(pch,StringID) == 0)
+	{
+		//printf ("%s=\n",pch);
+		pch = strtok (NULL, " =\"");
+		//printf ("\"%s\"\n",pch);
+		strcpy(StringValue, pch);
+		retval = 0;
+	}
+	else
+	{
+		retval = -1;
+	}
+
+	return retval;
+}
+int SubTable_AddItem(SubTable_t *pSubTable, char *itemName, char *itemFile)
+{
+	int retval = 0;
+	int currItemIndex;
+	if (pSubTable == NULL)
+	{
+		return -1;
+	}
+
+	if (itemName == NULL)
+	{
+		return -1;
+	}
+
+	if (itemFile == NULL)
+	{
+		return -1;
+	}
+
+	currItemIndex = pSubTable->itemNum;
+	pSubTable->itemList[currItemIndex] = malloc(sizeof(Item_t));
+
+	if (pSubTable->itemList[currItemIndex] == NULL)
+	{
+		retval = -1;
+	}
+	else
+	{
+		pSubTable->itemNum++;
+		memset(pSubTable->itemList[currItemIndex], 0 , sizeof(Item_t));
+		strcpy(pSubTable->itemList[currItemIndex]->name, itemName);
+		//check error
+		pSubTable->itemList[currItemIndex]->filepath = malloc(strlen(itemFile)+1);
+
+		if (pSubTable->itemList[currItemIndex]->filepath == NULL)
+		{
+			fprintf(stderr, "%s %d malloc error\n", __FUNCTION__, __LINE__);
+			pSubTable->itemNum--;
+			retval = -1;
+		}
+		else
+		{
+			strcpy(pSubTable->itemList[currItemIndex]->filepath, itemFile);
+		}
+
+	}
+
+	return retval;
+}
+
+
+int parseItem(Item_t *pItem)
+{
+	int retval = 0;
+	if (pItem != NULL)
+	{
+		if (strcmp(pItem->name, "AQ_OSD_TAB") == 0)
+		{
+			retval = parseAQ(pItem);
+		}
+		else if (strcmp(pItem->name, "PQ_OSD_TAB") == 0)
+		{
+			retval = parsePQ(pItem);
+		}
+		else if (strcmp(pItem->name, "COLOR_TMP_TAB") == 0)
+		{
+			retval = parsePQ(pItem);
+		}
+		else
+		{
+			retval = -1;
+		}
+
+	}
+
+
+	return retval;
+}
+
+int parseSubTable(SubTable_t *pSubTable)
+{
+	int retval = 0;
+	int i;
+	if (pSubTable == NULL)
+	{
+		return -1;
+	}
+
+	for (i=0;i<pSubTable->itemNum; i++)
+	{
+		retval = parseItem(pSubTable->itemList[i]);
+
+		if (retval == -1)
+		{
+			fprintf(stderr, "%s %d parse Item %d fail\n", __FUNCTION__, __LINE__, i);
+			break;
+		}
+	}
+
+
+	return retval;
+
+}
+
+
+MultiTable_t *ParseMultiTableINI(char *filename)
+{
+	FILE *fp = NULL;
+	MultiTable_t *pMT = NULL;
+	int retval;
+	char buf[LINEMAX];
+	regmatch_t match[2];
+	int step = 0;
+	char StringValue[256];
+	char ItemNameStr[256];
+	int currModelIndex=0;
+
+
+	if (filename == NULL)
+	{
+		fprintf(stderr, "%s filename == NULL\n", __FUNCTION__);
+		return NULL;
+	}
+
+	printf("Read ini from %s\n", filename);
+
+	fp = fopen(filename, "rb");
+	if (fp == NULL)
+	{
+		fprintf(stderr, "%s Can't open file %s\n", __FUNCTION__, filename);
+		return NULL;
+	}
+
+	/* Compile regular expression */
+	//retval = regcomp(&regex, "^(TableName|DefaultModel|ModelName|ItemName|ItemFile)+[ \t]*=[ \t]*\"[a-zA-Z0-9._/\\]*\"[ \t]*", 0);
+	retval = regcomp(&regex, "[a-zA-Z][ \t]*=[ \t]*\"[a-zA-Z0-9._/\\]*\"[ \t]*", 0);
+	if(retval)
+	{
+		fprintf(stderr, "Could not compile regex\n");
+		fclose(fp);
+		return NULL;
+	}
+	retval = regcomp(&regex_comment, "^[ \t]*#[.]*", 0);
+	if(retval)
+	{
+		regfree(&regex);
+		fclose(fp);
+		fprintf(stderr, "Could not compile regex\n");
+		return NULL;
+	}
+
+	pMT = (MultiTable_t *)malloc(sizeof(MultiTable_t));
+
+	if (pMT == NULL)
+	{
+		regfree(&regex);
+		regfree(&regex_comment);
+		fclose(fp);
+		fprintf(stderr, "MultiTable_t malloc fail\n");
+		return NULL;
+	}
+
+	memset(pMT, 0, sizeof(MultiTable_t));
+
+	currLine = 0;
+
+	while( (fgets (buf , LINEMAX , fp) != NULL))
+	{
+		currLine++;
+
+		retval = regexec(&regex_comment, buf, 1, match, 0);
+		if( !retval ){
+			//puts("Match comment");
+			//printf("==>%s", buf);
+		}
+		else if( retval == REG_NOMATCH ){
+			//puts("No match");
+			//printf("==>%s", buf);
+			//printf("step %d\n", step);
+			switch (step)
+			{
+				case 0:
+					retval=GetValue(buf, "TableName", StringValue);
+					if (retval == 0)
+					{
+						if (strlen(StringValue) < TABLENAMELEN)
+						{
+							strcpy(pMT->name,StringValue);
+						}
+						else
+						{
+							fprintf(stderr, "Tablename too long, max len is %d\n", TABLENAMELEN);
+							memcpy(pMT->name,StringValue, TABLENAMELEN);
+							pMT->name[TABLENAMELEN]='\0';
+						}
+					}
+					else
+					{
+						fprintf(stderr, "Multitable file expect string: TableName=\"abcd\"\n");
+					}
+					break;
+				case 1:
+					retval=GetValue(buf, "DefaultModel", StringValue);
+					if (retval == 0)
+					{
+						if (strlen(StringValue) < MODELNAMELEN)
+						{
+							strcpy(pMT->defaultModelName,StringValue);
+						}
+						else
+						{
+							fprintf(stderr, "DefaultModelName too long, max len is %d\n", MODELNAMELEN);
+							memcpy(pMT->defaultModelName,StringValue, MODELNAMELEN);
+							pMT->defaultModelName[MODELNAMELEN]='\0';
+						}
+					}
+					else
+					{
+						fprintf(stderr,"Multitable file expect string: DefaultModel=\"abcd\"\n");
+					}
+					break;
+				case 2:
+					retval=GetValue(buf, "ModelName", StringValue);
+					if (retval == 0)
+					{
+						SubTable_t *pSubTable = NULL;
+						pMT->modelNum++;
+						currModelIndex = pMT->modelNum-1;
+						pSubTable = (SubTable_t*)malloc(sizeof(SubTable_t));
+						if (pSubTable == NULL)
+						{
+							fprintf(stderr, "Unable to allocate SubTable_t memory %s %d\n", __FUNCTION__, __LINE__);
+							retval = -1;
+						}
+						else
+						{
+							memset(pSubTable, 0, sizeof(SubTable_t));
+							pMT->modelList[currModelIndex] = pSubTable;
+							if (strlen(StringValue) < MODELNAMELEN)
+							{
+								strcpy(pSubTable->modelName,StringValue);
+							}
+							else
+							{
+								fprintf(stderr, "ModelName too long, max len is %d\n", MODELNAMELEN);
+								memcpy(pSubTable->modelName,StringValue, MODELNAMELEN);
+								pSubTable->modelName[MODELNAMELEN]='\0';
+							}
+						}
+					}
+					else
+					{
+						fprintf(stderr, "Multitable file expect string: DefaultModel=\"abcd\"\n");
+					}
+					break;
+				case 3:
+				case 5:
+				case 7:
+					retval=GetValue(buf, "ItemName", ItemNameStr);
+					break;
+				case 4:
+				case 6:
+				case 8:
+					retval=GetValue(buf, "ItemFile", StringValue);
+					if (retval == 0)
+					{
+						SubTable_AddItem(pMT->modelList[currModelIndex], ItemNameStr, StringValue);
+					}
+					break;
+			}
+
+			if (retval == 0)
+			{
+				step++;
+			}
+			else
+			{
+				//Error happen break
+				fprintf(stderr, "Error at %s line %d\n", filename, currLine);
+				break;
+			}
+
+			if (step >= 9)
+			{
+				break;
+			}
+
+		}
+		else{
+			//regerror(reti, &regex, msgbuf, sizeof(msgbuf));
+			fprintf(stderr, "Error at %s line %d\n", filename, currLine);
+			fclose(fp);
+			regfree(&regex);
+			regfree(&regex_comment);
+			free(pMT);
+			pMT = NULL;
+			return NULL;
+		}
+
+	}
+
+	if (step != 9)
+	{
+		fprintf(stderr, "Error Multitable ini missing item\n");
+		free(pMT);
+		pMT = NULL;
+	}
+
+	fclose(fp);
+	regfree(&regex);
+	regfree(&regex_comment);
+
+
+	return pMT;
+
+}
+
+
+int GenSubTableBuf(SubTable_t *pSubTable)
+{
+	int i;
+	Item_t *pItem = NULL;
+	unsigned char *pOutBuf = NULL;
+
+	if (pSubTable == NULL)
+	{
+		fprintf(stderr, "%s error, pSubTable == NULL\n", __FUNCTION__);
+		return -1;
+	}
+
+	pOutBuf = malloc(MAXBINSIZE);
+	if (pOutBuf== NULL)
+	{
+		fprintf(stderr, "%s error, pSubTable->pData malloc error!\n", __FUNCTION__);
+		return -1;
+	}
+	pSubTable->pData = pOutBuf;
+	pSubTable->subTableSize = 0;
+
+	//fwrite(pSubTable->modelName, sizeof(char)*MODELNAMELEN, 1, fp);
+	writeTempBuf(pSubTable->modelName,  sizeof(char)*MODELNAMELEN, &pOutBuf);
+	pSubTable->subTableSize += sizeof(char)*MODELNAMELEN;
+
+	//fwrite(&pSubTable->subTableSize, sizeof(unsigned int), 1, fp);
+	writeTempBuf(&pSubTable->subTableSize,  sizeof(unsigned int), &pOutBuf);
+	pSubTable->subTableSize += sizeof(unsigned int);
+
+	//fwrite(&pSubTable->currTableStartOffset, sizeof(unsigned int), 1, fp);
+	writeTempBuf(&pSubTable->currTableStartOffset,  sizeof(unsigned int), &pOutBuf);
+	pSubTable->subTableSize += sizeof(unsigned int);
+
+	//fwrite(&pSubTable->itemNum, sizeof(unsigned int), 1, fp);
+	writeTempBuf(&pSubTable->itemNum,  sizeof(unsigned int), &pOutBuf);
+	pSubTable->subTableSize += sizeof(unsigned int);
+
+	//fwrite(&pSubTable->subTableNo, sizeof(unsigned int), 1, fp);
+	writeTempBuf(&pSubTable->subTableNo,  sizeof(unsigned int), &pOutBuf);
+	pSubTable->subTableSize += sizeof(unsigned int);
+
+	for (i=0; i<pSubTable->itemNum; i++)
+	{
+
+		pItem = pSubTable->itemList[i];
+
+		if (i==0)
+		{
+			pItem->offset = 16+16+(16+8)*pSubTable->itemNum;
+		}
+		else
+		{
+			pItem->offset = pSubTable->itemList[i-1]->offset +
+					pSubTable->itemList[i-1]->size + pSubTable->itemList[i-1]->dummyByteNums;
+		}
+
+
+		//fwrite(pItem->name, sizeof(char)*ITEMNAMELEN, 1, fp);
+		writeTempBuf(pItem->name,  sizeof(char)*ITEMNAMELEN, &pOutBuf);
+		pSubTable->subTableSize += sizeof(char)*ITEMNAMELEN;
+
+		//fwrite(&pItem->offset, sizeof(unsigned int), 1, fp);
+		writeTempBuf(&pItem->offset,  sizeof(unsigned int), &pOutBuf);
+		pSubTable->subTableSize += sizeof(unsigned int);
+
+		//fwrite(&pItem->size, sizeof(unsigned int), 1, fp);
+		writeTempBuf(&pItem->size,  sizeof(unsigned int), &pOutBuf);
+		pSubTable->subTableSize += sizeof(unsigned int);
+	}
+
+	for (i=0; i<pSubTable->itemNum; i++)
+	{
+		pItem = pSubTable->itemList[i];
+		//fwrite(pItem->pData, pItem->size, 1, fp);
+		writeTempBuf(pItem->pData, pItem->size, &pOutBuf);
+		pSubTable->subTableSize += pItem->size;
+		//for 4 bytes aligment
+		if (pItem->dummyByteNums != 0)
+		{
+			char dummy = 0;
+			int j;
+			for(j=0; j<pItem->dummyByteNums; j++)
+			{
+				//fwrite(&dummy, sizeof(char), 1, fp);
+				writeTempBuf(&dummy,sizeof(char), &pOutBuf);
+			}
+			pSubTable->subTableSize += pItem->dummyByteNums;
+		}
+	}
+
+	pOutBuf = pSubTable->pData + (sizeof (char)*MODELNAMELEN);
+	writeTempBuf(&pSubTable->subTableSize,  sizeof(unsigned int), &pOutBuf);
+
+	//pSubTable->checksum = CalCulate_XOR_CheckSum(pSubTable->pData, pSubTable->subTableSize);
+
+	return 0;
+
+}
+
+int writeMultiTable(MultiTable_t *pMTab, char *outputFilename)
+{
+
+	FILE *fp = 0;
+	unsigned char *pOutBuf = NULL;
+	int i;
+
+	if (pMTab == NULL)
+	{
+		fprintf(stderr, "%s Error! pMTab == NULL\n", __FUNCTION__);
+		return -1;
+	}
+
+	pOutBuf = malloc(MAXMULTITABLEBINSIZE);
+	if (pOutBuf== NULL)
+	{
+		fprintf(stderr, "%s error, pMTab->pData malloc error!\n", __FUNCTION__);
+		return -1;
+	}
+
+	pMTab->pData = pOutBuf;
+	pMTab->totalSize = 0;
+
+	fp = fopen(outputFilename, "wb");
+	if (fp == NULL)
+	{
+		fprintf(stderr, "Unable to write file %s\n", outputFilename);
+		return -1;
+	}
+
+	for (i=0; i<pMTab->modelNum; i++)
+	{
+		pMTab->modelList[i]->subTableNo = i;
+
+		if (i==0)
+		{
+			pMTab->subTableOffset[0] = 24 + 8*pMTab->modelNum;
+			pMTab->modelList[0]->currTableStartOffset = pMTab->subTableOffset[0];
+		}
+		else
+		{
+			pMTab->subTableOffset[i] = pMTab->subTableOffset[i-1]+pMTab->modelList[i-1]->subTableSize;
+			pMTab->modelList[i]->currTableStartOffset = pMTab->subTableOffset[i];
+
+		}
+
+		GenSubTableBuf(pMTab->modelList[i]);
+		pMTab->modelList[i]->checksum = CalCulate_XOR_CheckSum(pMTab->modelList[i]->pData, pMTab->modelList[i]->subTableSize/sizeof(unsigned int));
+
+		if (i==0)
+		{
+			pMTab->subTableOffset[0] = 24 + 8*pMTab->modelNum;
+		}
+		else
+		{
+			pMTab->subTableOffset[i] = pMTab->subTableOffset[i-1]+pMTab->modelList[i-1]->subTableSize;
+		}
+	}
+
+	//fwrite(pMTab->name, sizeof(char)*TABLENAMELEN, 1, fp);
+	writeTempBuf(pMTab->name,  sizeof(char)*TABLENAMELEN, &pOutBuf);
+	pMTab->totalSize += sizeof(char)*TABLENAMELEN;
+
+	//fwrite(&pMTab->modelNum, sizeof(unsigned int), 1, fp);
+	writeTempBuf(&pMTab->modelNum,  sizeof(unsigned int), &pOutBuf);
+	pMTab->totalSize += sizeof(unsigned int);
+
+	//fwrite(&pMTab->totalSize, sizeof(unsigned int), 1, fp);
+	writeTempBuf(&pMTab->totalSize,  sizeof(unsigned int), &pOutBuf);
+	pMTab->totalSize += sizeof(unsigned int);
+
+	//fwrite(&pMTab->tableChecksum, sizeof(unsigned int), 1, fp);
+	writeTempBuf(&pMTab->tableChecksum,  sizeof(unsigned int), &pOutBuf);
+	pMTab->totalSize += sizeof(unsigned int);
+
+	for (i=0; i<pMTab->modelNum; i++)
+	{
+		//fwrite(&pMTab->subTableOffset[i], sizeof(unsigned int), 1, fp);
+		writeTempBuf(&pMTab->subTableOffset[i],  sizeof(unsigned int), &pOutBuf);
+		pMTab->totalSize += sizeof(unsigned int);
+
+		//fwrite(&pMTab->modelList[i]->checksum, sizeof(unsigned int), 1, fp);
+		writeTempBuf(&pMTab->modelList[i]->checksum,  sizeof(unsigned int), &pOutBuf);
+		pMTab->totalSize += sizeof(unsigned int);
+	}
+
+
+	for (i=0; i<pMTab->modelNum; i++)
+	{
+		writeTempBuf(pMTab->modelList[i]->pData, pMTab->modelList[i]->subTableSize, &pOutBuf);
+		pMTab->totalSize += pMTab->modelList[i]->subTableSize;
+	}
+
+	pOutBuf = pMTab->pData + 16; // point to Main Table total size
+	writeTempBuf(&pMTab->totalSize,  sizeof(unsigned int), &pOutBuf);
+
+	pOutBuf = pMTab->pData + 24; // point to SubTable 0 start offset position
+	pMTab->tableChecksum = CalCulate_XOR_CheckSum(pOutBuf, pMTab->modelNum*2);
+	pOutBuf = pMTab->pData + 20; // point to Table check sum
+	writeTempBuf(&pMTab->tableChecksum,  sizeof(unsigned int), &pOutBuf);
+
+
+	fwrite(pMTab->pData, pMTab->totalSize, 1, fp);
+
+	fflush(fp);
+	fclose(fp);
+	return 0;
+}
+
+
+int writeMultiTableFlag(MultiTable_t *pMTab, char *outputFilename)
+{
+	unsigned char updated = 0;
+	FILE *fp;
+	
+	if (pMTab == NULL)
+	{
+		fprintf(stderr, "%s Error! pMTab == NULL\n", __FUNCTION__);
+		return -1;
+	}	
+
+	fp = fopen(outputFilename, "wb");
+	if (fp == NULL)
+	{
+		fprintf(stderr, "Unable to write file %s\n", outputFilename);
+		return -1;
+	}
+
+	fwrite(&updated, sizeof(unsigned char), 1, fp);
+	
+	fwrite(pMTab->defaultModelName, sizeof(char)*MODELNAMELEN, 1, fp);
+
+	fflush(fp);
+
+	fclose(fp);
+
+	return 0;
+	
+
+}
+
+
+int writeOutputBuf(void *pData, unsigned int size, unsigned char **pOutBuf, FILE *fp)
+{
+	int retval =0;
+
+#if WRITEITEMTOFILE
+	if (fp != NULL)
+	{
+		fwrite(pData, size, 1, fp);
+	}
+	else
+	{
+		fprintf(stderr, "%s %d error\n", __FUNCTION__, __LINE__);
+		retval = -1;
+		goto out;
+	}
+#endif
+	if (*pOutBuf != NULL)
+	{
+		memcpy(*pOutBuf,pData, size);
+		*pOutBuf = *pOutBuf + size;
+	}
+	else
+	{
+		fprintf(stderr, "%s %d error\n", __FUNCTION__, __LINE__);
+		retval = -1;
+	}
+out:
+	return retval;
+
+}
+
+int writeTempBuf(void *pData, unsigned int size, unsigned char **pOutBuf)
+{
+	int retval =0;
+
+	if (*pOutBuf != NULL)
+	{
+		memcpy(*pOutBuf,pData, size);
+		*pOutBuf = *pOutBuf + size;
+	}
+	else
+	{
+		fprintf(stderr, "%s %d error\n", __FUNCTION__, __LINE__);
+		retval = -1;
+	}
+	return retval;
+
+}
+
+unsigned int CalCulate_XOR_CheckSum(void *pBuffer, unsigned int size)
+{
+	unsigned int idx = 0, checksum = 0;
+
+	for (idx = 0; idx < size; idx++)
+	{
+		checksum = checksum ^ ((unsigned int *)pBuffer)[idx];
+	}
+	return checksum;
+}

+ 72 - 0
tools/mergeImage/mt_mt.h

@@ -0,0 +1,72 @@
+/*
+ * mt.h
+ *
+ */
+
+#ifndef MT_H_
+#define MT_H_
+
+
+#define WRITEITEMTOFILE 1
+
+#define LINEMAX 256
+#define TABLENAMELEN 12
+#define MODELNAMELEN 16
+#define ITEMNAMELEN 16
+#define MODELNUMMAX 2
+#define SUBTABLEITEMMAX 3
+#define MAXBINSIZE 8*1024
+#define MAXMULTITABLEBINSIZE 8*1024
+
+typedef struct _Item_t
+{
+	char name[ITEMNAMELEN+1];
+	char *filepath;
+	unsigned int offset;
+	unsigned int size;
+	unsigned char *pData;
+	unsigned int dummyByteNums; //for 4 bytes data alignment;
+}Item_t;
+
+typedef struct _SubTable_t
+{
+	char modelName[MODELNAMELEN+1];
+	unsigned int subTableSize;
+	unsigned int currTableStartOffset;
+	unsigned int itemNum;
+	unsigned int subTableNo;
+	Item_t *itemList[SUBTABLEITEMMAX];
+	unsigned int checksum;
+	unsigned char *pData;
+}SubTable_t;
+
+
+typedef struct _MultiTable_t
+{
+	char name[TABLENAMELEN+1];
+	char defaultModelName[MODELNAMELEN+1];
+	unsigned int totalSize;
+	unsigned int tableChecksum;
+	unsigned int subTableOffset[MODELNUMMAX];
+	int modelNum;
+	SubTable_t *modelList[MODELNUMMAX];
+	unsigned char *pData;
+}MultiTable_t;
+
+
+int parseItem(Item_t *pItem);
+int parseSubTable(SubTable_t *pSubTable);
+MultiTable_t *ParseMultiTableINI(char *filename);
+int writeOutputBuf(void *pData, unsigned int size, unsigned char **pOutBuf, FILE *fp);
+int writeTempBuf(void *pData, unsigned int size, unsigned char **pOutBuf);
+int writeMultiTable(MultiTable_t *pMTab, char *outputFilename);
+int writeMultiTableFlag(MultiTable_t *pMTab, char *outputFilename);
+void ReleaseSubTableItem(Item_t *pItem);
+void ReleaseSubTable(SubTable_t *pSubTable);
+void ReleaseMultiTable(MultiTable_t *pMT);
+unsigned int CalCulate_XOR_CheckSum(void *pBuffer, unsigned int size);
+
+
+
+
+#endif /* MT_H_ */

+ 223 - 0
tools/mergeImage/mt_pq.c

@@ -0,0 +1,223 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <regex.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <string.h>
+
+#include "mt_mt.h"
+
+#define LINEMAX 256
+#define PQOSDSETTINGVER_LEN 16
+
+
+int parsePQ(Item_t *pItem)
+{
+	FILE *fp = NULL;
+	FILE *binfp = NULL;
+	//int retval;
+	//long filelen = 0;
+	char buf[LINEMAX];
+	unsigned char *pOutBuf;
+	//int datasize= 0;
+	int line = 0;
+	int retval = 0;
+	int value;
+	int databyte;
+	char PQOSDSetting_ver[PQOSDSETTINGVER_LEN];
+
+#if WRITEITEMTOFILE
+	char binFileName[256];
+#endif
+
+
+
+
+	pOutBuf = (unsigned char *)malloc(MAXBINSIZE);
+
+	if (pOutBuf == NULL)
+	{
+		fprintf(stderr, "Unable alloc pOutBuf buffer\n");
+		return -1;
+	}
+
+
+	pItem->pData = pOutBuf;
+	pItem->size = 0;
+
+	if (pItem->filepath != NULL && pOutBuf!= NULL)
+	{
+		printf("%s open file %s\n", __FUNCTION__, pItem->filepath);
+		fp = fopen(pItem->filepath, "rb");
+#if WRITEITEMTOFILE
+		strcpy(binFileName, pItem->name);
+		binfp = fopen(strcat(binFileName,".bin"), "wb");
+		if (fp != NULL && binfp != NULL)
+#else
+		if (fp != NULL)
+#endif
+		{
+
+			char *pch;
+			//int reti;
+			//regmatch_t match[2];
+			/* Compile regular expression */
+			//reti = regcomp(&regex, "^ItemFile[ \t]*=[ \t]*\"[a-zA-Z0-9._/\\]*\"[ \t]*", 0);
+			//reti = regcomp(&regex, "^[ \t]*#[.]*", 0);
+			//if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }
+
+			/* Free compiled regular expression if you want to use the regex_t again */
+
+			if (fgets (buf , LINEMAX , fp) == NULL)
+			{
+				fprintf(stderr, "%s %d fgets error!\n", __FUNCTION__, __LINE__);
+#if WRITEITEMTOFILE
+				fclose(binfp);
+
+#endif
+				fclose(fp);
+				free(pOutBuf);
+				return -1;
+			}
+			line++;
+			if (fgets (buf , LINEMAX , fp) == NULL)
+			{
+				fprintf(stderr, "%s %d fgets error!\n", __FUNCTION__, __LINE__);
+#if WRITEITEMTOFILE
+				fclose(binfp);
+
+#endif				
+				fclose(fp);
+				free(pOutBuf);
+				return -1;
+			}			
+			pch = strtok (buf," \t\r\n");
+			pch = strtok (NULL, " \t\r\n");
+			if (strlen(pch) <=PQOSDSETTINGVER_LEN)
+			{
+				fprintf(stderr, "strlen(pch) = %d\n", strlen(pch));
+				memset(PQOSDSetting_ver,0,PQOSDSETTINGVER_LEN);
+				memcpy(PQOSDSetting_ver, pch, strlen(pch));
+
+				//fwrite(PQOSDSetting_ver, sizeof(char)*PQOSDSETTINGVER_LEN, 1, binfp);
+				writeOutputBuf(PQOSDSetting_ver, sizeof(char)*PQOSDSETTINGVER_LEN, &pOutBuf, binfp);
+				pItem->size += sizeof(char)*PQOSDSETTINGVER_LEN;
+			}
+			else
+			{
+				//fprintf(stderr, "PQOSDSetting_ver len > %d, strip it\n",PQOSDSETTINGVER_LEN);
+				//fprintf(stderr, "strlen(pch) = %d\n", strlen(pch));
+				memset(PQOSDSetting_ver,0,PQOSDSETTINGVER_LEN);
+				memcpy(PQOSDSetting_ver, pch, PQOSDSETTINGVER_LEN);
+
+				//fwrite(PQOSDSetting_ver, sizeof(char)*PQOSDSETTINGVER_LEN, 1, binfp);
+				writeOutputBuf(PQOSDSetting_ver, sizeof(char)*PQOSDSETTINGVER_LEN, &pOutBuf, binfp);
+				pItem->size += sizeof(char)*PQOSDSETTINGVER_LEN;
+
+			}
+			line++;
+			if (fgets (buf , LINEMAX , fp) == NULL)
+			{
+#if WRITEITEMTOFILE
+				fclose(binfp);
+
+#endif				
+				fclose(fp);
+				free(pOutBuf);
+				return -1;
+					
+			}	
+			line++;
+
+		    while( fgets (buf , LINEMAX , fp) != NULL )
+			{
+		    	short data_word;
+		    	char data_byte;
+		    	line++;
+				//reti = regexec(&regex, buf, 1, match, 0);
+				//if( !reti ){
+				//	puts("Match");
+				//	printf("==>%s", buf);
+				//}
+				//else if( reti == REG_NOMATCH ){
+				//	puts("No match");
+				//	printf("==>%s", buf);
+				//}
+				//else{
+				//	//regerror(reti, &regex, msgbuf, sizeof(msgbuf));
+				//	fprintf(stderr, "Regex match failed:\n");
+				//}
+				pch = strtok (buf,"@");
+				pch = strtok (NULL, " @\t\r\n");
+				value = atoi(pch);
+				//printf ("%s\n",pch);
+				pch = strtok (NULL, " @\t\r\n");
+				//printf ("%s\n",pch);
+				databyte = atoi(pch);
+
+
+				switch (databyte)
+				{
+					case 1:
+						data_byte = (char) value;
+						//fwrite(&data_byte, sizeof(char), 1, binfp);
+						writeOutputBuf(&data_byte, sizeof(char), &pOutBuf, binfp);
+						pItem->size += sizeof(char);
+						break;
+					case 2:
+						data_word = (short) value;
+						//fwrite(&data_word, sizeof(short), 1, binfp);
+						writeOutputBuf(&data_word, sizeof(short), &pOutBuf, binfp);
+						pItem->size += sizeof(short);
+						break;
+					case 3:
+						data_byte = (char) (value & 0xff);
+						data_word = (short) (value>>8);
+						//fwrite(&data_byte, sizeof(char), 1, binfp);
+						//fwrite(&data_word, sizeof(short), 1, binfp);
+						writeOutputBuf(&data_byte, sizeof(char), &pOutBuf, binfp);
+						writeOutputBuf(&data_word, sizeof(short), &pOutBuf, binfp);
+						pItem->size += sizeof(char)+ sizeof(short);
+						break;
+					case 4:
+						//fwrite(&value, sizeof(int), 1, binfp);
+						writeOutputBuf(&value, sizeof(int), &pOutBuf, binfp);
+						pItem->size += sizeof(int);
+						break;
+				}
+
+			}
+
+		    //regfree(&regex);
+		}
+		else
+		{
+			perror("Can't open file");
+		}
+
+	}
+
+
+	//for 4 bytes aligment
+	pItem->dummyByteNums = 0;
+	if ((pItem->size % 4) != 0)
+	{
+		pItem->dummyByteNums = 4 - (pItem->size % 4);
+	}
+
+	if (fp != NULL)
+	{
+		fclose(fp);
+	}
+
+
+	if (binfp != NULL)
+	{
+		fflush(binfp);
+		fclose(binfp);
+	}
+	return retval;
+
+}

+ 12 - 0
tools/mergeImage/mt_pq.h

@@ -0,0 +1,12 @@
+/*
+ * pq.h
+ *
+ */
+
+#ifndef PQ_H_
+#define PQ_H_
+
+
+int parsePQ(Item_t *pItem);
+
+#endif /* PQ_H_ */

+ 258 - 0
tools/mergeImage/option.h

@@ -0,0 +1,258 @@
+/************************/
+/* SiS P330 option file */
+/* Version 2012/09/28   */
+/*                      */
+/************************/
+
+//#define		OP_IRCommandType			1		// 0:PHILIPS 1:NEC 2:SONY 3:JVC 4:SHARP 5:SAMPO 6:CUSTOUM define
+// IRCommandTable=Ir_Set_090512.bin			//file name 256 bye bin file
+#define		OP_TV_ProjectID			0		//20110713 for OAD
+#define		OP_TV_TerminalCustomerID	0 		//20110713 for OAD
+#define		OP_TV_VersionNo			0		//20110713 for OAD
+
+#define		OP_ATV_TunerDelay			3
+#define		OP_ATV_CVD2SyncDetect		0x3c
+#define		OP_DTV_TunerDelay			0x0a
+#define		OP_DTV_DemuxWait			0x2e
+	               ;// Nile setting
+// NileSet=NileSet_20081217.bin				//file name 512 bye bin file
+	               ;// Audio
+#define		OP_AudioConnect			0		//A-AMP=0 , D-AMP(ST)=31 , D-AMP(TI)=41 , D-AMP(YAMAHA)=51
+#define		OP_TSXTOutputGain			0x40       
+       ;// TSXTOutputGain outputgain control the compensated gain when SRS TSXT output gain
+       ;// 0: 0dB, 1: 0.125dB .... 0x8: 1dB,  0x30: 6dB   0x40: 8db(default)
+	               ;// CVD2
+// CVD2Set=CVD2Set128_temp0X.bin           //file name 128 bye bin file
+	               ;//Reserve
+	               ;//Reserved_Data[128];
+
+// Audio SIF threshold setting
+#define		OP_ATV_MN1ThH				0x22		//Carrier 1 Quality AAOS Threshold High Register (0x4A)
+#define		OP_ATV_MN1ThL				0x16		//Carrier 1 Quality AAOS Threshold Low Register (0x4B)
+#define		OP_ATV_MN2ThH				0x34		//Carrier 2 Quality AAOS Threshold High Register (0x4C)
+#define		OP_ATV_MN2ThL				0x21		//Carrier 2 Quality AAOS Threshold Low Register (0x4D)
+#define		OP_ATV_PN2ThH				0x80		//Carrier 1 Phase Noise AAOS Threshold high (0x4E)
+#define		OP_ATV_PN2ThL				0x20		//Carrier 1 Phase Noise AAOS Threshold low (0x4F)
+#define		OP_ATV_FMSMTh				0x4b		//FM Subcarrier Magnitude AAOS Threshold High Registers (0x50)
+#define		OP_ATV_FMSMTl				0x32		//FM Subcarrier Magnitude AAOS Threshold Low Registers (0x51)
+#define		OP_ATV_FMSNTh				0x14		//FM Subcarrier Noise AAOS Threshold High Registers (0x52)
+#define		OP_ATV_FMSNTl				0x0a 		//FM Subcarrier Noise AAOS Threshold Low Registers (0x53)
+#define		OP_ATV_NIERTh				0x50		//NICAM Error Rate AAOS Threshold High Register (0x54)
+#define		OP_ATV_NIERTl				0x30		//NICAM Error Rate AAOS Threshold Low Register (0x55)
+#define		OP_ATV_PILMTh				0xb0		//Pilot Magnitude AAOS Threshold High Register (0x56)
+#define		OP_ATV_PILMTl				0x64		//Pilot Magnitude AAOS Threshold Low Register (0x57)
+#define		OP_ATV_ASMTh				0x19		//Carrier Magnitude ASD Threshold (0x81)
+#define		OP_ATV_ASQTh				0x1a		//Carrier FM Quality ASD Threshold (0x83)
+#define		OP_ATV_AANTh				0x09		//Carrier AM Noise ASD Threshold (0x84)
+#define		OP_ATV_ANNTh				0x1e		//NICAM Noise ASD Threshold (0x85)
+#define		OP_ATV_SQlTh				0x1a		//Carrier FM Quality SCS Threshold (0x8D)
+#define		OP_ATV_SNsTh				0x1e		//NICAM Noise SCS Threshold (0x8E)
+
+	//110908
+#define		OP_ATV_ASFTh				0x18		//Carrier Average Frequency ASD Threshold (0x82)
+#define		OP_ATV_AVOLCo				0x09		//Automatic Volume Correction (0x90): AVCEn[0]¡BAVCDcy[2:1]¡BAVCAtk[4:3]
+#define		OP_ATV_PSCLCh				0xff		//Prescaler Level Left Channel (0x92)
+#define		OP_ATV_PSCRCh				0xff		//Prescaler Level Right Channel (0x93)
+#define		OP_ATV_AVCThH				0x7c		//AVC Level Thresholds High (0x96)
+#define		OP_ATV_AVCThL				0x6e		//AVC Level Thresholds Low (0x97)
+#define		OP_ATV_NIAMPLe				0x32		//NICAM Analog Mono Prescaler Level (0x98)
+#define		OP_ATV_NIPLe				0xff		//NICAM Prescaler Level (0x99)
+#define		OP_ATV_A2PLe				0x32		//A2 Prescaler Level (0x9A)
+#define		OP_ATV_IAVCLo				0x00		//AVC Manual Gain Control (0xA2)
+#define		OP_ATV_IAVCRo				0x00		//AVC Manual Gain Control (0xA3)
+
+
+//**************************************************************************************
+//   PLC_enable; //0x3AD(941)
+//       PLC_enable define
+//       b[0] : SISDAC PLC,  0: Disable,  1: Enable
+//       b[1:2] : DAMP PLC,  0: Disable,  1: Enable SW DPLC,   2: Enable DAMP HW PLC function (if DAMP can support PLC feature)
+//       b[3] : PLC channel select(only for DAMP use),  0: master channel , 1:  CH1_CH2
+//       b[4] : PLC enable control:  0: by option data,  1: by menu control
+//       b[5] : PLC unit : 0: dbfs , 1: watt (current not support)
+//       b[6:7] : Reserved
+//
+//       PLC_timer;  //0x3AE(942)
+//       PLC_Sp_attack; //0x3AF (943)
+//       PLC_Sp_release; //0x3B0(944)
+//       PLC_Hp_attack;//0x3B1(945)
+//       PLC_Hp_release;//0x3B2(946)
+//       PLC_Lo_attack; //0x3BC(956)   
+//       PLC_Lo_release;  //0x3BD(957)
+//***************************************************************************************
+
+// Audio PowerLimiterControl_Option
+#define		OP_PLC_enable				0x01; //0x3AD(941)
+#define		OP_PLC_timer				0x03 ; //0x3AE(942) , min = 3 (0.1s) , 10(0.5s)  max = ff
+#define		OP_PLC_Sp_attack			0x58; //0x3AF (943), min :F0 = -30db  , default: 58 = -11db , max: 0 = 0db
+#define		OP_PLC_Sp_release			0x58; //0x3B0(944), min :F8 = -31db  , default: 58 = -11db , max: 0 = 0db
+#define		OP_PLC_Hp_attack			0xb8; //0x3B1 (945), min :F0 = -30db  , default: b8 = -23db , max: 0 = 0db
+#define		OP_PLC_Hp_release			0xb8; //0x3B2(946), min :F8 = -31db  , default: b8 = -23db , max: 0 = 0db
+#define		OP_PLC_Lo_attack			0x00    // 00~ff; //0x3BC(956) // audio only for SISDAC line out use, if not use please set 00
+#define		OP_PLC_Lo_release			0x00   // 00~ff; //0x3BD(957) // audio only for SISDAC line out use, if not use please set 00
+	               	               
+// Audio SINGLE VOL TB
+        //please use the source that has smallest input level to be reference, and set its offset = 0db, 
+        //offset unit is -0.125db, and it must be hex, not dec      
+        //0: 0db, 0x1: -0.125db, 0x2:-0.25db 0x3:-0.375db....8: -1db, e:-1.75db, f:-1.875db...10:-2db, 30:-6db ....ff: -31.875db 
+#define		OP_VolTB_Single			0x00          //0: multi volume table   1: single volume table
+#define		OP_VolTB_Offset_ATV		0x30     // 00~ff   if(==30) is 0x30 = 48/8 = -6db
+#define		OP_VolTB_Offset_DTV		0x00     // 00~ff 
+#define		OP_VolTB_Offset_HDMI		0x00    // 00~ff 
+#define		OP_VolTB_Offset_LINEIN		0x30  // 00~ff 
+#define		OP_VolTB_Offset_MP3		0x00     // 00~ff 
+#define		OP_VolTB_Offset_PC			0x30      // 00~ff 
+#define		OP_VolTB_Offset_C1			0x00      // 00~ff  for movies source <= 20110509
+#define		OP_VolTB_Offset_C2			0x00      // 00~ff 
+
+#define		OP_standByPowerON			0x02fd48b7	;//IR  remote controller Power ID
+#define		OP_To_Panel_1_IR			0x00F61109   //0x3D0 IR_KeyCOde for change panel setting to
+#define		OP_To_Panel_2_IR			0x00F61209   //0x3D4 IR_KeyCOde for change panel setting to
+#define		OP_To_Panel_3_IR			0x00F64109   //0x3D8 IR_KeyCOde for change panel setting to
+
+//IR_POWER_KEY_1  ;// at Ir_set
+//IR_POWER_KEY_2  ;// at Ir_set
+#define		OP_IR_power_key_3			0x00  		//0x3DC  (988)
+#define		OP_IR_power_key_4			0x00  		//0x3E0  (992)
+#define		OP_IR_power_key_5			0x00  		//0x3E4  (996)
+#define		OP_IR_power_key_6			0x00  		//0x3E8 (1000)
+
+#define		OP_DC_OFF_DELAY_TIME		0x00000001	// 0x770
+#define		OP_KEYPAD_PWR_ON_KEY		0x00300000	// 0x774	//set 1: 1.98~1.32V
+//---------------------------------
+#define		OP_DVD_IR_OUT_GPIO			0x1A		// 0x778	//26
+#define		OP_GPIO_V33_ENABLE			0x22		// 0x779	//34
+#define		OP_GREEN_LED_GPIO_EN		0x01		// 0x77a
+#define		OP_GREEN_LED_GPIO_NO		0x01		// 0x77b	//GPIO01
+#define		OP_GREEN_LED_PWM_NO		0x00		// 0x77c
+#define		OP_RED_LED_GPIO_EN			0x00		// 0x77d
+#define		OP_RED_LED_GPIO_NO			0x00		// 0x77e
+#define		OP_RED_LED_PWM_NO			0x01		// 0x77f
+//-------------  for 330 Reserved 128 bytes  20120705
+#define		OP_pReserved_00			0x00		//0x77c
+#define		OP_pReserved_01			0x01				
+#define		OP_pReserved_02			0x02				
+#define		OP_pReserved_03			0x03				
+#define		OP_pReserved_04			0x04				
+#define		OP_pReserved_05			0x05				
+#define		OP_pReserved_06			0x06				
+#define		OP_pReserved_07			0x07				
+#define		OP_pReserved_08			0x08				
+#define		OP_pReserved_09			0x09				
+#define		OP_pReserved_10			0x10				
+#define		OP_pReserved_11			0x11				
+#define		OP_pReserved_12			0x12				
+#define		OP_pReserved_13			0x13				
+#define		OP_pReserved_14			0x14				
+#define		OP_pReserved_15			0x15				
+#define		OP_pReserved_16			0x16				
+#define		OP_pReserved_17			0x17				
+#define		OP_pReserved_18			0x18				
+#define		OP_pReserved_19			0x19				
+#define		OP_pReserved_20			0x20				
+#define		OP_pReserved_21			0x21				
+#define		OP_pReserved_22			0x22				
+#define		OP_pReserved_23			0x23				
+#define		OP_pReserved_24			0x24				
+#define		OP_pReserved_25			0x25				
+#define		OP_pReserved_26			0x26				
+#define		OP_pReserved_27			0x27				
+#define		OP_pReserved_28			0x28				
+#define		OP_pReserved_29			0x29		//0x7f7	//add for 16-byt alignment
+//-------------
+//GPIO=GPIO.bin		//0x7f8~877	// 128 bytes
+//-------------
+			//ATV/DTV chennel scan		
+#define		OP_ChannelScan				0x03		//0:default value, 1:scan ATV only, 2:scan DTV  only, 3: scan ATV and DTV
+//PWM control   (BYTE SystemLED[15])
+//Bit[7]:Green 	Bit[6]:Red	Bit[5:0]:flick frequency
+#define		OP_Custom_LED_EntryOFF		0x4f        //81~8F (81: fastest light flash)
+#define		OP_Custom_LED_OFF			0x4f        //40:Red
+#define		OP_Custom_LED_EntryOn		0xcc        //41~4F(41:fastest light flash)
+#define		OP_Custom_LED_LogoOn		0x8f        //C0:G+R
+#define		OP_Custom_LED_EntryLinux	0x80       	//C1~CF(C1:faster light flash )
+#define		OP_Custom_LED_AllReady		0x80 
+#define		OP_Custom_LED_PowerSaveOn	0xc2
+#define		OP_Custom_LED_PowerSaveOff	0xc0
+#define		OP_Custom_LED_DPMSON		0x00
+#define		OP_Custom_LED_07			0x00
+#define		OP_Custom_LED_09			0x00
+#define		OP_Custom_LED_0B			0x00
+#define		OP_Custom_LED_0C			0x00
+#define		OP_Custom_LED_0D			0x00
+#define		OP_Custom_LED_0E			0x00
+                       //; Test only
+#define		OP_TestValue				0x00
+#define		OP_CursorXY				0x00		// 0:(0,0) 1:(w/2,h/2) 1: in middle
+#define		OP_Reserved_DW_A			0x00		//Reserve DWORD
+#define		OP_Custom_self_ID			0x00		// Owner each project PM  recommend as manufactur ID + serial
+#define		OP_Custom_self_Feature		0x00   		// Owner each project PM  for bit use it; bit[0] 1: panel Inverse
+#define		OP_Custom_Globe_Feature	0x00  		// Owner n/a  for bit use it
+
+#define		OP_Custom_Feature			0x00		//UMF use
+			//HDCP version (BYTE)
+#define		OP_HDCP_version			0x00
+                       ;//Reserve BYTE
+#define		OP_CIOption				0x00		//index
+#define		OP_Reserved_B_B			0x00
+#define		OP_Reserved_B_C			0x00
+#define		OP_Reserved_B_D			0x00
+#define		OP_Reserved_B_E			0x00
+#define		OP_Reserved_B_F			0x00
+#define		OP_Reserved_B_G			0x00
+#define		OP_versionCheck			0x10390516	//It must be 0x10390516
+#define		OP_structVersion			0x13		//major version for the struct 
+#define		OP_FAE_Version				0x00000000	//minor version for FAE assign (DWORD)
+#define		OP_testerVersion			0x00000000	//any tester can assign (DWORD)
+
+#define		OP_ChannelScan_ChangeScreen	0x00	//When channel scan, 0:set blue screen
+
+#define		OP_EDIDEepromEnable		0x00		//0x4D9(1241) bit0:slave0->HDMI1
+			//	   bit1:slave1->HDMI2
+			//        bit2:slave2->VGA 
+
+//KeyPad=KeyPad.bin		256 bytes
+
+#define		OP_standByPowerON2			0xcc33c13e
+
+#define		OP_NormalWaitingTime		0x0a 	//NonPC_DPMSOff_PanelOff_Time
+#define		OP_ESWaitingTime			0x0a 	//NonPC_DPMSOn_PowerOff_Time
+#define		OP_NonPCPowerOffTime		0x0e10 	//NonPC_DPMSOff_PowerOff_Time
+#define		OP_DPMSOnWaitingTime		0x05 	//PWS_PC_DPMSOn_PowerOff_Time
+#define		OP_DPMSOffWaitingTime		0x0a 	//PWS_PC_DPMSOff_PanelOff_Time
+#define		OP_PCPowerOffTime			0x0e10 	//PWS_PC_DPMSOff_PowerOff_Time
+#define		OP_PseudoPowerTime			0x0e10
+
+#define		OP_EpgParamData			0x00		;// bit0:??? 
+			// 0:SiS, 6:HannStar, b:Tatung
+#define		OP_Line1					"T01S_US_M"
+#define		OP_Line2					"T01S_US_D"
+#define		OP_Line3					"CMO 37"
+#define		OP_Line4					"12345678901234567890"
+#define		OP_Line5					"Line5!!"
+#define		OP_Line6					"Line6!!"
+#define		OP_Line7					"Line7!!"
+#define		OP_Line8					"Line8!!"
+
+//Freq_Table=Freq_Table.bin		Not use 20120927
+
+#define		OP_HDMI_SWITCH				0x00
+#define		OP_HDMI_PORT_MAP			0x21
+
+    //--------------------------- Ex Option =>
+#define		OP_ExVersion				0x15
+            //line09~12 20 bytes line13~16 40 bytes and it will stop at "Enter" or max length
+#define 	OP_Line09					"line_09" //20byte
+#define 	OP_Line10					"line_10" //20byte
+#define 	OP_Line11					"line_11" //20byte
+#define 	OP_Line12					"line_12" //20byte
+#define 	OP_Line13					"line_13" //40byte
+#define 	OP_Line14					"line_14" //40byte
+#define 	OP_Line15					"line_15" //40byte
+#define 	OP_Line16					"line_16" //40byte
+#define 	OP_OPTION_CHECK_STRUCT_CODE 0x10390516
+//--------------------------- Ex Option <=
+
+
+
+

+ 171 - 0
tools/mergeImage/option_330.c

@@ -0,0 +1,171 @@
+#include "mergeImage.h"
+#include <Customization.h>
+#include "gpioset.h"
+
+#ifdef OP_IRCommandType
+#define showMsg( args... ) printf( args )
+
+CUSTIMIZATION_TABLE OptionData;
+
+int GetOptionData(void )
+{
+	//unsigned char i, j;
+	showMsg( "\n**** GetOptionData ****\n");
+	memset(&OptionData, 0, sizeof(OptionData));
+	/* ------------------------------------------------*/
+	#if 0
+	OptionData.GPIOSET[0] = 0x1e;
+	OptionData.GPIOSET[1] = 0x02;
+	OptionData.GPIOSET[2] = 0x15;
+	OptionData.GPIOSET[3] = 0x16;
+	OptionData.GPIOSET[4] = 0xe0;
+	OptionData.GPIOSET[5] = 0xa4;
+	OptionData.GPIOSET[6] = 0x88;
+	OptionData.GPIOSET[7] = 0x09;
+	OptionData.GPIOSET[8] = 0x0a;
+	OptionData.GPIOSET[9] = 0x0b;
+	OptionData.GPIOSET[10] = 0x0c;
+	OptionData.GPIOSET[11] = 0x0d;
+	OptionData.GPIOSET[12] = 0x0e;
+	OptionData.GPIOSET[13] = 0x11;
+	OptionData.GPIOSET[14] = 0xc3;
+	OptionData.GPIOSET[15] = 0xbf;
+	OptionData.GPIOSET[16] = 0xff;
+	OptionData.GPIOSET[17] = 0x00;
+	#endif
+	/*------------------------------------------------*/
+	OptionData.IRCommandType = OP_IRCommandType;
+	// IR setting
+	OptionData.pIR_Set[0] = OP_IR_Protocol_reg;				/* 0xbe080004 */
+	showMsg( "OP_IR_Protocol_reg=%x\tpIR_Set=%x\n", (unsigned int)OP_IR_Protocol_reg, (unsigned int)OptionData.pIR_Set[0]);
+	OptionData.pIR_Set[1] = OP_IR_Interrupt_en_reg;			/* 0xbe080008 */
+	OptionData.pIR_Set[2] = OP_IR_Interrupt_staus;			/* 0xbe08000c */
+	OptionData.pIR_Set[3] = OP_IR_MinSpaceBetweenPacket;	/* 0xbe080010 */
+	OptionData.pIR_Set[4] = OP_IR_Max_Min_Symbol;			/* 0xbe080014 */
+	OptionData.pIR_Set[5] = OP_IR_Max_Min_Short_Mark;		/* 0xbe080018 */
+	OptionData.pIR_Set[6] = OP_IR_Max_Min_Short_Space;		/* 0xbe08001c */
+	OptionData.pIR_Set[7] = OP_IR_Max_Min_Long_Mark;		/* 0xbe080020 */
+	OptionData.pIR_Set[8] = OP_IR_Max_Min_Head_Mark;		/* 0xbe080024 */
+	OptionData.pIR_Set[9] = OP_IR_Max_Min_Head_Space;		/* 0xbe080028 */
+	OptionData.pIR_Set[10] =OP_IR_REG_2C;					/* 0xbe08002c */
+	OptionData.pIR_Set[11] =OP_IR_Max_Min_Repeat_Space;		/* 0xbe080030 */
+	OptionData.pIR_Set[12] =OP_IR_Extra_Decode_Option;		/* 0xbe080034 */
+	OptionData.pIR_Set[13] =OP_IR_REG_38;					/* 0xbe080038 */
+	OptionData.pIR_Set[14] =OP_IR_WatchDog_Timeout;			/* 0xbe08003c */
+	OptionData.pIR_Set[15] =OP_IR_Repeat_Threshold;			/* 0xbe080040 */
+	OptionData.pIR_Set[16] =OP_IR_Packet_Timeout_Threshold;	/* 0xbe080044 */
+	OptionData.pIR_Set[17] =OP_IR_Key_Press_Counter;		/* 0xbe080048 */
+	OptionData.pIR_Set[18] =OP_IR_Protocol_Type_Option;		/* 0xbe08004c */
+	OptionData.pIR_Set[19] =OP_IR_Internal_Counter;			/* 0xbe080050 */
+	OptionData.pIR_Set[20] =OP_IR_Bit47_to_Bit16;			/* 0xbe080054 */
+	OptionData.pIR_Set[21] =OP_IR_Receiver_Signal;			/* 0xbe080058 */
+	OptionData.pIR_Set[22] =OP_IR_Power_Code_Option;		/* 0xbe08005c */
+	OptionData.pIR_Set[23] =OP_IR_Power_Code_A_Low_Channel;	/* 0xbe080060 */
+	OptionData.pIR_Set[24] =OP_IR_Power_Code_A_High_Channel;/* 0xbe080064 */
+	OptionData.pIR_Set[25] =OP_IR_Power_Code_B_Low_Channel;	/* 0xbe080068 */
+	OptionData.pIR_Set[26] =OP_IR_Power_Code_B_High_Channel;/* 0xbe08006c */
+	OptionData.pIR_Set[27] =OP_IR_Power_Code_C_Low_Channel;	/* 0xbe080070 */
+	OptionData.pIR_Set[28] =OP_IR_Power_Code_C_High_Channel;/* 0xbe080074 */
+	OptionData.pIR_Set[29] =OP_IR_Power_Code_D_Low_Channel;	/* 0xbe080078 */
+	OptionData.pIR_Set[30] =OP_IR_Power_Code_D_High_Channel;/* 0xbe08007c */
+	OptionData.pIR_Set[31] =OP_IR_Max_Min_Long1_MarkSpace;	/* 0xbe080080 */
+	OptionData.pIR_Set[32] =OP_IR_Max_Min_Long2_MarkSpace;	/* 0xbe080084 */
+	//------------------------------------------------//
+	OptionData.PowerOnKeySets = 2;
+	OptionData.KEYPAD_PWR_ON_KEY = OP_KEYPAD_PWR_ON_KEY;
+	showMsg("----\n");
+	//------------------------------------------------//
+	// LED
+	OptionData.GreenLEDNum = 0x01;		// GPIO 01 as Green LED
+	OptionData.GreenLEDMode = 1;		// GPIO mode
+	OptionData.RedLEDNum = 1;			// PWM0 as Red LED
+	OptionData.RedLEDMode = 0;			// PWM mode
+	OptionData.LEDOnStatus = 0x80;
+	OptionData.LEDOffStatus = 0x40;
+	// Panel
+	OptionData.PanelPWROnGPIONum = 2;	// GPIO 02 as panel power control
+	OptionData.PanelBackLightGPIONum = 30;	// GPIO 30 as Back Light control
+	OptionData.PanelPWMNum = 2;				// PWM 2 as Back Light Brig
+	//------------------------------------------------//
+	OptionData.DVD_IROUT_GPIO_NO = 28;			/* 0xbe080098 */
+	//------------------------------------------------//
+	OptionData.HDMISwitchMap = OP_HDMI_SWITCH;				/* 0xbe08009A */
+	OptionData.HDMIPortMap = OP_HDMI_PORT_MAP;				/* 0xbe08009C */
+	
+	OptionData.IR_PowerOnKey[0].Custom_Code = 0x09f6;		/* 0xbe0800A0 */
+	OptionData.IR_PowerOnKey[0].Key_Code[0] = 0x45ba;
+	OptionData.IR_PowerOnKey[1].Custom_Code = 0x649b;		/* 0xbe0800C0 */
+	OptionData.IR_PowerOnKey[1].Key_Code[0] = 0x50af;
+
+	showMsg( "\n**** GetOptionData done ****\n");
+	//------------------------------------------------//
+	showMsg( "**** size of Option:%x ****\n", sizeof(OptionData));
+	return 0;
+}
+
+int GPIOini2Bin(unsigned char *GPIOData)
+{
+	int i, j;
+	char pChar[256];
+	PADJUST_GPIO GPIOiniData;
+	GPIO_FORMAT GPIOset[64];
+	FILE *fPtr;
+	char GPIOdescript[256];
+	int nFieldNum;
+
+	showMsg( "\n**** GPIOini2Bin ****\n");
+	memset(pChar, 0xFF, sizeof(pChar));
+	memset(GPIOset, 0, sizeof(GPIOset));
+	memset(GPIOdescript, 0, sizeof(GPIOdescript));
+	GPIOiniData = (PADJUST_GPIO)(pChar);
+
+	fPtr = fopen(GPIOSetIniFileName, "r");
+	if ( fPtr == NULL ) {
+		showMsg("### Open %s file fail ###\n", GPIOSetIniFileName);
+		return -1;
+	}
+	do {
+		// Get string from file
+		if(fgets(GPIOdescript, sizeof(GPIOdescript), fPtr));
+	} while (((GPIOdescript[0]=='#')&&(GPIOdescript[1]!='i')&&(GPIOdescript[2]!='n')&&(GPIOdescript[3]!='d')&&(GPIOdescript[4]!='e')&&(GPIOdescript[5]!='x')) || \
+			 ((GPIOdescript[0]!='i')&&(GPIOdescript[1]!='n')&&(GPIOdescript[2]!='d')&&(GPIOdescript[3]!='e')&&(GPIOdescript[4]!='x')) );
+	j = 0;
+	for ( i=0;i<64;i++) {
+		nFieldNum  = fscanf(fPtr,"%d %d %d %d %d %d %d %d %d %d %d %x",(int *)&GPIOset[i].index, \
+															  (int *)&GPIOset[i].AuxEnalbe,\
+															  (int *)&GPIOset[i].AuxMode,\
+															  (int *)&GPIOset[i].AuxValue,\
+															  (int *)&GPIOset[i].AInternalPU,\
+															  (int *)&GPIOset[i].AInternalPD, \
+															  (int *)&GPIOset[i].MainEnalbe,\
+															  (int *)&GPIOset[i].MainMode,\
+															  (int *)&GPIOset[i].MainValue,\
+															  (int *)&GPIOset[i].MInternalPU, \
+															  (int *)&GPIOset[i].MInternalPD, \
+															  (int *)&GPIOset[i].MDELAY_TIME);
+		GPIOiniData->GPIO[j] = GPIOset[i].index;
+		GPIOiniData->GPIO[j+1] = GPIOset[i].AuxEnalbe +\
+								(GPIOset[i].AuxMode<<1) +\
+								(GPIOset[i].AuxValue<<2) +\
+								(GPIOset[i].AInternalPU<<3) +\
+								(GPIOset[i].AInternalPD<<4) +\
+								(GPIOset[i].MainEnalbe<<5) +\
+								(GPIOset[i].MainMode<<6) +\
+								(GPIOset[i].MainValue<<7);
+
+
+		GPIOiniData->GPIO[j+2] = (GPIOset[i].MInternalPU<<6) +\
+								 (GPIOset[i].MInternalPD<<7) +\
+								 (GPIOset[i].MDELAY_TIME&0x3F);
+		//showMsg("\n**** GPIO%d:%02x %02x ****\n", GPIOiniData->GPIO[j], GPIOiniData->GPIO[j+1], GPIOiniData->GPIO[j+2]);
+		j = j+3;
+		if ( feof(fPtr) ) break;
+	}
+	fclose(fPtr);
+	memcpy(GPIOData, GPIOiniData, sizeof(ADJUST_GPIO));
+	showMsg( "\n**** GPIOini2Bin done (%d sets) ****\n", nFieldNum);
+	return 0;
+}
+
+#endif	// OP_IRCommandType
+

+ 726 - 0
tools/mergeImage/parseConfig.c

@@ -0,0 +1,726 @@
+//-------------------------------------------------------------------------------
+#include "parseConfig.h"
+#include "loadBasicPacket.h"
+//-------------------------------------------------------------------------------
+
+const char* ACTION_NAME[ACTION_MAX] = { "FileName", "Protected", "MaxSize", "NVMData", "PathName", "Output", "BasicPacket", "END" };
+
+enum {
+	ACTION_FILENAME = 0,
+	ACTION_PROTECTED,
+	ACTION_MAXSIZE,
+	ACTION_NVMDATA,
+	ACTION_PATHNAME,	
+	ACTION_OUTPUT,	
+	ACTION_BASICPACKET,
+	ACTION_ENDFILE
+};
+
+int parseAction;
+//u32 flashModuleInfoNum;
+NorFlashModuleInfo flashModuleInfo[MODULE_MAX];
+NorFlashModulePathInfo flashModulePathInfo[PATHINFO_MAX];
+char DEFAULT_FILE_NAME[] = "S2.code.bin";
+char BIN_FILENAME[128];
+
+NVMData gNVMData[MODULE_MAX];
+u32 gNVMData_count = 0;
+
+
+#ifndef CONFIG_BIN_FILENAME
+   #define CONFIG_BIN_FILENAME DEFAULT_FILE_NAME
+#endif
+
+//---------------------------------------------------------------------------
+static inline int check_keyword( const char *keyword, const char* tempString )
+{	//return (!strncmp(keyword, tempString, strlen(keyword)))  ;gaia fixed
+    char tmp[FILENAME_SIZE];
+    char *ptr = NULL;
+    memset(tmp ,'\0', FILENAME_SIZE);
+    strcpy(tmp ,tempString);
+    ptr = strstr(tmp, "=" );
+    if (ptr != NULL)
+	{
+        *ptr = '\0';
+	}
+	if(!strncmp(keyword, "CONFIG_", (int)7))	//parse string CONFIG_
+		return false;
+    return (strlen(keyword)==0)?false:(!strncmp(keyword, tmp, strlen(tmp)))  ;
+}
+//---------------------------------------------------------------------------
+static bool copy_settingString( char* dstString, const char* tempString )
+{
+	char* tmp = strstr( tempString, "=" );
+	if (tmp == NULL)
+		return false;
+	tempString = tmp + 1;
+	strcpy( dstString, tempString );
+	return true;
+}
+//---------------------------------------------------------------------------
+static bool copy_settingYesNo( bool* dstValue, const char* tempString )
+{
+	char* tmp = strstr( tempString, "=" );
+	if (tmp == NULL)
+		return false;
+	tempString = tmp + 1;
+
+	switch( tempString[0] )
+	{
+		case 'y': case 'Y': *dstValue = true; break;
+		case 'n': case 'N': *dstValue = false; break;
+		default: return false;
+	}
+	
+	return true;
+}
+//---------------------------------------------------------------------------
+char* fgetLine( char *s, int size, FILE *fpIn )
+{
+	int i = 0;
+
+	while( i == 0 )
+	{
+		if( fgets( s, size, fpIn ) == NULL ) return NULL;
+
+		i = strlen( s );
+
+		if( s[i-1] == '\n' )
+		{
+			i--;
+			if( (i != 0) && s[i-1] == '\r' ) i--;
+			s[i] = '\0';
+		}
+	}
+	
+	return s;
+}
+
+//---------------------------------------------------------------------------
+// Search ModuleInfo & ActionIndex
+//---------------------------------------------------------------------------
+
+NorFlashModuleInfo* searchModuleInfo( const char *moduleName )
+{
+	int i = 0;
+	for( i = 0; i < MODULE_MAX; i++ )
+	{
+		if( check_keyword( flashModuleInfo[i].moduleName, moduleName ) ) {
+			//printFlashModuleInfo( &flashModuleInfo[i] );
+			return &flashModuleInfo[i];
+		}
+	}
+
+	//showMsg( "warning! searchModuleInfo failed (%s)\n", moduleName );
+	return NULL;
+}
+
+NorFlashModulePathInfo* searchModulePathInfo( const char *moduleName )
+{
+	int i = 0;
+	for( i = 0; i < PATHINFO_MAX; i++ )
+	{
+		if( check_keyword( flashModulePathInfo[i].moduleName, moduleName ) ) 
+			return &flashModulePathInfo[i];
+	}
+
+	errMsg( "searchModulePathInfo failed (%s)\n", moduleName );
+	return NULL;
+}
+
+static inline int searchActionIndex( const char *actionName )
+{
+	int i = 0;
+	for( i = 0; i <ACTION_MAX; i++ )
+	{
+		if( check_keyword( ACTION_NAME[i], actionName ) ) return i;
+	}
+
+	return -1;
+}
+#if 0//ndef RELEASE_VER
+
+static inline void bootrom_append_dbg_string(NorFlashModuleInfo *moduleInfo)
+{
+	static char* bootrom_str = "BootROM";
+	static char* dbg_str = "_dbg.bin";
+	if(!strncmp(moduleInfo->moduleName , bootrom_str, strlen(bootrom_str))){
+		//hard coding.....carefully
+		int tmp_str_len = strlen(moduleInfo->fileName);
+		showMsg( "bootrom_append_dbg_string: %s ->", moduleInfo->fileName);
+		memcpy(&moduleInfo->fileName[tmp_str_len-4], dbg_str, strlen(dbg_str)+1);
+		//moduleInfo->fileName[tmp_str_len+4]='\0';
+		showMsg( " %s \n", moduleInfo->fileName);
+	}
+
+}
+#endif
+void initFlashModuleInfo(int moduleIndex, const char *moduleName, u32 flashAddr1, u32 flashSize1)
+{
+	//initSingleNorFlashModuleInfoCrossFlash( moduleName, flashAddr1, flashSize1, 0, 0 );
+	
+	NorFlashModuleInfo *info;
+
+	info = &flashModuleInfo[moduleIndex];
+	//flashModuleInfoNum++
+	info->isValid = false;
+	info->isProtected = false;
+	info->isInitModuleNameByUser = false;
+	info->isInitProtectedByUser = false;
+	info->flashAddr1 = flashAddr1;
+	info->flashSize1 = flashSize1;		
+    info->max_module_size = 0;
+//	info->flashAddr2 = 0; 
+//	info->flashSize2 = 0;	
+	info->fileName[0] = '\0';
+	strcpy( info->moduleName, moduleName );
+	printf("info->moduleName %s\n", info->moduleName);
+}
+
+
+//---------------------------------------------------------------------------
+// Parse mergeImage.cfg 
+//---------------------------------------------------------------------------
+
+static inline bool parseMIC_FileName( const char* tempString )
+{	
+	bool ret = false;
+#ifdef CONFIG_APPEND_NAME_TO_CIKEY_HDCPKEY
+	char *token;
+	char tokenfileName[FILENAME_SIZE];	
+	char tname[FILENAME_SIZE];	
+#endif
+	NorFlashModuleInfo *moduleInfo = searchModuleInfo( tempString );
+	if( moduleInfo == NULL ) return false;
+
+	if( moduleInfo->isInitModuleNameByUser )
+	{
+		errMsg( "[%s] re-assign fileName\n", moduleInfo->moduleName );
+		return false;
+	}
+
+	if( copy_settingString( moduleInfo->fileName, tempString ) )
+	{
+		moduleInfo->isInitModuleNameByUser = true;
+		if(  moduleInfo->fileName[0] != '\0' ) moduleInfo->isValid = true;
+		ret = true;
+	}
+#ifdef CONFIG_APPEND_NAME_TO_CIKEY_HDCPKEY
+	memset(tname, 0, FILENAME_SIZE);
+	strcpy(tokenfileName, moduleInfo->fileName );
+	token = strtok(tokenfileName,"/"); /*There are two delimiters here*/
+    while (token != NULL){
+		strcpy(tname, token);
+        token = strtok(NULL," /");
+    }
+	strcpy(moduleInfo->eachfileName, tname);
+#endif
+#if 0//ndef RELEASE_VER
+	/*special take care bootrom debug/release version */
+	bootrom_append_dbg_string(moduleInfo);
+#endif
+	return ret;
+}
+
+static inline bool parseMIC_Protected( const char* tempString )
+{	
+	NorFlashModuleInfo *moduleInfo = searchModuleInfo( tempString );
+	if( moduleInfo == NULL ) return false;
+
+	if( moduleInfo->isInitProtectedByUser )
+	{
+		errMsg( "[%s] re-assign protect\n", moduleInfo->moduleName );
+		return false;
+	}
+
+	if( copy_settingYesNo( &moduleInfo->isProtected, tempString ) )
+	{
+		moduleInfo->isInitProtectedByUser = true;
+		return true;
+	}
+
+	return false;
+}
+
+static inline bool parseMIC_MaxSize( const char* tempString )
+{
+    char max_size[12];
+    NorFlashModuleInfo *moduleInfo = searchModuleInfo( tempString );
+
+    memset(max_size, '\0', 12);
+    if( moduleInfo == NULL ) return false;
+
+    if(copy_settingString(max_size, tempString ) )
+    {
+        moduleInfo->max_module_size = atoi(max_size);
+        return true;
+    }
+
+    return false;
+}
+
+
+static inline bool parseMIC_NVMdata( const char* tempString )
+{
+    char tmp[FILENAME_SIZE];
+    char *ptr;
+
+    memset(tmp, 0, FILENAME_SIZE);
+    strcpy(tmp, tempString);
+    ptr = strstr(tmp, "=" );
+	if (ptr == NULL)
+		return false;
+    *ptr = '\0';
+    gNVMData[gNVMData_count].id = atoi(tmp);
+    strcpy(gNVMData[gNVMData_count].pathName, ptr+1);
+    gNVMData_count++;
+    return true;
+}
+
+#if 0
+static inline bool parseMIC_PathName( const char* tempString )
+{
+	NorFlashModulePathInfo *modulePathInfo = searchModulePathInfo( tempString );
+	if( modulePathInfo == NULL ) return false;
+
+	return copy_settingString( modulePathInfo->pathName, tempString );
+}
+#endif
+static inline bool parseMIC_Output( const char* tempString )
+{
+	if( check_keyword( "Folder", tempString ) ) 
+		return copy_settingString( miOutputPathName, tempString );
+	else if( check_keyword( "judgeDebugVersion", tempString )  )
+		return copy_settingYesNo( &miJudgeDebugVersionFlag, tempString );
+	return false;
+}
+
+static inline bool parseMIC_BasicPacket( const char* tempString )
+{
+	if( check_keyword( "BasicPacket", tempString ) ) 
+	{
+		if( !copy_settingString( miBaseImageName, tempString ) ) return false;
+		return loadBasicPacket();
+	}
+		
+	return false;
+}
+
+//---------------------------------------------------------------------------
+
+static inline bool parseMIC_Action( const char* tempString )
+{	
+	int index = searchActionIndex( tempString );
+	if( index < 0 ) return false;
+
+	parseAction = index;
+	return true;
+}
+
+static inline bool parseMIC_Setting( const char* tempString )
+{	
+	switch( parseAction )
+	{
+		case ACTION_FILENAME: return parseMIC_FileName( tempString );
+		case ACTION_PROTECTED: return parseMIC_Protected( tempString );
+        case ACTION_MAXSIZE: return parseMIC_MaxSize( tempString );
+        case ACTION_NVMDATA: return parseMIC_NVMdata( tempString );
+	//	case ACTION_PATHNAME: return parseMIC_PathName( tempString );
+		case ACTION_OUTPUT: return parseMIC_Output( tempString );			
+		case ACTION_BASICPACKET: return parseMIC_BasicPacket( tempString );
+		case ACTION_ENDFILE: return true;
+		default:
+			errMsg( "parseAction (%d) not define\n", parseAction ); return false;
+	}
+}
+
+static inline bool parseMergeImageConfigString( const char* tempString )
+{	
+	switch( tempString[0] )
+	{
+		case '@': return parseMIC_Action( tempString+1 );
+		case '#': return true;
+		default: return parseMIC_Setting( tempString );
+	}	
+}
+// ivan
+char *parseQuota(char *str)
+{
+    int i, n=strlen(str);
+    char *p=str;
+	for(i=0;i<n;)
+	{
+		if(*p!='"')
+			str[i++] = *p;
+		p++;
+	}
+	return str;
+}
+
+bool parseMergeImageConfigFile( const char *filename)
+{
+	int parseLine; bool ret = true;
+	char tempString[TMP_BUFFER_SIZE];
+	FILE *fpIn = fopen( filename, "rt" );     
+    	if( fpIn == NULL ) 
+  	{
+  		errMsg( "MergeImageConfig (%s) not found!\n", filename );
+		return false;
+  	}    
+
+	for( parseLine = 1; !feof(fpIn); parseLine++ )
+	{
+		if( fgetLine( tempString, TMP_BUFFER_SIZE, fpIn ) != NULL ) 
+		{
+#if DBG_SHOW_CONFIG_LINE
+			dbgMsg( "line%d: %s\n",parseLine, tempString );
+#endif
+			 // ivan
+			strcpy(tempString, parseQuota( tempString ));
+			ret = parseMergeImageConfigString( tempString );
+		}
+
+		if( !ret ) 
+		{
+			showMsg( "\nwarning!Parse config failed , line:%d , string: \n\"%s\"\n\n", parseLine, tempString );
+			ret = true;//gaia
+			//break;
+		}
+
+		if( parseAction == ACTION_ENDFILE ) break;
+	}
+	
+	fclose( fpIn ); 
+	return ret; 
+}
+
+//---------------------------------------------------------------------------
+// Parse BasicSaveInfo
+//---------------------------------------------------------------------------
+
+static inline bool parseBasicSaveInfoString( const char* tempString )
+{
+	u32 searchSize;
+	const char *endString;
+	char searchName[32];
+	NorFlashModuleInfo* info;
+	
+	if( tempString[0] != '[' ) return true;
+	tempString += 1;
+	
+	if( check_keyword( "CODE", tempString ) ) return true;
+	else if( check_keyword( "DATA", tempString ) ) return true; 
+	else if( check_keyword( "MODEL", tempString ) ) return true; 
+
+	endString = strstr( tempString, "]" );
+	if( endString == NULL ) return false;
+
+	searchSize = endString - tempString;
+	strncpy( searchName, tempString, searchSize );
+	searchName[searchSize] = '\0';
+
+	info = searchModuleInfo( searchName );
+	if( info == NULL ) return true;
+	if( info->isInitModuleNameByUser ) return true;
+	if( info->isInitProtectedByUser ) return true;
+
+	info->isProtected = true;
+ 	dbgMsg( "BasicSaveInfo: set %s protected\n", info->moduleName );
+	return true;
+}
+
+static inline bool parseBasicSaveInfo( const char *filename)
+{
+	int parseLine; bool ret = true;
+	char tempString[TMP_BUFFER_SIZE];
+	FILE *fpIn = fopen( filename, "rt" );     
+    	if( fpIn == NULL ) 
+  	{
+  		errMsg( "BasicSaveInfo (%s) not found!\n", filename );
+		return false;
+  	}    
+
+	dbgMsg( "\nparseBasicSaveInfo =>\n" );
+	for( parseLine = 1; !feof(fpIn); parseLine++ )
+	{
+		if( fgetLine( tempString, TMP_BUFFER_SIZE, fpIn ) != NULL ) 
+        	{
+#if DBG_SHOW_CONFIG_LINE
+        		dbgMsg( "line%d: %s\n",parseLine, tempString );
+#endif
+			if( check_keyword( "#END", tempString ) ) break;
+			ret = parseBasicSaveInfoString( tempString );
+		}
+
+		if( !ret ) 
+        	{
+			errMsg( "Parse config failed\n, line:%d , string: %s\n", parseLine, tempString );
+			break;
+		}
+	}
+	
+	fclose( fpIn ); 
+	return ret; 
+}
+
+//---------------------------------------------------------------------------
+// init & load moduleInfo
+//---------------------------------------------------------------------------
+#if 0
+void initSingleNorFlashModuleInfoCrossFlash( 
+	const char *moduleName, u32 flashAddr1, u32 flashSize1, u32 flashAddr2, u32 flashSize2 )
+{
+	NorFlashModuleInfo *info;
+
+	info = &flashModuleInfo[flashModuleInfoNum++];
+	info->isValid = false;
+	info->isProtected = false;
+	info->isInitModuleNameByUser = false;
+	info->isInitProtectedByUser = false;
+	info->flashAddr1 = flashAddr1;
+	info->flashSize1 = flashSize1; 		
+	info->flashAddr2 = flashAddr2; 
+	info->flashSize2 = flashSize2;	
+	info->fileName[0] = '\0';
+	strcpy( info->moduleName, moduleName );
+}
+#endif
+
+
+inline void printFlashModuleInfo( NorFlashModuleInfo *info )
+{
+#if DBG_SHOW_PARSE_RESULT
+	showMsg( "[Module] %s\n", info->moduleName );
+	showMsg( "isValid=%s\n",  info->isValid ? "true" : "false" );
+	showMsg( "isProtected=%s\n", info->isProtected ? "true" : "false" );	
+	showMsg( "isInitModuleNameByUser=%s\n",  info->isInitModuleNameByUser ? "true" : "false" );		
+	showMsg( "isInitProtectedByUser=%s\n", info->isInitProtectedByUser ? "true" : "false" );	
+	showMsg( "flashAddr1=0x%08x\n", info->flashAddr1 );	
+	showMsg( "flashSize1=0x%08x\n", info->flashSize1 );	
+	showMsg( "flashAddr2=0x%08x\n", info->flashAddr2 );	
+	showMsg( "flashSize2=0x%08x\n", info->flashSize2 );	
+	showMsg( "fileName=%s\n", info->fileName );		
+#endif
+}
+
+static inline void reviewFlashModuleInfoFlag(int index)
+{
+	//NorFlashModuleInfo *info
+	if( isLoadBasicPacket() ) return;
+
+#if MI_PROTECT_INVALID_MODULE	
+	if( (flashModuleInfo[index].isInitModuleNameByUser) && (!flashModuleInfo[index].isValid) )
+	{
+	
+#if defined(OP_IRCommandType)
+		if( MODULE_OPTION == index) return;
+#endif
+
+		flashModuleInfo[index].isProtected= true;
+		showMsg( "[%s] Auto force set protect=y\n", flashModuleInfo[index].moduleName );
+	}
+#endif
+}
+
+/* remove space after filename */
+static inline void reviewFlashModuleFileName( NorFlashModuleInfo *info )
+{
+	int max = strlen(info->fileName);
+
+	for( ; max > 0 ; max-- )
+	{
+		if( info->fileName[max-1] != ' ' ) break; 
+	}
+
+	info->fileName[max] = '\0';
+}
+
+static inline void reviewFolderString( const char *folderName, char *folderString, const char *defaultFolder )
+{
+	u32 strLen = strlen(folderString);
+	while( strLen && (folderString[strLen-1] == '/' )  ) folderString[--strLen] = '\0';
+
+	if( strLen == 0 ) strcpy( folderString, defaultFolder );
+	dbgMsg( "%s : %s\n", folderName, folderString );
+}
+
+#include "init_flash_module.h"
+//---------------------------------------------------------------------------
+
+static inline void initSingleNorFlashModulePathInfo( 
+	NorFlashModulePathInfo *info, const char *moduleName, const char *pathName )
+{
+	strcpy( info->moduleName, moduleName );
+	strcpy( info->pathName, pathName );
+}
+#if 0
+static inline void initNorFlashModulePathInfo()
+{
+	initSingleNorFlashModulePathInfo( &flashModulePathInfo[0], "BootROM", PATHNAME_BOOTROM );
+	initSingleNorFlashModulePathInfo( &flashModulePathInfo[1], "AudioROM", PATHNAME_AUDIOROM );
+}
+#endif
+//---------------------------------------------------------------------------
+
+bool loadNorFlashModuleInfo()
+{
+	int index;
+	//initNorFlashModulePathInfo();
+    initNorFlashModuleInfo();
+    parseAction = -1;
+    flashModuleInfo[MODULE_OPTION].isValid = true;   //force Option = valid
+    flashModuleInfo[MODULE_END].isValid = true;   //force END = valid
+#ifdef CONFIG_SUPPORT_NVM_PRELOAD
+    flashModuleInfo[MODULE_NVM].isValid = true;   //force END = valid
+#endif
+	if( !parseMergeImageConfigFile(miConfigFile) ) return false;
+
+	for( index = 0; index < MODULE_MAX; index++ )
+	{
+		reviewFlashModuleInfoFlag(index);
+		reviewFlashModuleFileName( &flashModuleInfo[index] );
+		printFlashModuleInfo( &flashModuleInfo[index] );
+	}
+	reviewFolderString( "OutputFolder", miOutputPathName, PATHNAME_OUTPUT );
+	//reviewFolderString( "BootROMFolder", searchModulePathInfo( MODULENAME_BOOTROM )->pathName, PATHNAME_BOOTROM );
+	//reviewFolderString( "AudioROMFolder", searchModulePathInfo( MODULENAME_AUDIOROM )->pathName, PATHNAME_AUDIOROM );
+
+	//if( isLoadBasicPacket() ) parseBasicSaveInfo( BASEIMAGE_SAVE );
+	return true;
+}
+
+//---------------------------------------------------------------------------
+// parse Program Argument ... 
+//---------------------------------------------------------------------------
+
+static inline void showProgramUsageHint()
+{
+	showMsg( "\nUsage: mergeImage targetDir targetName <option(s)>\n\n" );
+	showMsg( "=> targetDir: The directory of source files.\n");
+	showMsg( "=> targetName: Final production file-name. Don't need to include the file extension. (*.packet *.bin)\n\n");
+
+	showMsg( "The options are:\n" );
+	showMsg( "=> -Config=<configFile>:	Re-specified the mergeImage configuration file.\n" );
+	showMsg( "=> -deleteTempFile=<Y/N>:	Re-specified delete intermediate files or not.\n" );
+	showMsg( "=> -generatePacket=<Y/N>:	Re-specified generate packet or not.\n" );
+	showMsg( "=> -generateOriginalBin=<Y/N>:	Re-specified generate original-bin or not.\n" );	
+	showMsg( "\n" );
+}
+
+static inline void showFlashMapItemInfo( const char* s, u32 addr, u32 size )
+{
+	showMsg( "%8s: 0x%08x, %d KB\n", s, addr, ROUND_KB( size ) );
+}
+#if 0
+static inline void showDynamicItemOfFlashMap()	/* debug for sisspi_flashalloc.h*/
+{
+	showMsg( "\nDynamicItemOfFlashMap=>\n" );
+	showFlashMapItemInfo( "RRTTable", SPI_RRTTABLE_FLASHADDR, SPI_RRTTABLE_FLASHSIZE );
+//	showFlashMapItemInfo( "RRTTable2", SPI_RRTTABLE2_FLASHADDR, SPI_RRTTABLE2_FLASHSIZE );	
+	showFlashMapItemInfo( "Logo", SPI_LOGO_FLASHADDR, SPI_LOGO_FLASHSIZE );
+//	showFlashMapItemInfo( "Logo2", SPI_LOGO2_FLASHADDR, SPI_LOGO2_FLASHSIZE );
+	showFlashMapItemInfo( "Backup64K", SPI_MEMALLOCBACKUP_FLASHADDR, 64*1024 );		
+	showFlashMapItemInfo( "MultiTable", SPI_MULTITABLE_FLASHADDR, SPI_MULTITABLE_FLASHSIZE );		
+	showFlashMapItemInfo( "AudioROM", SPI_AUDIOROM_FLASHADDR, SPI_AUDIOROM_FLASHSIZE );	
+	showFlashMapItemInfo( "Kernel", SPI_KERNEL_FLASHADDR, SPI_KERNEL_FLASHSIZE );		
+	showMsg( "\n" );
+}
+#endif
+static inline bool parseProgArg_Option( const char *optionArgument )
+{
+	if( check_keyword( "-Config=", optionArgument ) )
+	{
+		if( copy_settingString( miConfigFile, optionArgument ) ) return true;
+	}
+	else if( check_keyword( "-deleteTempFile=", optionArgument ) ) 
+	{
+		if( copy_settingYesNo( &miDeleteTempFileFlag, optionArgument ) ) return true;
+	}
+	else if( check_keyword( "-generatePacket=", optionArgument ) )
+	{
+		if( copy_settingYesNo( &miGeneratePacketFlag, optionArgument ) ) return true;
+	}
+	else if( check_keyword( "-generateOriginalBib=", optionArgument ) )
+	{
+		if( copy_settingYesNo( &miGenerateOriginalBinFlag, optionArgument ) ) return true;
+	}
+
+	return false;
+}
+
+static inline bool parseProgArg_Necessary( const char *targetDir, const char *targetName )
+{
+	if( chdir( targetDir ) != 0 )
+	{
+		errMsg( "Cannot find the specified folder: %s\n", targetDir );
+		return false;
+	}
+
+
+	strcpy( miPacketName, targetName );
+	strcat( miPacketName, ".packet" );
+#if 0
+
+	strcpy( miCodeBinName, targetName );
+	strcat( miCodeBinName, ".code.bin" );
+
+	strcpy( miDataBinName, targetName );
+	strcat( miDataBinName, ".data.bin" );
+#endif
+	strcpy( miBinWithInfo, targetName );
+	//strcat( miBinWithInfo, ".code.bin" );
+
+	
+	strcpy( miSaveInfoName, targetName );
+	strcat( miSaveInfoName, ".save" );
+
+#ifdef MERGEFEATURE
+	strcpy( miConfigFile , MERGEFEATURE );
+#else
+	showMsg( "[Waring] No define MERGEFEATURE in Project.h\n" );	
+	strcpy( miConfigFile , FILENAME_MICONFIG );	
+#endif
+
+	miBaseImageName[0] = '\0';
+	strcpy( miOutputPathName, PATHNAME_OUTPUT );
+	
+	showMsg( "TargetDirectory: %s\n", targetDir );	
+	showMsg( "TargetName: %s\n", targetName );
+	return true;
+}
+
+bool parseProgArg( int argc, char *argv[] )
+{
+	int i;
+	if( argc < 2 )
+	{
+		showProgramUsageHint();
+		return false;
+	}
+	#if 0
+	if( argc == 2 )
+	{
+		if( check_keyword( "-printmap", argv[1] ) ) showDynamicItemOfFlashMap( );
+		return false;		
+	}
+	#endif
+	strcpy( BIN_FILENAME , CONFIG_BIN_FILENAME );
+
+	if( !parseProgArg_Necessary( argv[1], BIN_FILENAME ) ) return false;
+
+	for( i = 3; i < argc; i++ )
+	{
+		if( !parseProgArg_Option( argv[i] ) )
+		{
+			errMsg( "parse Argument Option failed : %s\n", argv[i] );
+			return false;
+		}
+	}
+
+	showMsg( "miConfigFile: %s\n", miConfigFile );
+	showMsg( "miDeleteTempFileFlag: %d\n", miDeleteTempFileFlag );	
+	showMsg( "miGeneratePacketFlag: %d\n", miGeneratePacketFlag );
+	showMsg( "miGenerateOriginalBinFlag: %d\n", miGenerateOriginalBinFlag );
+	return true;
+}
+

+ 77 - 0
tools/mergeImage/parseConfig.h

@@ -0,0 +1,77 @@
+//-------------------------------------------------------------------------------
+// parse mergeImage Config & program argument
+//-------------------------------------------------------------------------------
+#ifndef _PARSECONFIG_H_
+#define _PARSECONFIG_H_
+//-------------------------------------------------------------------------------
+#include "mergeImage.h"
+//-------------------------------------------------------------------------------
+
+
+//-------------------------------------------------------------------------------
+
+typedef struct _NorFlashModuleInfo
+{
+	bool isValid;						/* fileName is valid ? */
+	bool isProtected;					/* Protect in saveinfo ? */
+	bool isInitModuleNameByUser;	/* #define fileName by cfg ? */
+	bool isInitProtectedByUser;		/* #define protect by cfg ? */
+
+	u32 flashAddr1;
+	u32 flashSize1;
+
+	u32 flashAddr2;
+	u32 flashSize2;
+
+    u32 max_module_size;
+
+	char moduleName[32];	//"ShellROM"=SHELLROM/SHELL.bin
+	char fileName[FILENAME_SIZE];	
+	char tmpBinName[FILENAME_SIZE];	
+#ifdef CONFIG_APPEND_NAME_TO_CIKEY_HDCPKEY
+	char eachfileName[FILENAME_SIZE];	
+#endif
+}NorFlashModuleInfo;
+
+typedef struct _NorFlashModulePathInfo
+{
+	char moduleName[32];
+	char pathName[FILENAME_SIZE];
+}NorFlashModulePathInfo;
+
+typedef struct _NVMData
+{
+    u32  id;
+    char pathName[FILENAME_SIZE];
+}NVMData;
+
+
+#define PATHINFO_MAX	2
+#define ACTION_MAX		8
+
+extern NorFlashModuleInfo flashModuleInfo[MODULE_MAX];
+extern NorFlashModulePathInfo flashModulePathInfo[PATHINFO_MAX];
+extern NVMData gNVMData[MODULE_MAX];
+extern u32 gNVMData_count;
+
+
+//-------------------------------------------------------------------------------
+bool loadNorFlashModuleInfo();
+NorFlashModuleInfo* searchModuleInfo( const char *moduleName );
+NorFlashModulePathInfo* searchModulePathInfo( const char *moduleName );
+char* fgetLine( char *s, int size, FILE *fpIn );
+bool parseProgArg( int argc, char *argv[] );
+//-------------------------------------------------------------------------------
+#endif
+
+char module_extend1[12];
+char module_extend2[12];
+char module_extend3[12];
+char module_extend4[12];
+char module_extend5[12];
+char module_extend6[12];
+char module_extend7[12];
+
+
+
+

+ 1507 - 0
tools/mergeImage/pnlset2bin.c

@@ -0,0 +1,1507 @@
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include "pnlset2bin.h"
+#define CustomerLOGO 1
+#define PanelSet_Header "PanelSet_Ascii_Version"
+
+#if 0
+static long filelength(FILE * pFile)
+{
+	long ret;
+	long oldpos;
+	oldpos = ftell(pFile);
+	fseek(pFile, 0, SEEK_END);
+	ret = ftell(pFile);
+	fseek(pFile, oldpos, SEEK_SET);
+	return ret;
+}
+#endif
+
+uint StrToHexNumber(char* szText, uint* pNumber, uint nMax)
+{
+	uint i,nValue= 0;
+
+	i= 0;
+	while( i<nMax )
+	{
+		if( szText[i] >='0' && szText[i]<= '9' )
+			nValue= (nValue<<4) | (szText[i]-'0');
+		else if( szText[i] >='a' && szText[i]<= 'f' )
+			nValue= (nValue<<4) | (szText[i]-'a'+10);
+		else if( szText[i] >='A' && szText[i]<= 'F' )
+			nValue= (nValue<<4) | (szText[i]-'A'+10);
+		else break;
+		i++;
+	}
+	*pNumber= nValue;
+	return i;
+}
+
+uint StrToDecimalNumber(char* szText, uint* pNumber, uint nMax)
+{
+	uint i,nValue= 0;
+
+	i= 0;
+	while( i<nMax )
+	{
+		if( szText[i] >='0' && szText[i]<= '9' )
+			nValue= (nValue*10) + (szText[i]-'0');
+		else break;
+		i++;
+	}
+	*pNumber= nValue;
+	return i;
+}
+
+bool GetBit(const unsigned char pByte[], uint nBitIndex)
+{
+	uint nQuot,nRem;
+	nQuot= nBitIndex >> 3;
+	nRem= nBitIndex & 0x7;
+	return (pByte[nQuot] >> nRem) & 0x01;
+}
+
+uint GetBitData(const unsigned char pByte[], uint nBitIndex, uint nBitWidth)
+{
+	uint i,nBit,nValue= 0;
+
+	for(i=0; i<nBitWidth; i++)
+	{
+		nBit= GetBit(pByte, nBitIndex+i);
+		nValue= (nBit<<i) | nValue;
+	}
+	return nValue;
+}
+
+void SetBit(unsigned char pByte[], uint nBitIndex, bool bValue)
+{
+	uint nQuot,nRem;
+	unsigned char nMask;
+
+	nQuot= nBitIndex >> 3;
+	nRem= nBitIndex & 0x7;
+	nMask= (1 << nRem) & 0xff;
+	if( bValue )
+	{
+		pByte[nQuot]|= nMask;
+	}
+	else
+	{
+		nMask= ~nMask;
+		pByte[nQuot]&= nMask;
+	}
+}
+
+void SetBitData(unsigned char pByte[], uint nBitIndex, uint nBitWidth, uint nData)
+{
+	uint i;
+	for(i=0; i<nBitWidth; i++)
+		SetBit(pByte, nBitIndex+i, (nData>>i)&0x1);
+}
+
+void PrintUsage(void)
+{
+	fprintf(stderr, "\n");
+	fprintf(stderr, "pnlset2bin v0.01\n");
+	fprintf(stderr, "Usage:   pnlset2bin inputINIfile outputBINfile\n");
+	fprintf(stderr, "Example: pnlset2bin panelset.ini panelset.bin\n");
+	fprintf(stderr, "\n");
+}
+
+int cmN_getFileOneLineDataAscii(FILE *fpIn,char *pData, int maxLen)
+{     //return is get len  not add null
+	int i;
+	char line[maxLen];
+	
+	while(fgets(line, maxLen, fpIn)){
+		if(strncmp(line, PanelSet_Header, strlen(PanelSet_Header)) == 0)
+			break;
+	}
+
+	for(i=0; i<maxLen;i++)
+	{
+		if( i>= maxLen) //end size
+		{
+			return i; // not add null
+		}
+		
+		if(line[i] == 0x0A )//line end ** OK
+		{
+			pData[i] = 0x00;
+			return i;
+		}
+		if((isascii(line[i]))&&(!iscntrl(line[i])))
+		{
+				pData[i] = line[i];
+		}
+		else
+		{
+				pData[i] = 0x20;
+		}
+	}
+	return 0; // fail
+}
+
+
+int cmN_getLineAsciiData_PanelSetVer2(char *pInData, char *pOutData, int Len)
+{     //return is get len and add null
+	int i, num, start;
+	int headLen;
+	headLen = (int)strlen(PANELSET_VERSION2_NAME_HEADER);
+	if (!strncmp(PANELSET_VERSION2_NAME_HEADER,pInData, headLen))
+	{
+		num = 0;
+		start  = 0;
+		for(i=headLen; i<Len;i++)
+		{
+			if(pInData[i] != 0x20)
+			{
+				start = i;
+				break;
+			}
+		}
+		if( (start == 0)||(i==Len) ) // empty give 0x20
+		{
+			pOutData[0] = 0x20;
+			return 1;
+		}
+		for(i=start; i<Len;i++)
+		{
+			if((isascii(pInData[i]))&&(!iscntrl(pInData[i])))
+			{
+				pOutData[num]  = pInData[i];
+			}
+			else
+			{
+				pOutData[num] = 0x20;
+			}
+			num ++;
+			if(num >=PANELSET_VERSION2_NAME_MAX_LEN)
+			{
+				break;
+			}
+		}
+		//move 0x20 at last
+		for(i=(num - 1); i>= 0;i--)
+		{
+			if(pOutData[i] != 0x20)
+			{
+				if(i == 0)
+				{
+					return 1;//fix all is empty
+				}
+				else
+				{
+					return (i+1);
+				}
+			}
+		}
+	}
+	else
+	{
+		return 0; // fail
+	}
+	return 0; // fail
+}
+
+#if 0
+DWORD ini2bin(char* pInFile, char *pOutFile)
+{
+	FILE *InFile,*OutFile;
+	DWORD isFill = TRUE, isAdd = TRUE; //for many VIP merge //add MMIO
+	int i, len, tmp, mmioflag=0, optionflag=0;
+	DWORD tempDW = 0;
+	BRVIP_FLASH BrvipFlash;
+	char ptr[0x100];
+	unsigned int data,data1,data2,data3;
+	unsigned long ULData[2000],ULSize;
+	char pExist[PB_MAX_END];//for check only
+	memset(pExist, 0, sizeof(char));
+
+
+	InFile = fopen(pInFile,"r");
+	if (InFile == NULL)
+	{
+		fprintf(stderr, "Can't open ini file\n");
+		return FALSE;
+	}
+
+
+	if(isAdd == TRUE)
+	{
+		OutFile = fopen(pOutFile,"ab");
+	}
+	else
+	{
+		OutFile = fopen(pOutFile,"wb");
+	}
+
+	if (OutFile == NULL)
+	{
+		fclose(InFile);
+		fprintf(stderr, "Can't open will write file\n");
+		return FALSE;
+	}
+
+	int mergeToSize;//should "PANELSET SIZE" 2K, but boo t Rom give 8K   So, Some where will add
+	mergeToSize = PANELSET_SIZE; //--2k   //; 0x2000=8k;//should "PANELSET SIZE" 2K, but boo t Rom give 8K   So, Some where will add
+
+	//---------- for isAdd fill to 8K
+	if( (isFill == TRUE)&&(isAdd) )
+	{
+		DWORD fileLen, fillLen;
+		fileLen = filelength(OutFile);
+
+		if(fileLen % PANELSET_SIZE)  //---by each size #1
+		{
+			if( PANELSET_SIZE > 0 )
+			{
+				int range = mergeToSize;// should "PANELSET SIZE" 2K, but boo t Rom give 8K   So, Some where will add
+				fillLen = range -(fileLen & (range-1));
+			}
+			else
+			{
+				fillLen = 0;
+			}
+
+			fseek( OutFile, 0, SEEK_END);
+
+			for(i=0; i< fillLen ;i++)
+			{
+				fputc(0xFF,OutFile);
+			}
+		}
+		//fclose(OutFile);
+	}
+	//----------
+
+	//?? does need to init "BrvipFlash
+	memset(&BrvipFlash, 0, sizeof(BRVIP_FLASH));//not init value is diff linux 0 windows CC
+	                                            //Reserve01 and Reserve02
+	//----- ver =>
+	tmp = 100;
+	i = cmN_getFileOneLineDataAscii(InFile,ptr, tmp);
+	len = cmN_getLineAsciiData_PanelSetVer2(ptr, ptr+tmp, i);
+	memset(ptr, 0, PANELSET_VERSION2_NAME_MAX_LEN);
+	memcpy(ptr , ptr+tmp, len);
+	if(len == 0)
+	{
+		fclose(InFile);
+		fclose(OutFile);
+		fprintf(stderr, "Error ! \n First line must be PanelSet_Ascii_Version\n");
+		return FALSE;
+	}
+	for(i=0; i< PANELSET_VERSION2_NAME_MAX_LEN;i++)
+	{
+		BrvipFlash.ScalerRegister.VersionOfAscii_20[i] = ptr[i];
+	}
+
+	//----- ver <=
+
+	//start fill //source from Ics 172.18.252.142\sis1259\brvip\work\utility\utility.c+flash.h
+	while (fscanf(InFile,"%s",ptr) != EOF) {
+		if (!strcmp("[MMIO0]",ptr)) fgetpos(InFile, (fpos_t*)&mmioflag);
+		if (0 != mmioflag && !optionflag)
+		{
+			if (0 == strstr(ptr, "OffsetLast0x14=")) continue;
+			else
+			{
+				optionflag = 1;
+				sscanf(ptr, "OffsetLast0x14=%d", (int*)&tempDW);
+			}
+		}
+
+		if (EOF == fscanf(InFile," %x\n",&data)) break;
+		if (!strcmp("PanelHorizontalEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalEnd = data;
+			pExist[PB_PanelHorizontalEnd] = 1;
+		} else if (!strcmp("PanelVerticalEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalEnd = data;
+			pExist[PB_PanelVerticalEnd] = 1;
+		} else if (!strcmp("PanelHorizontalSyncStart",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalSyncStart = (unsigned char)data;
+			pExist[PB_PanelHorizontalSyncStart] = 1;
+		} else if (!strcmp("PanelHorizontalSyncEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalSyncEnd = (unsigned char)data;
+			pExist[PB_PanelHorizontalSyncEnd] = 1;
+		} else if (!strcmp("PanelVerticalSyncStart",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalSyncStart = (unsigned char)data;
+			pExist[PB_PanelVerticalSyncStart] = 1;
+		} else if (!strcmp("PanelVerticalSyncEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalSyncEnd = (unsigned char)data;
+			pExist[PB_PanelVerticalSyncEnd] = 1;
+		} else if (!strcmp("PanelVerticalMaxEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalMaxEnd = (unsigned short)data;
+			pExist[PB_PanelVerticalMaxEnd] = 1;
+		} else if (!strcmp("PanelHorizontalDisplayStart",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalDisplayStart = data;
+			pExist[PB_PanelHorizontalDisplayStart] = 1;
+		} else if (!strcmp("PanelVerticalDisplayStart",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalDisplayStart = data;
+			pExist[PB_PanelVerticalDisplayStart] = 1;
+		} else if (!strcmp("PanelHorizontalDisplayEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalDisplayEnd = data;
+			pExist[PB_PanelHorizontalDisplayEnd] = 1;
+		} else if (!strcmp("PanelVerticalDisplayEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalDisplayEnd = data;
+			pExist[PB_PanelVerticalDisplayEnd] = 1;
+		} else if (!strcmp("PanelBlueOverScan",ptr)) {
+			BrvipFlash.PanelParameter.PanelBlueOverScan = (unsigned char)data;
+			pExist[PB_PanelBlueOverScan] = 1;
+		} else if (!strcmp("PanelGreenOverScan",ptr)) {
+			BrvipFlash.PanelParameter.PanelGreenOverScan = (unsigned char)data;
+			pExist[PB_PanelGreenOverScan] = 1;
+		} else if (!strcmp("PanelRedOverScan",ptr)) {
+			BrvipFlash.PanelParameter.PanelRedOverScan = (unsigned char)data;
+			pExist[PB_PanelRedOverScan] = 1;
+		} else if (!strcmp("DpyHorizontalDisplayStart",ptr)) {
+			BrvipFlash.DisplayPosition.DpyHorizontalDisplayStart = data;
+			pExist[PB_DpyHorizontalDisplayStart] = 1;
+		} else if (!strcmp("DpyVerticalDisplayStart",ptr)) {
+			BrvipFlash.DisplayPosition.DpyVerticalDisplayStart = data;
+			pExist[PB_DpyVerticalDisplayStart] = 1;
+		} else if (!strcmp("DpyHorizontalDisplayEnd",ptr)) {
+			BrvipFlash.DisplayPosition.DpyHorizontalDisplayEnd = data;
+			pExist[PB_DpyHorizontalDisplayEnd] = 1;
+		} else if (!strcmp("DpyVerticalDisplayEnd",ptr)) {
+			BrvipFlash.DisplayPosition.DpyVerticalDisplayEnd = data;
+			pExist[PB_DpyVerticalDisplayEnd] = 1;
+		} else if (!strcmp("DpyOffset",ptr)) {
+			BrvipFlash.DisplayPosition.DpyOffset = (unsigned char)data;
+			pExist[PB_DpyOffset] = 1;
+		} else if (!strcmp("DpySize",ptr)) {
+			BrvipFlash.DisplayPosition.DpySize = (unsigned char)data;
+			pExist[PB_DpySize] = 1;
+		} else if (!strcmp("DpyLine",ptr)) {
+			BrvipFlash.DisplayPosition.DpyLine = data;
+			pExist[PB_DpyLine] = 1;
+		} else if (!strcmp("Version",ptr)) {
+			BrvipFlash.Version = data;
+			pExist[PB_Version] = 1;
+		} else if (!strcmp("DeviceID",ptr)) {
+			BrvipFlash.DeviceID = (unsigned short)data;
+			pExist[PB_DeviceID] = 1;
+		} else if (!strcmp("VendorID",ptr)) {
+			BrvipFlash.VendorID = (unsigned short)data;
+			pExist[PB_VendorID] = 1;
+		} else if (!strcmp("Dpy00",ptr)) {
+			BrvipFlash.Dpy00 = data;
+			pExist[PB_Dpy00] = 1;
+		} else if (!strcmp("Dpy20",ptr)) {
+			BrvipFlash.Dpy20 = data;
+			pExist[PB_Dpy20] = 1;
+		} else if (!strcmp("Before_MMIOAddress",ptr)) {
+			BrvipFlash.Before_MMIOAddress = data;
+			pExist[PB_Before_MMIOAddress] = 1;
+		} else if (!strcmp("VIPAddress",ptr)) {
+			BrvipFlash.VIPAddress = data;
+			pExist[PB_VIPAddress] = 1;
+		} else if (!strcmp("After_MMIOAddress",ptr)) {
+			BrvipFlash.After_MMIOAddress = data;
+			pExist[PB_After_MMIOAddress] = 1;
+		} else if (!strcmp("SlrReset",ptr)) {;
+			BrvipFlash.ScalerRegister.SlrReset = data;
+			pExist[PB_SlrReset] = 1;
+		} else if (!strcmp("SlrConfig",ptr)) {
+			BrvipFlash.ScalerRegister.SlrConfig = data;
+			pExist[PB_SlrConfig] = 1;
+		} else if (!strcmp("SlrHorizontalFactor",ptr)) {
+			BrvipFlash.ScalerRegister.SlrHorizontalFactor = data;
+			pExist[PB_SlrHorizontalFactor] = 1;
+		} else if (!strcmp("SlrVerticalFactor",ptr)) {
+			BrvipFlash.ScalerRegister.SlrVerticalFactor = data;
+			pExist[PB_SlrVerticalFactor] = 1;
+		} else if (!strcmp("SlrVerticalDown",ptr)) {
+			BrvipFlash.ScalerRegister.SlrVerticalDown = data;
+			pExist[PB_SlrVerticalDown] = 1;
+		}
+		/* else if (!strcmp("SlrLeft",ptr)) {
+			BrvipFlash.ScalerRegister.SlrLeft = data;
+			pExist[PB_SlrLeft] = 1;
+		} else if (!strcmp("SlrRight",ptr)) {
+			BrvipFlash.ScalerRegister.SlrRight = data;
+			pExist[PB_SlrRight] = 1;
+		} else if (!strcmp("SlrLeft0",ptr)) {
+			BrvipFlash.ScalerRegister.SlrLeft0 = data;
+			pExist[PB_SlrLeft0] = 1;
+		} else if (!strcmp("SlrRight0",ptr)) {
+			BrvipFlash.ScalerRegister.SlrRight0 = data;
+			pExist[PB_SlrRight0] = 1;
+		} else if (!strcmp("SlrHorizontalFactor0",ptr)) {
+			BrvipFlash.ScalerRegister.SlrHorizontalFactor0 = data;
+			pExist[PB_SlrHorizontalFactor0] = 1;
+		}  */
+		else if (!strcmp("SlrLine",ptr)) {
+			BrvipFlash.ScalerRegister.SlrLine = data;
+			pExist[PB_SlrLine] = 1;
+		} else if (!strcmp("SlrInc",ptr)) {
+			BrvipFlash.ScalerRegister.SlrInc = data;
+			pExist[PB_SlrInc] = 1;
+		} else if (!strcmp("Gpio_15",ptr)) {
+			BrvipFlash.Gpio_15 = data;
+			pExist[PB_Gpio_15] = 1;
+		} else if (!strcmp("Gpio_16",ptr)) {
+			BrvipFlash.Gpio_16 = data;
+			pExist[PB_Gpio_16] = 1;
+		}
+		else if (!strcmp("PanelBackLight_GPIOPin",ptr)) {
+			BrvipFlash.PanelBackLight_GPIOPin = (unsigned char)data;
+			pExist[PB_PanelBackLight_GPIOPin] = 1;
+		}
+		else if (!strcmp("PanelPower_GPIOPin",ptr)) {
+			BrvipFlash.PanelPower_GPIOPin = (unsigned char)data;
+			pExist[PB_PanelPower_GPIOPin] = 1;
+		}
+		else if (!strcmp("PanelBackLight_ActiveValue",ptr)) {
+			BrvipFlash.PanelBackLight_ActiveValue = (unsigned char)data;
+			pExist[PB_PanelBackLight_ActiveValue] = 1;
+		}
+		else if (!strcmp("PanelPower_ActiveValue",ptr)) {
+			BrvipFlash.PanelPower_ActiveValue = (unsigned char)data;
+			pExist[PB_PanelPower_ActiveValue] = 1;
+		}
+		else if (!strcmp("LCDBackLightOrder",ptr)) {
+			BrvipFlash.LCDBackLightOrder = (DWORD)data;
+			pExist[PB_LCDBackLightOrder] = 1;
+		}
+		else if (!strcmp("LCDBackLight_OtherFrq",ptr)) {
+			BrvipFlash.LCDBackLight_OtherFrq = (DWORD)data;
+			pExist[PB_LCDBackLight_OtherFrq] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_00",ptr)) {
+			BrvipFlash.LCDBackLightMap_00 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_00] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_01",ptr)) {
+			BrvipFlash.LCDBackLightMap_01 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_01] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_02",ptr)) {
+			BrvipFlash.LCDBackLightMap_02 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_02] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_03",ptr)) {
+			BrvipFlash.LCDBackLightMap_03 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_03] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_04",ptr)) {
+			BrvipFlash.LCDBackLightMap_04 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_04] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_05",ptr)) {
+			BrvipFlash.LCDBackLightMap_05 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_05] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_06",ptr)) {
+			BrvipFlash.LCDBackLightMap_06 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_06] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_07",ptr)) {
+			BrvipFlash.LCDBackLightMap_07 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_07] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_08",ptr)) {
+			BrvipFlash.LCDBackLightMap_08 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_08] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_09",ptr)) {
+			BrvipFlash.LCDBackLightMap_09 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_09] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_10",ptr)) {
+			BrvipFlash.LCDBackLightMap_10 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_10] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_11",ptr)) {
+			BrvipFlash.LCDBackLightMap_11 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_11] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_12",ptr)) {
+			BrvipFlash.LCDBackLightMap_12 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_12] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_13",ptr)) {
+			BrvipFlash.LCDBackLightMap_13 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_13] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_14",ptr)) {
+			BrvipFlash.LCDBackLightMap_14 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_14] = 1;
+		}
+		else if (!strcmp("LogoType",ptr)) {
+			BrvipFlash.LogoType = (DWORD)data;
+			pExist[PB_LogoType] = 1;
+		}
+		else if (!strcmp("LogoSize",ptr)) {
+			BrvipFlash.LogoSize = (DWORD)data;
+			pExist[PB_LogoSize] = 1;
+		}
+		else if (!strcmp("PanelBackLight_OffdelayTime",ptr)) {
+			BrvipFlash.PanelBackLight_OffdelayTime = (DWORD)data;
+			pExist[PB_PanelBackLight_OffdelayTime] = 1;
+		}
+		else if (!strcmp("PanelBackPower_OffdelayTime",ptr)) {
+			BrvipFlash.PanelBackPower_OffdelayTime = (DWORD)data;
+			pExist[PB_PanelBackPower_OffdelayTime] = 1;
+		}
+
+	}
+
+	fseek(InFile, mmioflag, SEEK_SET);
+	//BrvipFlash.Before_MMIOAddress = 0xbc0b0000+sizeof(BRVIP_FLASH);	07/03/02008 David.
+	BrvipFlash.Before_MMIOAddress = BR_ADDR_VIP+sizeof(BRVIP_FLASH);
+	BrvipFlash.After_MMIOAddress = BrvipFlash.Before_MMIOAddress;
+	ULSize = 0;
+	//fwrite(&BrvipFlash,sizeof(BRVIP_FLASH),1,OutFile);
+	while (fscanf(InFile,"\n%x %x %x %x",&data,&data1,&data2,&data3) != EOF)
+	{
+		if ((data == 0xffffffff)||(data == 0x00000000))
+		{
+			break;
+		}
+		//fwrite(&data,4,1,OutFile);
+		//fwrite(&data1,4,1,OutFile);
+		//fwrite(&data2,4,1,OutFile);
+		//fwrite(&data3,4,1,OutFile);
+		//BrvipFlash.After_MMIOAddress += 0x10;
+		ULData[ULSize] = data;
+		ULData[ULSize+1] = data1;
+		ULData[ULSize+2] = data2;
+		ULData[ULSize+3] = data3;
+		ULSize += 4;
+	}
+	data=0xffffffff;
+	//fwrite(&data,4,1,OutFile);
+	//fwrite(&data,4,1,OutFile);
+	//fwrite(&data,4,1,OutFile);
+	//fwrite(&data,4,1,OutFile);
+	//BrvipFlash.After_MMIOAddress += 0x10;
+	ULData[ULSize] = data;
+	ULData[ULSize+1] = data;
+	ULData[ULSize+2] = data;
+	ULData[ULSize+3] = data;
+	ULSize += 4;
+	BrvipFlash.After_MMIOAddress += (ULSize*4);
+	printf("Before_MMIOAddress %x\n",(unsigned int)BrvipFlash.Before_MMIOAddress);
+	printf("ULSize %x\n",(unsigned int)ULSize);
+	printf("After_MMIOAddress %x\n",(unsigned int)BrvipFlash.After_MMIOAddress);
+	fwrite(&BrvipFlash,sizeof(BRVIP_FLASH),1,OutFile);
+	fwrite(ULData,4*ULSize,1,OutFile);
+
+	while (fscanf(InFile,"\n%x %x %x %x",&data,&data1,&data2,&data3) != EOF)
+	{
+		if ((data == 0xffffffff)||(data == 0x00000000))
+		{
+			break;
+		}
+		fwrite(&data,4,1,OutFile);
+		fwrite(&data1,4,1,OutFile);
+		fwrite(&data2,4,1,OutFile);
+		fwrite(&data3,4,1,OutFile);
+	}
+	data=0xffffffff;
+	fwrite(&data,4,1,OutFile);
+	fwrite(&data,4,1,OutFile);
+	fwrite(&data,4,1,OutFile);
+	fwrite(&data,4,1,OutFile);
+
+#ifdef SET_338_VIP
+	while (fscanf(InFile,"\n%x %x %x %x",&data,&data1,&data2,&data3) != EOF)
+	{
+		if ((data == 0xffffffff)||(data == 0x00000000))
+		{
+			break;
+		}
+		fwrite(&data,4,1,OutFile);
+		fwrite(&data1,4,1,OutFile);
+		fwrite(&data2,4,1,OutFile);
+		fwrite(&data3,4,1,OutFile);
+	}
+
+	data=0xffffffff;
+	fwrite(&data,4,1,OutFile);
+	fwrite(&data,4,1,OutFile);
+	fwrite(&data,4,1,OutFile);
+	fwrite(&data,4,1,OutFile);
+#endif //SET_338_VIP
+
+	fclose(InFile);
+
+	//--------- Option
+	if (optionflag)
+	{
+		if(PANELSET_SIZE != PANELSET_NOW_USE_FIX_SIZE)
+		{
+			fprintf(stderr, "Error! \nPanelSet Size change !\n  Driver must update for this");
+			fclose(OutFile);
+			return FALSE;
+		}
+		DWORD fileLen, fillLen;
+		fgetpos(OutFile,(fpos_t*)&fileLen);
+		fileLen = fileLen % mergeToSize;
+		if(fileLen >= (PANELSET_OPTION_D_OFFSET)) //0x7ec
+		{
+			fprintf(stderr, "Error! \nPanelSet Size change ! Over ox 7 e c\n  Tool must update");
+			fclose(OutFile);
+			return FALSE;
+		}
+		fillLen = (PANELSET_OPTION_D_OFFSET - fileLen);
+
+		if(PANELSET_OPTION_D_OFFSET < fileLen) //avoid
+		{
+			fillLen = 0;
+			fprintf(stderr, "Error! \nPanelSet Error size \n  Tool must update");
+		}
+
+//		OutFile = fopen(pOutFile,"ab");
+		for(i=0; i< fillLen ;i++)
+		{
+			fputc(0xFF,OutFile);
+		}
+		fwrite(&tempDW,4,1,OutFile);
+	}
+	//---------
+
+	fclose(OutFile);
+
+
+	if(isFill == TRUE)
+	{
+		OutFile = fopen(pOutFile,"ab");
+		if (OutFile == NULL)
+		{
+			fprintf(stderr, "Can't open will write2 file\n");
+			return FALSE;
+		}
+		DWORD fileLen, fillLen;
+		fileLen = filelength(OutFile);
+
+		if(fileLen % PANELSET_SIZE)  //---by each size #2
+		{
+#ifdef FILL_MEM_BY_INI
+			if( PANELSET_SIZE > 0 )
+			{
+				int range;
+				if(isAdd)
+				{
+					range = mergeToSize;// should "PANELSET SIZE" 2K, but boo t Rom give 8K   So, Some where will add
+				}
+				else
+				{
+					range = PANELSET_SIZE;// general case
+				}
+				fillLen = range -(fileLen & (range-1));
+			}
+			else
+				fillLen = 0;
+#else
+			fillLen = 0x1000 -(fileLen & 0x0fff);
+#endif //FILL_MEM_BY_INI
+
+			fseek( OutFile, 0, SEEK_END);
+
+			for(i=0; i< fillLen ;i++)
+			{
+				fputc(0xFF,OutFile);
+			}
+		}
+		fclose(OutFile);
+	}
+	//check lost only
+	for(i=0; i<PB_MAX_END ;i++)
+	{
+		if(pExist[i]!=1)
+		{
+			fprintf(stderr, "Error \n\n It must have lost data at No %d\n", i);
+			return FALSE;
+		}
+	}
+
+	return TRUE;
+}
+#endif
+#if 1
+char* fgetLine( char *s, int size, FILE *fpIn );
+/* return writed size, */
+int write_i2c_data_to_bin(FILE *fp, int fileoffset, char* output_mem, int mem_offset){
+//	int i, length;
+	char *line_buff, *outbuff, *ch_p;
+	int tmp_data, outbuff_idx = 0,exit = 0;
+	
+	line_buff = malloc(256);
+	if (line_buff == NULL)
+		return -1;
+	
+	outbuff = malloc(1024);
+	if (outbuff == NULL) {
+		free(line_buff);
+		return -1;
+	}
+	
+	printf("i2c[%x]: \n", mem_offset );
+	if (fseek(fp, fileoffset, SEEK_SET) < 0) {
+		free(line_buff);
+		free(outbuff);
+		return -1;
+	}
+	
+	//fgetLine(line_buff, 256, InFile);//bypasss [I2C]\n
+	while(1){
+		if(exit)
+			break;
+		if(fgetLine(line_buff, 256, fp) != (char *)NULL){
+			//printf("i2c[%x]: %s\n", mem_offset,line_buff );
+			ch_p = strtok (line_buff,", ");
+			#if 0
+			if(!strcmp("00",ch_p)){
+				exit =1;
+			}
+			#endif
+			 while ((ch_p != NULL) && (exit == 0))
+			 {
+				if(sscanf(ch_p, "%x", &tmp_data) <=0){
+					exit =1;
+					break;
+				}
+				//printf ("%x ",tmp_data);
+				outbuff[outbuff_idx++] = (char)tmp_data;
+					ch_p = strtok (NULL, ", ");
+			 }
+			 //printf ("\n");
+		}
+	}
+
+	if(mem_offset + outbuff_idx > PANELSET_SIZE) {
+		free(line_buff);
+		free(outbuff);
+		return -1;
+	}
+	
+	memcpy(output_mem+mem_offset, outbuff, outbuff_idx);
+	free(line_buff);
+	free(outbuff);
+	return outbuff_idx;
+}
+#endif
+
+/*
+	return writed size if success
+	else  -1
+*/
+int ini2binmem(char* pInFile, char *pOutData, int nBufSize)
+{
+	FILE *InFile;
+	int i, len, tmp, mmioflag=0;	//, optionflag=0;
+	int i2c0_fileoffset = 0, i2c1_fileoffset = 0;
+	int writeOffset = 0;
+//	DWORD tempDW = 0;
+	BRVIP_FLASH BrvipFlash;
+	char ptr[0x100];
+	unsigned int data,data1,data2,data3;
+	unsigned long ULData[2000],ULSize;
+	char pExist[PB_MAX_END];//for check only
+	memset(pExist, 0, sizeof(char));
+	memset(pOutData, 0xFF, nBufSize);
+
+	if (nBufSize < PANELSET_SIZE)
+	{
+		fprintf(stderr, "Out buffer is too small\n");
+		return -1;
+	}
+
+	InFile = fopen(pInFile,"r");
+	if (InFile == NULL)
+	{
+		fprintf(stderr, "Can't open ini file\n");
+		return -1;
+	}
+
+	/*
+	int mergeToSize;//should "PANELSET SIZE" 2K, but boo t Rom give 8K   So, Some where will add
+	mergeToSize = PANELSET_SIZE; //--2k   //; 0x2000=8k;//should "PANELSET SIZE" 2K, but boo t Rom give 8K   So, Some where will add
+	*/
+
+	//?? does need to init "BrvipFlash
+	memset(&BrvipFlash, 0, sizeof(BRVIP_FLASH));//not init value is diff linux 0 windows CC
+	                                            //Reserve01 and Reserve02
+	//----- ver =>
+	tmp = 100;
+	i = cmN_getFileOneLineDataAscii(InFile,ptr, tmp);
+	len = cmN_getLineAsciiData_PanelSetVer2(ptr, ptr+tmp, i);
+	memset(ptr, 0, PANELSET_VERSION2_NAME_MAX_LEN);
+	memcpy(ptr , ptr+tmp, len);
+	if(len == 0)
+	{
+		fclose(InFile);
+		fprintf(stderr, "Error ! \n First line must be PanelSet_Ascii_Version\n");
+		return -1;
+	}
+	for(i=0; i< PANELSET_VERSION2_NAME_MAX_LEN;i++)
+	{
+		BrvipFlash.ScalerRegister.VersionOfAscii_20[i] = ptr[i];
+	}
+
+	//----- ver <=
+
+	//start fill //source from Ics 172.18.252.142\sis1259\brvip\work\utility\utility.c+flash.h
+	while (fscanf(InFile,"%s",ptr) != EOF) {
+		if (!strcmp("[MMIO0]",ptr)) fgetpos(InFile, (fpos_t*)&mmioflag);
+		if (!strcmp("[I2C0]",ptr)) fgetpos(InFile, (fpos_t*)&i2c0_fileoffset);
+		if (!strcmp("[I2C1]",ptr)) fgetpos(InFile, (fpos_t*)&i2c1_fileoffset);
+#if 0	//gaia, 2013.05.02 ya! i don't know what is this..
+		if (0 != mmioflag && !optionflag)
+		{
+			if (0 == strstr(ptr, "OffsetLast0x14=")) continue;
+			else
+			{
+				optionflag = 1;
+				sscanf(ptr, "OffsetLast0x14=%d", (int*)&tempDW);
+			}
+		}
+#endif
+		if (EOF == fscanf(InFile," %x\n",&data)) break;
+		if (!strcmp("PanelHorizontalEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalEnd = data;
+			pExist[PB_PanelHorizontalEnd] = 1;
+		} else if (!strcmp("PanelVerticalEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalEnd = data;
+			pExist[PB_PanelVerticalEnd] = 1;
+		} else if (!strcmp("PanelHorizontalSyncStart",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalSyncStart = (unsigned char)data;
+			pExist[PB_PanelHorizontalSyncStart] = 1;
+		} else if (!strcmp("PanelHorizontalSyncEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalSyncEnd = (unsigned char)data;
+			pExist[PB_PanelHorizontalSyncEnd] = 1;
+		} else if (!strcmp("PanelVerticalSyncStart",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalSyncStart = (unsigned char)data;
+			pExist[PB_PanelVerticalSyncStart] = 1;
+		} else if (!strcmp("PanelVerticalSyncEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalSyncEnd = (unsigned char)data;
+			pExist[PB_PanelVerticalSyncEnd] = 1;
+		} else if (!strcmp("PanelVerticalMaxEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalMaxEnd = (unsigned short)data;
+			pExist[PB_PanelVerticalMaxEnd] = 1;
+		} else if (!strcmp("PanelHorizontalDisplayStart",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalDisplayStart = data;
+			pExist[PB_PanelHorizontalDisplayStart] = 1;
+		} else if (!strcmp("PanelVerticalDisplayStart",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalDisplayStart = data;
+			pExist[PB_PanelVerticalDisplayStart] = 1;
+		} else if (!strcmp("PanelHorizontalDisplayEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelHorizontalDisplayEnd = data;
+			pExist[PB_PanelHorizontalDisplayEnd] = 1;
+		} else if (!strcmp("PanelVerticalDisplayEnd",ptr)) {
+			BrvipFlash.PanelParameter.PanelVerticalDisplayEnd = data;
+			pExist[PB_PanelVerticalDisplayEnd] = 1;
+		} else if (!strcmp("PanelBlueOverScan",ptr)) {
+			BrvipFlash.PanelParameter.PanelBlueOverScan = (unsigned char)data;
+			pExist[PB_PanelBlueOverScan] = 1;
+		} else if (!strcmp("PanelGreenOverScan",ptr)) {
+			BrvipFlash.PanelParameter.PanelGreenOverScan = (unsigned char)data;
+			pExist[PB_PanelGreenOverScan] = 1;
+		} else if (!strcmp("PanelRedOverScan",ptr)) {
+			BrvipFlash.PanelParameter.PanelRedOverScan = (unsigned char)data;
+			pExist[PB_PanelRedOverScan] = 1;
+		} else if (!strcmp("DpyHorizontalDisplayStart",ptr)) {
+			BrvipFlash.DisplayPosition.DpyHorizontalDisplayStart = data;
+			pExist[PB_DpyHorizontalDisplayStart] = 1;
+		} else if (!strcmp("DpyVerticalDisplayStart",ptr)) {
+			BrvipFlash.DisplayPosition.DpyVerticalDisplayStart = data;
+			pExist[PB_DpyVerticalDisplayStart] = 1;
+		} else if (!strcmp("DpyHorizontalDisplayEnd",ptr)) {
+			BrvipFlash.DisplayPosition.DpyHorizontalDisplayEnd = data;
+			pExist[PB_DpyHorizontalDisplayEnd] = 1;
+		} else if (!strcmp("DpyVerticalDisplayEnd",ptr)) {
+			BrvipFlash.DisplayPosition.DpyVerticalDisplayEnd = data;
+			pExist[PB_DpyVerticalDisplayEnd] = 1;
+		} else if (!strcmp("DpyOffset",ptr)) {
+			BrvipFlash.DisplayPosition.DpyOffset = (unsigned short)data;
+			pExist[PB_DpyOffset] = 1;
+		} else if (!strcmp("DpySize",ptr)) {
+			BrvipFlash.DisplayPosition.DpySize = (unsigned short)data;
+			pExist[PB_DpySize] = 1;
+		} else if (!strcmp("DpyLine",ptr)) {
+			BrvipFlash.DisplayPosition.DpyLine = data;
+			pExist[PB_DpyLine] = 1;
+		} else if (!strcmp("Version",ptr)) {
+			BrvipFlash.Version = data;
+			pExist[PB_Version] = 1;
+		} else if (!strcmp("DeviceID",ptr)) {
+			BrvipFlash.DeviceID = (unsigned short)data;
+			pExist[PB_DeviceID] = 1;
+		} else if (!strcmp("VendorID",ptr)) {
+			BrvipFlash.VendorID = (unsigned short)data;
+			pExist[PB_VendorID] = 1;
+		} else if (!strcmp("Dpy00",ptr)) {
+			BrvipFlash.Dpy00 = data;
+			pExist[PB_Dpy00] = 1;
+		} else if (!strcmp("Dpy20",ptr)) {
+			BrvipFlash.Dpy20 = data;
+			pExist[PB_Dpy20] = 1;
+		} else if (!strcmp("Before_MMIOAddress",ptr)) {
+			BrvipFlash.Before_MMIOAddress = data;
+			pExist[PB_Before_MMIOAddress] = 1;
+		} else if (!strcmp("VIPAddress",ptr)) {
+			BrvipFlash.VIPAddress = data;
+			pExist[PB_VIPAddress] = 1;
+		} else if (!strcmp("After_MMIOAddress",ptr)) {
+			BrvipFlash.After_MMIOAddress = data;
+			pExist[PB_After_MMIOAddress] = 1;
+		} else if (!strcmp("SlrReset",ptr)) {;
+			BrvipFlash.ScalerRegister.SlrReset = data;
+			pExist[PB_SlrReset] = 1;
+		} else if (!strcmp("SlrConfig",ptr)) {
+			BrvipFlash.ScalerRegister.SlrConfig = data;
+			pExist[PB_SlrConfig] = 1;
+		} else if (!strcmp("SlrHorizontalFactor",ptr)) {
+			BrvipFlash.ScalerRegister.SlrHorizontalFactor = data;
+			pExist[PB_SlrHorizontalFactor] = 1;
+		} else if (!strcmp("SlrVerticalFactor",ptr)) {
+			BrvipFlash.ScalerRegister.SlrVerticalFactor = data;
+			pExist[PB_SlrVerticalFactor] = 1;
+		} else if (!strcmp("SlrVerticalDown",ptr)) {
+			BrvipFlash.ScalerRegister.SlrVerticalDown = data;
+			pExist[PB_SlrVerticalDown] = 1;
+		}
+		/* else if (!strcmp("SlrLeft",ptr)) {
+			BrvipFlash.ScalerRegister.SlrLeft = data;
+			pExist[PB_SlrLeft] = 1;
+		} else if (!strcmp("SlrRight",ptr)) {
+			BrvipFlash.ScalerRegister.SlrRight = data;
+			pExist[PB_SlrRight] = 1;
+		} else if (!strcmp("SlrLeft0",ptr)) {
+			BrvipFlash.ScalerRegister.SlrLeft0 = data;
+			pExist[PB_SlrLeft0] = 1;
+		} else if (!strcmp("SlrRight0",ptr)) {
+			BrvipFlash.ScalerRegister.SlrRight0 = data;
+			pExist[PB_SlrRight0] = 1;
+		} else if (!strcmp("SlrHorizontalFactor0",ptr)) {
+			BrvipFlash.ScalerRegister.SlrHorizontalFactor0 = data;
+			pExist[PB_SlrHorizontalFactor0] = 1;
+		}  */
+		else if (!strcmp("SlrLine",ptr)) {
+			BrvipFlash.ScalerRegister.SlrLine = data;
+			pExist[PB_SlrLine] = 1;
+		} else if (!strcmp("SlrInc",ptr)) {
+			BrvipFlash.ScalerRegister.SlrInc = data;
+			pExist[PB_SlrInc] = 1;
+		}
+#if 0
+		else if (!strcmp("Gpio_15",ptr)) {
+			BrvipFlash.Gpio_15 = data;
+			pExist[PB_Gpio_15] = 1;
+		} else if (!strcmp("Gpio_16",ptr)) {
+			BrvipFlash.Gpio_16 = data;
+			pExist[PB_Gpio_16] = 1;
+		}
+#else
+		else if (!strcmp("PanelBackLight_GPIOmode",ptr)) {
+			BrvipFlash.PanelBackLight_GPIOPin = (unsigned char)data;
+			//pExist[PB_PanelBackLight_GPIOmode] = 1;
+		}
+		else if (!strcmp("PanelPower_GPIOmode",ptr)) {
+			BrvipFlash.PanelPower_GPIOPin = (unsigned char)data;
+			//pExist[PB_PanelPower_GPIOmode] = 1;
+		}
+
+#endif
+		else if (!strcmp("PanelBackLight_GPIOPin",ptr)) {
+			BrvipFlash.PanelBackLight_GPIOPin = (unsigned char)data;
+			pExist[PB_PanelBackLight_GPIOPin] = 1;
+		}
+		else if (!strcmp("PanelPower_GPIOPin",ptr)) {
+			BrvipFlash.PanelPower_GPIOPin = (unsigned char)data;
+			pExist[PB_PanelPower_GPIOPin] = 1;
+		}
+		else if (!strcmp("PanelBackLight_ActiveValue",ptr)) {
+			BrvipFlash.PanelBackLight_ActiveValue = (unsigned char)data;
+			pExist[PB_PanelBackLight_ActiveValue] = 1;
+		}
+		else if (!strcmp("PanelPower_ActiveValue",ptr)) {
+			BrvipFlash.PanelPower_ActiveValue = (unsigned char)data;
+			pExist[PB_PanelPower_ActiveValue] = 1;
+		}
+		else if (!strcmp("LCDBackLightOrder",ptr)) {
+			BrvipFlash.LCDBackLightOrder = (DWORD)data;
+			pExist[PB_LCDBackLightOrder] = 1;
+		}
+		else if (!strcmp("LCDBackLight_OtherFrq",ptr)) {
+			BrvipFlash.LCDBackLight_OtherFrq = (DWORD)data;
+			pExist[PB_LCDBackLight_OtherFrq] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_00",ptr)) {
+			BrvipFlash.LCDBackLightMap_00 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_00] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_01",ptr)) {
+			BrvipFlash.LCDBackLightMap_01 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_01] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_02",ptr)) {
+			BrvipFlash.LCDBackLightMap_02 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_02] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_03",ptr)) {
+			BrvipFlash.LCDBackLightMap_03 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_03] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_04",ptr)) {
+			BrvipFlash.LCDBackLightMap_04 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_04] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_05",ptr)) {
+			BrvipFlash.LCDBackLightMap_05 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_05] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_06",ptr)) {
+			BrvipFlash.LCDBackLightMap_06 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_06] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_07",ptr)) {
+			BrvipFlash.LCDBackLightMap_07 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_07] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_08",ptr)) {
+			BrvipFlash.LCDBackLightMap_08 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_08] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_09",ptr)) {
+			BrvipFlash.LCDBackLightMap_09 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_09] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_10",ptr)) {
+			BrvipFlash.LCDBackLightMap_10 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_10] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_11",ptr)) {
+			BrvipFlash.LCDBackLightMap_11 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_11] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_12",ptr)) {
+			BrvipFlash.LCDBackLightMap_12 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_12] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_13",ptr)) {
+			BrvipFlash.LCDBackLightMap_13 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_13] = 1;
+		}
+		else if (!strcmp("LCDBackLightMap_14",ptr)) {
+			BrvipFlash.LCDBackLightMap_14 = (DWORD)data;
+			pExist[PB_LCDBackLightMap_14] = 1;
+		}
+		else if (!strcmp("LogoType",ptr)) {
+			BrvipFlash.LogoType = (DWORD)data;
+			pExist[PB_LogoType] = 1;
+		}
+		else if (!strcmp("LogoSize",ptr)) {
+			BrvipFlash.LogoSize = (DWORD)data;
+			pExist[PB_LogoSize] = 1;
+		}
+		else if (!strcmp("PanelBackLight_OffdelayTime",ptr)) {
+			BrvipFlash.PanelBackLight_OffdelayTime = (DWORD)data;
+			pExist[PB_PanelBackLight_OffdelayTime] = 1;
+		}
+		else if (!strcmp("PanelBackPower_OffdelayTime",ptr)) {
+			BrvipFlash.PanelBackPower_OffdelayTime = (DWORD)data;
+			pExist[PB_PanelBackPower_OffdelayTime] = 1;
+		}
+
+	}
+
+	fseek(InFile, mmioflag, SEEK_SET);
+	//BrvipFlash.Before_MMIOAddress = 0xbc0b0000+sizeof(BRVIP_FLASH);	07/03/02008 David.
+	BrvipFlash.Before_MMIOAddress = BR_ADDR_VIP+sizeof(BRVIP_FLASH);
+	BrvipFlash.After_MMIOAddress = BrvipFlash.Before_MMIOAddress;
+	ULSize = 0;
+	//fwrite(&BrvipFlash,sizeof(BRVIP_FLASH),1,OutFile);
+	while (fscanf(InFile,"\n%x %x %x %x",&data,&data1,&data2,&data3) != EOF)
+	{
+		if ((data == 0xffffffff)||(data == 0x00000000))
+		{
+			break;
+		}
+		//fwrite(&data,4,1,OutFile);
+		//fwrite(&data1,4,1,OutFile);
+		//fwrite(&data2,4,1,OutFile);
+		//fwrite(&data3,4,1,OutFile);
+		//BrvipFlash.After_MMIOAddress += 0x10;
+		ULData[ULSize] = data;
+		ULData[ULSize+1] = data1;
+		ULData[ULSize+2] = data2;
+		ULData[ULSize+3] = data3;
+		ULSize += 4;
+	}
+	data=0xffffffff;
+	//fwrite(&data,4,1,OutFile);
+	//fwrite(&data,4,1,OutFile);
+	//fwrite(&data,4,1,OutFile);
+	//fwrite(&data,4,1,OutFile);
+	//BrvipFlash.After_MMIOAddress += 0x10;
+	ULData[ULSize] = data;
+	ULData[ULSize+1] = data;
+	ULData[ULSize+2] = data;
+	ULData[ULSize+3] = data;
+	ULSize += 4;
+	BrvipFlash.After_MMIOAddress += (ULSize*4);
+	printf("Before_MMIOAddress %x\n",(unsigned int)BrvipFlash.Before_MMIOAddress);
+	printf("ULSize %x",(unsigned int)ULSize);
+	printf("After_MMIOAddress %x\n",(unsigned int)BrvipFlash.After_MMIOAddress);
+
+	//memcpy(pOutData+writeOffset, &BrvipFlash, sizeof(BRVIP_FLASH));  //write it later
+	writeOffset += sizeof(BRVIP_FLASH);
+	memcpy(pOutData+writeOffset, ULData, 4*ULSize);
+	writeOffset += 4*ULSize;
+
+	while (fscanf(InFile,"\n%x %x %x %x",&data,&data1,&data2,&data3) != EOF)
+	{
+		if ((data == 0xffffffff)||(data == 0x00000000))
+		{
+			break;
+		}
+		memcpy(pOutData+writeOffset, &data, 4);
+		writeOffset += 4;
+		memcpy(pOutData+writeOffset, &data1, 4);
+		writeOffset += 4;
+		memcpy(pOutData+writeOffset, &data2, 4);
+		writeOffset += 4;
+		memcpy(pOutData+writeOffset, &data3, 4);
+		writeOffset += 4;
+	}
+	data=0xffffffff;
+	memcpy(pOutData+writeOffset, &data, 4);
+	writeOffset += 4;
+	memcpy(pOutData+writeOffset, &data, 4);
+	writeOffset += 4;
+	memcpy(pOutData+writeOffset, &data, 4);
+	writeOffset += 4;
+	memcpy(pOutData+writeOffset, &data, 4);
+	writeOffset += 4;
+
+#ifdef SET_338_VIP
+	while (fscanf(InFile,"\n%x %x %x %x",&data,&data1,&data2,&data3) != EOF)
+	{
+		if ((data == 0xffffffff)||(data == 0x00000000))
+		{
+			break;
+		}
+		memcpy(pOutData+writeOffset, &data, 4);
+		writeOffset += 4;
+		memcpy(pOutData+writeOffset, &data1, 4);
+		writeOffset += 4;
+		memcpy(pOutData+writeOffset, &data2, 4);
+		writeOffset += 4;
+		memcpy(pOutData+writeOffset, &data3, 4);
+		writeOffset += 4;
+
+	}
+
+	data=0xffffffff;
+	memcpy(pOutData+writeOffset, &data, 4);
+	writeOffset += 4;
+	memcpy(pOutData+writeOffset, &data, 4);
+	writeOffset += 4;
+	memcpy(pOutData+writeOffset, &data, 4);
+	writeOffset += 4;
+	memcpy(pOutData+writeOffset, &data, 4);
+	writeOffset += 4;
+
+#endif //SET_338_VIP
+#if 1
+	if(i2c0_fileoffset){
+		int tmp_write_size = write_i2c_data_to_bin(InFile, i2c0_fileoffset, pOutData, writeOffset);
+		if(tmp_write_size > 0){
+			BrvipFlash.I2C0_IndexAddress = (short)writeOffset;
+			writeOffset += tmp_write_size;
+		}
+	}
+	if(i2c1_fileoffset){
+		int tmp_write_size = write_i2c_data_to_bin(InFile, i2c1_fileoffset, pOutData, writeOffset);
+		if(tmp_write_size > 0){
+			BrvipFlash.I2C1_IndexAddress = (short)writeOffset;
+			writeOffset += tmp_write_size;
+		}
+	}
+
+
+#endif
+
+	fclose(InFile);
+	/* store brvip after save all struct data */
+
+	memcpy(pOutData, &BrvipFlash, sizeof(BRVIP_FLASH));
+#if 0	//gaia, 2013.05.02 ya! i don't know what is this..
+	//--------- Option
+	if (optionflag)
+	{
+		if(PANELSET_SIZE != PANELSET_NOW_USE_FIX_SIZE)
+		{
+			fprintf(stderr, "Error! \nPanelSet Size change !\n  Driver must update for this");
+			return -1;
+		}
+		DWORD fileLen;
+		fileLen = writeOffset % mergeToSize;
+		if(fileLen >= (PANELSET_OPTION_D_OFFSET)) //0x7ec
+		{
+			fprintf(stderr, "Error! \nPanelSet Size change ! Over ox 7 e c\n  Tool must update");
+			return -1;
+		}
+		writeOffset = PANELSET_OPTION_D_OFFSET;
+
+		memcpy(pOutData+writeOffset, &tempDW,4);
+	}
+	//---------
+
+	//check lost only
+	for(i=0; i<PB_MAX_END ;i++)
+	{
+		if(pExist[i]!=1)
+		{
+			fprintf(stderr, "Error \n\n It must have lost data at No %d\n", i);
+			return -1;
+		}
+	}
+#endif
+	return writeOffset;
+}
+
+int BMP2Bin(char *szFileIn, char *szFileOut)
+{
+	unsigned char BMPFILEHEADER[14],BMPINFOSIZE[4],WIDTH[4],HEIGHT[4];
+	FILE *fin,*fout;
+	int numread,i,dataoffset;//fseekresult;
+	int width,height;//,size;
+	int outwidth,align_offset;
+	int icolor;
+	//int line_offset;
+	int line_length_pad;
+	unsigned char *READLINE, *ZERO;
+	unsigned char MYWORD[2];
+	int fin_index,fout_index;
+#ifdef CustomerLOGO
+	unsigned char buf[8]={0x00};
+#endif
+
+	READLINE = malloc(12288);
+	if (READLINE == NULL)
+		return 0;
+
+	ZERO = malloc(12288);
+	if (ZERO == NULL) 
+	{
+		free(READLINE);
+		return 0;
+	}
+	
+	fout_index=0;
+	for(i=0;i<12288;i++)
+	{
+		ZERO[i]=0;
+		if((i%3)==0) ZERO[i]=0xff;
+	}
+
+	//line_offset=0;
+
+	fin=fopen(szFileIn,"rb");
+	fout=fopen(szFileOut,"wb");
+
+	//foutARGB=fopen(argv[3],"w+");
+	if (fin == NULL || fout == NULL)
+	{
+		if (fin) fclose(fin);
+		if (fout) fclose(fout);
+		free(READLINE);
+		free(ZERO);
+		fprintf(stderr, "Open file fail!!");
+		return 0;
+	}
+	fseek( fin, 0, SEEK_SET);//fseekresult=fseek( fin, 0, SEEK_SET);
+	numread = fread( BMPFILEHEADER, sizeof( char ), 14, fin );
+	if(numread!=14)
+	{
+		fprintf(stderr, "Error:read file header error!!\n");
+		fclose(fout);
+		fclose(fin);
+		free(READLINE);
+		free(ZERO);
+		return 0;
+	}
+    if((BMPFILEHEADER[0]!=0x42)||(BMPFILEHEADER[1]!=0x4d))
+	{
+		fprintf(stderr, "Error:Not BMP File!!");
+		fclose(fout);
+		fclose(fin);
+		free(READLINE);
+		free(ZERO);
+		return 0;
+	}
+
+	//<=============================Process Header======================>
+	//< Just capture what we need.....									>
+	//< DataOffSet:														>
+	//< Width:															>
+	//< Height:															>
+	//<=================================================================>
+
+	//for(i=0;i<14;i++)
+	//	printf("0x%02x ",(char)BMPFILEHEADER[i]);
+	//printf("\n");
+
+	dataoffset=(((BMPFILEHEADER[13]<<8)+BMPFILEHEADER[12])<<16)+(BMPFILEHEADER[11]<<8)+BMPFILEHEADER[10];
+
+	//printf("dataoffset=%d\n",dataoffset);
+	fseek( fin, 14, SEEK_SET);//fseekresult=fseek( fin, 14, SEEK_SET);
+	numread =fread( BMPINFOSIZE, sizeof( char ), 4, fin );
+	if(numread!=4)
+	{
+		fprintf(stderr, "Error:read BMP Info Header error!!");
+		fclose(fout);
+		fclose(fin);
+		free(READLINE);
+		free(ZERO);
+		return 0;
+	}
+#if 0	//fgets( BMPINFOSIZE,  4, fin );
+	size=(((BMPINFOSIZE[3]<<8)+BMPINFOSIZE[2])<<16)+(BMPINFOSIZE[1]<<8)+BMPINFOSIZE[0];
+#endif
+	fseek( fin, 18, SEEK_SET);//fseekresult=fseek( fin, 18, SEEK_SET);
+    numread=fread( WIDTH, sizeof( char ), 4, fin );
+
+	if(numread!=4)
+	{
+		fprintf(stderr, "Error:read BMP Info Header error!!");
+		fclose(fout);
+		fclose(fin);
+		free(READLINE);
+		free(ZERO);
+		return 0;
+	}
+	width=(((WIDTH[3]<<8)+WIDTH[2])<<16)+(WIDTH[1]<<8)+WIDTH[0];
+	fseek( fin, 22, SEEK_SET);//fseekresult=fseek( fin, 22, SEEK_SET);
+	numread=fread( HEIGHT, sizeof( char ), 4, fin );
+	if(numread!=4)
+	{
+		fprintf(stderr, "Error:read BMP Info Header error!!");
+		fclose(fout);
+		fclose(fin);
+		free(READLINE);
+		free(ZERO);
+		return 0;
+	}
+	height=(((HEIGHT[3]<<8)+HEIGHT[2])<<16)+(HEIGHT[1]<<8)+HEIGHT[0];
+	printf("Input BMP width=%d,height=%d\n",width,height);
+	fseek( fin, 28, SEEK_SET);//fseekresult=fseek( fin, 28, SEEK_SET);
+	numread=fread( MYWORD, sizeof( char ), 2, fin );
+	if(numread!=2)
+	{
+		fprintf(stderr, "Error:read BMP Info Header error!!");
+		fclose(fout);
+		fclose(fin);
+		free(READLINE);
+		free(ZERO);
+		return 0;
+	}
+	icolor=(MYWORD[1]<<8)+MYWORD[0];
+	printf("icolor=%d\n",icolor);
+	//<======================== Read Data ================================>
+	//< (GBR)(GBR)(GBR)...................................................>
+	//< (RBG)(RBG)........................................................>
+	//<===================================================================>
+
+	outwidth=(((width*3)+255)/256)*256;
+	//outwidth=line_offset*256;
+
+    if((width*3)%4)
+    	line_length_pad=(4-((width*3)%4));
+    else
+    	line_length_pad=0;
+    printf("line_length_pad=%d\n",line_length_pad);
+    fin_index=dataoffset+(height-1)*width*3+(height-1)*line_length_pad;
+    align_offset=outwidth-width*3-line_length_pad;
+    printf("align_offset=%d,outwidth=%d\n",align_offset,outwidth);
+//	for(i=height-1;i>0;i--)
+	for(i=0;i<height;i++)
+	{
+		//printf("line %d\n",i);
+    	//printf("offset(fin_index):0x%x\n",fin_index);
+    	fseek( fin, fin_index, SEEK_SET);//fseekresult=fseek( fin, fin_index, SEEK_SET);
+
+    	numread=fread( READLINE, sizeof( char ),(line_length_pad+(width*3)) , fin );
+    	if(numread!=line_length_pad+(width*3))
+		{
+			//printf("fseekresult=%d numread should be %d,but is %d\n",fseekresult,line_length_pad+(width*3),numread);
+    		fseek( fin, fin_index, SEEK_SET);//fseekresult=fseek( fin, fin_index, SEEK_SET);
+    		numread=fread( READLINE, sizeof( char ),( line_length_pad+(width*3)), fin );
+
+			if(numread!=line_length_pad+(width*3))
+			{
+				if ( ferror( fin ) )
+					printf( "rs:file Read error\n" );
+				else
+					printf("rs:not ferror\n");
+
+				if ( feof( fin ) )
+					printf( "rs:file end\n" );
+				else
+					printf("rs:not feof\n");
+
+				fprintf(stderr, "Error:read RGB row data failed!");
+				printf("numread should be %d,but is %d\n",line_length_pad+(width*3),numread);
+				fclose(fout);
+				fclose(fin);
+				free(READLINE);
+				free(ZERO);
+				return 0;
+			}
+		}
+
+		{
+    		int j;
+			unsigned char G,B,R;
+			//======Transfer GBR to RBG============
+			for(j=0;j<width;j++)
+			{
+				//printf("j=%d,SRC(%02x,%02x,%02x)",j,READLINE[j*3],READLINE[j*3+1],READLINE[j*3+2]);
+				int p;
+				B=READLINE[j*3];
+				G=READLINE[j*3+1];
+				R=READLINE[j*3+2];
+
+				READLINE[j*3]=R;
+				READLINE[j*3+1]=B;
+				READLINE[j*3+2]=G;
+				//printf("j=%d,DES(%02x,%02x,%02x)\n",j,READLINE[j*3],READLINE[j*3+1],READLINE[j*3+2]);
+				if(j==width-1)
+				{
+					for(p=0;p<line_length_pad;p++)
+					{
+						READLINE[j*3+3+p]=0;
+					}
+				}
+			}
+		}
+
+		fseek( fout, fout_index, SEEK_SET);//fseekresult=fseek( fout, fout_index, SEEK_SET);
+		fwrite(READLINE, sizeof( char ), line_length_pad+width*3, fout);
+		fout_index+=line_length_pad+width*3;
+		fseek( fout, fout_index, SEEK_SET);//fseekresult=fseek( fout, fout_index, SEEK_SET);
+		fwrite(ZERO, sizeof( char ), align_offset, fout);
+		//printf("write 0x%3x bytes",align_offset+width*3);
+		fout_index+=align_offset;
+		fin_index-=line_length_pad+width*3;
+		//printf("fout_index: 0x%3x ,fin_index:%d=0x%08x\n",fout_index,fin_index,fin_index);
+	}
+#ifdef CustomerLOGO
+	fseek( fout, 0, SEEK_SET);//fseekresult=fseek( fout, fout_index, SEEK_SET);
+	fwrite(WIDTH, sizeof( char ), 4, fout);
+	fwrite(HEIGHT, sizeof( char ), 4, fout);
+	fwrite(buf, sizeof( char ), 8, fout);
+#endif
+	fclose(fout);
+	fclose(fin);
+	free(READLINE);
+	free(ZERO);
+	return 1;
+}

+ 199 - 0
tools/mergeImage/pnlset2bin.h

@@ -0,0 +1,199 @@
+#ifndef __PNLSET2BIN_H_
+#define __PNLSET2BIN_H_
+
+#ifdef _windows_
+	#include "../sisspi_flashalloc.h"
+#else
+	#include <drv_spi_flashalloc_external.h>
+#endif
+
+#define _GNU_SOURCE
+#define _XOPEN_SOURCE 600
+
+#define DWORD 	unsigned long
+#define FALSE	0
+#define TRUE	1
+
+#define PANELSET_VERSION2_NAME_HEADER "PanelSet_Ascii_Version"
+#define PANELSET_VERSION2_NAME_MAX_LEN 20
+
+#define PANELSET_SIZE (2*1024)//SPI_PANELSET_MAXSIZE
+#define BR_ADDR_VIP 0
+#define FILL_MEM_BY_INI
+#define SET_338_VIP
+#define PANELSET_OPTION_D_OFFSET  (PANELSET_SIZE - 0x14)
+#define PANELSET_NOW_USE_FIX_SIZE  (2 * 1024) //for woring
+
+typedef struct _PANEL_PARAMETER_ {
+	unsigned long	PanelHorizontalEnd;
+	unsigned long	PanelVerticalEnd;
+	unsigned char	PanelHorizontalSyncStart;
+	unsigned char	PanelHorizontalSyncEnd;
+	unsigned char	PanelVerticalSyncStart;
+	unsigned char	PanelVerticalSyncEnd;
+	//unsigned long	Reserve01;
+	unsigned short	PanelVerticalMaxEnd;
+	unsigned short	Reserve01;
+	unsigned long	PanelHorizontalDisplayStart;
+	unsigned long	PanelVerticalDisplayStart;
+	unsigned long	PanelHorizontalDisplayEnd;
+	unsigned long	PanelVerticalDisplayEnd;
+	unsigned char	PanelBlueOverScan;
+	unsigned char	PanelGreenOverScan;
+	unsigned char	PanelRedOverScan;
+	unsigned char	Reserve02;
+}PANEL_PARAMETER,*PPANEL_PARAMETER;
+
+typedef struct _DISPLAY_POSITION_ {
+	unsigned long	DpyHorizontalDisplayStart;
+	unsigned long	DpyVerticalDisplayStart;
+	unsigned long	DpyHorizontalDisplayEnd;
+	unsigned long	DpyVerticalDisplayEnd;
+	unsigned short	DpyOffset;
+	unsigned short	DpySize;
+	unsigned long	DpyLine;
+}DISPLAY_POSITION,*PDISPLAY_POSITION;
+
+typedef struct _SCALER_REGISTER_ {
+	unsigned long	SlrReset;
+	unsigned long	SlrConfig;
+	unsigned long	SlrHorizontalFactor;
+	unsigned long	SlrVerticalFactor;
+	unsigned long	SlrVerticalDown;
+/*
+	unsigned long	SlrLeft;
+	unsigned long	SlrRight;
+	unsigned long	SlrLeft0;
+	unsigned long	SlrRight0;
+	unsigned long	SlrHorizontalFactor0;
+*/
+	unsigned char	VersionOfAscii_20[20];
+	unsigned long	SlrLine;
+	unsigned long	SlrInc;
+}SCALER_REGISTER,*PSCALER_REGISTER;
+
+typedef struct _BRVIP_FLASH_ {
+	PANEL_PARAMETER		PanelParameter;
+	DISPLAY_POSITION	DisplayPosition;
+	unsigned long		Version;
+	unsigned short		DeviceID;
+	unsigned short		VendorID;
+	unsigned long		Dpy00;
+	unsigned long		Dpy20;
+	unsigned long		Before_MMIOAddress;
+	unsigned long		VIPAddress;
+	unsigned long		After_MMIOAddress;
+	SCALER_REGISTER		ScalerRegister;
+	unsigned short				  I2C0_IndexAddress;
+	unsigned short 			   I2C1_IndexAddress;
+	unsigned short 			   reserve;
+	unsigned char				   PanelBackLight_GPIOmode;
+	unsigned char				   PanelPower_GPIOmode;
+	unsigned char		PanelBackLight_GPIOPin;
+	unsigned char		PanelPower_GPIOPin;
+	unsigned char		PanelBackLight_ActiveValue;
+	unsigned char		PanelPower_ActiveValue;
+	DWORD				LCDBackLightOrder;
+	DWORD				LCDBackLight_OtherFrq;
+	DWORD				LCDBackLightMap_00;
+	DWORD				LCDBackLightMap_01;
+	DWORD				LCDBackLightMap_02;
+	DWORD				LCDBackLightMap_03;
+	DWORD				LCDBackLightMap_04;
+	DWORD 				LCDBackLightMap_05;
+	DWORD 				LCDBackLightMap_06;
+	DWORD 				LCDBackLightMap_07;
+	DWORD 				LCDBackLightMap_08;
+	DWORD 				LCDBackLightMap_09;
+	DWORD 				LCDBackLightMap_10;
+	DWORD 				LCDBackLightMap_11;
+	DWORD 				LCDBackLightMap_12;
+	DWORD 				LCDBackLightMap_13;
+	DWORD 				LCDBackLightMap_14;
+	DWORD 				LogoType;
+	DWORD 				LogoSize;
+	DWORD               PanelBackLight_OffdelayTime;
+	DWORD				PanelBackPower_OffdelayTime;
+}BRVIP_FLASH,*PBRVIP_FLASH;
+
+enum
+{
+	PB_PanelHorizontalEnd           =0,
+	PB_PanelVerticalEnd               ,
+	PB_PanelHorizontalSyncStart       ,
+	PB_PanelHorizontalSyncEnd         ,
+	PB_PanelVerticalSyncStart	       ,
+	PB_PanelVerticalSyncEnd	       ,
+	PB_PanelVerticalMaxEnd	       ,
+	PB_PanelHorizontalDisplayStart	   ,
+	PB_PanelVerticalDisplayStart	   ,
+	PB_PanelHorizontalDisplayEnd      ,
+	PB_PanelVerticalDisplayEnd		   ,
+	PB_PanelBlueOverScan		       ,
+	PB_PanelGreenOverScan		       ,
+	PB_PanelRedOverScan	           ,
+	PB_DpyHorizontalDisplayStart      ,
+	PB_DpyVerticalDisplayStart	       ,
+	PB_DpyHorizontalDisplayEnd        ,
+	PB_DpyVerticalDisplayEnd          ,
+	PB_DpyOffset			           ,
+	PB_DpySize				           ,
+	PB_DpyLine				           ,
+	PB_Version				           ,
+	PB_DeviceID			           ,
+	PB_VendorID			           ,
+	PB_Dpy00				           ,
+	PB_Dpy20				           ,
+	PB_Before_MMIOAddress			   ,
+	PB_VIPAddress				       ,
+	PB_After_MMIOAddress			   ,
+	PB_SlrReset					       ,
+	PB_SlrConfig				       ,
+	PB_SlrHorizontalFactor			   ,
+	PB_SlrVerticalFactor			   ,
+	PB_SlrVerticalDown				   ,
+	//PB_SlrLeft				           ,
+	//PB_SlrRight				           ,
+	//PB_SlrLeft0				           ,
+	//PB_SlrRight0				       ,
+	//PB_SlrHorizontalFactor0			   ,
+	PB_SlrLine				           ,
+	PB_SlrInc				           ,
+	//PB_Gpio_15				           ,
+	//PB_Gpio_16				           ,
+//	PB_PanelBackLight_GPIOmode	,
+//	PB_PanelPower_GPIOmode		,
+	PB_PanelBackLight_GPIOPin          ,
+	PB_PanelPower_GPIOPin	           ,
+	PB_PanelBackLight_ActiveValue      ,
+	PB_PanelPower_ActiveValue          ,
+	PB_LCDBackLightOrder				,
+	PB_LCDBackLight_OtherFrq			,
+	PB_LCDBackLightMap_00				,
+	PB_LCDBackLightMap_01				,
+	PB_LCDBackLightMap_02				,
+	PB_LCDBackLightMap_03				,
+	PB_LCDBackLightMap_04				,
+	PB_LCDBackLightMap_05				,
+	PB_LCDBackLightMap_06				,
+	PB_LCDBackLightMap_07				,
+	PB_LCDBackLightMap_08				,
+	PB_LCDBackLightMap_09				,
+	PB_LCDBackLightMap_10				,
+	PB_LCDBackLightMap_11				,
+	PB_LCDBackLightMap_12				,
+	PB_LCDBackLightMap_13				,
+	PB_LCDBackLightMap_14				,
+	PB_LogoType							,
+	PB_LogoSize							,
+	PB_PanelBackLight_OffdelayTime		,
+	PB_PanelBackPower_OffdelayTime		,
+	PB_MAX_END                         ,
+};
+
+#endif
+
+int ini2binmem(char* pInFile, char *pOutData, int nBufSize);
+DWORD ini2bin(char* pInFile, char *pOutFile);
+int BMP2Bin(char *szFileIn, char *szFileOut);
+

+ 493 - 0
tools/mergeImage/sisspi_encrypt.c

@@ -0,0 +1,493 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include "mergeImage.h"
+
+#ifndef DWORD
+#define DWORD	unsigned int
+#endif
+
+#ifndef BYTE
+#define BYTE	unsigned char
+#endif
+
+#ifndef bool
+#define bool	unsigned int
+#endif
+
+#define FLASH_HW_KEY		0x08825252U
+#define FLASH_HW_KEY_0 		((FLASH_HW_KEY <<(32-11)) |(FLASH_HW_KEY>>11))
+#define FLASH_HW_KEY_1 		((FLASH_HW_KEY <<(32-20)) |(FLASH_HW_KEY>>20))
+#define FLASH_HW_KEY_2 		((FLASH_HW_KEY <<(32-26)) |(FLASH_HW_KEY>>26))
+#define FLASH_HW_KEY_3 		((FLASH_HW_KEY <<(32-7)) |(FLASH_HW_KEY>>7))
+
+DWORD cmN_BytesToDWORD(char* bytes)
+{
+	int i;
+	DWORD value;
+	value = 0;
+	char* tmpByte;
+	//printf("cmN_BytesToDWORD %p\n", bytes);
+	for(i=0;i<4;i++)
+	{
+		tmpByte = &bytes[i];
+		if(tmpByte)
+		{
+			value |= (*tmpByte & 0xFF) <<(8*i);
+			//printf("%x\t ", value);
+		}
+	}
+	return value;
+}
+
+void cmN_DWORDToBytes(char* bytes, DWORD value)
+{
+	int i;
+	char* tmpbyte;
+	
+	for(i=0;i<4;i++)
+	{
+		tmpbyte = &bytes[i];
+		*tmpbyte = (BYTE)(value >> (8*i)) & 0xFF;
+	}
+}
+
+bool cmN_GetBitFromDword(DWORD data, BYTE i)
+{
+	if( (data>>i)&1 )
+		return 1;
+	else
+		return 0;
+}
+
+DWORD Mix_0(DWORD data)
+{
+	return ( (cmN_GetBitFromDword(data, 22)<<31) 
+			| (cmN_GetBitFromDword(data, 8)<<30)
+			| (cmN_GetBitFromDword(data, 7)<<29)
+			| (cmN_GetBitFromDword(data, 21)<<28)
+			| (cmN_GetBitFromDword(data, 0)<<27)
+			| (cmN_GetBitFromDword(data, 25)<<26)
+			| (cmN_GetBitFromDword(data, 20)<<25)
+			| (cmN_GetBitFromDword(data, 6)<<24)
+			| (cmN_GetBitFromDword(data, 19)<<23)
+			| (cmN_GetBitFromDword(data, 16)<<22)
+			| (cmN_GetBitFromDword(data, 24)<<21)
+			| (cmN_GetBitFromDword(data, 5)<<20)
+			| (cmN_GetBitFromDword(data, 23)<<19)
+			| (cmN_GetBitFromDword(data, 1)<<18)
+			| (cmN_GetBitFromDword(data, 18)<<17)
+			| (cmN_GetBitFromDword(data, 15)<<16)
+			| (cmN_GetBitFromDword(data, 26)<<15)
+			| (cmN_GetBitFromDword(data, 3)<<14)
+			| (cmN_GetBitFromDword(data, 17)<<13)
+			| (cmN_GetBitFromDword(data, 14)<<12)
+			| (cmN_GetBitFromDword(data, 4)<<11)
+			| (cmN_GetBitFromDword(data, 13)<<10)
+			| (cmN_GetBitFromDword(data, 2)<<9)
+			| (cmN_GetBitFromDword(data, 30)<<8)
+			| (cmN_GetBitFromDword(data, 12)<<7)
+			| (cmN_GetBitFromDword(data, 29)<<6)
+			| (cmN_GetBitFromDword(data, 28)<<5)
+			| (cmN_GetBitFromDword(data, 11)<<4)
+			| (cmN_GetBitFromDword(data, 9)<<3)
+			| (cmN_GetBitFromDword(data, 31)<<2)
+			| (cmN_GetBitFromDword(data, 27)<<1)
+			| (cmN_GetBitFromDword(data, 10)<<0) );
+}
+
+
+DWORD Mix_1(DWORD data)
+{
+	return ( (cmN_GetBitFromDword(data, 11)<<31) 
+			| (cmN_GetBitFromDword(data, 7)<<30)
+			| (cmN_GetBitFromDword(data, 21)<<29)
+			| (cmN_GetBitFromDword(data, 29)<<28)
+			| (cmN_GetBitFromDword(data, 18)<<27)
+			| (cmN_GetBitFromDword(data, 31)<<26)
+			| (cmN_GetBitFromDword(data, 3)<<25)
+			| (cmN_GetBitFromDword(data, 30)<<24)
+			| (cmN_GetBitFromDword(data, 8)<<23)
+			| (cmN_GetBitFromDword(data, 26)<<22)
+			| (cmN_GetBitFromDword(data, 12)<<21)
+			| (cmN_GetBitFromDword(data, 28)<<20)
+			| (cmN_GetBitFromDword(data, 2)<<19)
+			| (cmN_GetBitFromDword(data, 25)<<18)
+			| (cmN_GetBitFromDword(data, 17)<<17)
+			| (cmN_GetBitFromDword(data, 14)<<16)
+			| (cmN_GetBitFromDword(data, 23)<<15)
+			| (cmN_GetBitFromDword(data, 1)<<14)
+			| (cmN_GetBitFromDword(data, 20)<<13)
+			| (cmN_GetBitFromDword(data, 5)<<12)
+			| (cmN_GetBitFromDword(data, 19)<<11)
+			| (cmN_GetBitFromDword(data, 15)<<10)
+			| (cmN_GetBitFromDword(data, 9)<<9)
+			| (cmN_GetBitFromDword(data, 4)<<8)
+			| (cmN_GetBitFromDword(data, 0)<<7)
+			| (cmN_GetBitFromDword(data, 16)<<6)
+			| (cmN_GetBitFromDword(data, 24)<<5)
+			| (cmN_GetBitFromDword(data, 6)<<4)
+			| (cmN_GetBitFromDword(data, 10)<<3)
+			| (cmN_GetBitFromDword(data, 22)<<2)
+			| (cmN_GetBitFromDword(data, 27)<<1)
+			| (cmN_GetBitFromDword(data, 13)<<0) );
+}
+
+
+DWORD Mix_2(DWORD data)
+{
+	return ( (cmN_GetBitFromDword(data, 13)<<31) 
+			| (cmN_GetBitFromDword(data, 23)<<30)
+			| (cmN_GetBitFromDword(data, 9)<<29)
+			| (cmN_GetBitFromDword(data, 20)<<28)
+			| (cmN_GetBitFromDword(data, 3)<<27)
+			| (cmN_GetBitFromDword(data, 25)<<26)
+			| (cmN_GetBitFromDword(data, 14)<<25)
+			| (cmN_GetBitFromDword(data, 24)<<24)
+			| (cmN_GetBitFromDword(data, 2)<<23)
+			| (cmN_GetBitFromDword(data, 11)<<22)
+			| (cmN_GetBitFromDword(data, 30)<<21)
+			| (cmN_GetBitFromDword(data, 16)<<20)
+			| (cmN_GetBitFromDword(data, 6)<<19)
+			| (cmN_GetBitFromDword(data, 19)<<18)
+			| (cmN_GetBitFromDword(data, 1)<<17)
+			| (cmN_GetBitFromDword(data, 5)<<16)
+			| (cmN_GetBitFromDword(data, 0)<<15)
+			| (cmN_GetBitFromDword(data, 22)<<14)
+			| (cmN_GetBitFromDword(data, 12)<<13)
+			| (cmN_GetBitFromDword(data, 26)<<12)
+			| (cmN_GetBitFromDword(data, 8)<<11)
+			| (cmN_GetBitFromDword(data, 21)<<10)
+			| (cmN_GetBitFromDword(data, 10)<<9)
+			| (cmN_GetBitFromDword(data, 17)<<8)
+			| (cmN_GetBitFromDword(data, 28)<<7)
+			| (cmN_GetBitFromDword(data, 4)<<6)
+			| (cmN_GetBitFromDword(data, 29)<<5)
+			| (cmN_GetBitFromDword(data, 15)<<4)
+			| (cmN_GetBitFromDword(data, 31)<<3)
+			| (cmN_GetBitFromDword(data, 18)<<2)
+			| (cmN_GetBitFromDword(data, 7)<<1)
+			| (cmN_GetBitFromDword(data, 27)<<0) );
+}
+
+
+DWORD Mix_3(DWORD data)
+{
+	return ( (cmN_GetBitFromDword(data, 20)<<31) 
+			| (cmN_GetBitFromDword(data, 11)<<30)
+			| (cmN_GetBitFromDword(data, 31)<<29)
+			| (cmN_GetBitFromDword(data, 25)<<28)
+			| (cmN_GetBitFromDword(data, 10)<<27)
+			| (cmN_GetBitFromDword(data, 17)<<26)
+			| (cmN_GetBitFromDword(data, 29)<<25)
+			| (cmN_GetBitFromDword(data, 7)<<24)
+			| (cmN_GetBitFromDword(data, 13)<<23)
+			| (cmN_GetBitFromDword(data, 27)<<22)
+			| (cmN_GetBitFromDword(data, 2)<<21)
+			| (cmN_GetBitFromDword(data, 22)<<20)
+			| (cmN_GetBitFromDword(data, 26)<<19)
+			| (cmN_GetBitFromDword(data, 16)<<18)
+			| (cmN_GetBitFromDword(data, 6)<<17)
+			| (cmN_GetBitFromDword(data, 30)<<16)
+			| (cmN_GetBitFromDword(data, 14)<<15)
+			| (cmN_GetBitFromDword(data, 24)<<14)
+			| (cmN_GetBitFromDword(data, 4)<<13)
+			| (cmN_GetBitFromDword(data, 19)<<12)
+			| (cmN_GetBitFromDword(data, 0)<<11)
+			| (cmN_GetBitFromDword(data, 8)<<10)
+			| (cmN_GetBitFromDword(data, 18)<<9)
+			| (cmN_GetBitFromDword(data, 1)<<8)
+			| (cmN_GetBitFromDword(data, 21)<<7)
+			| (cmN_GetBitFromDword(data, 15)<<6)
+			| (cmN_GetBitFromDword(data, 3)<<5)
+			| (cmN_GetBitFromDword(data, 5)<<4)
+			| (cmN_GetBitFromDword(data, 23)<<3)
+			| (cmN_GetBitFromDword(data, 9)<<2)
+			| (cmN_GetBitFromDword(data, 28)<<1)
+			| (cmN_GetBitFromDword(data, 12)<<0) );
+}
+
+DWORD unMix_0(DWORD data)
+{
+	return ( (cmN_GetBitFromDword(data, 2)<<31) 
+			| (cmN_GetBitFromDword(data, 8)<<30)
+			| (cmN_GetBitFromDword(data, 6)<<29)
+			| (cmN_GetBitFromDword(data, 5)<<28)
+			| (cmN_GetBitFromDword(data, 1)<<27)
+			| (cmN_GetBitFromDword(data, 15)<<26)
+			| (cmN_GetBitFromDword(data, 26)<<25)
+			| (cmN_GetBitFromDword(data, 21)<<24)
+			| (cmN_GetBitFromDword(data, 19)<<23)
+			| (cmN_GetBitFromDword(data, 31)<<22)
+			| (cmN_GetBitFromDword(data, 28)<<21)
+			| (cmN_GetBitFromDword(data, 25)<<20)
+			| (cmN_GetBitFromDword(data, 23)<<19)
+			| (cmN_GetBitFromDword(data, 17)<<18)
+			| (cmN_GetBitFromDword(data, 13)<<17)
+			| (cmN_GetBitFromDword(data, 22)<<16)
+			| (cmN_GetBitFromDword(data, 16)<<15)
+			| (cmN_GetBitFromDword(data, 12)<<14)
+			| (cmN_GetBitFromDword(data, 10)<<13)
+			| (cmN_GetBitFromDword(data, 7)<<12)
+			| (cmN_GetBitFromDword(data, 4)<<11)
+			| (cmN_GetBitFromDword(data, 0)<<10)
+			| (cmN_GetBitFromDword(data, 3)<<9)
+			| (cmN_GetBitFromDword(data, 30)<<8)
+			| (cmN_GetBitFromDword(data, 29)<<7)
+			| (cmN_GetBitFromDword(data, 24)<<6)
+			| (cmN_GetBitFromDword(data, 20)<<5)
+			| (cmN_GetBitFromDword(data, 11)<<4)
+			| (cmN_GetBitFromDword(data, 14)<<3)
+			| (cmN_GetBitFromDword(data, 9)<<2)
+			| (cmN_GetBitFromDword(data, 18)<<1)
+			| (cmN_GetBitFromDword(data, 27)<<0) );
+}
+DWORD unMix_1(DWORD data)
+{
+	return ( (cmN_GetBitFromDword(data, 26)<<31) 
+			| (cmN_GetBitFromDword(data, 24)<<30)
+			| (cmN_GetBitFromDword(data, 28)<<29)
+			| (cmN_GetBitFromDword(data, 20)<<28)
+			| (cmN_GetBitFromDword(data, 1)<<27)
+			| (cmN_GetBitFromDword(data, 22)<<26)
+			| (cmN_GetBitFromDword(data, 18)<<25)
+			| (cmN_GetBitFromDword(data, 5)<<24)
+			| (cmN_GetBitFromDword(data, 15)<<23)
+			| (cmN_GetBitFromDword(data, 2)<<22)
+			| (cmN_GetBitFromDword(data, 29)<<21)
+			| (cmN_GetBitFromDword(data, 13)<<20)
+			| (cmN_GetBitFromDword(data, 11)<<19)
+			| (cmN_GetBitFromDword(data, 27)<<18)
+			| (cmN_GetBitFromDword(data, 17)<<17)
+			| (cmN_GetBitFromDword(data, 6)<<16)
+			| (cmN_GetBitFromDword(data, 10)<<15)
+			| (cmN_GetBitFromDword(data, 16)<<14)
+			| (cmN_GetBitFromDword(data, 0)<<13)
+			| (cmN_GetBitFromDword(data, 21)<<12)
+			| (cmN_GetBitFromDword(data, 31)<<11)
+			| (cmN_GetBitFromDword(data, 3)<<10)
+			| (cmN_GetBitFromDword(data, 9)<<9)
+			| (cmN_GetBitFromDword(data, 23)<<8)
+			| (cmN_GetBitFromDword(data, 30)<<7)
+			| (cmN_GetBitFromDword(data, 4)<<6)
+			| (cmN_GetBitFromDword(data, 12)<<5)
+			| (cmN_GetBitFromDword(data, 8)<<4)
+			| (cmN_GetBitFromDword(data, 25)<<3)
+			| (cmN_GetBitFromDword(data, 19)<<2)
+			| (cmN_GetBitFromDword(data, 14)<<1)
+			| (cmN_GetBitFromDword(data, 7)<<0) );
+}
+
+DWORD unMix_2(DWORD data)
+{
+	return ( (cmN_GetBitFromDword(data, 3)<<31) 
+			| (cmN_GetBitFromDword(data, 21)<<30)
+			| (cmN_GetBitFromDword(data, 5)<<29)
+			| (cmN_GetBitFromDword(data, 7)<<28)
+			| (cmN_GetBitFromDword(data, 0)<<27)
+			| (cmN_GetBitFromDword(data, 12)<<26)
+			| (cmN_GetBitFromDword(data, 26)<<25)
+			| (cmN_GetBitFromDword(data, 24)<<24)
+			| (cmN_GetBitFromDword(data, 30)<<23)
+			| (cmN_GetBitFromDword(data, 14)<<22)
+			| (cmN_GetBitFromDword(data, 10)<<21)
+			| (cmN_GetBitFromDword(data, 28)<<20)
+			| (cmN_GetBitFromDword(data, 18)<<19)
+			| (cmN_GetBitFromDword(data, 2)<<18)
+			| (cmN_GetBitFromDword(data, 8)<<17)
+			| (cmN_GetBitFromDword(data, 20)<<16)
+			| (cmN_GetBitFromDword(data, 4)<<15)
+			| (cmN_GetBitFromDword(data, 25)<<14)
+			| (cmN_GetBitFromDword(data, 31)<<13)
+			| (cmN_GetBitFromDword(data, 13)<<12)
+			| (cmN_GetBitFromDword(data, 22)<<11)
+			| (cmN_GetBitFromDword(data, 9)<<10)
+			| (cmN_GetBitFromDword(data, 29)<<9)
+			| (cmN_GetBitFromDword(data, 11)<<8)
+			| (cmN_GetBitFromDword(data, 1)<<7)
+			| (cmN_GetBitFromDword(data, 19)<<6)
+			| (cmN_GetBitFromDword(data, 16)<<5)
+			| (cmN_GetBitFromDword(data, 6)<<4)
+			| (cmN_GetBitFromDword(data, 27)<<3)
+			| (cmN_GetBitFromDword(data, 23)<<2)
+			| (cmN_GetBitFromDword(data, 17)<<1)
+			| (cmN_GetBitFromDword(data, 15)<<0) );
+}
+DWORD unMix_3(DWORD data)
+{
+	return ( (cmN_GetBitFromDword(data, 29)<<31) 
+			| (cmN_GetBitFromDword(data, 16)<<30)
+			| (cmN_GetBitFromDword(data, 25)<<29)
+			| (cmN_GetBitFromDword(data, 1)<<28)
+			| (cmN_GetBitFromDword(data, 22)<<27)
+			| (cmN_GetBitFromDword(data, 19)<<26)
+			| (cmN_GetBitFromDword(data, 28)<<25)
+			| (cmN_GetBitFromDword(data, 14)<<24)
+			| (cmN_GetBitFromDword(data, 3)<<23)
+			| (cmN_GetBitFromDword(data, 20)<<22)
+			| (cmN_GetBitFromDword(data, 7)<<21)
+			| (cmN_GetBitFromDword(data, 31)<<20)
+			| (cmN_GetBitFromDword(data, 12)<<19)
+			| (cmN_GetBitFromDword(data, 9)<<18)
+			| (cmN_GetBitFromDword(data, 26)<<17)
+			| (cmN_GetBitFromDword(data, 18)<<16)
+			| (cmN_GetBitFromDword(data, 6)<<15)
+			| (cmN_GetBitFromDword(data, 15)<<14)
+			| (cmN_GetBitFromDword(data, 23)<<13)
+			| (cmN_GetBitFromDword(data, 0)<<12)
+			| (cmN_GetBitFromDword(data, 30)<<11)
+			| (cmN_GetBitFromDword(data, 27)<<10)
+			| (cmN_GetBitFromDword(data, 2)<<9)
+			| (cmN_GetBitFromDword(data, 10)<<8)
+			| (cmN_GetBitFromDword(data, 24)<<7)
+			| (cmN_GetBitFromDword(data, 17)<<6)
+			| (cmN_GetBitFromDword(data, 4)<<5)
+			| (cmN_GetBitFromDword(data, 13)<<4)
+			| (cmN_GetBitFromDword(data, 5)<<3)
+			| (cmN_GetBitFromDword(data, 21)<<2)
+			| (cmN_GetBitFromDword(data, 8)<<1)
+			| (cmN_GetBitFromDword(data, 11)<<0) );
+}
+
+
+//example                                  1M     code flash address
+// => cmN_hwEncodeRawDataForFlash(pData, 0x100000, 0xbc000000);
+
+void hwEncodeRawDataForFlash(char * pChar, DWORD length, DWORD ref_address)
+{
+	DWORD tmplength=0;
+	DWORD in_data, data_add, pre_xor_data, out_data;
+	BYTE type;
+
+	//to handle for each DWORD
+	while( tmplength < length)
+	{
+		//printf("tmplength %d\n", tmplength);
+		in_data = cmN_BytesToDWORD(pChar);
+		data_add = in_data + FLASH_HW_KEY;
+		type = (BYTE)(ref_address>>2) & 0x03;
+
+		if(type==0)
+		{
+			pre_xor_data = Mix_0(data_add);
+			out_data = pre_xor_data^FLASH_HW_KEY_0;
+			cmN_DWORDToBytes(pChar, out_data);
+			
+		}
+		else if(type==1)
+		{
+			pre_xor_data = Mix_1(data_add);
+			out_data = pre_xor_data^FLASH_HW_KEY_1;
+			cmN_DWORDToBytes(pChar, out_data);
+		}
+		else if(type==2)
+		{
+			pre_xor_data = Mix_2(data_add);
+			out_data = pre_xor_data^FLASH_HW_KEY_2;
+			cmN_DWORDToBytes(pChar, out_data);
+		}
+		else if(type==3)
+		{
+			pre_xor_data = Mix_3(data_add);
+			out_data = pre_xor_data^FLASH_HW_KEY_3;
+			cmN_DWORDToBytes(pChar, out_data);
+		}
+
+		ref_address += 4;
+		pChar += 4;
+		tmplength += 4;
+	}
+
+	//pChar -= tmplength;
+}
+
+void hwDecodeRawDataForFlash(char * pChar, DWORD length, DWORD ref_address)
+{
+	DWORD tmplength=0;
+	DWORD in_data, pre_xor_data, out_data;
+	BYTE type;
+
+	//to handle for each DWORD
+	while( tmplength < length)
+	{
+		//printf("tmplength %d\n", tmplength);
+		in_data = cmN_BytesToDWORD(pChar);
+		type = (BYTE)(ref_address>>2) & 0x03;
+		if(type==0)
+		{
+			in_data = in_data^FLASH_HW_KEY_0;
+			pre_xor_data = unMix_0(in_data);
+			out_data = pre_xor_data - FLASH_HW_KEY;
+			cmN_DWORDToBytes(pChar, out_data);
+			
+		}
+		else if(type==1)
+		{
+			in_data = in_data^FLASH_HW_KEY_1;
+			pre_xor_data = unMix_1(in_data);
+			out_data = pre_xor_data - FLASH_HW_KEY;
+			cmN_DWORDToBytes(pChar, out_data);
+		}
+		else if(type==2)
+		{
+			in_data = in_data^FLASH_HW_KEY_2;
+			pre_xor_data = unMix_2(in_data);
+			out_data = pre_xor_data - FLASH_HW_KEY;
+			cmN_DWORDToBytes(pChar, out_data);
+		}
+		else if(type==3)
+		{
+			in_data = in_data^FLASH_HW_KEY_3;
+			pre_xor_data = unMix_3(in_data);
+			out_data = pre_xor_data - FLASH_HW_KEY;
+			cmN_DWORDToBytes(pChar, out_data);
+		}
+		
+
+		ref_address += 4;
+		pChar += 4;
+		tmplength += 4;
+	}
+
+	pChar -= tmplength;
+}
+
+
+#define BUF_SIZE		128
+
+int sisspi_encrypt( const char *inFile, const char *outFile, int encryptMode )
+{
+	char buf[BUF_SIZE];
+    	int mode = encryptMode;
+		
+	FILE *filein = fopen( inFile, "rb" );
+	if(filein == NULL) {
+		printf("open %s fail\n", inFile );
+		return 1;	
+	}
+
+	FILE *fileout=fopen( outFile, "wb" );
+	if(fileout == NULL)	{
+		printf("open %s fail\n", outFile );
+		fclose(filein);
+		return 1;	
+	}	
+
+	while(1){
+		int ret = fread(buf, 1, BUF_SIZE, filein);
+		if(ret <=0){
+			//printf( "file end, exit ~\n");
+			break;	//let it write whole blk...plz
+		}
+		if(mode == 0)
+			hwDecodeRawDataForFlash( &buf[0], BUF_SIZE, 0);
+		else
+			hwEncodeRawDataForFlash( &buf[0], BUF_SIZE, 0);
+		fwrite(buf, 1, BUF_SIZE, fileout);
+	}
+	fclose(filein);
+	fclose(fileout);
+	return 0;
+}
+
+

BIN
tools/mergeImage/spi_encrypt.o


+ 25 - 0
tools/mergeImage/types.h

@@ -0,0 +1,25 @@
+/*
+ * This file is subject to the terms and conditions of the GNU General Public
+ * License.  See the file "COPYING" in the main directory of this archive
+ * for more details.
+ *
+ * Copyright (C) 1994, 1995, 1996, 1999 by Ralf Baechle
+ * Copyright (C) 1999 Silicon Graphics, Inc.
+ */
+#ifndef _ASM_TYPES_H
+#define _ASM_TYPES_H
+
+//-------------------------------------------------------------------------------
+// typedef
+//-------------------------------------------------------------------------------
+typedef unsigned int u32;
+typedef unsigned short u16;
+typedef unsigned char u8;
+
+#ifndef _windows_
+typedef unsigned char bool;
+#define false 0
+#define true 1
+#endif
+
+#endif /* _ASM_TYPES_H */