xref: /utopia/UTPA2-700.0.x/modules/xc/api/xc/apiXC_Auto.c (revision 53ee8cc121a030b8d368113ac3e966b4705770ef)
1 //<MStar Software>
2 //******************************************************************************
3 // MStar Software
4 // Copyright (c) 2010 - 2012 MStar Semiconductor, Inc. All rights reserved.
5 // All software, firmware and related documentation herein ("MStar Software") are
6 // intellectual property of MStar Semiconductor, Inc. ("MStar") and protected by
7 // law, including, but not limited to, copyright law and international treaties.
8 // Any use, modification, reproduction, retransmission, or republication of all
9 // or part of MStar Software is expressly prohibited, unless prior written
10 // permission has been granted by MStar.
11 //
12 // By accessing, browsing and/or using MStar Software, you acknowledge that you
13 // have read, understood, and agree, to be bound by below terms ("Terms") and to
14 // comply with all applicable laws and regulations:
15 //
16 // 1. MStar shall retain any and all right, ownership and interest to MStar
17 //    Software and any modification/derivatives thereof.
18 //    No right, ownership, or interest to MStar Software and any
19 //    modification/derivatives thereof is transferred to you under Terms.
20 //
21 // 2. You understand that MStar Software might include, incorporate or be
22 //    supplied together with third party`s software and the use of MStar
23 //    Software may require additional licenses from third parties.
24 //    Therefore, you hereby agree it is your sole responsibility to separately
25 //    obtain any and all third party right and license necessary for your use of
26 //    such third party`s software.
27 //
28 // 3. MStar Software and any modification/derivatives thereof shall be deemed as
29 //    MStar`s confidential information and you agree to keep MStar`s
30 //    confidential information in strictest confidence and not disclose to any
31 //    third party.
32 //
33 // 4. MStar Software is provided on an "AS IS" basis without warranties of any
34 //    kind. Any warranties are hereby expressly disclaimed by MStar, including
35 //    without limitation, any warranties of merchantability, non-infringement of
36 //    intellectual property rights, fitness for a particular purpose, error free
37 //    and in conformity with any international standard.  You agree to waive any
38 //    claim against MStar for any loss, damage, cost or expense that you may
39 //    incur related to your use of MStar Software.
40 //    In no event shall MStar be liable for any direct, indirect, incidental or
41 //    consequential damages, including without limitation, lost of profit or
42 //    revenues, lost or damage of data, and unauthorized system use.
43 //    You agree that this Section 4 shall still apply without being affected
44 //    even if MStar Software has been modified by MStar in accordance with your
45 //    request or instruction for your use, except otherwise agreed by both
46 //    parties in writing.
47 //
48 // 5. If requested, MStar may from time to time provide technical supports or
49 //    services in relation with MStar Software to you for your use of
50 //    MStar Software in conjunction with your or your customer`s product
51 //    ("Services").
52 //    You understand and agree that, except otherwise agreed by both parties in
53 //    writing, Services are provided on an "AS IS" basis and the warranty
54 //    disclaimer set forth in Section 4 above shall apply.
55 //
56 // 6. Nothing contained herein shall be construed as by implication, estoppels
57 //    or otherwise:
58 //    (a) conferring any license or right to use MStar name, trademark, service
59 //        mark, symbol or any other identification;
60 //    (b) obligating MStar or any of its affiliates to furnish any person,
61 //        including without limitation, you and your customers, any assistance
62 //        of any kind whatsoever, or any information; or
63 //    (c) conferring any license or right under any intellectual property right.
64 //
65 // 7. These terms shall be governed by and construed in accordance with the laws
66 //    of Taiwan, R.O.C., excluding its conflict of law rules.
67 //    Any and all dispute arising out hereof or related hereto shall be finally
68 //    settled by arbitration referred to the Chinese Arbitration Association,
69 //    Taipei in accordance with the ROC Arbitration Law and the Arbitration
70 //    Rules of the Association by three (3) arbitrators appointed in accordance
71 //    with the said Rules.
72 //    The place of arbitration shall be in Taipei, Taiwan and the language shall
73 //    be English.
74 //    The arbitration award shall be final and binding to both parties.
75 //
76 //******************************************************************************
77 //<MStar Software>
78 ////////////////////////////////////////////////////////////////////////////////
79 //
80 // Copyright (c) 2008-2009 MStar Semiconductor, Inc.
81 // All rights reserved.
82 //
83 // Unless otherwise stipulated in writing, any and all information contained
84 // herein regardless in any format shall remain the sole proprietary of
85 // MStar Semiconductor Inc. and be kept in strict confidence
86 // ("MStar Confidential Information") by the recipient.
87 // Any unauthorized act including without limitation unauthorized disclosure,
88 // copying, use, reproduction, sale, distribution, modification, disassembling,
89 // reverse engineering and compiling of the contents of MStar Confidential
90 // Information is unlawful and strictly prohibited. MStar hereby reserves the
91 // rights to any and all damages, losses, costs and expenses resulting therefrom.
92 //
93 ////////////////////////////////////////////////////////////////////////////////
94 
95 ///////////////////////////////////////////////////////////////////////////////////////////////////
96 /// file    apiXC_Auto.c
97 /// @brief  Scaler API layer Interface
98 /// @author MStar Semiconductor Inc.
99 ///////////////////////////////////////////////////////////////////////////////////////////////////
100 
101 #define _APIXC_AUTO_C_
102 
103 //-------------------------------------------------------------------------------------------------
104 //  Include Files
105 //-------------------------------------------------------------------------------------------------
106 #if !defined(MSOS_TYPE_LINUX_KERNEL)
107 #include "string.h"
108 #else
109 #include <linux/string.h>
110 #endif
111 //#include <assert.h>
112 // Common Definition
113 #include "MsCommon.h"
114 #include "MsOS.h"
115 #include "utopia.h"
116 #include "utopia_dapi.h"
117 // Driver
118 #include "drvXC_IOPort.h"
119 #include "mhal_xc_chip_config.h"
120 #include "xc_hwreg_utility2.h"
121 // Api
122 #include "apiXC.h"
123 #include "apiXC_Adc.h"
124 #include "drv_sc_display.h"
125 #include "drv_sc_isr.h"
126 #include "apiXC_Auto.h"
127 #include "apiXC_PCMonitor.h"
128 #include "apiXC_ModeParse.h"
129 #include "drvXC_HDMI_if.h"
130 #include "drv_sc_ip.h"
131 #include "ULog.h"
132 #include "mvideo_context.h"
133 #if (LD_ENABLE==1)
134 #include "mdrv_ld.h"
135 #include "mdrv_ldalgo.h"
136 #endif
137 #include "mdrv_sc_3d.h"
138 #include "drv_sc_menuload.h"
139 #include "drvXC_ADC_Internal.h"
140 #include "mhal_sc.h"
141 #if FRC_INSIDE
142 #include "mdrv_frc.h"
143 #include "mhal_frc.h"
144 #endif
145 #include "XC_private.h"
146 #include "apiXC_v2.h"
147 #include "apiXC_Auto_v2.h"
148 
149 #include "drv_sc_scaling.h"
150 #include "drv_xc_calibration.h"
151 
152 #ifndef DONT_USE_CMA
153 #if (XC_SUPPORT_CMA ==TRUE)
154 #ifdef MSOS_TYPE_LINUX_KERNEL
155 #include "drvCMAPool_v2.h"
156 #else
157 #include "drvCMAPool.h"
158 #endif
159 #include "msos/linux/mdrv_cma_pool_st.h"
160 #include "mhal_sc.h"
161 #include "halCHIP.h"
162 #endif
163 #endif
164 
165 //-------------------------------------------------------------------------------------------------
166 //  Driver Compiler Options
167 //-------------------------------------------------------------------------------------------------
168 #define AUTOMSG(x)          //x
169 
170 #define COMPONENT_AUTO_SW_MODE  FALSE
171 #define AUTO_PHASE_METHOD       0       // 0 = found maximum
172 #define GET_RGB_REPORT          DISABLE
173 #define FAST_AUTO_TUNE          1
174 #define AUTO_GAIN_SW_MODE       0
175 #define AUTO_PHASE_STEP         4
176 
177 #define AUTO_YUV_GAIN_STEP      1
178 #define AUTO_YUV_MAX_CNT        30
179 
180 #define ENABLE_VGA_EIA_TIMING   0
181 //-------------------------------------------------------------------------------------------------
182 //  Local Defines
183 //-------------------------------------------------------------------------------------------------
184 
185 #define Y_AUTO_COLOR_75IRE          0   // 0: 100IRE / 1: 75IRE
186 #define PbPr_AUTO_COLOR_75IRE       0   // 0: 100IRE / 1: 75IRE
187 
188 #if Y_AUTO_COLOR_75IRE
189 #define Y_MAX_VALUE                 180 // For 75IRE Y value
190 #define Y_MIN_VALUE                 16
191 #else
192 #define Y_MAX_VALUE                 235 // For 100IRE Y value
193 #define Y_MIN_VALUE                 16
194 #endif
195 
196 #if PbPr_AUTO_COLOR_75IRE
197 #define PbPr_MAX_VALUE              212 // For 75IRE PbPr value
198 #define PbPr_MIN_VALUE              44
199 #else
200 #define PbPr_MAX_VALUE              240 // For 100IRE PbPr value
201 #define PbPr_MIN_VALUE              16
202 #endif
203 
204 #define Y_AUTO_ACTIVE_RANGE         (Y_MAX_VALUE - Y_MIN_VALUE)
205 #define PbPr_AUTO_ACTIVE_RANGE      (PbPr_MAX_VALUE - PbPr_MIN_VALUE)
206 #define Y_AUTO_MIN_VALUE            (Y_MIN_VALUE - 16)
207 #define PbPr_AUTO_MIN_VALUE         (PbPr_MIN_VALUE)
208 
209 #define MIN_PC_AUTO_H_START            (StandardInfo->u16HorizontalStart - (StandardInfo->u16HorizontalStart * 8 / 10) )
210 
211 #if ENABLE_VGA_EIA_TIMING
212   #define MAX_PC_AUTO_H_START            (StandardInfo->u16HorizontalStart + (StandardInfo->u16HorizontalStart* 18 / 10) )
213 #else
214   #define MAX_PC_AUTO_H_START            (StandardInfo->u16HorizontalStart + (StandardInfo->u16HorizontalStart* 8 / 10) )
215 #endif
216 
217 #define MIN_PC_AUTO_V_START            (1)
218 #define MAX_PC_AUTO_V_START            (StandardInfo->u16VerticalStart*2 - MIN_PC_AUTO_V_START/*MIN_PC_V_START*/)
219 
220 /*!
221     1. RGB mode, full scale�٬O����10bit 1023�o��code, �ҥHgain �٬O�ե���Ū��0.5/0.7*1023.
222        Offset�]�O�ե��� 0�o��code, RGB�T��channel ���@��.
223     2. YCbCr mode, �бNY��full scale�令10bit code �O(235-16)*4, Cb/Cr full scale �令10bit (240-16)*4.
224        �ҥHY gain�ȭn�ը�� digital code �ݨ� 0.5/0.7*(235-16)*4, Cb/Cr�h�O0.5/0.7*(240-16)*4.
225        Offset �h�O�N Y ���Ǩ�64 (10bit), Cb/Cr ��512 (10bit).
226 */
227 
228 #define   AUTO_GAIN_RANGE_RGB_INTERNAL       731   //0.5/0.7*1023=730.7
229 #define   AUTO_GAIN_RANGE_Y_INTERNAL         626   //(235-16)*4 *0.5/0.7,
230 #define   AUTO_GAIN_RANGE_CBCR_INTERNAL      640   //(240-16)*4 *0.5/0.7,
231 
232 #define   AUTO_GAIN_RANGE_RGB_EXTERNAL       1018  //Find gain setting from 1018. Than fine tune to 1023
233 #define   AUTO_GAIN_RANGE_Y_EXTERNAL         876   //(235-16)*4,
234 #define   AUTO_GAIN_RANGE_CBCR_EXTERNAL      896   //(240-16)*4,
235 
236 
237 #define   AUTO_GAIN_BONDARY           1
238 
239 #define   AUTO_GAIN_MAX_RGB         (AUTO_GAIN_RANGE_RGB_INTERNAL+AUTO_GAIN_BONDARY )
240 #define   AUTO_GAIN_MIN_RGB         (AUTO_GAIN_RANGE_RGB_INTERNAL-AUTO_GAIN_BONDARY )
241 
242 #define   AUTO_GAIN_MAX_Y           (AUTO_GAIN_RANGE_Y_INTERNAL+AUTO_GAIN_BONDARY )
243 #define   AUTO_GAIN_MAX_CBCR        (AUTO_GAIN_RANGE_CBCR_INTERNAL+AUTO_GAIN_BONDARY )
244 #define   AUTO_GAIN_MIN_Y           (AUTO_GAIN_RANGE_Y_INTERNAL-AUTO_GAIN_BONDARY )
245 #define   AUTO_GAIN_MIN_CBCR        (AUTO_GAIN_RANGE_CBCR_INTERNAL-AUTO_GAIN_BONDARY )
246 
247 #define   AUTO_OFFSET_Y             0x40
248 #define   AUTO_OFFSET_CBCR          0x200
249 
250 #define MAX_AUTO_POSITION_WAIT_READY_TIME 500
251 
252 //-------------------------------------------------------------------------------------------------
253 //  Local Structurs
254 //-------------------------------------------------------------------------------------------------
255 
256 typedef struct
257 {
258       MS_U8   L_BkAtop_01;
259       MS_U8   L_BkAtop_0C;
260       MS_U8   L_BkAtop_2C;
261       MS_U16  L_BkAtop_05;
262       MS_U16  L_BkAtop_06;
263       MS_U8   L_BkAtop_1C;
264       MS_U8   L_BkAtop_1F;
265 
266       MS_U16 BkDtop_01;
267       MS_U16 BkDtop_02;
268       MS_U8   L_BkDtop_06;
269       MS_U8   H_BkChipTop_1F;
270       MS_U8   L_BkIpMux_1;
271       MS_U16 SC_BK1_02;
272       MS_U16 SC_BK1_03;
273       MS_U16 SC_BK1_04;
274       MS_U16 SC_BK1_05;
275       MS_U16 SC_BK1_06;
276       MS_U16 SC_BK1_07;
277       MS_U16 SC_BK1_0E;
278       MS_U8   L_SC_BK1_21;
279       MS_U8   L_SC_BK10_19;
280 } MS_AUTOADC_REG_BAK;
281 
282 typedef enum
283 {
284     E_XC_AUTO_GET_HSTART,
285     E_XC_AUTO_GET_HEND,
286     E_XC_AUTO_GET_VSTART,
287     E_XC_AUTO_GET_VEND,
288 }XC_Auto_GetAutoPositionType;
289 
290 typedef enum
291 {
292     E_WAITING_AUTO_POSITION_READY,
293     E_WAITING_AUTO_GAIN_READY,
294 }XC_Auto_WaitingType;
295 
296 //-------------------------------------------------------------------------------------------------
297 //  Global Variables
298 //-------------------------------------------------------------------------------------------------
299 
300 //-------------------------------------------------------------------------------------------------
301 //  Local Variables
302 //-------------------------------------------------------------------------------------------------
303 
304 //-------------------------------------------------------------------------------------------------
305 //  Debug Functions
306 //-------------------------------------------------------------------------------------------------
307 
308 //-------------------------------------------------------------------------------------------------
309 //  Local Functions
310 //-------------------------------------------------------------------------------------------------
_MApi_XC_Auto_SetCalibrartinWindow(void * pInstance,MS_BOOL bEnable,SCALER_WIN scwin)311 static void _MApi_XC_Auto_SetCalibrartinWindow(void *pInstance, MS_BOOL bEnable, SCALER_WIN scwin )
312 {
313     //set auto range window for calibrartin
314     MS_U16 Vcut,Hcut;
315     MS_WINDOW_TYPE cap_win;
316     memset(&cap_win, 0, sizeof(MS_WINDOW_TYPE));
317 
318     if (bEnable)
319     {
320         _XC_ENTRY(pInstance);
321         MDrv_XC_GetCaptureWindow(pInstance, &cap_win,scwin );
322         _XC_RETURN(pInstance);
323         Vcut = cap_win.height/ 10;
324         Hcut = cap_win.width/ 10;
325 
326         MApi_XC_AutoRangeEnable(pInstance, ENABLE, scwin);
327 
328         MApi_XC_SetAutoRangeWindow(pInstance, cap_win.y + (Vcut/2),
329                                    cap_win.x + (Hcut/2),
330                                    cap_win.height- Vcut,
331                                    cap_win.width- Hcut,
332                                    scwin
333                                    );
334     }
335     else
336     {
337         MApi_XC_AutoRangeEnable(pInstance, DISABLE, scwin);
338     }
339 
340     //printf("capture: %d %d %d %d \n",Vstart, Hstart, Vsize , Hsize );
341 
342 }
343 
344 //----------------------------------------------------------------------
345 //
346 // gain setting: 00 is maximum ~~ 0xff is minmum
347 //----------------------------------------------------------------------
348 enum {
349     DOWN_TOP= 1,
350     TOP_DOWN= 2,
351 };
352 
MApi_XC_Auto_SetValidData_U2(void * pInstance,MS_U8 Value)353 MS_BOOL MApi_XC_Auto_SetValidData_U2(void* pInstance, MS_U8 Value)
354 {
355     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
356     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
357     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
358     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
359     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
360     pXCResourcePrivate->stapiXC_Auto._u8ThresholdValue = Value;
361     _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
362     return TRUE;
363 }
364 
MApi_XC_Auto_SetValidData(MS_U8 Value)365 MS_BOOL MApi_XC_Auto_SetValidData(MS_U8 Value)
366 {
367     if (pu32XCInst == NULL)
368     {
369         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
370         return FALSE;
371     }
372 
373     stXC_AUTO_SETVALIDDATA XCArgs;
374     XCArgs.Value = Value;
375     XCArgs.bReturnValue = FALSE;
376 
377     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_SETVALIDDATA, (void*)&XCArgs) != 0)
378     {
379         printf("Obtain XC engine fail\n");
380         return FALSE;
381     }
382     else
383     {
384         return XCArgs.bReturnValue;
385     }
386 }
387 
_GetAverageDataFromMemory(void * pInstance,MS_WINDOW_TYPE * mem_win,SCALER_WIN eWindow)388 static MS_AUTOADC_TYPE _GetAverageDataFromMemory(void *pInstance, MS_WINDOW_TYPE* mem_win, SCALER_WIN eWindow)
389 {
390     MS_IMAGE_MEM_INFO  pMemInfo;
391 
392     pMemInfo.eCal_Win_Size.u16X = mem_win->x ;
393     pMemInfo.eCal_Win_Size.u16Y = mem_win->y ;
394     pMemInfo.eCal_Win_Size.u16Xsize = mem_win->width;
395     pMemInfo.eCal_Win_Size.u16Ysize = mem_win->height ;
396 
397     MS_PIXEL_32BIT sMemBuf[(pMemInfo.eCal_Win_Size.u16Xsize)*(pMemInfo.eCal_Win_Size.u16Ysize)];
398     memset(&sMemBuf, 0 , sizeof(sMemBuf) );
399     printf("x=%u, y=%u, xsize=%u, ysize=%u\n",pMemInfo.eCal_Win_Size.u16X,pMemInfo.eCal_Win_Size.u16Y,
400         pMemInfo.eCal_Win_Size.u16Xsize,pMemInfo.eCal_Win_Size.u16Ysize);
401     Hal_SC_set_freezeimg(pInstance, ENABLE, eWindow);
402 
403     pMemInfo.pixelAverage = MDrv_XC_GetAverageData(pInstance, sMemBuf, pMemInfo.eCal_Win_Size, eWindow);
404     Hal_SC_set_freezeimg(pInstance, DISABLE, eWindow);
405 
406     return pMemInfo.pixelAverage;
407 }
408 
_GetGainRange(void * pInstance,XC_Auto_CalibrationType type,XC_Auto_TuneType tune_type,MS_AUTOADC_TYPE * Diff,SCALER_WIN eWindow)409 static void _GetGainRange(void *pInstance, XC_Auto_CalibrationType type,XC_Auto_TuneType tune_type ,MS_AUTOADC_TYPE* Diff, SCALER_WIN eWindow)
410 {
411     MS_AUTOADC_TYPE pAutoAdc_105;
412     MS_AUTOADC_TYPE pAutoAdc_055;
413     MS_WINDOW_TYPE mem_win;
414     int ch ;
415 
416     // External YUV need gather Max/Min by differnt win
417     if ( tune_type != E_XC_AUTO_TUNE_YUV_COLOR || type != E_XC_EXTERNAL_CALIBRATION )
418     {
419         //////////////////////////////
420         // Get Max value
421         if (type == E_XC_INTERNAL_CALIBRATION)
422         {
423             // internal have to generate internal voltage.
424             mem_win.x = 5;
425             mem_win.y = 5;
426             mem_win.width = 10;
427             mem_win.height= 10;
428             MApi_XC_ADC_SetInternalVoltage(pInstance, E_ADC_Internal_0_6V);
429         }
430         else
431         {
432             mem_win.x = 640;
433             mem_win.y = 360;
434             mem_win.width = 10;
435             mem_win.height= 10;
436         }
437         _XC_ENTRY(pInstance);
438         MDrv_XC_wait_input_vsync(pInstance, 5, 200,eWindow);
439         _XC_RETURN(pInstance);
440         pAutoAdc_105 = _GetAverageDataFromMemory(pInstance, &mem_win, eWindow);
441 
442         //printf("[internal 1.05V]  %04d %04d %04d \n",pAutoAdc_105.u16CH_AVG[0],pAutoAdc_105.u16CH_AVG[1],pAutoAdc_105.u16CH_AVG[2]);
443 
444         //////////////////////////////
445         // Get Min value
446         if (type == E_XC_INTERNAL_CALIBRATION)
447         {
448             // internal have to generate internal voltage.
449             mem_win.x = 5;
450             mem_win.y = 5;
451             mem_win.width = 10;
452             mem_win.height= 10;
453             MApi_XC_ADC_SetInternalVoltage(pInstance, E_ADC_Internal_0_1V);  //MDrv_WriteByteMask( L_BK_ADC_DTOP(0x13) , 0x20, 0x30 ); //switch internal to 0.1V
454         }
455         else
456         {
457             mem_win.x = 5;
458             mem_win.y = 5;
459             mem_win.width = 10;
460             mem_win.height= 10;
461         }
462         _XC_ENTRY(pInstance);
463         MDrv_XC_wait_input_vsync(pInstance, 5, 200,eWindow);
464         _XC_RETURN(pInstance);
465         pAutoAdc_055 = _GetAverageDataFromMemory(pInstance, &mem_win, eWindow);
466 
467         //printf("[internal 0.55V]  %04d %04d %04d \n",pAutoAdc_055.u16CH_AVG[0],pAutoAdc_055.u16CH_AVG[1],pAutoAdc_055.u16CH_AVG[2]);
468         for (ch =0; ch  < 3;ch ++)
469           Diff->u16CH_AVG[ch] = pAutoAdc_105.u16CH_AVG[ch] - pAutoAdc_055.u16CH_AVG[ch];
470     }
471     else
472     {
473         //////////////////////////////
474         // Get Y Max
475         mem_win.x = 0X200;
476         mem_win.y = 0X10;
477         mem_win.width = 10;
478         mem_win.height= 10;
479 
480         _XC_ENTRY(pInstance);
481         MDrv_XC_wait_input_vsync(pInstance, 5, 200,eWindow);
482         _XC_RETURN(pInstance);
483 
484         pAutoAdc_105 = _GetAverageDataFromMemory(pInstance, &mem_win, eWindow);
485 
486         //////////////////////////////
487         // Get Y Min
488         mem_win.x = 0X200;
489         mem_win.y = 0X280;
490         mem_win.width = 10;
491         mem_win.height= 10;
492 
493         _XC_ENTRY(pInstance);
494         MDrv_XC_wait_input_vsync(pInstance, 5, 200,eWindow);
495         _XC_RETURN(pInstance);
496 
497         pAutoAdc_055 = _GetAverageDataFromMemory(pInstance, &mem_win, eWindow);
498         Diff->u16CH_AVG[1] = pAutoAdc_105.u16CH_AVG[1] - pAutoAdc_055.u16CH_AVG[1];
499 
500         //////////////////////////////
501         // Get Pb Max
502         mem_win.x = 0X200;
503         mem_win.y = 0X220;
504         mem_win.width = 10;
505         mem_win.height= 10;
506 
507         _XC_ENTRY(pInstance);
508         MDrv_XC_wait_input_vsync(pInstance, 5, 200,eWindow);
509         _XC_RETURN(pInstance);
510 
511         pAutoAdc_105 = _GetAverageDataFromMemory(pInstance, &mem_win, eWindow);
512 
513         //////////////////////////////
514         // Get Pb Min
515         mem_win.x = 0X200;
516         mem_win.y = 0X60;
517         mem_win.width = 10;
518         mem_win.height= 10;
519 
520         _XC_ENTRY(pInstance);
521         MDrv_XC_wait_input_vsync(pInstance, 5, 200,eWindow);
522         _XC_RETURN(pInstance);
523 
524         pAutoAdc_055 = _GetAverageDataFromMemory(pInstance, &mem_win, eWindow);
525         Diff->u16CH_AVG[2] = pAutoAdc_105.u16CH_AVG[2] - pAutoAdc_055.u16CH_AVG[2];
526 
527         //////////////////////////////
528         // Get Pr Max
529         mem_win.x = 0X200;
530         mem_win.y = 0X1C0;
531         mem_win.width = 10;
532         mem_win.height= 10;
533 
534         _XC_ENTRY(pInstance);
535         MDrv_XC_wait_input_vsync(pInstance, 5, 200,eWindow);
536         _XC_RETURN(pInstance);
537 
538         pAutoAdc_105 = _GetAverageDataFromMemory(pInstance, &mem_win, eWindow);
539 
540         //////////////////////////////
541         // Get Pr Min
542         mem_win.x = 0X200;
543         mem_win.y = 0XB0;
544         mem_win.width = 10;
545         mem_win.height= 10;
546 
547         _XC_ENTRY(pInstance);
548         MDrv_XC_wait_input_vsync(pInstance, 5, 200,eWindow);
549         _XC_RETURN(pInstance);
550 
551         pAutoAdc_055 = _GetAverageDataFromMemory(pInstance, &mem_win, eWindow);
552         Diff->u16CH_AVG[0] = pAutoAdc_105.u16CH_AVG[0] - pAutoAdc_055.u16CH_AVG[0];
553 
554     }
555 }
556 
557 //*************************************************************************
558 /// -This function internal Auto-tune gain of ADC.
559 /// @param enAutoTuneType   \b IN:  tune type
560 /// @param pstADCSetting    \b OUT: gain offset setting
561 /// @param eWindow          \b IN:  window type, main/sub
562 /// @return MS_BOOL TRUE succeed, FALSE fail
563 //*************************************************************************
_MApi_XC_Auto_InternalTuneGain(void * pInstance,XC_Auto_TuneType enAutoTuneType,APIXC_AdcGainOffsetSetting * pstADCSetting,SCALER_WIN eWindow)564 static MS_BOOL _MApi_XC_Auto_InternalTuneGain(void *pInstance, XC_Auto_TuneType enAutoTuneType, APIXC_AdcGainOffsetSetting *pstADCSetting, SCALER_WIN eWindow )
565 {
566     #define TOLERATE_ERROR 65 // 10%
567     #define MAX_CALIBRATION_ITERATION_EXTERNAL   12
568 
569     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
570     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
571 
572     MS_AUTOADC_TYPE Diff;
573     MS_BOOL bDone[3] = {FALSE, FALSE, FALSE};
574     MS_U16 GainTargetLBound[3];
575     MS_U16 GainTargetUBound[3];
576 
577     MS_U16 Gain[3]      ={0x1000, 0x1000, 0x1000};
578     MS_U16 TempGain[3]  ={0x1000, 0x1000, 0x1000};
579     MS_U16 delta[3]={0x800, 0x800, 0x800};
580     MS_U16 u16UpperDiff[3] = {0xFFFF, 0xFFFF, 0xFFFF};
581     MS_U16 u16LowerDiff[3] = {0xFFFF, 0xFFFF, 0xFFFF};
582     MS_U16 u16UpperGain[3] = {0, 0, 0};
583     MS_U16 u16LowerGain[3] = {0, 0, 0};
584     MS_U16 GainTarget[3];
585     MS_U8 u8Direction[3] = {0, 0, 0};
586     MS_U16 ch;
587     MS_U16 y = 0;
588     MS_U16 u16Diff;
589     MS_BOOL bResult = FALSE;
590     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
591     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
592     //////////////////////////////
593     // Initialize
594     bResult = MDrv_XC_ADC_GetGainSetting(pInstance, pstADCSetting);
595     if (bResult)
596     {
597         if (enAutoTuneType & E_XC_AUTO_TUNE_RGB_GAIN)
598         {
599             //printf("RGB\n");
600             GainTarget[0] = AUTO_GAIN_RANGE_RGB_INTERNAL;
601             GainTarget[1] = AUTO_GAIN_RANGE_RGB_INTERNAL;
602             GainTarget[2] = AUTO_GAIN_RANGE_RGB_INTERNAL;
603         }
604         else if(enAutoTuneType & E_XC_AUTO_TUNE_SCART_RGB_GAIN)
605         {
606             GainTarget[0] = AUTO_GAIN_RANGE_RGB_INTERNAL;
607             GainTarget[1] = AUTO_GAIN_RANGE_RGB_INTERNAL;
608             GainTarget[2] = AUTO_GAIN_RANGE_RGB_INTERNAL;
609         }
610         else
611         {
612             //printf("YUV\n");
613             GainTarget[0] = AUTO_GAIN_RANGE_CBCR_INTERNAL;
614             GainTarget[1] = AUTO_GAIN_RANGE_Y_INTERNAL;
615             GainTarget[2] = AUTO_GAIN_RANGE_CBCR_INTERNAL;
616         }
617 
618         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"GainTarget R: %x  G: %x  B: %x\n",GainTarget[0],GainTarget[1],GainTarget[2]);
619 
620 
621         // Set initial gain value
622         for (ch=0; ch<3; ch++)
623         {
624             GainTargetUBound[ch] = GainTarget[ch] + AUTO_GAIN_BONDARY;
625             GainTargetLBound[ch] = GainTarget[ch] - AUTO_GAIN_BONDARY;
626             MDrv_XC_ADC_SetGain(pInstance, ch, Gain[ch]);
627         }
628 
629         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"GainTarget Upper Bound R: %x  G: %x  B: %x \n", GainTargetUBound[0],GainTargetUBound[1],GainTargetUBound[2]);
630         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"GainTarget Lower Bound R: %x  G: %x  B: %x \n", GainTargetLBound[0],GainTargetLBound[1],GainTargetLBound[2]);
631 
632         // Start Gain calibration
633         for ( y = 0; y < MAX_CALIBRATION_ITERATION_EXTERNAL; y++)
634         {
635             _GetGainRange(pInstance, E_XC_INTERNAL_CALIBRATION, enAutoTuneType,&Diff, eWindow);
636 
637             //////////////////////////////
638             // Adjust for RGB / YUV
639             for (ch=0; ch<3; ch++)
640             {
641                 if (ch==0) {
642                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"============No. %02d=============>\n", (y+1));
643                 }
644                 if (!bDone[ch])
645                 {
646                     u16Diff = Diff.u16CH_AVG[ch];
647                     if ( y == (MAX_CALIBRATION_ITERATION_EXTERNAL-1) )
648                     {
649                         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Gain[%u]=0x%x, diff=%d\n", ch, Gain[ch], u16Diff);
650 
651                         if (u16Diff >= GainTarget[ch])
652                         {
653                             if (u16UpperDiff[ch] > (u16Diff - GainTarget[ch]))
654                             {
655                                 u16UpperDiff[ch] = u16Diff - GainTarget[ch];
656                                 u16UpperGain[ch] = TempGain[ch];
657                                 //AUTOMSG(printk("Cr Upper Diff %04d, Gain %04d\n", u16UpperDiff_R, u16UpperGain_R));
658                             }
659                         }
660 
661                         if (u16Diff <= GainTarget[ch])
662                         {
663                             if (u16LowerDiff[ch] > (GainTarget[ch] - u16Diff))
664                             {
665                                 u16LowerDiff[ch] = GainTarget[ch] - u16Diff;
666                                 u16LowerGain[ch] = TempGain[ch];
667                                 //AUTOMSG(printk("Cr Lower Diff %04d, Gain %04d\n", u16LowerDiff_R, u16LowerGain_R));
668                             }
669                         }
670                     }
671                     else
672                     {
673                         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Gain[%u]=0x%x, diff=%d\n", ch, Gain[ch], u16Diff);
674 
675                         // Found a target gain.
676                         if ( (u16Diff>=GainTargetLBound[ch] ) && (u16Diff<=GainTargetUBound[ch] ) )
677                         {
678                             //MS_U16 target,u16Result[5],Step;
679                             //MS_AUTOADC_TYPE modifiy_diff;
680                             //MS_U8 index,bRetry = TRUE ;
681 
682                             bDone[ch] = TRUE;
683                             u16UpperDiff[ch] = u16LowerDiff[ch] = 0;
684 
685                             u8Direction[ch] = 0;
686 
687                             ////////////Find a best solution////////////////////////
688                             //target = ( GainTargetLBound[ch] + GainTargetUBound[ch] )  / 2 ;
689                             //XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," target : %d  current : %d\n",target,u16Diff);
690 
691                             #if 0 // This section takes long time. Remove first.
692                             // Retrieve result array, and make sure it is linear.
693                             while (bRetry)
694                             {
695                                 for (index = 0, Step = Gain[ch] - 0x08; Step <= Gain[ch] + 0x08 ; Step+= 0x04,index++)
696                                 {
697                                     MDrv_XC_ADC_SetGain(pInstance, ch, Step);
698                                     _GetGainRange(E_XC_INTERNAL_CALIBRATION,enAutoTuneType,&modifiy_diff);
699                                     u16Result[index] = modifiy_diff.u16CH_AVG[ch];
700                                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Result index: %d Gain: 0x%4x   %d \n",index,Step,u16Result[index] );
701                                 }
702 
703                                 // check result is linear
704                                 for ( index = 0 ; index < 5 ; index ++)
705                                 {
706                                     if ( index >= 4 )
707                                     {
708                                         bRetry = FALSE;
709                                         break;
710                                     }
711 
712                                     if ( u16Result[index] > u16Result[index+1] )
713                                     {
714                                         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," fail \n");
715                                         break;
716                                     }
717                                 }
718                                 if ( bRetry)
719                                     continue;
720 
721                                 // Find Best solution
722                                 MS_U8 Index_Start = 0 ,Index_End = 4;
723                                 MS_BOOL bFound1 = FALSE, bFound2 = FALSE;
724 
725                                 while ( Index_End > Index_Start && ( !bFound1 || !bFound2) )
726                                 {
727                                     if ( u16Result[Index_Start] != target )
728                                         Index_Start++;
729                                     else
730                                         bFound1 = TRUE;
731 
732                                     if ( u16Result[Index_End] != target)
733                                         Index_End--;
734                                     else
735                                         bFound2 = TRUE;
736                                 }
737 
738                                 // Founded
739                                 if ( Index_End >= Index_Start)
740                                 {
741                                     Step = Gain[ch] - 0x08;
742                                     Gain[ch] = Step + ( ( (Index_Start + Index_End ) * 10 ) / 2 ) * 0x04 / 10;
743                                 }
744                                 else
745                                 {
746                                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," not found \n");
747                                 }
748 
749                             }
750 
751                             #endif
752                             /////////////////////////////////////////////////
753 
754                             u16UpperGain[ch] = u16LowerGain[ch] = Gain[ch];
755 
756                             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"=====ch:%u--OK--0x%x=======\n", ch, Gain[ch]);
757                         }
758                         // continoue
759                         else
760                         {
761                             if (u16Diff >= GainTarget[ch])
762                             {
763                                 if (u16UpperDiff[ch] > (u16Diff - GainTarget[ch]))
764                                 {
765                                     u16UpperDiff[ch] = u16Diff - GainTarget[ch];
766                                     u16UpperGain[ch] = Gain[ch];
767                                     //AUTOMSG(printk("Upper Diff %04d, Gain %04d\n", u16UpperDiff[ch], u16UpperGain[ch]));
768                                 }
769                             }
770 
771                             if (u16Diff <= GainTarget[ch])
772                             {
773                                 if (u16LowerDiff[ch] > (GainTarget[ch] - u16Diff))
774                                 {
775                                     u16LowerDiff[ch] = GainTarget[ch] - u16Diff;
776                                     u16LowerGain[ch] = Gain[ch];
777                                     //AUTOMSG(printk("Lower Diff %04d, Gain %04d\n", u16LowerDiff[ch], u16LowerGain[ch]));
778                                 }
779                             }
780 
781                             if (u16Diff < GainTargetLBound[ch] )
782                             {
783 
784                                 Gain[ch]+=delta[ch];
785                                 u8Direction[ch] = DOWN_TOP; //DownToUp
786                             }
787                             else   //(u16Diff > GainTargetUBound[ch] )
788                             {
789 
790                                 Gain[ch]-=delta[ch];
791                                 u8Direction[ch] = TOP_DOWN; //UpToDown
792                             }
793                             delta[ch]=delta[ch]>>1;
794                         }
795 
796                         if ( y == (MAX_CALIBRATION_ITERATION_EXTERNAL-2) )
797                         {
798                             if (u8Direction[ch] == DOWN_TOP)
799                             {
800                                 // T2 is 1
801                                 TempGain[ch] = Gain[ch]-0x02;
802 
803                             }
804                             else if (u8Direction[ch] == TOP_DOWN)
805                             {
806                                 // T2 is 1
807                                 TempGain[ch] = Gain[ch]+0x02;
808                             }
809                             MDrv_XC_ADC_SetGain(pInstance, ch, TempGain[ch]);
810                         }
811                         else
812                         {
813                             //AUTOMSG( printk("Gain[%u] 0x%x\n", ch, Gain[ch]));
814                             //AUTOMSG( printk("delta[%u] 0x%x\n", ch, delta[ch]));
815                             MDrv_XC_ADC_SetGain(pInstance, ch, Gain[ch]);
816                         }
817                     }
818                 }
819             }
820 
821             if ( bDone[0] && bDone[1] && bDone[2] )
822             {
823                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"done - \n");
824                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"gain check ok \33[0;31m 0x%x 0x%x 0x%x \33[m \n",Gain[0],Gain[1],Gain[2]);
825                 bResult = TRUE;
826                 break;
827             }
828         }
829 
830     }
831 
832     if (!bResult)
833     {
834         // If code flow reach here, that's meaning we can not find a good gain value.
835         // Choose best gain value in TOLERATE_ERROR.
836         if ( !(bDone[0] && bDone[1] && bDone[2]) )
837         {
838             bDone[0] = bDone[1] = bDone[2] = 0;
839 
840             for (ch=0; ch<3; ch++)
841             {
842                 if (u16UpperDiff[ch] <= u16LowerDiff[ch])
843                 {
844                     if (u16UpperDiff[ch] <= TOLERATE_ERROR )
845                     {
846                         Gain[ch] = u16UpperGain[ch];
847                         bDone[ch] = TRUE;
848                     }
849                 }
850                 else
851                 {
852                     if (u16LowerGain[ch] <= TOLERATE_ERROR )
853                     {
854                         Gain[ch] = u16LowerGain[ch];
855                         bDone[ch] = TRUE;
856                     }
857                 }
858             }
859         }
860 
861         if (bDone[0] && bDone[1] && bDone[2])
862         {
863             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Chose one best gain value - ");
864             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"gain check ok  0x%x 0x%x 0x%x\n",Gain[0],Gain[1],Gain[2]);
865             bResult = TRUE;
866         }
867     }
868 
869     if (bResult)
870     {
871         pstADCSetting->u16RedGain =  Gain[0];
872         pstADCSetting->u16GreenGain = Gain[1];
873         pstADCSetting->u16BlueGain = Gain[2];
874         for (ch=0; ch<3; ch++)
875         {
876             MDrv_XC_ADC_SetGain(pInstance, ch, Gain[ch]);
877         }
878     }
879     else
880     {
881         Gain[0] = pstADCSetting->u16RedGain;
882         Gain[1] = pstADCSetting->u16GreenGain;
883         Gain[2] = pstADCSetting->u16BlueGain;
884         for (ch=0; ch<3; ch++)
885         {
886             MDrv_XC_ADC_SetGain(pInstance, ch, Gain[ch]);
887         }
888     }
889     return bResult;
890 }
891 
_MApi_XC_Auto_Internal_AutoCablication(void * pInstance,XC_Auto_TuneType enAutoTuneType,APIXC_AdcGainOffsetSetting * pstADCSetting,SCALER_WIN eWindow)892 static MS_BOOL _MApi_XC_Auto_Internal_AutoCablication(void* pInstance, XC_Auto_TuneType enAutoTuneType, APIXC_AdcGainOffsetSetting *pstADCSetting , SCALER_WIN eWindow)
893 {
894     // Do not use 720P and 1080P timing in Internal calibration.
895     #define ADC_720P    0
896     #define ADC_1080P   0
897 
898     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
899     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
900 
901     APIXC_AdcGainOffsetSetting tempADCSetting;
902     MS_BOOL result;
903     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
904     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
905     MirrorMode_t enMirrorBackup[MAX_WINDOW] = {gSrcInfo[MAIN_WINDOW].Status2.eMirrorMode,gSrcInfo[SUB_WINDOW].Status2.eMirrorMode};
906     MS_U16 u16BackupHsize, u16BackupVsize;
907     _XC_ENTRY(pInstance);
908     MS_BOOL bInputSourceEnabledBackup = MDrv_XC_IsInputSourceDisabled(pInstance, eWindow);
909     _XC_RETURN(pInstance);
910 
911     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"======== Start : Calibration Type: %x ======== \n",enAutoTuneType);
912     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Backup Register setting\n");
913     if ((eWindow >= MAX_WINDOW) || (NULL == pstADCSetting))
914     {
915         printf("%s %d:Parameter error!\n",__FUNCTION__,__LINE__);
916         return FALSE;
917     }
918     //MS_AUTOADC_REG_BAK  AutoAdcRegBak;
919     MDrv_XC_ADC_BackupAdcReg(pInstance, eWindow);
920     u16BackupHsize = gSrcInfo[eWindow].u16H_SizeAfterPreScaling;
921     u16BackupVsize = gSrcInfo[eWindow].u16V_SizeAfterPreScaling;
922     if ((MIRROR_V_ONLY == enMirrorBackup[eWindow]) || (MIRROR_HV == enMirrorBackup[eWindow]))
923     {
924         gSrcInfo[eWindow].Status2.eMirrorMode = MIRROR_NORMAL;
925 
926         MDrv_XC_FreezeImg(pInstance, ENABLE, eWindow);
927 
928         // For re-assign memory address, the input source need to be disabled
929         if (bInputSourceEnabledBackup == TRUE)
930             MDrv_XC_DisableInputSource(pInstance, ENABLE, eWindow);
931 
932         if(eWindow == MAIN_WINDOW)
933         {
934             MDrv_XC_SetFrameBufferAddress(pInstance, pXCResourcePrivate->stdrvXC_MVideo_Context.g_XC_InitData.u32Main_FB_Start_Addr, pXCResourcePrivate->stdrvXC_MVideo_Context.g_XC_InitData.u32Main_FB_Size, eWindow);
935         }
936         else
937         {
938              MDrv_XC_SetFrameBufferAddress(pInstance, pXCResourcePrivate->stdrvXC_MVideo_Context.g_XC_InitData.u32Sub_FB_Start_Addr, pXCResourcePrivate->stdrvXC_MVideo_Context.g_XC_InitData.u32Sub_FB_Size, eWindow);
939         }
940 
941         if (bInputSourceEnabledBackup == TRUE)
942             MDrv_XC_DisableInputSource(pInstance, DISABLE, eWindow);
943 
944         MDrv_SC_set_mirror(pInstance, FALSE, eWindow);
945         MDrv_SC_Set_pre_align_pixel(pInstance, DISABLE, 0, eWindow );
946 
947         MDrv_XC_FreezeImg(pInstance, DISABLE, eWindow);
948 
949     }
950 
951     _XC_ENTRY(pInstance);
952     MDrv_XC_WaitOutputVSync(pInstance, 1, 50, eWindow);
953     MDrv_SC_GenerateBlackVideo(pInstance, ENABLE, eWindow );  //balck screen
954     _XC_RETURN(pInstance);
955     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Initial internal calibration setting");
956 
957     if (enAutoTuneType & E_XC_AUTO_TUNE_RGB_GAIN)
958     {
959         INPUT_SOURCE_TYPE_t enInputSourcetype;
960 
961         enInputSourcetype = pXCResourcePrivate->stdrvXC_MVideo._SCShared.StatusInfo[eWindow].enInputSourceType;
962 
963         if(enInputSourcetype == INPUT_SOURCE_SCART)
964         {
965             MDrv_XC_ADC_InitInternalCalibrationWithFixedOffset(pInstance, INPUT_SOURCE_SCART, &tempADCSetting, eWindow);
966             MDrv_XC_ADC_Source_Calibrate(pInstance, MDrv_XC_ADC_ConvertSrcToADCSrc(pInstance, INPUT_SOURCE_SCART));
967         }
968         else
969         {
970             MDrv_XC_ADC_InitInternalCalibrationWithFixedOffset(pInstance, INPUT_SOURCE_VGA, &tempADCSetting, eWindow);
971             MDrv_XC_ADC_Source_Calibrate(pInstance, MDrv_XC_ADC_ConvertSrcToADCSrc(pInstance, INPUT_SOURCE_VGA));
972         }
973 
974     }
975     else if (enAutoTuneType & E_XC_AUTO_TUNE_YUV_COLOR)
976     {
977         MDrv_XC_ADC_InitInternalCalibrationWithFixedOffset(pInstance, INPUT_SOURCE_YPBPR, &tempADCSetting, eWindow);
978         MDrv_XC_ADC_Source_Calibrate(pInstance, MDrv_XC_ADC_ConvertSrcToADCSrc(pInstance, INPUT_SOURCE_YPBPR));
979     }
980     else
981     {
982         MDrv_XC_ADC_InitInternalCalibrationWithFixedOffset(pInstance, INPUT_SOURCE_SCART, &tempADCSetting, eWindow);
983         MDrv_XC_ADC_Source_Calibrate(pInstance, MDrv_XC_ADC_ConvertSrcToADCSrc(pInstance, INPUT_SOURCE_SCART));
984     }
985 #if ADC_720P
986     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Auto Gen timing: 720p\n");
987     MApi_XC_ADC_GenClock(pInstance, E_ADC_Gen_720P_Clk);
988     _XC_ENTRY(pInstance);
989     MDrv_XC_GenSpecificTiming(pInstance, E_XC_720P);
990     _XC_RETURN(pInstance);
991     MDrv_XC_InitIPForInternalTiming(pInstance, E_XC_720P, eWindow);
992 
993     gSrcInfo[eWindow].u16H_SizeAfterPreScaling = 1280;
994     gSrcInfo[eWindow].u16V_SizeAfterPreScaling = 720;
995 #elif ADC_1080P
996     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Auto Gen timing: 1080p\n");
997 
998     MApi_XC_ADC_GenClock(pInstance, E_ADC_Gen_1080P_Clk);
999     _XC_ENTRY(pInstance);
1000     MDrv_XC_GenSpecificTiming(pInstance, E_XC_1080P);
1001     _XC_RETURN(pInstance);
1002     MDrv_XC_InitIPForInternalTiming(pInstance, E_XC_1080P, eWindow);
1003 
1004     gSrcInfo[eWindow].u16H_SizeAfterPreScaling = 1920;
1005     gSrcInfo[eWindow].u16V_SizeAfterPreScaling = 1080;
1006 #else
1007     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Auto Gen timing: 480p\n");
1008 
1009     MApi_XC_ADC_GenClock(pInstance, E_ADC_Gen_480P_Clk);
1010     _XC_ENTRY(pInstance);
1011     MDrv_XC_GenSpecificTiming(pInstance, E_XC_480P);
1012     _XC_RETURN(pInstance);
1013     MDrv_XC_InitIPForInternalTiming(pInstance, E_XC_480P, eWindow);
1014 
1015     gSrcInfo[eWindow].u16H_SizeAfterPreScaling = 720;
1016     gSrcInfo[eWindow].u16V_SizeAfterPreScaling = 480;
1017 #endif
1018     //MyMDrv_SetCalibrartinWindow(1, 16);
1019     //MDrv_ADC_gainoffset_reset();
1020     MApi_XC_ADC_AutoSetting(pInstance, ENABLE,TRUE,COMPONENT_AUTO_SW_MODE);
1021 
1022     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Start Auto Gain Procedure\n");
1023     result = _MApi_XC_Auto_InternalTuneGain(pInstance, enAutoTuneType, &tempADCSetting , eWindow );
1024     pstADCSetting->u16RedOffset = tempADCSetting.u16RedOffset;
1025     pstADCSetting->u16GreenOffset = tempADCSetting.u16GreenOffset;
1026     pstADCSetting->u16BlueOffset = tempADCSetting.u16BlueOffset;
1027 
1028     pstADCSetting->u16RedGain = tempADCSetting.u16RedGain;
1029     pstADCSetting->u16GreenGain = tempADCSetting.u16GreenGain;
1030     pstADCSetting->u16BlueGain = tempADCSetting.u16BlueGain;
1031 
1032     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"gain check ok  0x%02x 0x%02x 0x%02x\n",
1033         pstADCSetting->u16RedGain,pstADCSetting->u16GreenGain,pstADCSetting->u16BlueGain);
1034 
1035     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"offset check ok  0x%02x 0x%02x 0x%02x\n",
1036         pstADCSetting->u16RedOffset,pstADCSetting->u16GreenOffset,pstADCSetting->u16BlueOffset);
1037 
1038     MApi_XC_ADC_SetInternalVoltage(pInstance, E_ADC_Internal_None );
1039 
1040     //remove the delay time to HAL layer escape from garbage when interal SW calibration
1041     //MsOS_DelayTask(200);
1042     MApi_XC_AutoGainEnable(pInstance, DISABLE,eWindow);
1043     //MDrv_WriteByte(L_BK_IP1F2(0x0E), 0x00); // disable auto gain function
1044     //MDrv_WriteByte( BK_SELECT_00, u8Bank );
1045     //test----start----
1046 #if ( GET_RGB_REPORT == ENABLE )
1047     if ( result == TRUE )
1048     {
1049        GetTestReport();
1050 
1051        GetTestReport_Bk1A();
1052      }
1053      //test----start----
1054 #endif
1055     _XC_ENTRY(pInstance);
1056     MDrv_XC_GenSpecificTiming(pInstance, E_XC_OFF);
1057     _XC_RETURN(pInstance);
1058 
1059     if ((MIRROR_V_ONLY == enMirrorBackup[eWindow]) || (MIRROR_HV == enMirrorBackup[eWindow]))
1060     {
1061 
1062         gSrcInfo[eWindow].Status2.eMirrorMode = enMirrorBackup[eWindow];
1063     }
1064     MDrv_XC_ADC_RestoreAdcReg(pInstance, eWindow);
1065 
1066     gSrcInfo[eWindow].u16H_SizeAfterPreScaling = u16BackupHsize;
1067     gSrcInfo[eWindow].u16V_SizeAfterPreScaling = u16BackupVsize;
1068 
1069     return  result;
1070 
1071 }
1072 
1073 
1074 //-----------------------------------------------------------------------------------------------------------
1075 //
1076 //-----------------------------------------------------------------------------------------------------------
1077 
1078 
1079 
1080 
_MApi_XC_Auto_WaitStatusReady(void * pInstance,XC_Auto_WaitingType type,SCALER_WIN eWindow)1081 static void _MApi_XC_Auto_WaitStatusReady(void *pInstance, XC_Auto_WaitingType type, SCALER_WIN eWindow  )
1082 {
1083     MS_U16 u16Dummy = 1000;
1084     if ( type == E_WAITING_AUTO_POSITION_READY )
1085         while(!( MApi_XC_IsAutoPositionResultReady(pInstance, eWindow) ) && (u16Dummy--)) ;
1086     else
1087         while(!( MApi_XC_IsAutoGainResultReady(pInstance, eWindow) ) && (u16Dummy--)) ;
1088 }
1089 
1090 
1091 //*************************************************************************
1092 //Function name: MDrv_Auto_CheckSyncLoss
1093 //Passing parameter: NO
1094 //Return parameter:
1095 //  MS_BOOL: If PC mode change, return TRUE.
1096 //Description: Check PC mode change when auto-tune executive.
1097 //*************************************************************************
_MApi_XC_Auto_CheckSyncLoss(void * pInstance,SCALER_WIN eWindow)1098 static MS_BOOL _MApi_XC_Auto_CheckSyncLoss(void *pInstance, SCALER_WIN eWindow)
1099 {
1100     MS_BOOL bResult = FALSE;
1101     _XC_ENTRY(pInstance);
1102     bResult = MDrv_XC_PCMonitor_InvalidTimingDetect(pInstance, TRUE, eWindow);
1103     _XC_RETURN(pInstance);
1104     if(bResult)
1105     {
1106         MDrv_XC_PCMonitor_Restart(pInstance, eWindow);
1107     }
1108     return bResult;
1109 }
1110 
1111 
1112 //*************************************************************************
1113 //Function name: _MApi_XC_Auto_GetPosition
1114 //Passing parameter:
1115 //  MS_U8 u8RegIndex: Register index
1116 //  MS_U8 u8VSyncTime: VSync time
1117 //Return parameter:
1118 //  MS_U16: Position value.
1119 //Description: Get position by register select
1120 //*************************************************************************
_MApi_XC_Auto_GetPosition(void * pInstance,XC_Auto_GetAutoPositionType type,MS_U8 u8VSyncTime,SCALER_WIN eWindow)1121 static MS_U16 _MApi_XC_Auto_GetPosition(void *pInstance, XC_Auto_GetAutoPositionType type , MS_U8 u8VSyncTime, SCALER_WIN eWindow)
1122 {
1123     MS_U16 u16ComparePos=0,u16AutoPos; // position buffer,  Add the initial value
1124     MS_U8 u8Dummy = 20; // loop dummy
1125     MS_U8 u8Count = 0; // counter of compare alike
1126     MS_U16 (*GetPositionFunction)(void *pInstance,  SCALER_WIN eWindow ) = MApi_XC_SetAutoPositionHstart;//simply assign a trivial initial value
1127 
1128 
1129     MApi_XC_AutoPositionEnable(pInstance, ENABLE, eWindow);
1130 
1131     switch ( type )
1132     {
1133         case E_XC_AUTO_GET_HSTART:
1134             GetPositionFunction = MApi_XC_SetAutoPositionHstart;
1135             break;
1136         case E_XC_AUTO_GET_HEND:
1137             GetPositionFunction = MApi_XC_SetAutoPositionHend;
1138             break;
1139         case E_XC_AUTO_GET_VSTART:
1140             GetPositionFunction = MApi_XC_SetAutoPositionVstart;
1141             break;
1142         case E_XC_AUTO_GET_VEND:
1143             GetPositionFunction = MApi_XC_SetAutoPositionVend;
1144             break;
1145         default:
1146             break;
1147     }
1148     while(u8Dummy--)
1149     {
1150         _MApi_XC_Auto_WaitStatusReady(pInstance, E_WAITING_AUTO_POSITION_READY, eWindow); // auto position result ready
1151 
1152         u16AutoPos = GetPositionFunction(pInstance, eWindow); //MDrv_Read2Byte(u32RegIndex) & 0xFFF; // get auto position
1153         if(u16AutoPos == u16ComparePos) // match
1154             u8Count++;
1155         else // different
1156         {
1157             u8Count = 0; // reset counter
1158             u16ComparePos = u16AutoPos; // reset position
1159         }
1160 
1161         if(u8Count == 3) // match counter ok
1162             break;
1163 
1164         if(_MApi_XC_Auto_CheckSyncLoss(pInstance, eWindow)) // check no signal
1165         {
1166 
1167             return -1; // return fail
1168         }
1169 
1170         MsOS_DelayTask(u8VSyncTime); // wait next frame
1171     } // while
1172     return u16AutoPos;
1173 }
1174 
1175 #if (!FAST_AUTO_TUNE)
1176 //*************************************************************************
1177 //Function name: MDrv_Auto_SetValidData
1178 //Passing parameter:
1179 //  MS_U8 u8VSyncTime : VSync time for delay
1180 //Return parameter:
1181 //  MS_BOOL: If PC mode change, return FALSE.
1182 //Description: Auto set valid data value.
1183 //*************************************************************************
_MApi_XC_Auto_SetValidData(void * pInstance,MS_U8 u8VSyncTime,SCALER_WIN eWindow)1184 static MS_BOOL _MApi_XC_Auto_SetValidData(void *pInstance, MS_U8 u8VSyncTime, SCALER_WIN eWindow)
1185 {
1186     MS_U8 u8ValidData; // valide dataa value
1187     MS_U16 u16PhaseIndex; // phase index
1188     MS_U16 u16ComapreHPos; // compare horizontal position
1189 
1190     for(u8ValidData = 0x04; u8ValidData != 0x10; u8ValidData++)
1191     {
1192         MDrv_XC_SetValidDataThreshold(pInstance, u8ValidData, eWindow);
1193 
1194         MDrv_XC_ADC_SetPhaseEx(pInstance, 0x00); // set phase
1195         MsOS_DelayTask(u8VSyncTime);
1196 
1197         u16ComapreHPos = _MApi_XC_Auto_GetPosition(pInstance, E_XC_AUTO_GET_HSTART ,u8VSyncTime , eWindow); // horizontal position
1198         for(u16PhaseIndex = 0x01; u16PhaseIndex < 0x10; u16PhaseIndex++)
1199         {
1200             MDrv_XC_ADC_SetPhaseEx(pInstance, u16PhaseIndex * 4); // set phase
1201             MsOS_DelayTask(u8VSyncTime);
1202 
1203             if(abs(u16ComapreHPos - _MApi_XC_Auto_GetPosition(pInstance, E_XC_AUTO_GET_HSTART ,u8VSyncTime , eWindow)) > 3) // check lose data
1204                 break;
1205 
1206             if(_MApi_XC_Auto_CheckSyncLoss(pInstance, eWindow)) // check Sync change
1207             {
1208                 return FALSE;
1209             }
1210         } // for
1211 
1212         if(u16PhaseIndex == 0x10)
1213             break;
1214     } // for
1215 
1216     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Valid=0x%x\n", u8ValidData << 4));
1217     return TRUE;
1218 }
1219 #endif
1220 
1221 
1222 
1223 //*************************************************************************
1224 //Function name: _MApi_XC_Auto_TunePosition
1225 //Passing parameter:
1226 //  MS_U8 u8VSyncTime : VSync time
1227 //  MS_PCADC_MODESETTING_TYPE *pstModesetting: Current PC mode setting
1228 //Return parameter:
1229 //  MS_BOOL: Success status. (If faile, return FALSE.)
1230 //Description: Auto-tune vertical and horizontal position for PC mode
1231 //*************************************************************************
_MApi_XC_Auto_TunePosition(void * pInstance,MS_U8 u8VSyncTime,XC_Auto_Signal_Info_Ex * Active,XC_Auto_Signal_Info_Ex * StandardInfo,SCALER_WIN eWindow)1232 static MS_BOOL _MApi_XC_Auto_TunePosition(void *pInstance, MS_U8 u8VSyncTime, XC_Auto_Signal_Info_Ex *Active , XC_Auto_Signal_Info_Ex *StandardInfo , SCALER_WIN eWindow)
1233 {
1234     MS_U16 u16PosBff; // position buffer
1235     MS_BOOL bResult=TRUE;
1236     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
1237     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
1238     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
1239     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
1240     // horizotal position
1241     // auto horizontal start position detected result
1242     u16PosBff = _MApi_XC_Auto_GetPosition(pInstance, E_XC_AUTO_GET_HSTART ,u8VSyncTime , eWindow);
1243 
1244 #if ENABLE_VGA_EIA_TIMING
1245     if (MDrv_XC_PCMonitor_GetStatus(pInstance, eWindow) &XC_MD_INTERLACE_BIT)
1246     {
1247         u16PosBff++;
1248     }
1249 #endif
1250 
1251     if(u16PosBff > MAX_PC_AUTO_H_START || u16PosBff < MIN_PC_AUTO_H_START)
1252     {
1253         //printf("H start limit: 0x%x (%x->%x)\n", u16PosBff, (MS_U16) MIN_PC_AUTO_H_START, (MS_U16) MAX_PC_AUTO_H_START);
1254         u16PosBff = StandardInfo->u16HorizontalStart;
1255         bResult = FALSE;
1256     }
1257 
1258     Active->u16HorizontalStart = u16PosBff;
1259 
1260     MDrv_XC_SetCaptureWindowHstart(pInstance, u16PosBff , eWindow);
1261 
1262     // vertical positoin
1263     // auto vertical start position detected result
1264 
1265     u16PosBff =_MApi_XC_Auto_GetPosition(pInstance, E_XC_AUTO_GET_VSTART ,u8VSyncTime , eWindow);
1266 
1267     if(u16PosBff > MAX_PC_AUTO_V_START || u16PosBff < MIN_PC_AUTO_V_START)
1268     {
1269         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"V start limit: 0x%x (%x->%x)\n", u16PosBff, (MS_U16) MIN_PC_AUTO_V_START, (MS_U16) MAX_PC_AUTO_V_START);
1270         u16PosBff = StandardInfo->u16VerticalStart;
1271         bResult = FALSE;
1272     }
1273 
1274     Active->u16VerticalStart = u16PosBff;
1275 
1276     MDrv_XC_SetCaptureWindowVstart(pInstance, u16PosBff, eWindow);
1277 
1278     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"AutoPosition VStart=0x%x\n", Active->u16VerticalStart);
1279 
1280     return bResult;
1281 }
1282 
1283 //*************************************************************************
1284 //Function name: _MApi_XC_Auto_GetTransPos
1285 //Passing parameter:
1286 //  MS_U8 u8VSyncTime : VSync time
1287 //Return parameter:
1288 //  MS_U16: If faile, return -1. else return phase setting
1289 //Description: Get trans-position.
1290 //*************************************************************************
_MApi_XC_Auto_GetTransPos(void * pInstance,MS_U8 u8VSyncTime,SCALER_WIN eWindow)1291 static MS_U16 _MApi_XC_Auto_GetTransPos(void *pInstance, MS_U8 u8VSyncTime, SCALER_WIN eWindow)
1292 {
1293     MS_U16 u16ComparePos; // compare start position
1294     MS_U16 u16AdjustPhase = 0x20;
1295     MS_U8 u8PhaseDelta = 0x20; // phase data buffer
1296 
1297     MDrv_XC_ADC_SetPhaseEx(pInstance, 0x00); // intialize
1298     u16ComparePos = _MApi_XC_Auto_GetPosition(pInstance, E_XC_AUTO_GET_HSTART ,u8VSyncTime , eWindow);
1299 
1300     while(1)
1301     {
1302         MDrv_XC_ADC_SetPhaseEx(pInstance, u16AdjustPhase); // set phase
1303 
1304         u8PhaseDelta /= 2; // next step
1305         if(u8PhaseDelta == 0x00) // check end
1306             break;
1307 
1308         if( _MApi_XC_Auto_GetPosition(pInstance, E_XC_AUTO_GET_HSTART ,u8VSyncTime , eWindow) == u16ComparePos) // find critical phase
1309             u16AdjustPhase += u8PhaseDelta; // right shift
1310         else
1311             u16AdjustPhase -= u8PhaseDelta; // left shift
1312 
1313         if(_MApi_XC_Auto_CheckSyncLoss(pInstance, eWindow)) // check no signal
1314         {
1315             return -1;
1316         }
1317     } // while
1318 
1319     return (u16AdjustPhase);
1320 }
1321 
1322 //*************************************************************************
1323 //Function name: _MApi_XC_Auto_GetActualWidth
1324 //Passing parameter:
1325 //  MS_U8 u8VSyncTime : VSync time
1326 //Return parameter:
1327 //  MS_U16: return actual image width
1328 //Description: Get actual image width.
1329 //*************************************************************************
_MApi_XC_Auto_GetActualWidth(void * pInstance,MS_U8 u8VSyncTime,SCALER_WIN eWindow)1330 static MS_U16 _MApi_XC_Auto_GetActualWidth(void *pInstance, MS_U8 u8VSyncTime, SCALER_WIN eWindow)
1331 {
1332     MS_U16 u16HStart; // actual horizontal start
1333     MS_U16 u16Width;
1334     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
1335     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
1336     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
1337     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
1338     MDrv_XC_ADC_SetPhaseEx(pInstance, 0x00); // initialize phase value
1339 
1340     u16HStart =  _MApi_XC_Auto_GetPosition(pInstance, E_XC_AUTO_GET_HSTART ,u8VSyncTime , eWindow); // horizontal start position
1341     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Get %s Window's VSync Time =%d and H Start=%d\n", eWindow?("Sub"):("Main"), u8VSyncTime, u16HStart);
1342     _MApi_XC_Auto_GetTransPos(pInstance, u8VSyncTime, eWindow); // seek critical phase
1343 
1344     u16Width = (( _MApi_XC_Auto_GetPosition(pInstance, E_XC_AUTO_GET_HEND ,u8VSyncTime , eWindow) - u16HStart) + 1); // actual image width
1345 
1346     return u16Width;
1347 }
1348 
1349 //*************************************************************************
1350 //Function name: _MApi_XC_Auto_TuneHTotal
1351 //Passing parameter:
1352 //  MS_U8 u8VSyncTime: VSync time
1353 //  MS_PCADC_MODESETTING_TYPE *pstModesetting: Current PC mode setting
1354 //Return parameter:
1355 //  MS_BOOL: Success status. (If faile, return FALSE.)
1356 //Description: auto-tune horizontal total.
1357 //*************************************************************************
_MApi_XC_Auto_TuneHTotal(void * pInstance,MS_U8 u8VSyncTime,XC_Auto_Signal_Info_Ex * Active,XC_Auto_Signal_Info_Ex * StandardInfo,SCALER_WIN eWindow)1358 static MS_BOOL _MApi_XC_Auto_TuneHTotal(void *pInstance, MS_U8 u8VSyncTime, XC_Auto_Signal_Info_Ex *Active , XC_Auto_Signal_Info_Ex *StandardInfo , SCALER_WIN eWindow)
1359 {
1360     MS_U16 u16ActualWidth; // actual width
1361     MS_U16 u16StdWidth; // standard width
1362     MS_U16 u16HTotalBff; // horizontal total buffer
1363     MS_BOOL bResult = FALSE;
1364 
1365     MDrv_XC_ADC_SetPhaseEx(pInstance, 0x00); // initialize phase value
1366 
1367     // Get Active width from Scaler.
1368     u16ActualWidth = _MApi_XC_Auto_GetActualWidth(pInstance, u8VSyncTime, eWindow);
1369 
1370     // Get standard width from PCmonitor (mode table)
1371     u16StdWidth = StandardInfo->u16HResolution;
1372 
1373     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Step1 u16StdWidth=%u, u16ActualWidth=%u\n",u16StdWidth, u16ActualWidth);
1374 
1375     if(abs(u16ActualWidth - u16StdWidth) > (u16StdWidth / 6)) // check actual width over standard
1376     {
1377         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"AWoverSW(%u,%u)\n", u16ActualWidth, u16StdWidth);
1378         return FALSE;
1379     }
1380     u16HTotalBff = Active->u16HorizontalTotal; // intialize horizontal total buffer
1381     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Step2 Htt=%u, Std Htt=%u\n", u16HTotalBff, StandardInfo->u16HorizontalTotal);
1382 
1383     if(abs(u16ActualWidth - u16StdWidth) > 1) // check width difference
1384     {
1385         // calculate horizontal total
1386         u16HTotalBff = ((MS_U32) Active->u16HorizontalTotal * u16StdWidth) / u16ActualWidth;
1387 
1388         // check over range of adjusting
1389         if(abs(u16HTotalBff - StandardInfo->u16HorizontalTotal) > (Active->u16HorizontalTotal/4) )
1390         {
1391             //XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"OverADJ %u\n", ADJUST_CLOCK_RANGE));
1392             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"OverADJ\n");
1393             return FALSE;
1394         }
1395         MDrv_XC_ADC_SetPcClock(pInstance, u16HTotalBff); // set clock
1396         // check width
1397         u16ActualWidth = _MApi_XC_Auto_GetActualWidth(pInstance, u8VSyncTime, eWindow);
1398     }
1399     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Step3 HTT=%u, Actual Width=%u\n", u16HTotalBff, u16ActualWidth);
1400 
1401     if(u16ActualWidth != u16StdWidth) // match width
1402     {
1403         // adjust horizontal total
1404         u16HTotalBff = u16HTotalBff + (u16StdWidth - u16ActualWidth);
1405 
1406         MDrv_XC_ADC_SetPcClock(pInstance, u16HTotalBff);
1407 
1408         u16ActualWidth = _MApi_XC_Auto_GetActualWidth(pInstance, u8VSyncTime, eWindow);
1409 
1410         // adjust horizontal total again
1411         u16HTotalBff = u16HTotalBff + (u16StdWidth - u16ActualWidth);
1412     }
1413     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Step4 HTT=%u, Actual Width=%u\n", u16HTotalBff, u16ActualWidth);
1414     if(u16HTotalBff & 0x01) // match width and check odd
1415     {
1416         MDrv_XC_ADC_SetPcClock(pInstance, (u16HTotalBff - 1)); // find decrement
1417 
1418         u16ActualWidth = _MApi_XC_Auto_GetActualWidth(pInstance, u8VSyncTime, eWindow);
1419         if(u16ActualWidth == u16StdWidth) // match width
1420             u16HTotalBff--;
1421         else
1422         {
1423             MDrv_XC_ADC_SetPcClock(pInstance, (u16HTotalBff + 1)); // find increment
1424             u16ActualWidth = _MApi_XC_Auto_GetActualWidth(pInstance, u8VSyncTime, eWindow);
1425             if(u16ActualWidth == u16StdWidth) // match width
1426                 u16HTotalBff++;
1427         }
1428     }
1429     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Step5 HTT=%u, Actual Width=%u\n", u16HTotalBff, u16ActualWidth);
1430     // check horizontal total range
1431     if(abs(u16HTotalBff - (StandardInfo->u16HorizontalTotal)) < (StandardInfo->u16HorizontalTotal/4) )
1432     {
1433         Active->u16HorizontalTotal = u16HTotalBff;
1434         Active->u16HResolution = u16ActualWidth;
1435         bResult = TRUE;
1436     }
1437     else
1438     {
1439         Active->u16HResolution = 0xFFFF;
1440     }
1441 
1442     MDrv_XC_ADC_SetPcClock(pInstance, Active->u16HorizontalTotal); // setting ADC clock
1443     MDrv_XC_ADC_SetPhaseEx(pInstance, Active->u16Phase); // setting ADC phase
1444 
1445     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"AutoHtt bResult=%u, Htt = %u, Actual Width=%u\n", bResult, Active->u16HorizontalTotal, u16ActualWidth);
1446     return bResult;
1447 }
1448 
1449 
1450 //*************************************************************************
1451 //Function name: _MApi_XC_Auto_TunePhase
1452 //Passing parameter:
1453 //  MS_U8 u8VSyncTime: VSync time
1454 //  MS_PCADC_MODESETTING_TYPE *pstModesetting: Current PC mode setting
1455 //Return parameter:
1456 //  MS_BOOL: Success status. (If faile, return FALSE.)
1457 //Description: auto-tune phase.
1458 //*************************************************************************
1459 
_MApi_XC_Auto_TunePhase(void * pInstance,MS_U8 u8VSyncTime,XC_Auto_Signal_Info_Ex * Active,SCALER_WIN eWindow)1460 MS_BOOL _MApi_XC_Auto_TunePhase(void *pInstance, MS_U8 u8VSyncTime, XC_Auto_Signal_Info_Ex *Active, SCALER_WIN eWindow)
1461 {
1462 
1463 #if AUTO_PHASE_METHOD
1464     MS_U16 u16Index; // loop index
1465     MS_U16 u16PhaseRange = MDrv_XC_ADC_GetPhaseRange(pInstance) - 1;
1466     MS_U32 u32AutoPhaseVal; // auto phase value result
1467     MS_U32 u32MiniPhaseVal = -1; // minimum phase value
1468     MS_U16 u16WorstPhase1 = 0, u16WorstPhase2 = 0;
1469 
1470     MApi_XC_AutoPhaseEnable(pInstance, ENABLE, eWindow);
1471 
1472     u16WorstPhase1 = 0x00; // initizlize
1473     for(u16Index = u16WorstPhase1; u16Index <= u16PhaseRange; u16Index += AUTO_PHASE_STEP)
1474     {
1475         MDrv_XC_ADC_SetPhaseEx(pInstance, u16Index);
1476         MsOS_DelayTask(u8VSyncTime); // delay 1 frame
1477         u32AutoPhaseVal = MApi_XC_GetPhaseValue(pInstance, eWindow);
1478 
1479         if(u32AutoPhaseVal < u32MiniPhaseVal) // check minimum
1480         {
1481             u16WorstPhase1 = u16Index; // refresh best phase
1482             u32MiniPhaseVal = u32AutoPhaseVal; // refresh minimum value
1483         }
1484 
1485         if(_MApi_XC_Auto_CheckSyncLoss(pInstance, eWindow)) // check no signal
1486             return FALSE;
1487     } // for
1488 
1489        // initizlize
1490     u16WorstPhase2 = (u16WorstPhase1 - AUTO_PHASE_STEP + 1) & u16PhaseRange;
1491     u16WorstPhase1 = (u16WorstPhase1 + AUTO_PHASE_STEP) & u16PhaseRange;
1492     u32MiniPhaseVal = -1;
1493     for(u16Index = u16WorstPhase2; u16Index != u16WorstPhase1; u16Index = ((u16Index + 1) & u16PhaseRange))
1494     {
1495           MDrv_XC_ADC_SetPhaseEx(pInstance, u16Index);
1496         MsOS_DelayTask(u8VSyncTime); // delay 1 frame
1497         u32AutoPhaseVal = MApi_XC_GetPhaseValue(pInstance, eWindow);
1498 
1499         if(u32AutoPhaseVal < u32MiniPhaseVal) // check minimum
1500         {
1501             u16WorstPhase2 = u16Index; // refresh best phase
1502             u32MiniPhaseVal = u32AutoPhaseVal; // refresh minimum value
1503         }
1504 
1505         if(_MApi_XC_Auto_CheckSyncLoss(pInstance, eWindow)) // check no signal
1506             return FALSE;
1507     } // for
1508 
1509       Active->u16Phase = (u16WorstPhase2 + (u16PhaseRange / 2)) & u16PhaseRange;
1510     MDrv_XC_ADC_SetPhaseEx(pInstance, Active->u16Phase);
1511 
1512 #else
1513 
1514     MS_U16 u16PhaseRange = MDrv_XC_ADC_GetPhaseRange(pInstance);
1515     const MS_U16 u16PhaseStep = (u16PhaseRange + 63) / 64;
1516 
1517     MS_U32 u32AutoPhaseVal, u32MaxPhaseVal = 0; // maximum phase value
1518     MS_U16 u16CurPhase, u16BestPhase = 0;
1519 
1520     MApi_XC_AutoPhaseEnable(pInstance, ENABLE, eWindow);
1521 
1522      for (u16CurPhase = 0; u16CurPhase < u16PhaseRange; u16CurPhase += u16PhaseStep)
1523     {
1524         MDrv_XC_ADC_SetPhaseEx(pInstance, u16CurPhase);
1525         MsOS_DelayTask(u8VSyncTime);
1526 
1527         u32AutoPhaseVal = MApi_XC_GetPhaseValue(pInstance, eWindow);
1528 
1529         if (u32AutoPhaseVal > u32MaxPhaseVal) // check maximum
1530         {
1531             u16BestPhase = u16CurPhase;
1532             u32MaxPhaseVal = u32AutoPhaseVal;
1533         }
1534 
1535         if (_MApi_XC_Auto_CheckSyncLoss(pInstance, eWindow))
1536             return FALSE;
1537     }
1538 
1539      // 2nd stage for searching best phase around prvious "BestPhase"
1540     // initizlize (Set range)
1541     u16CurPhase   = u16BestPhase == 0 ? 0 : u16BestPhase - u16PhaseStep + 1;
1542     u16PhaseRange = u16BestPhase + u16PhaseStep;
1543     u32MaxPhaseVal = 0;
1544 
1545     for (; u16CurPhase < u16PhaseRange; u16CurPhase += 1)
1546     {
1547         MDrv_XC_ADC_SetPhaseEx(pInstance, u16CurPhase);
1548         MsOS_DelayTask(u8VSyncTime);
1549 
1550         u32AutoPhaseVal = MApi_XC_GetPhaseValue(pInstance, eWindow);
1551 
1552         if (u32AutoPhaseVal > u32MaxPhaseVal) // check maximum
1553         {
1554             u16BestPhase = u16CurPhase;
1555             u32MaxPhaseVal = u32AutoPhaseVal;
1556         }
1557 
1558         if (_MApi_XC_Auto_CheckSyncLoss(pInstance, eWindow))
1559             return FALSE;
1560     }
1561 
1562     MDrv_XC_ADC_SetPhaseEx(pInstance, u16BestPhase);
1563     Active->u16Phase = u16BestPhase;
1564 #endif
1565 
1566     //printf("AutoPhase %x\n", Active->u16Phase);
1567     return TRUE;
1568 }
1569 
1570 //*************************************************************************
1571 //Function name: _MApi_XC_Auto_ExternalTuneVgaOffset
1572 //Passing parameter:
1573 //  MS_U8 u8VSyncTime: VSync time
1574 //  APIXC_AdcGainOffsetSetting * pstADCSetting: ADC setting of Current PC mode
1575 //Return parameter:
1576 //  MS_BOOL: Success status. (If faile, return FALSE.)
1577 //Description: Auto-tune R/G/B Offset of ADC.
1578 //*************************************************************************
1579 
1580 #if 1
_MApi_XC_Auto_ExternalTuneVgaOffset(void * pInstance,MS_U8 u8VSyncTime,APIXC_AdcGainOffsetSetting * pstADCSetting)1581 static MS_BOOL _MApi_XC_Auto_ExternalTuneVgaOffset(void *pInstance, MS_U8 u8VSyncTime, APIXC_AdcGainOffsetSetting *pstADCSetting)
1582 {
1583     APIXC_AdcGainOffsetSetting stTmpAdcSetting, stBackupAdcSetting;
1584     MS_U16 u16OffsetDelta = (MDrv_XC_ADC_GetMaximalOffsetValue(pInstance) + 1) >> 1; // adjust step
1585     MS_U8 u8ATGStatus = 0; // auto gain status//ERROR FIX Prevent Tool 070522
1586     MS_U8 u8FlowFlag = 0x00; // underflow or overflow flag
1587     MS_BOOL bResult = FALSE;
1588     memset(&stTmpAdcSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
1589     memset(&stBackupAdcSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
1590 
1591     bResult = MDrv_XC_ADC_GetGainSetting(pInstance, &stBackupAdcSetting);
1592     if (bResult)
1593     {
1594         bResult = MDrv_XC_ADC_GetOffsetSetting(pInstance, &stBackupAdcSetting);
1595         if (bResult)
1596         {
1597             bResult = MDrv_XC_ADC_InitExternalCalibration(pInstance, INPUT_SOURCE_VGA, &stTmpAdcSetting);
1598             if (bResult)
1599             {
1600                 while(TRUE)
1601                 {
1602                     u16OffsetDelta /= 2; // next
1603 
1604                     if(u16OffsetDelta == 0x00) // check end
1605                         break;
1606 
1607                     _XC_ENTRY(pInstance);
1608                     MDrv_XC_ADC_SetOffsetSetting(pInstance, &stTmpAdcSetting);
1609                     MDrv_XC_ADC_SetGainSetting(pInstance, &stTmpAdcSetting);
1610                     _XC_RETURN(pInstance);
1611 
1612                     MsOS_DelayTask(u8VSyncTime * 3); // wait stable
1613                     _MApi_XC_Auto_WaitStatusReady(pInstance, E_WAITING_AUTO_GAIN_READY, MAIN_WINDOW);
1614 
1615                     {
1616                         MS_U16 u16ResultR,u16ResultG,u16ResultB;
1617 
1618                         u16ResultR = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_R, u8VSyncTime, MAIN_WINDOW);
1619                         u16ResultG = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_G, u8VSyncTime, MAIN_WINDOW);
1620                         u16ResultB = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_B, u8VSyncTime, MAIN_WINDOW);
1621                         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," Result R: %d  G: %d  B: %d \n", u16ResultR,u16ResultG,u16ResultB);
1622                         if (u16ResultR == 0x00)
1623                             u8ATGStatus |= BIT(2);
1624                         else
1625                             u8ATGStatus &= ~BIT(2);
1626 
1627                         if (u16ResultG == 0x00)
1628                             u8ATGStatus |= BIT(1);
1629                         else
1630                             u8ATGStatus &= ~BIT(1);
1631 
1632 
1633                         if (u16ResultB == 0x00)
1634                             u8ATGStatus |= BIT(0);
1635                         else
1636                             u8ATGStatus &= ~BIT(0);
1637                     }
1638 
1639                     // red
1640                     if(u8ATGStatus & BIT(2) )
1641                     {
1642                         stTmpAdcSetting.u16RedOffset += u16OffsetDelta;
1643                         u8FlowFlag |= BIT(0);
1644                     }
1645                     else
1646                     {
1647                         stTmpAdcSetting.u16RedOffset -= u16OffsetDelta;
1648                         u8FlowFlag |= BIT(1);
1649                     }
1650 
1651                     // green
1652                     if( u8ATGStatus & BIT(1) )
1653                     {
1654                         stTmpAdcSetting.u16GreenOffset += u16OffsetDelta;
1655                         u8FlowFlag |= BIT(2);
1656                     }
1657                     else
1658                     {
1659                         stTmpAdcSetting.u16GreenOffset -= u16OffsetDelta;
1660                         u8FlowFlag |= BIT(3);
1661                     }
1662 
1663                     // blue
1664                     if(u8ATGStatus & BIT(0))
1665                     {
1666                         stTmpAdcSetting.u16BlueOffset += u16OffsetDelta;
1667                         u8FlowFlag |= BIT(4);
1668                     }
1669                     else
1670                     {
1671                         stTmpAdcSetting.u16BlueOffset -= u16OffsetDelta;
1672                         u8FlowFlag |= BIT(5);
1673                     }
1674                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"OffATG=0x%x,FF=0x%x\n", u8ATGStatus, u8FlowFlag);
1675                 } // while
1676 
1677                 // if calibration successed, will write new value, else, write original value
1678                 if(u8FlowFlag == 0x3f)
1679                 {
1680                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"VGA calibration succeed!!\n");
1681                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," offset R: %d G: %d  B: %d \n",pstADCSetting->u16RedOffset,
1682                         pstADCSetting->u16GreenOffset, pstADCSetting->u16BlueOffset);
1683                     pstADCSetting->u16RedGain = stBackupAdcSetting.u16RedGain;
1684                     pstADCSetting->u16GreenGain = stBackupAdcSetting.u16GreenGain;
1685                     pstADCSetting->u16BlueGain = stBackupAdcSetting.u16BlueGain;
1686                     pstADCSetting->u16RedOffset = stTmpAdcSetting.u16RedOffset;
1687                     pstADCSetting->u16GreenOffset = stTmpAdcSetting.u16GreenOffset;
1688                     pstADCSetting->u16BlueOffset = stTmpAdcSetting.u16BlueOffset;
1689                     _XC_ENTRY(pInstance);
1690                     MDrv_XC_ADC_SetOffsetSetting(pInstance, pstADCSetting);
1691                     MDrv_XC_ADC_SetGainSetting(pInstance, pstADCSetting);
1692                     _XC_RETURN(pInstance);
1693                     bResult = TRUE;
1694                 }
1695                 else
1696                 {
1697                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"VGA calibration fail!!\n");
1698                     _XC_ENTRY(pInstance);
1699                     MDrv_XC_ADC_SetOffsetSetting(pInstance, &stBackupAdcSetting);
1700                     MDrv_XC_ADC_SetGainSetting(pInstance, &stBackupAdcSetting);
1701                     _XC_RETURN(pInstance);
1702 
1703                     bResult = FALSE;
1704                 }
1705             }
1706             else
1707             {
1708                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"External offset Calibration initial fail !! \n");
1709             }
1710         }
1711         else
1712         {
1713             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"ExternalTuneVgaOffset GetOffsetSetting fail!!\n");
1714         }
1715     }
1716     else
1717     {
1718         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"ExternalTuneVgaOffset GetGainSetting fail!!\n");
1719     }
1720     return bResult;
1721 }
1722 #endif
1723 
_MApi_XC_Auto_ExternalTuneVgaRGBGain(void * pInstance,MS_U8 u8VSyncTime,APIXC_AdcGainOffsetSetting * pstADCSetting,SCALER_WIN eWindow)1724 MS_BOOL _MApi_XC_Auto_ExternalTuneVgaRGBGain(void *pInstance, MS_U8 u8VSyncTime, APIXC_AdcGainOffsetSetting *pstADCSetting,SCALER_WIN eWindow)
1725 {
1726     APIXC_AdcGainOffsetSetting stTmpAdcSetting, stBackupAdcSetting;
1727     MS_U16 u8GainDelta = (MDrv_XC_ADC_GetMaximalGainValue(pInstance) + 1) >> 1;
1728     MS_U8 u8ATGStatus = 0 ;
1729     MS_U8 u8FlowFlag = 0x00;
1730     MS_BOOL bResult = FALSE;
1731     memset(&stTmpAdcSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
1732     memset(&stBackupAdcSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
1733 
1734     bResult = MDrv_XC_ADC_GetGainSetting(pInstance, &stBackupAdcSetting);
1735     if (bResult)
1736     {
1737         bResult = MDrv_XC_ADC_GetOffsetSetting(pInstance, &stBackupAdcSetting);
1738         if (bResult)
1739         {
1740             bResult = MDrv_XC_ADC_InitExternalCalibrationWithFixedOffset(pInstance, INPUT_SOURCE_VGA, &stTmpAdcSetting);
1741             if (bResult)
1742             {
1743                 while (TRUE)
1744                 {
1745                     u8GainDelta /= 2; // next
1746 
1747                     if (u8GainDelta == 0x00) // check end
1748                         break;
1749 
1750                     MDrv_XC_ADC_SetGainSetting(pInstance, &stTmpAdcSetting);
1751                     MsOS_DelayTask(u8VSyncTime * 3); // wait stable
1752                     _MApi_XC_Auto_WaitStatusReady(pInstance, E_WAITING_AUTO_GAIN_READY, eWindow);
1753 
1754                     u8ATGStatus = MApi_XC_GetAutoGainMaxValueStatus(pInstance, MAIN_WINDOW);
1755                     // red
1756                     if (u8ATGStatus & BIT(2))
1757                     {
1758                         stTmpAdcSetting.u16RedGain -= u8GainDelta;
1759                         u8FlowFlag |= BIT(0);
1760                     }
1761                     else
1762                     {
1763                         stTmpAdcSetting.u16RedGain += u8GainDelta;
1764                         u8FlowFlag |= BIT(1);
1765                     }
1766 
1767                     // green
1768                     if (u8ATGStatus & BIT(1) )
1769                     {
1770                         stTmpAdcSetting.u16GreenGain -= u8GainDelta;
1771                         u8FlowFlag |= BIT(2);
1772                     }
1773                     else
1774                     {
1775                         stTmpAdcSetting.u16GreenGain += u8GainDelta;
1776                         u8FlowFlag |= BIT(3);
1777                     }
1778 
1779                     // blue
1780                     if (u8ATGStatus & BIT(0) )
1781                     {
1782                         stTmpAdcSetting.u16BlueGain -= u8GainDelta;
1783                         u8FlowFlag |= BIT(4);
1784                     }
1785                     else
1786                     {
1787                         stTmpAdcSetting.u16BlueGain += u8GainDelta;
1788                         u8FlowFlag |= BIT(5);
1789                     }
1790                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"GainATG=0x%x,FF=0x%x\n", u8ATGStatus, u8FlowFlag);
1791                 } // while
1792 
1793                 // if calibration successed, will write new value, else, write original value
1794                 if (u8FlowFlag == 0x3f)
1795                 {
1796                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"VGA calibration succeed!!\n");
1797                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," Gain R: %d G: %d  B: %d \n",pstADCSetting->u16RedGain,
1798                         pstADCSetting->u16GreenGain, pstADCSetting->u16BlueGain);
1799                     pstADCSetting->u16RedGain = stTmpAdcSetting.u16RedGain;
1800                     pstADCSetting->u16GreenGain = stTmpAdcSetting.u16GreenGain;
1801                     pstADCSetting->u16BlueGain = stTmpAdcSetting.u16BlueGain;
1802                     pstADCSetting->u16RedOffset = stTmpAdcSetting.u16RedOffset;
1803                     pstADCSetting->u16GreenOffset = stTmpAdcSetting.u16GreenOffset;
1804                     pstADCSetting->u16BlueOffset = stTmpAdcSetting.u16BlueOffset;
1805                     _XC_ENTRY(pInstance);
1806                     MDrv_XC_ADC_SetOffsetSetting(pInstance, pstADCSetting);
1807                     MDrv_XC_ADC_SetGainSetting(pInstance, pstADCSetting);
1808                     _XC_RETURN(pInstance);
1809                     bResult = TRUE;
1810                 }
1811                 else
1812                 {
1813                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"VGA calibration fail!!\n");
1814                     _XC_ENTRY(pInstance);
1815                     MDrv_XC_ADC_SetOffsetSetting(pInstance, &stBackupAdcSetting);
1816                     MDrv_XC_ADC_SetGainSetting(pInstance, &stBackupAdcSetting);
1817                     _XC_RETURN(pInstance);
1818                     bResult = FALSE;
1819                 }
1820             }
1821             else
1822             {
1823                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"External VGA Calibration initial fail !! \n");
1824             }
1825         }
1826         else
1827         {
1828             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"ExternalTuneVgaRGBGain GetOffsetSetting fail!!\n");
1829         }
1830     }
1831     else
1832     {
1833         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"ExternalTuneVgaRGBGain GetGainSetting fail!!\n");
1834     }
1835     return bResult;
1836 }
1837 
_MApi_XC_Auto_ExternalTuneScartRGBGain(void * pInstance,MS_U8 u8VSyncTime,APIXC_AdcGainOffsetSetting * pstADCSetting,SCALER_WIN eWindow)1838 MS_BOOL _MApi_XC_Auto_ExternalTuneScartRGBGain(void *pInstance, MS_U8 u8VSyncTime, APIXC_AdcGainOffsetSetting *pstADCSetting,SCALER_WIN eWindow)
1839 {
1840     APIXC_AdcGainOffsetSetting stTmpADCSetting, stBackupAdcSetting;
1841     MS_U16 u16GainDelta = (MDrv_XC_ADC_GetMaximalGainValue(pInstance) + 1) >> 1; // adjust step
1842     MS_U8 u8ATGStatus = 0 ; // auto gain status
1843     MS_U8 u8FlowFlag = 0x00; // underflow or overflow flag
1844     MS_U16 u16ResultR = 0;
1845     MS_U16 u16ResultG = 0;
1846     MS_U16 u16ResultB = 0;
1847     MS_BOOL bResult = FALSE;
1848     memset(&stTmpADCSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
1849     memset(&stBackupAdcSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
1850 
1851     bResult = MDrv_XC_ADC_GetGainSetting(pInstance, &stBackupAdcSetting);
1852     if (bResult)
1853     {
1854         bResult = MDrv_XC_ADC_GetOffsetSetting(pInstance, &stBackupAdcSetting);
1855         if (bResult)
1856         {
1857             bResult = MDrv_XC_ADC_InitExternalCalibrationWithFixedOffset(pInstance, INPUT_SOURCE_SCART, &stTmpADCSetting);
1858             if (bResult)
1859             {
1860                 while (TRUE)
1861                 {
1862                     u16GainDelta /= 2; // next
1863                     MDrv_XC_ADC_SetGainSetting(pInstance, &stTmpADCSetting);
1864                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," Gain R: %d  G: %d  B: %d \n",stTmpADCSetting.u16RedGain,
1865                             stTmpADCSetting.u16GreenGain,
1866                             stTmpADCSetting.u16BlueGain);
1867 
1868                     if (u16GainDelta == 0x00) // check end
1869                     {
1870                         break;
1871                     }
1872 
1873                     u16ResultR = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_R, u8VSyncTime, MAIN_WINDOW);
1874                     u16ResultG = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_G, u8VSyncTime, MAIN_WINDOW);
1875                     u16ResultB = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_B, u8VSyncTime, MAIN_WINDOW);
1876                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," Result R: %d  G: %d  B: %d \n", u16ResultR,u16ResultG,u16ResultB);
1877 
1878                     // Target is 235 ( 10 bit mode : 235 * 4 = 940 = 0x3AC)
1879                     if (u16ResultR >= 0x3AC)
1880                     {
1881                         u8ATGStatus |= BIT(2);
1882                     }
1883                     else
1884                     {
1885                         u8ATGStatus &= ~BIT(2);
1886                     }
1887 
1888                     if (u16ResultG >= 0x3AC)
1889                     {
1890                         u8ATGStatus |= BIT(1);
1891                     }
1892                     else
1893                     {
1894                         u8ATGStatus &= ~BIT(1);
1895                     }
1896 
1897 
1898                     if (u16ResultB >= 0x3AC)
1899                     {
1900                         u8ATGStatus |= BIT(0);
1901                     }
1902                     else
1903                     {
1904                         u8ATGStatus &= ~BIT(0);
1905                     }
1906 
1907                     //adjust gain
1908                     // red
1909                     if (u8ATGStatus & BIT(2))
1910                     {
1911                         stTmpADCSetting.u16RedGain -= u16GainDelta;
1912                         u8FlowFlag |= BIT(0);
1913                     }
1914                     else
1915                     {
1916                         stTmpADCSetting.u16RedGain += u16GainDelta;
1917                         u8FlowFlag |= BIT(1);
1918                     }
1919 
1920                     // green
1921                     if (u8ATGStatus & BIT(1) )
1922                     {
1923                         stTmpADCSetting.u16GreenGain -= u16GainDelta;
1924                         u8FlowFlag |= BIT(2);
1925                     }
1926                     else
1927                     {
1928                         stTmpADCSetting.u16GreenGain += u16GainDelta;
1929                         u8FlowFlag |= BIT(3);
1930                     }
1931 
1932                     // blue
1933                     if (u8ATGStatus & BIT(0) )
1934                     {
1935                         stTmpADCSetting.u16BlueGain -= u16GainDelta;
1936                         u8FlowFlag |= BIT(4);
1937                     }
1938                     else
1939                     {
1940                         stTmpADCSetting.u16BlueGain += u16GainDelta;
1941                         u8FlowFlag |= BIT(5);
1942                     }
1943                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"GainATG=0x%x,FF=0x%x\n", u8ATGStatus, u8FlowFlag);
1944                 } // while
1945 
1946                 // calibration failed, restore original value
1947                 if (u8FlowFlag != 0x3f)
1948                 {
1949                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Calibration fail !! \n");
1950                     _XC_ENTRY(pInstance);
1951                     MDrv_XC_ADC_SetOffsetSetting(pInstance, &stBackupAdcSetting);
1952                     MDrv_XC_ADC_SetGainSetting(pInstance, &stBackupAdcSetting);
1953                     _XC_RETURN(pInstance);
1954                     MApi_XC_ADC_ExitExternalCalibration(pInstance, INPUT_SOURCE_SCART, &stBackupAdcSetting);
1955                     bResult = FALSE;
1956                 }
1957                 else
1958                 {
1959                     //adjust gain(+1/-1) after auto-tune
1960                     u16ResultR = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_R, u8VSyncTime, MAIN_WINDOW);
1961                     u16ResultG = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_G, u8VSyncTime, MAIN_WINDOW);
1962                     u16ResultB = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_B, u8VSyncTime, MAIN_WINDOW);
1963                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," Result R: %d  G: %d  B: %d \n", u16ResultR,u16ResultG,u16ResultB);
1964 
1965                     // Target is 235 ( 10 bit mode : 235 * 4 = 940 = 0x3AC)
1966                     if (u16ResultR < 0x3AC)
1967                     {
1968                         stTmpADCSetting.u16RedGain++;
1969                     }
1970 
1971                     if (u16ResultG < 0x3AC)
1972                     {
1973                         stTmpADCSetting.u16GreenGain++;
1974                     }
1975 
1976                     if (u16ResultB < 0x3AC)
1977                     {
1978                         stTmpADCSetting.u16BlueGain++;
1979                     }
1980 
1981                     MDrv_XC_ADC_SetGainSetting(pInstance, &stTmpADCSetting);
1982 
1983                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Calibration success !! \n");
1984                     // Because there are variaty between IP1 HW and memory.
1985                     // Add Gain value on all channel for this variaty (All channel have reach to 0x3AC by reading from memory)
1986                     // Add Gain value on all channel 26. (We do not know 0~255. The only part we know is 0~235.)
1987                     pstADCSetting->u16RedGain = stTmpADCSetting.u16RedGain + 0x0220;
1988                     pstADCSetting->u16GreenGain = stTmpADCSetting.u16GreenGain + 0x0220;
1989                     pstADCSetting->u16BlueGain = stTmpADCSetting.u16BlueGain + 0x0220;
1990                     pstADCSetting->u16RedOffset = stTmpADCSetting.u16RedOffset;
1991                     pstADCSetting->u16GreenOffset = stTmpADCSetting.u16GreenOffset;
1992                     pstADCSetting->u16BlueOffset = stTmpADCSetting.u16BlueOffset;
1993                     _XC_ENTRY(pInstance);
1994                     MDrv_XC_ADC_SetOffsetSetting(pInstance, pstADCSetting);
1995                     MDrv_XC_ADC_SetGainSetting(pInstance, pstADCSetting);
1996                     _XC_RETURN(pInstance);
1997                     MApi_XC_ADC_ExitExternalCalibration(pInstance, INPUT_SOURCE_SCART, pstADCSetting);
1998                     bResult = TRUE;
1999                 }
2000             }
2001             else
2002             {
2003                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"External Scart Calibration initial fail !! \n");
2004             }
2005         }
2006         else
2007         {
2008             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"ExternalTuneScartRGBGain GetOffsetSetting fail!!\n");
2009         }
2010     }
2011     else
2012     {
2013         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"ExternalTuneScartRGBGain GetGainSetting fail!!\n");
2014     }
2015     return bResult;
2016 }
2017 
2018 
2019 //*************************************************************************
2020 //Function name: _MApi_XC_Auto_ColorYUV
2021 //Passing parameter:
2022 //  MS_U8 u8VSyncTime: VSync time
2023 //  APIXC_AdcGainOffsetSetting * pstADCSetting: ADC setting of Current YCbCr mode
2024 //Return parameter:
2025 //  MS_BOOL: Success status. (If faile, return FALSE.)
2026 //Description: Auto-tune Y gain of ADC.
2027 //*************************************************************************
2028 #if COMPONENT_AUTO_SW_MODE
2029 
_MApi_XC_Auto_ExternalTuneComponetYpbprGain(void * pInstance,MS_U8 u8VSyncTime,APIXC_AdcGainOffsetSetting * pstADCSetting)2030 static MS_BOOL _MApi_XC_Auto_ExternalTuneComponetYpbprGain(void *pInstance, MS_U8 u8VSyncTime, APIXC_AdcGainOffsetSetting *pstADCSetting)
2031 {
2032     APIXC_AdcGainOffsetSetting tempADCSetting;
2033     MS_U8 u8ATGStatus =0, u8Tmp, u8TuneStep = 4;
2034     MS_U16 u8ResultR,u8ResultG,u8ResultB;
2035 
2036     // Using SMPTE 100% or 75% depends on the definition of devAuto.h
2037     tempADCSetting.u16RedGain = 0x1000;
2038     tempADCSetting.u16GreenGain = 0x1000;
2039     tempADCSetting.u16BlueGain = 0x1000;
2040     tempADCSetting.u16RedOffset = 0x800;
2041     tempADCSetting.u16GreenOffset =0x100;
2042     tempADCSetting.u16BlueOffset = 0x800;
2043 
2044     // Tune Gain
2045     for(u8Tmp=0; u8Tmp<0xFF; u8Tmp++)
2046     {
2047         _XC_ENTRY(pInstance);
2048         MDrv_XC_ADC_SetOffsetSetting(pInstance, &tempADCSetting);
2049         MDrv_XC_ADC_SetGainSetting(pInstance, &tempADCSetting);
2050         _XC_RETURN(pInstance);
2051 
2052         MsOS_DelayTask(u8VSyncTime *3 ); // wait stable
2053 
2054         // Get Pr active value (Max. value - Min. value)
2055         u8ResultR = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_R, u8VSyncTime, MAIN_WINDOW);
2056         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Min R: 0x%x ; ", u8ResultR);
2057         u8ResultR = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_R, u8VSyncTime, MAIN_WINDOW) - u8ResultR;
2058         // Get Y active value (Max. value - Min. value)
2059         u8ResultG = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_G, u8VSyncTime, MAIN_WINDOW);
2060         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Min G: 0x%x ; ", u8ResultG);
2061         u8ResultG = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_G, u8VSyncTime, MAIN_WINDOW) - u8ResultG;
2062         // Get Pb active value (Max. value - Min. value)
2063         u8ResultB = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_B, u8VSyncTime, MAIN_WINDOW);
2064         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Min B: 0x%x; \n", u8ResultB);
2065         u8ResultB = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_B, u8VSyncTime, MAIN_WINDOW) - u8ResultB;
2066         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Diff R=0x%x, Diff G=0x%x,Diff B=0x%x\n", u8ResultR, u8ResultG, u8ResultB);
2067 
2068         if((u8ResultR >= (PbPr_AUTO_ACTIVE_RANGE<<2)) && (u8ResultR <= ((PbPr_AUTO_ACTIVE_RANGE<<2)+1)))  // Range: 0x10~0xF0
2069         //if(u8ResultR == (PbPr_AUTO_ACTIVE_RANGE<<2))
2070         {
2071             u8ATGStatus |= BIT(4);
2072         }
2073         else
2074         {
2075             tempADCSetting.u16RedGain += (signed)((PbPr_AUTO_ACTIVE_RANGE<<2)*u8TuneStep - u8ResultR*u8TuneStep);
2076             u8ATGStatus &= ~BIT(4);
2077         }
2078 
2079         if( (u8ResultG >= (Y_AUTO_ACTIVE_RANGE<<2)) && (u8ResultG <= ((Y_AUTO_ACTIVE_RANGE<<2)+1)) )  // Range: 0x00~0xDB
2080         //if(u8ResultG == (Y_AUTO_ACTIVE_RANGE<<2))
2081         {
2082             u8ATGStatus |= BIT(3);
2083         }
2084         else
2085         {
2086             tempADCSetting.u16GreenGain += (signed)((Y_AUTO_ACTIVE_RANGE<<2)*u8TuneStep - u8ResultG*u8TuneStep);
2087             u8ATGStatus &= ~BIT(3);
2088         }
2089 
2090         if( (u8ResultB >= (PbPr_AUTO_ACTIVE_RANGE<<2)) && (u8ResultB <= ((PbPr_AUTO_ACTIVE_RANGE<<2)+1)))  // Range: 0x10~0xF0
2091         //if(u8ResultB == (PbPr_AUTO_ACTIVE_RANGE<<2))
2092         {
2093             u8ATGStatus |= BIT(2);
2094         }
2095         else
2096         {
2097             tempADCSetting.u16BlueGain += (signed)((PbPr_AUTO_ACTIVE_RANGE<<2)*u8TuneStep - u8ResultB*u8TuneStep);
2098             u8ATGStatus &= ~BIT(2);
2099         }
2100 
2101         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"u8ATGStatus=0x%x\n", u8ATGStatus);
2102         if(u8ATGStatus == 0x1C)
2103             break;
2104     }
2105 
2106     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"R gain: 0x%x, G gain: 0x%x, B gain: %x\n",tempADCSetting.u16RedGain, tempADCSetting.u16GreenGain, tempADCSetting.u16BlueGain);
2107 
2108     // Tune Offset
2109     for(u8Tmp=0; u8Tmp<0xFF; u8Tmp++)
2110     {
2111         _XC_ENTRY(pInstance);
2112         MDrv_XC_ADC_SetOffsetSetting(pInstance, &tempADCSetting);
2113         MDrv_XC_ADC_SetGainSetting(pInstance, &tempADCSetting);
2114         _XC_RETURN(pInstance);
2115         MsOS_DelayTask(u8VSyncTime * 3); // wait stable
2116 
2117         u8ResultR = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_R, u8VSyncTime, MAIN_WINDOW);
2118         u8ResultG = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_G, u8VSyncTime, MAIN_WINDOW);
2119         u8ResultB = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_B, u8VSyncTime, MAIN_WINDOW);
2120         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Min R=0x%x,G=0x%x,B=0x%x\n", u8ResultR, u8ResultG, u8ResultB);
2121         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Max R=0x%x,G=0x%x,B=0x%x\n", (MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_R, u8VSyncTime, MAIN_WINDOW)>>2),
2122             (MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_G, u8VSyncTime, MAIN_WINDOW)>>2), (MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_B, u8VSyncTime, MAIN_WINDOW)>>2));
2123 
2124         // Red - Pr
2125         if ( (u8ResultR >= (PbPr_AUTO_MIN_VALUE<<2)) && (u8ResultR <= ((PbPr_AUTO_MIN_VALUE<<2)+1)) )    // Range (0x10~0xF0)
2126         //if ( u8ResultR == (PbPr_AUTO_MIN_VALUE<<2) )
2127         {
2128             u8ATGStatus |= BIT(7);
2129         }
2130         else
2131         {
2132             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"old R offset: 0x%x\n", tempADCSetting.u16RedOffset);
2133             tempADCSetting.u16RedOffset += (signed)((PbPr_AUTO_MIN_VALUE<<2) - (u8ResultR));
2134             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"new R offset: 0x%x\n", tempADCSetting.u16RedOffset);
2135             u8ATGStatus &= ~BIT(7);
2136         }
2137 
2138         // Green - Y
2139         if ( (u8ResultG >= (Y_MIN_VALUE<<2)) && (u8ResultG <= ((Y_MIN_VALUE<<2)+1)) ) // Range (0x10~0xEB)
2140         //if ( u8ResultG == (Y_MIN_VALUE<<2) )
2141         {
2142             u8ATGStatus |= BIT(6);
2143         }
2144         else
2145         {
2146             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"old G offset: 0x%x\n", tempADCSetting.u16GreenOffset);
2147             tempADCSetting.u16GreenOffset += (signed)((Y_MIN_VALUE<<2) - (u8ResultG));
2148             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"new G offset: 0x%x\n", tempADCSetting.u16GreenOffset);
2149             u8ATGStatus &= ~BIT(6);
2150         }
2151 
2152         // Blue - Pb
2153         if ( (u8ResultB >= (PbPr_AUTO_MIN_VALUE<<2)) && (u8ResultB <= ((PbPr_AUTO_MIN_VALUE<<2)+1)) )    // Range (0x10~0xF0)
2154         //if ( u8ResultB == (PbPr_AUTO_MIN_VALUE<<2) )
2155         {
2156             u8ATGStatus |= BIT(5);
2157         }
2158         else
2159         {
2160             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"old B offset: 0x%x\n",tempADCSetting.u16BlueOffset);
2161             tempADCSetting.u16BlueOffset += (signed)((PbPr_AUTO_MIN_VALUE<<2) - (u8ResultB));
2162             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"new B offset: 0x%x\n",tempADCSetting.u16BlueOffset);
2163             u8ATGStatus &= ~BIT(5);
2164         }
2165 
2166         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"u8ATGStatus =0x%x\n", u8ATGStatus);
2167 
2168         if(u8ATGStatus == 0xFC)
2169             break;
2170     }
2171 
2172     if(u8ATGStatus == 0xFC)
2173     {
2174         // succssed, copy setting to user
2175         pstADCSetting->u16RedGain = tempADCSetting.u16RedGain;
2176         pstADCSetting->u16GreenGain = tempADCSetting.u16GreenGain;
2177         pstADCSetting->u16BlueGain = tempADCSetting.u16BlueGain;
2178         pstADCSetting->u16RedOffset = tempADCSetting.u16RedOffset;
2179         pstADCSetting->u16GreenOffset = tempADCSetting.u16GreenOffset;
2180         pstADCSetting->u16BlueOffset = tempADCSetting.u16BlueOffset;
2181     }
2182     else
2183     {
2184         _XC_ENTRY(pInstance);
2185         MDrv_XC_ADC_SetOffsetSetting(pInstance, pstADCSetting);
2186         MDrv_XC_ADC_SetGainSetting(pInstance, pstADCSetting);
2187         _XC_RETURN(pInstance);
2188     }
2189 
2190     return (u8ATGStatus == 0xFC ? TRUE : FALSE);
2191 
2192 }
2193 
2194 #if 0
2195 static MS_BOOL _MApi_XC_Auto_ColorYUV(MS_U8 u8VSyncTime, APIXC_AdcGainOffsetSetting *pstADCSetting)
2196 {
2197     APIXC_AdcGainOffsetSetting tempADCSetting;
2198     MS_U8 u8ATGStatus, u8Tmp, u8FlowFlag;
2199     MS_U8 u8ResultR,u8ResultG,u8ResultB;
2200 
2201     // Using SMPTE 100% or 75% depends on the definition of devAuto.h
2202     tempADCSetting.u16RedGain = 0x30;
2203     tempADCSetting.u16GreenGain = 0x30;
2204     tempADCSetting.u16BlueGain = 0x30;
2205     tempADCSetting.u16RedOffset = 0x80;
2206     tempADCSetting.u16GreenOffset =0x80;
2207     tempADCSetting.u16BlueOffset = 0x80;
2208 
2209     MApi_XC_ADC_AutoSetting(pInstance, DISABLE, TRUE, COMPONENT_AUTO_SW_MODE);
2210 
2211     u8ATGStatus = 0;
2212     u8FlowFlag = 0;
2213 
2214     // Tune offset
2215     for(u8Tmp=0; u8Tmp<0xFF; u8Tmp++)
2216     {
2217         //printf("u8Tmp=0x%bx\n", u8Tmp);
2218         MApi_XC_ADC_AdjustGainOffset(&tempADCSetting);
2219 
2220         MsOS_DelayTask(u8VSyncTime * 3); // wait stable
2221 
2222         u8ResultR = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_R, u8VSyncTime, MAIN_WINDOW);
2223         u8ResultG = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_G, u8VSyncTime, MAIN_WINDOW);
2224         u8ResultB = MApi_XC_GetAutoGainResult(pInstance, AUTO_MIN_B, u8VSyncTime, MAIN_WINDOW);
2225 
2226         if ((u8ResultR >= PbPr_AUTO_MIN_VALUE) && (u8ResultR <= (PbPr_AUTO_MIN_VALUE+1)))    // Range (0x10~0xF0)
2227             u8ATGStatus |= BIT(7);
2228         else
2229             u8ATGStatus &= ~BIT(7);
2230 
2231         if ((u8ResultG >= (Y_AUTO_MIN_VALUE+1)) && (u8ResultG <= (Y_AUTO_MIN_VALUE+2))) // Range (0x00~0xDB)
2232             u8ATGStatus |= BIT(6);
2233         else
2234             u8ATGStatus &= ~BIT(6);
2235 
2236         if ((u8ResultB >= PbPr_AUTO_MIN_VALUE) && (u8ResultB <= (PbPr_AUTO_MIN_VALUE+1)))    // Range (0x10~0xF0)
2237             u8ATGStatus |= BIT(5);
2238         else
2239             u8ATGStatus &= ~BIT(5);
2240 
2241         // Red - Pr
2242         if ( !(u8FlowFlag&BIT(0)) )
2243         {
2244             if (_bit7_(u8ATGStatus))
2245             {
2246                 // do nothing to RedOffset
2247                 u8FlowFlag |= BIT(0);
2248             }
2249             else
2250             {
2251                 tempADCSetting.u16RedOffset += (signed)(PbPr_AUTO_MIN_VALUE - u8ResultR);
2252             }
2253         }
2254 
2255         // Green - Y
2256         if ( !(u8FlowFlag&BIT(2)) )
2257         {
2258             if (_bit6_(u8ATGStatus))
2259             {
2260                 // do nothing to GreenOffset
2261                 u8FlowFlag |= BIT(2);
2262             }
2263             else
2264             {
2265                 tempADCSetting.u16GreenOffset += (signed)(Y_AUTO_MIN_VALUE+1 - u8ResultG);
2266             }
2267         }
2268 
2269         // Blue - Pb
2270         if ( !(u8FlowFlag&BIT(4)) )
2271         {
2272             if (_bit5_(u8ATGStatus))
2273             {
2274                 // do nothing to BlueOffset
2275                 u8FlowFlag |= BIT(4);
2276             }
2277             else
2278             {
2279                 tempADCSetting.u16BlueOffset += (signed)(PbPr_AUTO_MIN_VALUE - u8ResultB);
2280             }
2281         }
2282 
2283         //printf("ATG=0x%bx, FF=0x%bx, Min R=0x%bx,G=0x%bx,B=0x%bx\n", u8ATGStatus, u8FlowFlag, u8ResultR, u8ResultG, u8ResultG);
2284 
2285         // Get Pr active value (Max. value - Min. value)
2286         u8ResultR = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_R, u8VSyncTime, MAIN_WINDOW)-u8ResultR;
2287         // Get Y active value (Max. value - Min. value)
2288         u8ResultG = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_G, u8VSyncTime, MAIN_WINDOW)-u8ResultG;
2289         // Get Pb active value (Max. value - Min. value)
2290         u8ResultB = MApi_XC_GetAutoGainResult(pInstance, AUTO_MAX_B, u8VSyncTime, MAIN_WINDOW)-u8ResultB;
2291 
2292         if((u8ResultR >= PbPr_AUTO_ACTIVE_RANGE) && (u8ResultR <= (PbPr_AUTO_ACTIVE_RANGE+1)))  // Range: 0x10~0xF0
2293         {
2294             u8ATGStatus |= BIT(4);
2295         }
2296         else
2297         {
2298             u8FlowFlag &= ~(BIT(1)+BIT(0));
2299             u8ATGStatus &= ~BIT(4);
2300         }
2301 
2302         if((u8ResultG >= Y_AUTO_ACTIVE_RANGE) && (u8ResultG <= (Y_AUTO_ACTIVE_RANGE+1)))  // Range: 0x00~0xDB
2303         {
2304             u8ATGStatus |= BIT(3);
2305         }
2306         else
2307         {
2308             u8FlowFlag &= ~(BIT(3)+BIT(2));
2309             u8ATGStatus &= ~BIT(3);
2310         }
2311 
2312         if((u8ResultB >= PbPr_AUTO_ACTIVE_RANGE) && (u8ResultB <= (PbPr_AUTO_ACTIVE_RANGE+1)))  // Range: 0x10~0xF0
2313         {
2314             u8ATGStatus |= BIT(2);
2315         }
2316         else
2317         {
2318             u8FlowFlag &= ~(BIT(5)+BIT(4));
2319             u8ATGStatus &= ~BIT(2);
2320         }
2321 
2322         // Red - Pr
2323         if ( !(u8FlowFlag&BIT(1)) )
2324         {
2325             if (_bit4_(u8ATGStatus))
2326             {
2327                 u8FlowFlag |= BIT(1);
2328             }
2329             else
2330             {
2331                 tempADCSetting.u16RedGain += (signed)(PbPr_AUTO_ACTIVE_RANGE - u8ResultR);
2332                 u8FlowFlag &= ~BIT(1);
2333             }
2334         }
2335 
2336         // Green - Y
2337         if ( !(u8FlowFlag&BIT(3)) )
2338         {
2339             if (_bit3_(u8ATGStatus))
2340             {
2341                 u8FlowFlag |= BIT(3);
2342             }
2343             else
2344             {
2345                 tempADCSetting.u16GreenGain += (signed)(Y_AUTO_ACTIVE_RANGE - u8ResultG);
2346                 u8FlowFlag &= ~BIT(3);
2347             }
2348         }
2349 
2350         // Blue - Pb
2351         if ( !(u8FlowFlag&BIT(5)) )
2352         {
2353             if (_bit2_(u8ATGStatus))
2354             {
2355                 u8FlowFlag |= BIT(5);
2356             }
2357             else
2358             {
2359                 tempADCSetting.u16BlueGain += (signed)(PbPr_AUTO_ACTIVE_RANGE - u8ResultB);
2360                 u8FlowFlag &= ~BIT(5);
2361             }
2362         }
2363 
2364         //printf("ATG=0x%bx, FF=0x%bx, Max R=0x%bx,G=0x%bx,B=0x%bx\n", u8ATGStatus, u8FlowFlag, u8ResultR, u8ResultG, u8ResultG);
2365 
2366         if(u8FlowFlag == 0x3F)
2367             break;
2368     }
2369 
2370     MsOS_DelayTask(u8VSyncTime * 2);
2371 
2372 
2373 
2374     //printf("FF=0x%bx, Gain R=0x%bx,G=0x%bx,B=0x%bx\n", u8FlowFlag,
2375     //    ~tempADCSetting.u16RedGain, ~tempADCSetting.u16GreenGain, ~tempADCSetting.u16BlueGain);
2376     //printf("FF=0x%bx, Offset R=0x%bx,G=0x%bx,B=0x%bx\n", u8FlowFlag,
2377     //    ~tempADCSetting.u16RedOffset, ~tempADCSetting.u16GreenOffset, ~tempADCSetting.u16BlueOffset);
2378 
2379 
2380     if(u8FlowFlag == 0x3F)
2381     {
2382         // succssed, copy setting to user
2383         pstADCSetting->u16RedGain = tempADCSetting.u16RedGain;
2384         pstADCSetting->u16GreenGain = tempADCSetting.u16GreenGain;
2385         pstADCSetting->u16BlueGain = tempADCSetting.u16BlueGain;
2386         pstADCSetting->u16RedOffset = tempADCSetting.u16RedOffset;
2387         pstADCSetting->u16GreenOffset = tempADCSetting.u16GreenOffset;
2388         pstADCSetting->u16BlueOffset = tempADCSetting.u16BlueOffset;
2389     }
2390     else
2391     {
2392         MApi_XC_ADC_AdjustGainOffset(pstADCSetting);
2393         MApi_XC_ADC_AdjustGainOffset(pstADCSetting);
2394     }
2395 
2396     return (u8FlowFlag == 0x3F ? TRUE : FALSE);
2397 }
2398 #endif
2399 
2400 
2401 #else
2402 
_MApi_XC_Auto_ExternalTuneComponetYpbprGain(void * pInstance,MS_U8 u8VSyncTime,APIXC_AdcGainOffsetSetting * pstADCSetting)2403 static MS_BOOL _MApi_XC_Auto_ExternalTuneComponetYpbprGain(void *pInstance, MS_U8 u8VSyncTime, APIXC_AdcGainOffsetSetting *pstADCSetting)
2404 {
2405     APIXC_AdcGainOffsetSetting tempADCSetting, stBackupAdcSetting;
2406     MS_U8 u8ATGStatus;
2407     MS_U16 u16GainDelta = (MDrv_XC_ADC_GetMaximalGainValue(pInstance) + 1) >> 1;
2408     MS_U16 i = 0;
2409     MS_U8 u8FlowFlag = 0; // Add the initial value
2410     MS_BOOL bResult = FALSE;
2411     memset(&tempADCSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
2412     memset(&stBackupAdcSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
2413 
2414     bResult = MDrv_XC_ADC_GetGainSetting(pInstance, &stBackupAdcSetting);
2415     if (bResult)
2416     {
2417         bResult = MDrv_XC_ADC_GetOffsetSetting(pInstance, &stBackupAdcSetting);
2418         if (bResult)
2419         {
2420             // Initial
2421             bResult = MDrv_XC_ADC_InitExternalCalibrationWithFixedOffset(pInstance, INPUT_SOURCE_YPBPR, &tempADCSetting);
2422             if (bResult)
2423             {
2424                 MApi_XC_ADC_AutoSetting(pInstance, ENABLE, TRUE, COMPONENT_AUTO_SW_MODE);
2425 
2426                 while(TRUE)
2427                 {
2428                     u16GainDelta >>= 1;
2429                     if(u16GainDelta == 0x00)
2430                         break;
2431 
2432                     // Update gain.
2433                     _XC_ENTRY(pInstance);
2434                     MDrv_XC_ADC_SetOffsetSetting(pInstance, &tempADCSetting);
2435                     MDrv_XC_ADC_SetGainSetting(pInstance, &tempADCSetting);
2436                     _XC_RETURN(pInstance);
2437                     ///MApi_XC_ADC_AutoSetting(pInstance, ENABLE, TRUE, COMPONENT_AUTO_SW_MODE);
2438                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"RGain %x \n", tempADCSetting.u16RedGain );
2439                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"GGain %x \n", tempADCSetting.u16GreenGain );
2440                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"BGain %x \n", tempADCSetting.u16BlueGain );
2441                     MsOS_DelayTask(u8VSyncTime * 3); // wait stable
2442                     _MApi_XC_Auto_WaitStatusReady(pInstance, E_WAITING_AUTO_GAIN_READY, MAIN_WINDOW);
2443                     u8ATGStatus = MApi_XC_GetAutoGainMaxValueStatus(pInstance, MAIN_WINDOW); // get auto gain status
2444 
2445                     // Red - Pr
2446                     if ( u8ATGStatus & BIT(2) )
2447                     {
2448                         tempADCSetting.u16RedGain -= u16GainDelta;
2449                         u8FlowFlag |= BIT(0);
2450                     }
2451                     else
2452                     {
2453                         tempADCSetting.u16RedGain += u16GainDelta;
2454                         u8FlowFlag |= BIT(1);
2455                     }
2456 
2457                     // Green - Y
2458                     if ( u8ATGStatus & BIT(1) )
2459                     {
2460                         tempADCSetting.u16GreenGain -= u16GainDelta;
2461                         u8FlowFlag |= BIT(2);
2462                     }
2463                     else
2464                     {
2465                         tempADCSetting.u16GreenGain += u16GainDelta;
2466                         u8FlowFlag |= BIT(3);
2467                     }
2468 
2469                     // Blue - Pb
2470                     if (u8ATGStatus & BIT(0) )
2471                     {
2472                         tempADCSetting.u16BlueGain -= u16GainDelta;
2473                         u8FlowFlag |= BIT(4);
2474                     }
2475                     else
2476                     {
2477                         tempADCSetting.u16BlueGain += u16GainDelta;
2478                         u8FlowFlag |= BIT(5);
2479                     }
2480                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"u8FlowFlag %x\n",u8FlowFlag);
2481                 }
2482 
2483                 u8FlowFlag = 0;
2484 
2485                 //Decrease the gain setting and fine tune it
2486                 if(tempADCSetting.u16RedGain > 10)
2487                 {
2488                     tempADCSetting.u16RedGain -= 10;
2489                 }
2490                 else
2491                 {
2492                     tempADCSetting.u16RedGain = 0;
2493                 }
2494 
2495                 if(tempADCSetting.u16GreenGain > 10)
2496                 {
2497                     tempADCSetting.u16GreenGain -= 10;
2498                 }
2499                 else
2500                 {
2501                     tempADCSetting.u16GreenGain = 0;
2502                 }
2503 
2504                 if(tempADCSetting.u16BlueGain > 10)
2505                 {
2506                     tempADCSetting.u16BlueGain -= 10;
2507                 }
2508                 else
2509                 {
2510                     tempADCSetting.u16BlueGain = 0;
2511                 }
2512 
2513                 u16GainDelta =  MDrv_XC_ADC_GetMaximalGainValue(pInstance);
2514                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY," fine tune\n");
2515                 for(i=0; i<u16GainDelta; i++)
2516                 {
2517                     // Update gain.
2518                     _XC_ENTRY(pInstance);
2519                     MDrv_XC_ADC_SetOffsetSetting(pInstance, &tempADCSetting);
2520                     MDrv_XC_ADC_SetGainSetting(pInstance, &tempADCSetting);
2521                     _XC_RETURN(pInstance);
2522 
2523                     //MApi_XC_ADC_AutoSetting(pInstance, ENABLE, TRUE, COMPONENT_AUTO_SW_MODE);
2524                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"RGain %x \n", tempADCSetting.u16RedGain );
2525                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"GGain %x\n", tempADCSetting.u16GreenGain );
2526                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"BGain %x \n", tempADCSetting.u16BlueGain );
2527                     MsOS_DelayTask(u8VSyncTime * 3); // wait stable
2528                     _MApi_XC_Auto_WaitStatusReady(pInstance, E_WAITING_AUTO_GAIN_READY, MAIN_WINDOW);
2529 
2530                     u8ATGStatus = MApi_XC_GetAutoGainMaxValueStatus(pInstance, MAIN_WINDOW); // get auto gain status
2531 
2532                     // Red - Pr
2533                     if ((u8FlowFlag&(BIT(0)|BIT(1))) != (BIT(0)|BIT(1)))
2534                     {
2535                         if(u8ATGStatus & BIT(2))
2536                         {
2537                             u8FlowFlag |= BIT(0);
2538                             if ((u8FlowFlag&BIT(1)) != BIT(1))
2539                             {
2540                                 tempADCSetting.u16RedGain -= AUTO_YUV_GAIN_STEP;
2541                                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"R-\n");
2542                             }
2543                         }
2544                         else
2545                         {
2546                             tempADCSetting.u16RedGain += AUTO_YUV_GAIN_STEP;
2547                             u8FlowFlag |= BIT(1);
2548                             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"R+\n");
2549                         }
2550                     }
2551 
2552                     // Green - Y
2553                     if((u8FlowFlag&(BIT(2)|BIT(3))) != (BIT(2)|BIT(3)))
2554                     {
2555                         if(u8ATGStatus & BIT(1))
2556                         {
2557                             u8FlowFlag |= BIT(2);
2558                             if ((u8FlowFlag&BIT(3)) != BIT(3))
2559                             {
2560                                 tempADCSetting.u16GreenGain -= AUTO_YUV_GAIN_STEP;
2561                                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"G+\n");
2562                             }
2563                         }
2564                         else
2565                         {
2566                             tempADCSetting.u16GreenGain += AUTO_YUV_GAIN_STEP;
2567                             u8FlowFlag |= BIT(3);
2568                             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"G-\n");
2569                         }
2570                     }
2571 
2572                     // Blue - Pb
2573                     if((u8FlowFlag&(BIT(4)|BIT(5))) != (BIT(4)|BIT(5)))
2574                     {
2575                         if(u8ATGStatus & BIT(0) )
2576                         {
2577                             u8FlowFlag |= BIT(4);
2578                             if ((u8FlowFlag&BIT(5)) != BIT(5))
2579                             {
2580                                 tempADCSetting.u16BlueGain -= AUTO_YUV_GAIN_STEP;
2581                                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"B+\n");
2582                             }
2583                         }
2584                         else
2585                         {
2586                             tempADCSetting.u16BlueGain += AUTO_YUV_GAIN_STEP;
2587                             u8FlowFlag |= BIT(5);
2588                             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"B-\n");
2589                         }
2590                     }
2591 
2592                     if (u8FlowFlag == 0x3F || i > AUTO_YUV_MAX_CNT)
2593                     {
2594                         break;
2595                     }
2596                 }
2597 
2598                 // adjust gain after auto-tune
2599                 if (u8FlowFlag == 0x3f)
2600                 {
2601                     // successed
2602                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"success\n");
2603                     pstADCSetting->u16RedGain = tempADCSetting.u16RedGain;
2604                     pstADCSetting->u16GreenGain = tempADCSetting.u16GreenGain;
2605                     pstADCSetting->u16BlueGain = tempADCSetting.u16BlueGain;
2606                     pstADCSetting->u16RedOffset = tempADCSetting.u16RedOffset;
2607                     pstADCSetting->u16GreenOffset = tempADCSetting.u16GreenOffset;
2608                     pstADCSetting->u16BlueOffset = tempADCSetting.u16BlueOffset;
2609                     bResult = TRUE;
2610                 }
2611                 else
2612                 {
2613                     // Restore original setting.
2614                     _XC_ENTRY(pInstance);
2615                     MDrv_XC_ADC_SetOffsetSetting(pInstance, &stBackupAdcSetting);
2616                     MDrv_XC_ADC_SetGainSetting(pInstance, &stBackupAdcSetting);
2617                     _XC_RETURN(pInstance);
2618                     bResult = FALSE;
2619                 }
2620             }
2621             else
2622             {
2623                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"External YPbPr Calibration initial fail !! \n");
2624             }
2625         }
2626         else
2627         {
2628             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"ExternalTuneComponetYpbprGain GetOffsetSetting fail!!\n");
2629         }
2630     }
2631     else
2632     {
2633         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"ExternalTuneComponetYpbprGain GetGainSetting fail!!\n");
2634     }
2635     return bResult;
2636 }
2637 
2638 
2639 #endif
2640 
_MApi_XC_Auto_External_AutoCalibration(void * pInstance,XC_Auto_TuneType enAutoTuneType,APIXC_AdcGainOffsetSetting * pstADCSetting,SCALER_WIN eWindow)2641 static MS_BOOL _MApi_XC_Auto_External_AutoCalibration(void *pInstance, XC_Auto_TuneType enAutoTuneType, APIXC_AdcGainOffsetSetting *pstADCSetting,SCALER_WIN eWindow)
2642 {
2643     MS_BOOL bAutoResult = TRUE;
2644     MS_U8 u8VSyncTime; // VSync time
2645     XC_IP_SYNC_STATUS stXC_Sync_Status = {0, 0, 0};
2646 
2647     _MApi_XC_Auto_SetCalibrartinWindow(pInstance, ENABLE,eWindow);
2648     MApi_XC_AutoGainEnable(pInstance,ENABLE,eWindow);
2649 
2650     _XC_ENTRY(pInstance);
2651     MDrv_XC_GetSyncStatus(pInstance, INPUT_SOURCE_SCART, &stXC_Sync_Status, eWindow);
2652     _XC_RETURN(pInstance);
2653 
2654     //for scart pcmonitor can't give vsync time, so we calculate it ourselves
2655     u8VSyncTime = MApi_XC_CalculateVsyncTime(pInstance, stXC_Sync_Status.u16Vtotal, stXC_Sync_Status.u16Hperiod); // get VSync time
2656 
2657     // auto RGB offset
2658     if(enAutoTuneType & E_XC_AUTO_TUNE_RGB_OFFSET)
2659     {
2660         if (!MDrv_XC_ADC_use_hardware_auto_offset(pInstance, INPUT_SOURCE_VGA))
2661         {
2662             // Run software tune offset
2663             MDrv_XC_ADC_Source_Calibrate(pInstance,  MDrv_XC_ADC_ConvertSrcToADCSrc(pInstance,  INPUT_SOURCE_VGA));
2664             if(_MApi_XC_Auto_ExternalTuneVgaOffset(pInstance, u8VSyncTime, pstADCSetting) == FALSE)
2665             {
2666                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"AutoOffset failed\n");
2667                 //enAutoTuneType = E_XC_AUTO_TUNE_NULL;
2668                 bAutoResult = FALSE;
2669             }
2670         }
2671         else
2672         {
2673             APIXC_AdcGainOffsetSetting stTmpAdcSetting;
2674             memset(&stTmpAdcSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
2675 
2676             // Using HW offset, so use default offset value.
2677             MDrv_XC_ADC_GetDefaultGainOffset(pInstance, INPUT_SOURCE_VGA, &stTmpAdcSetting);
2678             pstADCSetting->u16RedOffset = stTmpAdcSetting.u16RedOffset;
2679             pstADCSetting->u16GreenOffset = stTmpAdcSetting.u16GreenOffset;
2680             pstADCSetting->u16BlueOffset = stTmpAdcSetting.u16BlueOffset;
2681         }
2682     } // auto-tune ADC offset
2683 
2684 
2685     // auto RGB gain
2686     if(enAutoTuneType & E_XC_AUTO_TUNE_RGB_GAIN)
2687     {
2688         MDrv_XC_ADC_Source_Calibrate(pInstance,  MDrv_XC_ADC_ConvertSrcToADCSrc(pInstance,  INPUT_SOURCE_VGA));
2689         if(_MApi_XC_Auto_ExternalTuneVgaRGBGain(pInstance, u8VSyncTime,pstADCSetting,eWindow) == FALSE)
2690         {
2691             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"AutoGain failed\n");
2692             //enAutoTuneType = E_XC_AUTO_TUNE_NULL;
2693             bAutoResult = FALSE;
2694         }
2695     } // auto-tune ADC gain
2696 
2697 
2698     // auto Scart RGB gain
2699     if(enAutoTuneType & E_XC_AUTO_TUNE_SCART_RGB_GAIN)
2700     {
2701         MDrv_XC_ADC_Source_Calibrate(pInstance,  MDrv_XC_ADC_ConvertSrcToADCSrc(pInstance,  INPUT_SOURCE_SCART));
2702         if(_MApi_XC_Auto_ExternalTuneScartRGBGain(pInstance, u8VSyncTime,pstADCSetting,eWindow) == FALSE)
2703         {
2704             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"AutoGain failed\n");
2705             //enAutoTuneType = E_XC_AUTO_TUNE_NULL;
2706             bAutoResult = FALSE;
2707         }
2708     } // auto-tune ADC gain
2709 
2710     if(enAutoTuneType & E_XC_AUTO_TUNE_YUV_COLOR)
2711     {
2712         MDrv_XC_ADC_Source_Calibrate(pInstance,  MDrv_XC_ADC_ConvertSrcToADCSrc(pInstance, INPUT_SOURCE_YPBPR));
2713         if (_MApi_XC_Auto_ExternalTuneComponetYpbprGain(pInstance, u8VSyncTime, pstADCSetting) == FALSE)
2714         {
2715             //enAutoTuneType = E_XC_AUTO_TUNE_NULL;
2716             bAutoResult = FALSE;
2717             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"AutoColorYUV failed\n");
2718         }
2719     } // auto-tune ADC gain
2720 
2721     // disable auto gain function
2722     MApi_XC_AutoGainEnable(pInstance,DISABLE,eWindow);
2723     _MApi_XC_Auto_SetCalibrartinWindow(pInstance, DISABLE,eWindow);
2724 
2725     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Offset R=0x%x,G=0x%x,B=0x%x\n",
2726                    pstADCSetting->u16RedOffset,
2727                    pstADCSetting->u16GreenOffset,
2728                    pstADCSetting->u16BlueOffset);
2729     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Gain R=0x%x,G=0x%x,B=0x%x\n",
2730                    pstADCSetting->u16RedGain,
2731                    pstADCSetting->u16GreenGain,
2732                    pstADCSetting->u16BlueGain);
2733     return bAutoResult;
2734 }
2735 
2736 //
2737 // The reason to wait stable here is some pattern gen such as MSPG-1025D,
2738 // when change timing of RGB, the pattern gen will send out H/V sync first,
2739 // then RGB signal later. (This is not measured by the scope. If pause the program,
2740 // change pattern gen timing, the video come out after around 5 seconds.
2741 // If used MSPG-925FS, change pattern gen timing, the video come out
2742 // within 1 second.) So, we've to wait auto-position H_Start, H_End avaliable and then proceed
2743 // RGB auto function, otherwise, the auto function will be failed because of using the wrong auto-position
2744 // H_Start, H_End.
2745 //
2746 // When waiting the H_Start, H_End to be stable, there are some cases:
2747 // (1) H_Start is 0x7ff, H_Size is 0x00: -> un-stable
2748 // (2) H_Start != 0x7ff and H_Size != 0x00, but H_Start == H_Size: -> un-stable
2749 // (3) H_Start != 0x7ff and H_Size != 0x00, and H_Start != H_Size, but H_Start is only about H_Size -1 or -2: -> un-stable
_MApi_XC_Auto_waitstable(void * pInstance,MS_U8 u8VSyncTime,MS_U16 u16WaitCnt,SCALER_WIN eWindow)2750 static MS_BOOL _MApi_XC_Auto_waitstable(void *pInstance, MS_U8 u8VSyncTime, MS_U16 u16WaitCnt, SCALER_WIN eWindow)
2751 {
2752     MS_U16 i;
2753     MS_U16 u16HStart, u16HEnd;
2754     MS_WINDOW_TYPE sWin;
2755     memset(&sWin, 0, sizeof(MS_WINDOW_TYPE));
2756 
2757     // use a short delay for stable
2758 
2759     for(i=0; i<u16WaitCnt; i++)
2760     {
2761         MsOS_DelayTask(u8VSyncTime);
2762 
2763         _XC_ENTRY(pInstance);
2764         MDrv_XC_GetDEWindow(pInstance, &sWin, eWindow);
2765         _XC_RETURN(pInstance);
2766 
2767         u16HStart = sWin.x;
2768         u16HEnd = sWin.x + sWin.width;
2769 
2770         if(((u16HStart != 0x7FF) && (u16HEnd != 0x000)) ||
2771             (u16HStart < u16HEnd))
2772         {
2773             if(abs(u16HStart - u16HEnd) > 10)
2774             {
2775                 break;
2776             }
2777         }
2778     }
2779 
2780     return (i == u16WaitCnt) ? FALSE : TRUE;
2781 }
2782 
2783 //-------------------------------------------------------------------------------------------------
2784 //  Global Functions
2785 //-------------------------------------------------------------------------------------------------
2786 
MApi_XC_Auto_GainOffset_U2(void * pInstance,XC_Auto_CalibrationType type,XC_Auto_TuneType enAutoTuneType,APIXC_AdcGainOffsetSetting * pstADCSetting,SCALER_WIN eWindow)2787 MS_BOOL MApi_XC_Auto_GainOffset_U2(void* pInstance, XC_Auto_CalibrationType type, XC_Auto_TuneType enAutoTuneType,  APIXC_AdcGainOffsetSetting *pstADCSetting, SCALER_WIN eWindow)
2788 {
2789     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
2790     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
2791     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
2792     MS_BOOL bReturn = FALSE;
2793     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
2794     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
2795 
2796 #ifndef DONT_USE_CMA
2797 #if (XC_SUPPORT_CMA ==TRUE)
2798     MS_BOOL bIsGetCMA = FALSE;
2799     if((eWindow==MAIN_WINDOW)&& (E_XC_SW_CALIBRATION == pXCResourcePrivate->stapiXC_Auto.g_enCalbrationMode))
2800     {
2801         if (  ((gSrcInfo[MAIN_WINDOW].u32PreCMAMemSCMSize[CMA_XC_SELF_MEM]+gSrcInfo[MAIN_WINDOW].u32PreCMAMemFRCMSize[CMA_XC_SELF_MEM]) == 0)
2802             &&((gSrcInfo[MAIN_WINDOW].u32PreCMAMemSCMSize[CMA_XC_COBUFF_MEM]+gSrcInfo[MAIN_WINDOW].u32PreCMAMemFRCMSize[CMA_XC_COBUFF_MEM]) == 0)
2803             )
2804         {
2805             MS_BOOL bIsGetCMA[CMA_XC_MEM_NUM] = {FALSE, };
2806             MS_U32 au32CMAMemSCMSize[CMA_XC_MEM_NUM] = {0, };
2807             MS_U32 au32CMAMemFRCMSize[CMA_XC_MEM_NUM] = {0, };
2808             MS_U32 u32DualMiuMemSize = 0;
2809             MS_U32 u32CMAAddr = 0;
2810             XC_CMA_CLIENT enCmaClient = CMA_XC_MEM_NUM;
2811 
2812             MHal_XC_Get_CMA_UsingCondition(pInstance, bIsGetCMA, au32CMAMemSCMSize, au32CMAMemFRCMSize, &u32DualMiuMemSize, CMA_XC_MEM_NUM, eWindow);
2813 
2814             XC_LOG_TRACE(XC_DBGLEVEL_SETWINDOW,"[%s,%5d][CMA] auto calibration bIsGetCMA[self]=%d bIsGetCMA[cobuff]=%d \n",__func__,__LINE__,bIsGetCMA[CMA_XC_SELF_MEM],bIsGetCMA[CMA_XC_COBUFF_MEM]);
2815             XC_LOG_TRACE(XC_DBGLEVEL_SETWINDOW,"[%s,%5d][CMA] auto calibration au32CMAMemSCMSize[self]=%x au32CMAMemSCMSize[cobuff]=%x \n",__func__,__LINE__,au32CMAMemSCMSize[CMA_XC_SELF_MEM],au32CMAMemSCMSize[CMA_XC_COBUFF_MEM]);
2816 
2817             MHal_XC_CMAPatchClose(pInstance, MAIN_WINDOW);
2818             if (bIsGetCMA[CMA_XC_SELF_MEM] == TRUE)
2819             {
2820                 enCmaClient = CMA_XC_SELF_MEM;
2821                 u32CMAAddr = MHal_XC_Get_CMA_Addr(pInstance, enCmaClient,  au32CMAMemSCMSize[enCmaClient]+au32CMAMemFRCMSize[enCmaClient], eWindow);
2822             }
2823             else if (bIsGetCMA[CMA_XC_COBUFF_MEM] == TRUE)
2824             {
2825                 enCmaClient = CMA_XC_COBUFF_MEM;
2826                 u32CMAAddr = MHal_XC_Get_CMA_Addr(pInstance, enCmaClient,  au32CMAMemSCMSize[enCmaClient]+au32CMAMemFRCMSize[enCmaClient], eWindow);
2827             }
2828             else
2829             {
2830                 printf("\033[35m   [CMA] Function = %s, Line = %d, CMA_POOL_INIT GetMem ERROR!!\033[m\n", __PRETTY_FUNCTION__, __LINE__);
2831                 while(1);
2832             }
2833 
2834             XC_LOG_TRACE(XC_DBGLEVEL_SETWINDOW,"[%s,%5d][CMA] auto calibration u32CMAAddr=%x \n",__func__,__LINE__,u32CMAAddr);
2835 
2836             gSrcInfo[eWindow].u32PreCMAMemSCMSize[enCmaClient] = au32CMAMemSCMSize[enCmaClient];
2837             pXCResourcePrivate->stdrvXC_MVideo_Context.g_XC_InitData.u32Main_FB_Start_Addr = (MS_U32)u32CMAAddr;
2838             pXCResourcePrivate->stdrvXC_MVideo_Context.g_XC_InitData.u32Main_FB_Size = gSrcInfo[eWindow].u32PreCMAMemSCMSize[enCmaClient];//48MB
2839 
2840             // default frame buffer address init
2841             MDrv_XC_SetFrameBufferAddress(pInstance, pXCResourcePrivate->stdrvXC_MVideo_Context.g_XC_InitData.u32Main_FB_Start_Addr,
2842                                           pXCResourcePrivate->stdrvXC_MVideo_Context.g_XC_InitData.u32Main_FB_Size, MAIN_WINDOW);
2843 
2844             Hal_SC_IP_Memory_Write_Request(pInstance, ENABLE, MAIN_WINDOW);
2845 #if (HW_DESIGN_4K2K_VER == 4)
2846             Hal_SC_frcmw_Memory_Write_Request(pInstance, ENABLE, MAIN_WINDOW);
2847 #endif
2848             Hal_SC_set_freezeimg(pInstance, DISABLE, MAIN_WINDOW);
2849         }
2850     }
2851 #endif
2852 #endif
2853     if(type == E_XC_INTERNAL_CALIBRATION)
2854     {
2855         if (E_XC_SW_CALIBRATION == pXCResourcePrivate->stapiXC_Auto.g_enCalbrationMode)
2856         {
2857             MDrv_XC_ADC_EnableHWCalibration(pInstance, DISABLE);
2858             bReturn = ( _MApi_XC_Auto_Internal_AutoCablication(pInstance, enAutoTuneType ,pstADCSetting,eWindow)) ;
2859             _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
2860 #ifndef DONT_USE_CMA
2861 #if (XC_SUPPORT_CMA ==TRUE)
2862             if(eWindow==MAIN_WINDOW && bIsGetCMA)
2863                 MHal_XC_CMAPatch(pInstance, MAIN_WINDOW);
2864 #endif
2865 #endif
2866             return bReturn;
2867         }
2868         else
2869         {
2870             MDrv_XC_ADC_EnableHWCalibration(pInstance, ENABLE);
2871             bReturn = MDrv_XC_Auto_GetHWFixedGainOffset(pInstance, enAutoTuneType, pstADCSetting);
2872             _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
2873             return bReturn;
2874         }
2875     }
2876     else
2877     {
2878         if (E_XC_SW_CALIBRATION == pXCResourcePrivate->stapiXC_Auto.g_enCalbrationMode)
2879         {
2880 #ifndef DONT_USE_CMA
2881 #if (XC_SUPPORT_CMA ==TRUE)
2882             // autonosignal will disable input source when ypbpr source do EXTERNAL CALIBRATION and SW CALIBRATION
2883             if(   eWindow==MAIN_WINDOW
2884                && gSrcInfo[eWindow].bAutoNoSignalEnabled
2885                && IsSrcTypeYPbPr( gSrcInfo[eWindow].enInputSourceType ))
2886             {
2887                 MHal_XC_CMAPatchClose(pInstance, MAIN_WINDOW);
2888                 bNeedDeattachCMAISR = TRUE;
2889             }
2890 #endif
2891 #endif
2892             MDrv_XC_ADC_EnableHWCalibration(pInstance, DISABLE);
2893             bReturn = ( _MApi_XC_Auto_External_AutoCalibration(pInstance, enAutoTuneType ,pstADCSetting,eWindow)) ;
2894             _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
2895             return bReturn;
2896         }
2897         else
2898         {
2899             // Not support HW mode + external calibration now
2900             _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
2901             return FALSE;
2902         }
2903 
2904     }
2905 }
2906 
MApi_XC_Auto_GainOffset(XC_Auto_CalibrationType type,XC_Auto_TuneType enAutoTuneType,APIXC_AdcGainOffsetSetting * pstADCSetting,SCALER_WIN eWindow)2907 MS_BOOL MApi_XC_Auto_GainOffset(XC_Auto_CalibrationType type, XC_Auto_TuneType enAutoTuneType,  APIXC_AdcGainOffsetSetting *pstADCSetting, SCALER_WIN eWindow)
2908 {
2909     if (pu32XCInst == NULL)
2910     {
2911         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
2912         return FALSE;
2913     }
2914     static APIXC_AdcGainOffsetSetting tmp_pstADCSetting;
2915     memcpy(&tmp_pstADCSetting,pstADCSetting,sizeof(APIXC_AdcGainOffsetSetting));
2916     stXC_AUTO_GAINOFFSET XCArgs;
2917     XCArgs.type = type;
2918     XCArgs.enAutoTuneType = enAutoTuneType;
2919     XCArgs.pstADCSetting = &tmp_pstADCSetting;
2920     XCArgs.eWindow = eWindow;
2921     XCArgs.bReturnValue = FALSE;
2922 
2923     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_GAINOFFSET, (void*)&XCArgs) != 0)
2924     {
2925         printf("Obtain XC engine fail\n");
2926         return FALSE;
2927     }
2928     else
2929     {
2930         memcpy(pstADCSetting,&tmp_pstADCSetting,sizeof(APIXC_AdcGainOffsetSetting));
2931         return XCArgs.bReturnValue;
2932     }
2933 }
2934 
2935 
MDrv_XC_Auto_GetHWFixedGainOffset(void * pInstance,XC_Auto_TuneType enAutoTuneType,APIXC_AdcGainOffsetSetting * pstADCSetting)2936 MS_BOOL MDrv_XC_Auto_GetHWFixedGainOffset(void *pInstance, XC_Auto_TuneType enAutoTuneType, APIXC_AdcGainOffsetSetting *pstADCSetting)
2937 {
2938 {
2939     MS_BOOL bResult = FALSE;
2940     INPUT_SOURCE_TYPE_t enInputSrc = INPUT_SOURCE_NONE;
2941     APIXC_AdcGainOffsetSetting tempADCSetting;
2942     memset(&tempADCSetting, 0, sizeof(APIXC_AdcGainOffsetSetting));
2943     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
2944     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
2945     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
2946     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
2947     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"======== Start : HW Calibration Type: %x ======== \n",enAutoTuneType);
2948 
2949     if ((E_XC_AUTO_TUNE_NULL == enAutoTuneType) || (NULL == pstADCSetting))
2950     {
2951         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"======== HW Calibration Error Parameter: enAutoTuneType = %x, (pstADCSetting == NULL) = %u ======== \n",enAutoTuneType, (NULL == pstADCSetting));
2952         return FALSE;
2953     }
2954 
2955     if (MDrv_XC_ADC_CheckHWCalibrationSupport(pInstance))
2956     {
2957         if (enAutoTuneType & E_XC_AUTO_TUNE_RGB_GAIN)
2958         {
2959             enInputSrc = INPUT_SOURCE_VGA;
2960             bResult = TRUE;
2961         }
2962         else if (enAutoTuneType & E_XC_AUTO_TUNE_YUV_COLOR)
2963         {
2964             enInputSrc = INPUT_SOURCE_YPBPR;
2965             bResult = TRUE;
2966         }
2967         else if (enAutoTuneType & E_XC_AUTO_TUNE_SCART_RGB_GAIN)
2968         {
2969             enInputSrc = INPUT_SOURCE_SCART;
2970             bResult = TRUE;
2971         }
2972         else
2973         {
2974             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Unsupported AutoTuneType: %x ======== \n",enAutoTuneType);
2975             bResult = FALSE;
2976         }
2977 
2978         if (bResult)
2979         {
2980             bResult = MDrv_ADC_GetFixedOffset(pInstance, enInputSrc, &tempADCSetting);
2981             if (bResult)
2982             {
2983                 bResult = MDrv_XC_ADC_GetFixedGain(pInstance, enInputSrc, &tempADCSetting);
2984                 if (bResult)
2985                 {
2986                     pstADCSetting->u16RedGain = tempADCSetting.u16RedGain;
2987                     pstADCSetting->u16GreenGain = tempADCSetting.u16GreenGain;
2988                     pstADCSetting->u16BlueGain = tempADCSetting.u16BlueGain;
2989 
2990                     pstADCSetting->u16RedOffset = tempADCSetting.u16RedOffset;
2991                     pstADCSetting->u16GreenOffset = tempADCSetting.u16GreenOffset;
2992                     pstADCSetting->u16BlueOffset = tempADCSetting.u16BlueOffset;
2993                 }
2994                 else
2995                 {
2996                     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"****** get initial gain fail!!! ******\n");
2997                 }
2998             }
2999             else
3000             {
3001                 XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"****** get initial offset fail!!! ******\n");
3002             }
3003         }
3004     }
3005     else
3006     {
3007         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"****** Unsupport HW Calibration ******\n");
3008         bResult = FALSE;
3009     }
3010     return bResult;
3011 }
3012 }
3013 
MApi_XC_Auto_GetHWFixedGainOffset_U2(void * pInstance,XC_Auto_TuneType enAutoTuneType,APIXC_AdcGainOffsetSetting * pstADCSetting)3014 MS_BOOL MApi_XC_Auto_GetHWFixedGainOffset_U2(void* pInstance, XC_Auto_TuneType enAutoTuneType, APIXC_AdcGainOffsetSetting *pstADCSetting)
3015 {
3016     return MDrv_XC_Auto_GetHWFixedGainOffset(pInstance, enAutoTuneType, pstADCSetting);
3017 }
3018 
MApi_XC_Auto_GetHWFixedGainOffset(XC_Auto_TuneType enAutoTuneType,APIXC_AdcGainOffsetSetting * pstADCSetting)3019 MS_BOOL MApi_XC_Auto_GetHWFixedGainOffset(XC_Auto_TuneType enAutoTuneType, APIXC_AdcGainOffsetSetting *pstADCSetting)
3020 {
3021     if (pu32XCInst == NULL)
3022     {
3023         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3024         return FALSE;
3025     }
3026 
3027     stXC_AUTO_GETHWFIXEDGAINOFFSET XCArgs;
3028     XCArgs.enAutoTuneType = enAutoTuneType;
3029     XCArgs.pstADCSetting = pstADCSetting;
3030     XCArgs.bReturnValue = FALSE;
3031 
3032     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_GETHWFIXEDGAINOFFSET, (void*)&XCArgs) != 0)
3033     {
3034         printf("Obtain XC engine fail\n");
3035         return FALSE;
3036     }
3037     else
3038     {
3039         return XCArgs.bReturnValue;
3040     }
3041 }
3042 
3043 
3044 //*************************************************************************
3045 //Function name: MApi_XC_Auto_Geometry
3046 //Passing parameter:
3047 //  enAutoTuneType: Auto function select
3048 //  ActiveInfo: Current PC mode setting
3049 //  StandardInfo: Standard mode. (This is singal information of stardard)
3050 //Return parameter:
3051 //  MS_BOOL: Success status. (If faile, return FALSE.)
3052 //Description: Auto-tune for PC mode
3053 //*************************************************************************
MApi_XC_Auto_Geometry_U2(void * pInstance,XC_Auto_TuneType enAutoTuneType,XC_Auto_Signal_Info * ActiveInfo,XC_Auto_Signal_Info * StandardInfo,SCALER_WIN eWindow)3054 MS_BOOL MApi_XC_Auto_Geometry_U2(void* pInstance, XC_Auto_TuneType enAutoTuneType, XC_Auto_Signal_Info *ActiveInfo, XC_Auto_Signal_Info *StandardInfo , SCALER_WIN eWindow)
3055 {
3056     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
3057     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
3058     XC_Auto_Signal_Info_Ex ActiveInfoEx, StandardInfoEx;
3059     MS_BOOL bResult;
3060 
3061     ActiveInfoEx.u16HorizontalStart = ActiveInfo->u16HorizontalStart;
3062     ActiveInfoEx.u16VerticalStart = ActiveInfo->u16VerticalStart;
3063     ActiveInfoEx.u16HorizontalTotal = ActiveInfo->u16HorizontalTotal;
3064     ActiveInfoEx.u16HResolution = ActiveInfo->u16HResolution;
3065     ActiveInfoEx.u16Phase = (MS_U16)ActiveInfo->u8Phase;
3066     ActiveInfoEx.u16Version = 0;
3067 
3068     StandardInfoEx.u16HorizontalStart = StandardInfo->u16HorizontalStart;
3069     StandardInfoEx.u16VerticalStart = StandardInfo->u16VerticalStart;
3070     StandardInfoEx.u16HorizontalTotal = StandardInfo->u16HorizontalTotal;
3071     StandardInfoEx.u16HResolution = StandardInfo->u16HResolution;
3072     StandardInfoEx.u16Phase = (MS_U16)StandardInfo->u8Phase;
3073     StandardInfoEx.u16Version= 0;
3074 
3075     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
3076     bResult = MDrv_XC_Auto_Geometry_Ex(pInstance,enAutoTuneType, &ActiveInfoEx, &StandardInfoEx , eWindow);
3077     _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3078 
3079     ActiveInfo->u16HorizontalStart = ActiveInfoEx.u16HorizontalStart;
3080     ActiveInfo->u16VerticalStart = ActiveInfoEx.u16VerticalStart;
3081     ActiveInfo->u16HorizontalTotal = ActiveInfoEx.u16HorizontalTotal;
3082     ActiveInfo->u16HResolution = ActiveInfoEx.u16HResolution;
3083 /*obsolete u8Phase*/    ActiveInfo->u8Phase = (MS_U8)ActiveInfoEx.u16Phase;
3084 
3085     return bResult;
3086 }
3087 
MApi_XC_Auto_Geometry(XC_Auto_TuneType enAutoTuneType,XC_Auto_Signal_Info * ActiveInfo,XC_Auto_Signal_Info * StandardInfo,SCALER_WIN eWindow)3088 MS_BOOL MApi_XC_Auto_Geometry(XC_Auto_TuneType enAutoTuneType, XC_Auto_Signal_Info *ActiveInfo, XC_Auto_Signal_Info *StandardInfo , SCALER_WIN eWindow)
3089 {
3090     if (pu32XCInst == NULL)
3091     {
3092         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3093         return FALSE;
3094     }
3095 
3096     stXC_AUTO_GEOMETRY XCArgs;
3097     XCArgs.enAutoTuneType = enAutoTuneType;
3098     XCArgs.ActiveInfo = ActiveInfo;
3099     XCArgs.StandardInfo = StandardInfo;
3100     XCArgs.eWindow = eWindow;
3101     XCArgs.bReturnValue = FALSE;
3102 
3103     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_GEOMETRY, (void*)&XCArgs) != 0)
3104     {
3105         printf("Obtain XC engine fail\n");
3106         return FALSE;
3107     }
3108     else
3109     {
3110         return XCArgs.bReturnValue;
3111     }
3112 }
3113 
3114 //*************************************************************************
3115 //Function name: MApi_XC_Auto_Geometry_Ex
3116 //Passing parameter:
3117 //  enAutoTuneType: Auto function select
3118 //  ActiveInfo: Current PC mode setting
3119 //  StandardInfo: Standard mode. (This is singal information of stardard)
3120 //Return parameter:
3121 //  MS_BOOL: Success status. (If faile, return FALSE.)
3122 //Description: Auto-tune for PC mode
3123 //*************************************************************************
MDrv_XC_Auto_Geometry_Ex(void * pInstance,XC_Auto_TuneType enAutoTuneType,XC_Auto_Signal_Info_Ex * ActiveInfo,XC_Auto_Signal_Info_Ex * StandardInfo,SCALER_WIN eWindow)3124 MS_BOOL MDrv_XC_Auto_Geometry_Ex(void *pInstance, XC_Auto_TuneType enAutoTuneType, XC_Auto_Signal_Info_Ex *ActiveInfo, XC_Auto_Signal_Info_Ex *StandardInfo , SCALER_WIN eWindow)
3125 {
3126 {
3127     MS_U8 u8VSyncTime; // VSync time
3128     MS_BOOL bAutoResult = TRUE;
3129     MS_U16 u16OldClk = MDrv_XC_ADC_GetPcClock(pInstance);
3130     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
3131     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
3132     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
3133     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
3134     // Reset flag. bHaltAutoGeometry should be update during auto geometry
3135     pXCResourcePrivate->stapiXC_Auto.bHaltAutoGeometry = FALSE;
3136 
3137     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"\n======== Auto Tune Type : 0x%x, Htt %u->%u ======== \n",enAutoTuneType, u16OldClk, ActiveInfo->u16HorizontalTotal);
3138     if( u16OldClk != ActiveInfo->u16HorizontalTotal )
3139     {
3140         MS_U16  u16OrgDefaultHtotal, u16OrgDefaultPhase;
3141         MS_BOOL bOrgHDuplicate;
3142         //Save original timing info first
3143         bOrgHDuplicate = gSrcInfo[eWindow].bHDuplicate;
3144         u16OrgDefaultHtotal = gSrcInfo[eWindow].u16DefaultHtotal;
3145         u16OrgDefaultPhase  = gSrcInfo[eWindow].u16DefaultPhase;
3146 
3147         //Use new timing info to tune
3148         gSrcInfo[eWindow].bHDuplicate = FALSE;
3149         gSrcInfo[eWindow].u16DefaultPhase = ActiveInfo->u16Phase;
3150         gSrcInfo[eWindow].u16DefaultHtotal = ActiveInfo->u16HorizontalTotal;
3151         PQ_ADC_SAMPLING_INFO stPQADCSamplingInfo;
3152         memset(&stPQADCSamplingInfo,0,sizeof(PQ_ADC_SAMPLING_INFO));
3153         if ( IsSrcTypeVga(gSrcInfo[eWindow].enInputSourceType) || IsSrcTypeYPbPr(gSrcInfo[eWindow].enInputSourceType) )
3154         {
3155             if(gSrcInfo[eWindow].bHDuplicate)
3156             {
3157                 MDrv_XC_ADC_GetPQADCSamplingInfo(pInstance, gSrcInfo[eWindow].enInputSourceType, &gSrcInfo[eWindow], &stPQADCSamplingInfo, eWindow);
3158             }
3159         }
3160         MDrv_XC_ADC_SetMode(pInstance, gSrcInfo[eWindow].enInputSourceType, &gSrcInfo[eWindow], &stPQADCSamplingInfo, eWindow);
3161 
3162         //Restore original timing info
3163         gSrcInfo[eWindow].bHDuplicate = bOrgHDuplicate;
3164         gSrcInfo[eWindow].u16DefaultHtotal = u16OrgDefaultHtotal ;
3165         gSrcInfo[eWindow].u16DefaultPhase = u16OrgDefaultPhase;
3166     }
3167     MApi_XC_AutoGainEnable(pInstance,ENABLE, eWindow);
3168 
3169     u8VSyncTime = MDrv_XC_PCMonitor_GetVSyncTime(pInstance, eWindow); // get VSync time
3170 
3171     // Should wait stable to proceed auto
3172     _MApi_XC_Auto_waitstable(pInstance, u8VSyncTime, ActiveInfo->u16HorizontalTotal*4/10, eWindow); // use u16HorizontalTotal as 2nd para is just to estimate
3173 
3174     #if (!FAST_AUTO_TUNE)
3175     // auto position valid data theshold
3176     if(enAutoTuneType & E_XC_AUTO_TUNE_VALID_DATA)
3177     {
3178         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Start to tune Valid data.\n");
3179 
3180         if(_MApi_XC_Auto_SetValidData(pInstance, u8VSyncTime, eWindow) == FALSE)
3181         {
3182             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"AutoValidData failed\n");
3183 
3184             bAutoResult = FALSE;
3185         }
3186         else // fixed valid data
3187         {
3188             MDrv_XC_SetValidDataThreshold(pInstance, 0x04, eWindow);
3189         }
3190     }
3191     #else
3192 
3193     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Force set valid data.\n");
3194 
3195     MDrv_XC_SetValidDataThreshold(pInstance, pXCResourcePrivate->stapiXC_Auto._u8ThresholdValue, eWindow);
3196 
3197     #endif
3198 
3199     ////////////////Stop Geometry checker/////////////////////////////
3200 if (pXCResourcePrivate->stapiXC_Auto.bHaltAutoGeometry)
3201     {
3202         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Halt auto geometry\n");
3203         pXCResourcePrivate->stapiXC_Auto.bHaltAutoGeometry = FALSE;
3204         return FALSE;
3205     }
3206 
3207     // Auto Tune H total
3208     if(enAutoTuneType & E_XC_AUTO_TUNE_FREQ)
3209     {
3210         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Start to tune HTotal\n");
3211 
3212         if(_MApi_XC_Auto_TuneHTotal(pInstance, u8VSyncTime, ActiveInfo, StandardInfo, eWindow) == FALSE)
3213         {
3214             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Tune HTotal fail!!\n");
3215 
3216             bAutoResult = FALSE;
3217         }
3218         else
3219         {
3220             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Tune HTotal success!!\n");
3221         }
3222     }
3223 
3224     ////////////////Stop Geometry checker/////////////////////////////
3225     if (pXCResourcePrivate->stapiXC_Auto.bHaltAutoGeometry)
3226     {
3227         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Halt auto geometry\n");
3228         pXCResourcePrivate->stapiXC_Auto.bHaltAutoGeometry = FALSE;
3229         return FALSE;
3230     }
3231 
3232     // auto phase
3233     if(enAutoTuneType & E_XC_AUTO_TUNE_PHASE)
3234     {
3235         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Start to tune phase\n");
3236 
3237         if(_MApi_XC_Auto_TunePhase(pInstance, u8VSyncTime, ActiveInfo, eWindow) == FALSE)
3238         {
3239             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Tune phase fail!!\n");
3240 
3241             bAutoResult = FALSE;
3242         }
3243         else
3244         {
3245             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Tune phase success!!\n");
3246         }
3247     }
3248 
3249     ////////////////Stop Geometry checker/////////////////////////////
3250     if (pXCResourcePrivate->stapiXC_Auto.bHaltAutoGeometry)
3251     {
3252         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Halt auto geometry\n");
3253         pXCResourcePrivate->stapiXC_Auto.bHaltAutoGeometry = FALSE;
3254         return FALSE;
3255     }
3256 
3257     // auto position
3258     if(enAutoTuneType & E_XC_AUTO_TUNE_POSITION)
3259     {
3260         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Start to tune position\n");
3261 
3262         if(_MApi_XC_Auto_TunePosition(pInstance, u8VSyncTime, ActiveInfo, StandardInfo, eWindow) == FALSE)
3263         {
3264             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Tune position fail!!\n");
3265             //enAutoTuneType = E_XC_AUTO_TUNE_NULL;
3266             bAutoResult = FALSE;
3267         }
3268         else
3269         {
3270             XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Tune position success!!\n");
3271         }
3272     }
3273 
3274     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Result: %d \n",bAutoResult);
3275 
3276     return    bAutoResult;
3277 }
3278 }
3279 
MApi_XC_Auto_Geometry_Ex_U2(void * pInstance,XC_Auto_TuneType enAutoTuneType,XC_Auto_Signal_Info_Ex * ActiveInfo,XC_Auto_Signal_Info_Ex * StandardInfo,SCALER_WIN eWindow)3280 MS_BOOL MApi_XC_Auto_Geometry_Ex_U2(void* pInstance, XC_Auto_TuneType enAutoTuneType, XC_Auto_Signal_Info_Ex *ActiveInfo, XC_Auto_Signal_Info_Ex *StandardInfo , SCALER_WIN eWindow)
3281 {
3282     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
3283     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
3284     MS_BOOL bReturn = FALSE;
3285     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
3286     bReturn = MDrv_XC_Auto_Geometry_Ex(pInstance,enAutoTuneType, ActiveInfo, StandardInfo , eWindow);
3287     _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3288     return bReturn;
3289 }
3290 
MApi_XC_Auto_Geometry_Ex(XC_Auto_TuneType enAutoTuneType,XC_Auto_Signal_Info_Ex * ActiveInfo,XC_Auto_Signal_Info_Ex * StandardInfo,SCALER_WIN eWindow)3291 MS_BOOL MApi_XC_Auto_Geometry_Ex(XC_Auto_TuneType enAutoTuneType, XC_Auto_Signal_Info_Ex *ActiveInfo, XC_Auto_Signal_Info_Ex *StandardInfo , SCALER_WIN eWindow)
3292 {
3293     if (pu32XCInst == NULL)
3294     {
3295         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3296         return FALSE;
3297     }
3298 
3299     stXC_AUTO_GEOMETRY_EX XCArgs;
3300     XCArgs.enAutoTuneType = enAutoTuneType;
3301     XCArgs.ActiveInfo = ActiveInfo;
3302     XCArgs.StandardInfo = StandardInfo;
3303     XCArgs.eWindow = eWindow;
3304     XCArgs.bReturnValue = FALSE;
3305 
3306     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_GEOMETRY_EX, (void*)&XCArgs) != 0)
3307     {
3308         printf("Obtain XC engine fail\n");
3309         return FALSE;
3310     }
3311     else
3312     {
3313         return XCArgs.bReturnValue;
3314     }
3315 }
3316 
3317 
3318 // Set flag as true to halt auto geometry
MApi_XC_Auto_StopAutoGeometry_U2(void * pInstance)3319 MS_BOOL MApi_XC_Auto_StopAutoGeometry_U2(void* pInstance)
3320 {
3321     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
3322     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
3323     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
3324     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
3325     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
3326     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Stop auto geometry.\n");
3327     pXCResourcePrivate->stapiXC_Auto.bHaltAutoGeometry = TRUE;
3328     _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3329     return TRUE;
3330 }
3331 
MApi_XC_Auto_StopAutoGeometry(void)3332 MS_BOOL MApi_XC_Auto_StopAutoGeometry(void)
3333 {
3334     if (pu32XCInst == NULL)
3335     {
3336         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3337         return FALSE;
3338     }
3339 
3340     stXC_AUTO_STOPAUTOGEOMETRY XCArgs;
3341     XCArgs.bReturnValue = FALSE;
3342 
3343     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_STOPAUTOGEOMETRY, (void*)&XCArgs) != 0)
3344     {
3345         printf("Obtain XC engine fail\n");
3346         return FALSE;
3347     }
3348     else
3349     {
3350         return XCArgs.bReturnValue;
3351     }
3352 }
3353 
3354 
3355 /******************************************************************************/
3356 /// -This function will recalibration ADC offset, must be called when mode change.
3357 /// @param bEnable \b IN:
3358 /// - 0: Disable offset recalibration
3359 /// - 1: Enable offset recalibration
3360 /// @param bIsYPbPrFlag \b IN: to tell if YPbPr in
3361 /// - 0: Vga mode
3362 /// - 1: YPbPr mode
3363 /******************************************************************************/
MApi_XC_Auto_AutoOffset_U2(void * pInstance,MS_BOOL bEnable,MS_BOOL bIsYPbPrFlag)3364 void MApi_XC_Auto_AutoOffset_U2(void* pInstance, MS_BOOL bEnable, MS_BOOL bIsYPbPrFlag)
3365 {
3366     MApi_XC_ADC_AutoSetting(pInstance, bEnable, bIsYPbPrFlag, COMPONENT_AUTO_SW_MODE);
3367 }
3368 
MApi_XC_Auto_AutoOffset(MS_BOOL bEnable,MS_BOOL bIsYPbPrFlag)3369 void MApi_XC_Auto_AutoOffset(MS_BOOL bEnable, MS_BOOL bIsYPbPrFlag)
3370 {
3371     if (pu32XCInst == NULL)
3372     {
3373         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3374         return;
3375     }
3376 
3377     stXC_AUTO_AUTOOFFSET XCArgs;
3378     XCArgs.bEnable = bEnable;
3379     XCArgs.bIsYPbPrFlag = bIsYPbPrFlag;
3380 
3381     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_AUTOOFFSET, (void*)&XCArgs) != 0)
3382     {
3383         printf("Obtain XC engine fail\n");
3384         return;
3385     }
3386     else
3387     {
3388         return;
3389     }
3390 }
3391 
MApi_XC_Auto_DetectWidth_U2(void * pInstance,XC_Auto_Signal_Info_Ex * pSignalInfo,SCALER_WIN eWindow)3392 MS_BOOL MApi_XC_Auto_DetectWidth_U2(void* pInstance, XC_Auto_Signal_Info_Ex *pSignalInfo , SCALER_WIN eWindow)
3393 {
3394     MS_U8 u8VSyncTime ; // VSync time
3395     MS_BOOL bAutoResult = TRUE;
3396     MS_U16 u16ActualWidth = 0xFFFF;
3397     MS_U16 u16OldClk = MDrv_XC_ADC_GetPcClock(pInstance);
3398     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
3399     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
3400     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
3401     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"\n======== Auto DetectWidth : eWindow=%u, Htt %u->%u ======== \n",eWindow, u16OldClk, pSignalInfo->u16HorizontalTotal);
3402     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
3403     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
3404     if( u16OldClk != pSignalInfo->u16HorizontalTotal )
3405     {
3406         MS_U16  u16OrgDefaultHtotal, u16OrgDefaultPhase;
3407         MS_BOOL bOrgHDuplicate;
3408         //Save original timing info first
3409 
3410         bOrgHDuplicate = gSrcInfo[eWindow].bHDuplicate;
3411         u16OrgDefaultHtotal = gSrcInfo[eWindow].u16DefaultHtotal;
3412         u16OrgDefaultPhase  = gSrcInfo[eWindow].u16DefaultPhase;
3413 
3414         //Use new timing info to tune
3415         gSrcInfo[eWindow].bHDuplicate = FALSE;
3416         gSrcInfo[eWindow].u16DefaultPhase = pSignalInfo->u16Phase;
3417         gSrcInfo[eWindow].u16DefaultHtotal = pSignalInfo->u16HorizontalTotal;
3418         PQ_ADC_SAMPLING_INFO stPQADCSamplingInfo;
3419         memset(&stPQADCSamplingInfo,0,sizeof(PQ_ADC_SAMPLING_INFO));
3420         if ( IsSrcTypeVga(gSrcInfo[eWindow].enInputSourceType) || IsSrcTypeYPbPr(gSrcInfo[eWindow].enInputSourceType) )
3421         {
3422             if(gSrcInfo[eWindow].bHDuplicate)
3423             {
3424                 _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3425                 MDrv_XC_ADC_GetPQADCSamplingInfo(pInstance, gSrcInfo[eWindow].enInputSourceType, &gSrcInfo[eWindow], &stPQADCSamplingInfo, eWindow);
3426                 _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR);
3427             }
3428         }
3429         MDrv_XC_ADC_SetMode(pInstance, gSrcInfo[eWindow].enInputSourceType, &gSrcInfo[eWindow], &stPQADCSamplingInfo, eWindow);
3430 
3431         //Restore original timing info
3432         gSrcInfo[eWindow].bHDuplicate = bOrgHDuplicate;
3433         gSrcInfo[eWindow].u16DefaultHtotal = u16OrgDefaultHtotal ;
3434         gSrcInfo[eWindow].u16DefaultPhase = u16OrgDefaultPhase;
3435 
3436     }
3437     MApi_XC_AutoGainEnable(pInstance, ENABLE, eWindow);
3438     u8VSyncTime = MDrv_XC_PCMonitor_GetVSyncTime(pInstance, eWindow); // get VSync time
3439     // Should wait stable to proceed auto
3440     _MApi_XC_Auto_waitstable(pInstance, u8VSyncTime, pSignalInfo->u16HorizontalTotal*4/10, eWindow); // use u16HorizontalTotal as 2nd para is just to estimate
3441 #if (!FAST_AUTO_TUNE)
3442     // auto position valid data theshold
3443     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Auto DetectWidth: Start to tune Valid data.\n");
3444     if(_MApi_XC_Auto_SetValidData(pInstance, u8VSyncTime, eWindow) == FALSE)
3445     {
3446         // auto position valid data theshold
3447         XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Auto DetectWidth: Start to tune Valid data.\n");
3448         bAutoResult = FALSE;
3449     }
3450     else // fixed valid data
3451     {
3452         MDrv_XC_SetValidDataThreshold(pInstance, 0x04, eWindow);
3453         u16ActualWidth = _MApi_XC_Auto_GetActualWidth(pInstance, u8VSyncTime, eWindow);
3454     }
3455 #else
3456     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Auto DetectWidth: Force set valid data.\n");
3457     MDrv_XC_SetValidDataThreshold(pInstance, pXCResourcePrivate->stapiXC_Auto._u8ThresholdValue, eWindow);
3458     u16ActualWidth = _MApi_XC_Auto_GetActualWidth(pInstance, u8VSyncTime, eWindow);
3459 #endif
3460     pSignalInfo->u16HResolution = u16ActualWidth; //Set to invalid resolution
3461     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"Auto DetectWidth: bResult=%u, DetectWidth=%u.\n", bAutoResult, u16ActualWidth);
3462     _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3463     return bAutoResult;
3464 }
3465 
MApi_XC_Auto_DetectWidth(XC_Auto_Signal_Info_Ex * pSignalInfo,SCALER_WIN eWindow)3466 MS_BOOL MApi_XC_Auto_DetectWidth(XC_Auto_Signal_Info_Ex *pSignalInfo , SCALER_WIN eWindow)
3467 {
3468     if (pu32XCInst == NULL)
3469     {
3470         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3471         return FALSE;
3472     }
3473 
3474     stXC_AUTO_DETECTWIDTH XCArgs;
3475     XCArgs.pSignalInfo = pSignalInfo;
3476     XCArgs.eWindow = eWindow;
3477     XCArgs.bReturnValue = FALSE;
3478 
3479     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_DETECTWIDTH, (void*)&XCArgs) != 0)
3480     {
3481         printf("Obtain XC engine fail\n");
3482         return FALSE;
3483     }
3484     else
3485     {
3486         return XCArgs.bReturnValue;
3487     }
3488 }
3489 
3490 
MApi_XC_Auto_SetCalibrationMode_U2(void * pInstance,XC_Auto_CalibrationMode eMode)3491 MS_BOOL MApi_XC_Auto_SetCalibrationMode_U2(void* pInstance, XC_Auto_CalibrationMode eMode)
3492 {
3493     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
3494     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
3495     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
3496 
3497     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
3498     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
3499     if (E_XC_SW_CALIBRATION == eMode)
3500     {
3501         pXCResourcePrivate->stapiXC_Auto.g_enCalbrationMode = eMode;
3502         _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3503         return TRUE;
3504     }
3505     else if ((E_XC_HW_CALIBRATION == eMode) && MDrv_XC_ADC_CheckHWCalibrationSupport(pInstance))
3506     {
3507         pXCResourcePrivate->stapiXC_Auto.g_enCalbrationMode = eMode;
3508         _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3509         return TRUE;
3510     }
3511     else
3512     {
3513         pXCResourcePrivate->stapiXC_Auto.g_enCalbrationMode = E_XC_SW_CALIBRATION;
3514         _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3515         return FALSE;
3516     }
3517 }
3518 
MApi_XC_Auto_SetCalibrationMode(XC_Auto_CalibrationMode eMode)3519 MS_BOOL MApi_XC_Auto_SetCalibrationMode(XC_Auto_CalibrationMode eMode)
3520 {
3521     if (pu32XCInst == NULL)
3522     {
3523         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3524         return FALSE;
3525     }
3526 
3527     stXC_AUTO_SETCALIBRATIONMODE XCArgs;
3528     XCArgs.eMode = eMode;
3529     XCArgs.bReturnValue = FALSE;
3530 
3531     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_SETCALIBRATIONMODE, (void*)&XCArgs) != 0)
3532     {
3533         printf("Obtain XC engine fail\n");
3534         return FALSE;
3535     }
3536     else
3537     {
3538         return XCArgs.bReturnValue;
3539     }
3540 }
3541 
MApi_XC_Auto_GetCalibrationMode_U2(void * pInstance,XC_Auto_CalibrationMode * eMode)3542 void MApi_XC_Auto_GetCalibrationMode_U2(void* pInstance, XC_Auto_CalibrationMode *eMode)
3543 {
3544     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
3545     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
3546     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
3547 
3548     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
3549     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
3550     *eMode = pXCResourcePrivate->stapiXC_Auto.g_enCalbrationMode;
3551     _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3552 }
3553 
MApi_XC_Auto_GetCalibrationMode(XC_Auto_CalibrationMode * eMode)3554 void MApi_XC_Auto_GetCalibrationMode(XC_Auto_CalibrationMode *eMode)
3555 {
3556     if (pu32XCInst == NULL)
3557     {
3558         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3559         return;
3560     }
3561 
3562     stXC_AUTO_GETCALIBRATIONMODE XCArgs;
3563     XCArgs.eMode = eMode;
3564 
3565     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_GETCALIBRATIONMODE, (void*)&XCArgs) != 0)
3566     {
3567         printf("Obtain XC engine fail\n");
3568         return;
3569     }
3570     else
3571     {
3572         return;
3573     }
3574 }
3575 
3576 //-------------------------------------------------------------------------------------------------
3577 /// get auto position window with the corresponding valid data threshold
3578 /// @param  u8ValidData                 \b IN: valid data threshold
3579 /// @param  eWindow                     \b IN: which window we are going to get
3580 /// @param  pstAutoPositionWindow       \b OUT: auto position window parameters
3581 /// @return MS_BOOL     TRUE: auto position window is valid     FALSE: auto position window is invalid
3582 //-------------------------------------------------------------------------------------------------
MApi_XC_GetAutoPositionWindow_U2(void * pInstance,MS_U8 u8ValidData,SCALER_WIN eWindow,MS_WINDOW_TYPE * pstAutoPositionWindow)3583 MS_BOOL MApi_XC_GetAutoPositionWindow_U2(void* pInstance, MS_U8 u8ValidData, SCALER_WIN eWindow, MS_WINDOW_TYPE *pstAutoPositionWindow)
3584 {
3585     MS_U16 u16VStart = 0, u16HStart = 0, u16VEnd = 0, u16HEnd = 0;
3586     MS_U16 u16Count = MAX_AUTO_POSITION_WAIT_READY_TIME;
3587     MS_BOOL bReady = FALSE;
3588     MS_WINDOW_TYPE stCapWin;
3589     memset(&stCapWin, 0, sizeof(MS_WINDOW_TYPE));
3590     MS_U8 u8VSyncTime = 0;
3591     MS_BOOL bHdmiDeMode = FALSE;
3592     MS_BOOL bDEModeGlitchProtectEnabled = FALSE;
3593     MS_U8 u8PostGlitchRemoval = 0;
3594     INPUT_SOURCE_TYPE_t enInputSourceType;
3595     XC_INSTANCE_PRIVATE *psXCInstPri = NULL;
3596     UtopiaInstanceGetPrivate(pInstance, (void**)&psXCInstPri);
3597     XC_RESOURCE_PRIVATE* pXCResourcePrivate = NULL;
3598 
3599     _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
3600     UtopiaResourceGetPrivate(g_pXCResource[_XC_SELECT_INTERNAL_VARIABLE(psXCInstPri->u32DeviceID)],(void**)(&pXCResourcePrivate));
3601     enInputSourceType = pXCResourcePrivate->stdrvXC_MVideo._SCShared.StatusInfo[eWindow].enInputSourceType;
3602 
3603     if(IsSrcTypeHDMI(enInputSourceType) && (MDrv_XC_GetHdmiSyncMode(pInstance) == HDMI_SYNC_DE))
3604     {
3605         bHdmiDeMode = TRUE;
3606         u8VSyncTime = MDrv_XC_PCMonitor_GetVSyncTime(pInstance, eWindow);
3607     }
3608     _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3609 
3610     if (bHdmiDeMode)
3611     {
3612         MDrv_XC_SetAutoPositionForcePixelMode(pInstance, ENABLE, eWindow);
3613     }
3614 
3615     _XC_ENTRY(pInstance);
3616     MDrv_XC_GetCaptureWindow(pInstance, &stCapWin, eWindow);
3617     _XC_RETURN(pInstance);
3618 
3619     MApi_XC_AutoRangeEnable(pInstance, DISABLE, eWindow);
3620     MApi_XC_SetAutoRangeWindow(pInstance, stCapWin.y, stCapWin.x, stCapWin.height, stCapWin.width, eWindow);
3621     MApi_XC_AutoRangeEnable(pInstance, ENABLE, eWindow);
3622 
3623     MApi_XC_AutoPositionEnable(pInstance, DISABLE, eWindow);
3624     MDrv_XC_SetValidDataThreshold(pInstance, u8ValidData, eWindow);
3625     MApi_XC_AutoPositionEnable(pInstance, ENABLE, eWindow);
3626 
3627     while(1)
3628     {
3629         bReady = MApi_XC_IsAutoPositionResultReady(pInstance, eWindow);
3630         if (bReady == TRUE)
3631         {
3632             break;
3633         }
3634         if (bReady == FALSE && u16Count == 0)
3635         {
3636             MApi_XC_AutoRangeEnable(pInstance, DISABLE, eWindow);
3637             return FALSE;
3638         }
3639         MsOS_DelayTask(1);
3640         u16Count--;
3641     }
3642 
3643     if(bHdmiDeMode)
3644     {
3645         MsOS_DelayTask(4 * u8VSyncTime);
3646     }
3647 
3648     u16VStart = MApi_XC_SetAutoPositionVstart(pInstance, eWindow);
3649     u16HStart = MApi_XC_SetAutoPositionHstart(pInstance, eWindow);
3650     u16VEnd = MApi_XC_SetAutoPositionVend(pInstance, eWindow);
3651     u16HEnd = MApi_XC_SetAutoPositionHend(pInstance, eWindow);
3652 
3653     if (bHdmiDeMode)
3654     {
3655         bDEModeGlitchProtectEnabled = MDrv_SC_ip_get_DE_mode_glitch_protect_enabled(pInstance, eWindow);
3656         if (bDEModeGlitchProtectEnabled)
3657         {
3658             u8PostGlitchRemoval = MDrv_SC_ip_get_post_glitch_removal(pInstance, eWindow);
3659         }
3660         else
3661         {
3662             u8PostGlitchRemoval = 0;
3663         }
3664 
3665         u16HStart += u8PostGlitchRemoval * 8;
3666         u16HEnd += u8PostGlitchRemoval * 8;
3667     }
3668 
3669     MApi_XC_AutoRangeEnable(pInstance, DISABLE, eWindow);
3670 
3671     if (bHdmiDeMode)
3672     {
3673         MDrv_XC_SetAutoPositionForcePixelMode(pInstance, DISABLE, eWindow);
3674         _XC_SEMAPHORE_ENTRY(pInstance,E_XC_ID_VAR)
3675         _XC_ENTRY(pInstance);
3676         while (MDrv_XC_PCMonitor_InvalidTimingDetect(pInstance, TRUE, eWindow));
3677         _XC_RETURN(pInstance);
3678         _XC_SEMAPHORE_RETURN(pInstance,E_XC_ID_VAR);
3679     }
3680 
3681     if ((u16VEnd < u16VStart) || (u16HEnd < u16HStart))
3682     {
3683         return FALSE;
3684     }
3685 
3686     pstAutoPositionWindow->x = u16HStart;
3687     pstAutoPositionWindow->y = u16VStart;
3688     pstAutoPositionWindow->width = u16HEnd - u16HStart + 1;
3689     pstAutoPositionWindow->height = u16VEnd - u16VStart + 1;
3690 
3691     return TRUE;
3692 }
3693 
MApi_XC_GetAutoPositionWindow(MS_U8 u8ValidData,SCALER_WIN eWindow,MS_WINDOW_TYPE * pstAutoPositionWindow)3694 MS_BOOL MApi_XC_GetAutoPositionWindow(MS_U8 u8ValidData, SCALER_WIN eWindow, MS_WINDOW_TYPE *pstAutoPositionWindow)
3695 {
3696     if (pu32XCInst == NULL)
3697     {
3698         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3699         return FALSE;
3700     }
3701 
3702     stXC_GET_AUTO_POSITION_WINDOW XCArgs;
3703     XCArgs.u8ValidData = u8ValidData;
3704     XCArgs.eWindow = eWindow;
3705     XCArgs.pstAutoPositionWindow = pstAutoPositionWindow;
3706     XCArgs.bReturnValue = FALSE;
3707 
3708     if(UtopiaIoctl(pu32XCInst, E_XC_CMD_GET_AUTO_POSITION_WINDOW, (void*)&XCArgs) != UTOPIA_STATUS_SUCCESS)
3709     {
3710         printf("Obtain XC engine fail\n");
3711         return FALSE;
3712     }
3713     else
3714     {
3715         return XCArgs.bReturnValue;
3716     }
3717 }
3718 //*************************************************************************
3719 //Function name: MApi_XC_AUTO_GetSyncInfo_U2
3720 //Return parameter:
3721 //  XC_AUTO_SYNC_INFO: sync info.
3722 //Description: The function just be used after sync stable. (ex. between setWindow and AutoAdjust)
3723 //*************************************************************************
MApi_XC_AUTO_GetSyncInfo_U2(void * pInstance,XC_AUTO_SYNC_INFO * pSyncInfo)3724 void MApi_XC_AUTO_GetSyncInfo_U2(void* pInstance,XC_AUTO_SYNC_INFO *pSyncInfo)
3725 {
3726     MS_U8 u8VSyncTime = 0;
3727     XC_IP_SYNC_STATUS stXC_Sync_Status = {0, 0, 0};
3728 
3729     u8VSyncTime = MDrv_XC_PCMonitor_GetVSyncTime(pInstance, pSyncInfo->eWindow); // get VSync time
3730     MDrv_XC_GetSyncStatus(pInstance, pSyncInfo->eCurrentSrc, &stXC_Sync_Status, pSyncInfo->eWindow);
3731 
3732     //fill polarity
3733     if(stXC_Sync_Status.u8SyncStatus & MD_FLAG_POR_HPVP)
3734     {
3735         pSyncInfo->eSyncPolarity = E_XC_AUTO_POR_HPVP;
3736     }
3737     else if(stXC_Sync_Status.u8SyncStatus & MD_FLAG_POR_HPVN)
3738     {
3739         pSyncInfo->eSyncPolarity = E_XC_AUTO_POR_HPVN;
3740     }
3741     else if(stXC_Sync_Status.u8SyncStatus & MD_FLAG_POR_HNVP)
3742     {
3743         pSyncInfo->eSyncPolarity = E_XC_AUTO_POR_HNVP;
3744     }
3745     else
3746     {
3747         pSyncInfo->eSyncPolarity = E_XC_AUTO_POR_HNVN;
3748     }
3749 
3750     //fill hsync start and hsync end
3751     pSyncInfo->u32HSyncStart = MApi_XC_SetAutoPositionHstart(pInstance, pSyncInfo->eWindow);
3752     pSyncInfo->u32HSyncEnd   = MApi_XC_SetAutoPositionHend(pInstance, pSyncInfo->eWindow);
3753 
3754     XC_LOG_TRACE(XC_DBGLEVEL_AUTOGEOMETRY,"\n======== Get SyncInfo:Polarity=%u,HSyncStart=%td,VSyncStart=%td ======== \n",pSyncInfo->eSyncPolarity, (ptrdiff_t)pSyncInfo->u32HSyncStart,(ptrdiff_t)pSyncInfo->u32HSyncEnd);
3755 }
3756 
MApi_XC_AUTO_GetSyncInfo(XC_AUTO_SYNC_INFO * pSyncInfo)3757 void MApi_XC_AUTO_GetSyncInfo(XC_AUTO_SYNC_INFO *pSyncInfo)
3758 {
3759     if (pu32XCInst == NULL)
3760     {
3761         printf("[%s,%5d]No instance existed, please get an instance by calling MApi_XC_Init() first\n",__FUNCTION__,__LINE__);
3762         return ;
3763     }
3764 
3765     stXC_AUTO_GETSYNCINFO XCArgs;
3766     XCArgs.pSyncInfo = pSyncInfo;
3767 
3768     if(UtopiaIoctl(pu32XCInst, E_XC_AUTO_CMD_GETSYNCINFO, (void*)&XCArgs) != UTOPIA_STATUS_SUCCESS)
3769     {
3770         printf("Obtain XC engine fail\n");
3771         return ;
3772     }
3773     else
3774     {
3775         return ;
3776     }
3777 }
3778 
3779 #undef _APIXC_AUTO_C_
3780