1 
2 /*
3  *  Copyright 2001-2008 Texas Instruments - http://www.ti.com/
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 /* ====================================================================
18 *             Texas Instruments OMAP(TM) Platform Software
19 * (c) Copyright Texas Instruments, Incorporated. All Rights Reserved.
20 *
21 * Use of this software is controlled by the terms and conditions found
22 * in the license agreement under which this software has been supplied.
23 * ==================================================================== */
24 #ifdef UNDER_CE
25 #include <windows.h>
26 #else
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #endif
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sched.h>
35 #include <unistd.h>
36 #include <sys/types.h>
37 #include <sys/select.h>
38 #include <time.h>
39 #include <OMX_Component.h>
40 #include "JPEGTest.h"
41 
42 /* DSP recovery includes */
43 #include <qosregistry.h>
44 #include <qosti.h>
45 #include <dbapi.h>
46 #include <DSPManager.h>
47 #include <DSPProcessor.h>
48 #include <DSPProcessor_OEM.h>
49 
50 #ifdef UNDER_CE
51 #define PRINT printf
52 #else
53 /*#define OMX_DEB*/
54 #ifdef OMX_DEB
55 #define PRINT(str,args...) fprintf(stdout,"[%s] %s():%d: *** "str"",__FILE__,__FUNCTION__,__LINE__,##args)
56 #else
57 #define PRINT(str, args...)
58 #endif
59 #endif
60 
61 typedef unsigned char uchar;
62 /**
63  * Pipe used to communicate back to the main thread from the component thread;
64 **/
65 
66 int IpBuf_Pipe[2];
67 int OpBuf_Pipe[2];
68 int Event_Pipe[2];
69 struct timeval tim;
70 int DEINIT_FLAG = 0;
71 int bPreempted=0;
72 
73 
74 /* safe routine to get the maximum of 2 integers */
75 
maxint(int a,int b)76 inline int maxint(int a, int b)
77 {
78     return(a>b) ? a : b;
79 }
80 
81 
82  /*Define prototypes*/
83 
84 #ifdef DSP_MMU_FAULT_HANDLING
85 int LoadBaseImage();
86 #endif
87 
88  static OMX_ERRORTYPE WaitForEvent_JPEG(OMX_HANDLETYPE* pHandle,
89                                   OMX_EVENTTYPE DesiredEvent,
90                                   OMX_U32 data,
91                                   OMX_STATETYPE DesiredState);
92 
93 
Get16m(const void * Short)94 static int Get16m(const void * Short)
95 {
96     return(((uchar *)Short)[0] << 8) | ((uchar *)Short)[1];
97 }
98 
FixFrameSize(IMAGE_INFO * imageinfo)99 void  FixFrameSize ( IMAGE_INFO* imageinfo)
100 {
101 
102     int nWidth=imageinfo->nWidth, nHeight=imageinfo->nHeight;
103 
104     /*round up if nWidth is not multiple of 32*/
105     ( (nWidth%32 ) !=0 ) ?  nWidth=32 * (  (  nWidth/32 ) + 1 )  : nWidth;
106     PRINT("411 file new nWidth %d \n", nWidth);
107 
108     /*round up if nHeight is not multiple of 16*/
109     ( (nHeight%16) !=0 ) ?  nHeight=16 * (  (  nHeight/16 ) + 1 )  : nHeight;
110     PRINT("new nHeight %d \n", nHeight);
111 
112     imageinfo->nWidth = nWidth;
113     imageinfo->nHeight = nHeight;
114 }
115 
116 
GetYUVformat(uchar * Data)117 int GetYUVformat(uchar * Data)
118 {
119     unsigned char Nf;
120     int j;
121      int temp_index;
122      int temp;
123      int image_format;
124     short           H[4],V[4];
125 
126      Nf = Data[7];
127 
128 
129     for (j = 0; j < Nf; j++)
130     {
131        temp_index = j * 3 + 7 + 2;
132         /*---------------------------------------------------------*/
133        /* H[j]: upper 4 bits of a byte, horizontal sampling fator.                  */
134        /* V[j]: lower 4 bits of a byte, vertical sampling factor.                    */
135        /*---------------------------------------------------------*/
136          H[j] = (0x0f & (Data[temp_index] >> 4));
137          V[j] = (0x0f & Data[temp_index]);
138     }
139 
140     /*------------------------------------------------------------------*/
141     /* Set grayscale flag, namely if image is gray then set it to 1,    */
142     /* else set it to 0.                                                */
143     /*------------------------------------------------------------------*/
144     image_format = -1;
145 
146 
147     if (Nf == 1){
148       image_format = OMX_COLOR_FormatL8;
149     }
150 
151 
152     if (Nf == 3)
153     {
154        temp = (V[0]*H[0])/(V[1]*H[1]) ;
155 
156       if (temp == 4 && H[0] == 2)
157         image_format = OMX_COLOR_FormatYUV420PackedPlanar;
158 
159       if (temp == 4 && H[0] == 4)
160         image_format = OMX_COLOR_FormatYUV411Planar;
161 
162       if (temp == 2)
163         image_format = OMX_COLOR_FormatCbYCrY; /* YUV422 interleaved, little endian */
164 
165       if (temp == 1)
166         image_format = OMX_COLOR_FormatYUV444Interleaved;
167     }
168 
169     return (image_format);
170 
171 }
172 
173 /*--------------------------------------------------------------------------
174 * Parse the marker stream until SOS or EOI is seen;
175 * ------------------------------------------------------------------------*/
176 
177 #ifdef UNDER_CE
ReadJpegSections(HANDLE infile,IMAGE_INFO * imageinfo)178 int ReadJpegSections (HANDLE infile,
179                       IMAGE_INFO* imageinfo)
180 #else
181 int ReadJpegSections (FILE * infile,
182                       IMAGE_INFO* imageinfo)
183 #endif
184 {
185     int a = 0;
186     long lSize = 0;
187 #ifdef UNDER_CE
188     int got = 0;
189     int b = 0;
190     lSize = GetFileSize(infile, NULL );
191     SetFilePointer(infile, 0, NULL, FILE_BEGIN);
192 #else
193     fseek (infile , 0 , SEEK_END);
194     lSize = ftell (infile);
195     rewind (infile);
196 #endif
197 
198     PRINT ("Size is %d \n", (int)lSize);
199     imageinfo->nProgressive = 0; /*Default value is non progressive*/
200 
201 
202 #ifdef UNDER_CE
203     ReadFile(infile, &a, 1, &got, NULL);
204 #else
205     a = fgetc(infile);
206 #endif
207 
208 #ifdef UNDER_CE
209     ReadFile(infile, &b, 1, &got, NULL);
210     if ( a != 0xff || b != M_SOI )  {
211 #else
212     if ( a != 0xff || fgetc(infile) != M_SOI )  {
213 #endif
214         return 0;
215     }
216     for ( ;; )  {
217         int itemlen = 0;
218         int marker = 0;
219         int ll = 0,lh = 0, got = 0;
220         uchar * Data = NULL;
221 
222         for ( a=0;a<7;a++ ) {
223 #ifdef UNDER_CE
224             ReadFile(infile, &marker, 1, &got, NULL);
225 #else
226             marker = fgetc(infile);
227 #endif
228             PRINT("MARKER IS %x\n",marker);
229 
230             if ( marker != 0xff )   {
231                 break;
232             }
233             if ( a >= 6 )   {
234                 PRINT("too many padding bytes\n");
235                 if ( Data != NULL ) {
236                     free(Data);
237                     Data=NULL;
238                 }
239                 return 0;
240             }
241         }
242         if ( marker == 0xff )   {
243             /* 0xff is legal padding, but if we get that many, something's wrong.*/
244             PRINT("too many padding bytes!");
245         }
246 
247         /* Read the length of the section.*/
248 #ifdef UNDER_CE
249         ReadFile(infile, &lh, 1, &got, NULL);
250         ReadFile(infile, &ll, 1, &got, NULL);
251 #else
252         lh = fgetc(infile);
253         ll = fgetc(infile);
254 #endif
255 
256         itemlen = (lh << 8) | ll;
257 
258         if ( itemlen < 2 )  {
259             PRINT("invalid marker");
260         }
261 
262         Data = (uchar *)malloc(itemlen);
263         if ( Data == NULL ) {
264             PRINT("Could not allocate memory");
265         }
266 
267         /* Store first two pre-read bytes. */
268         Data[0] = (uchar)lh;
269         Data[1] = (uchar)ll;
270 
271 #ifdef UNDER_CE
272         ReadFile(infile, Data+2, itemlen-2, &got, NULL);
273 #else
274         got = fread(Data+2, 1, itemlen-2, infile); /* Read the whole section.*/
275 #endif
276         if ( got != itemlen-2 ) {
277             PRINT("Premature end of file?");
278         }
279 
280         PRINT("Jpeg section marker 0x%02x size %d\n",marker, itemlen);
281         switch ( marker )   {
282 
283         case M_SOS:
284             if ( Data != NULL ) {
285                 free(Data);
286                 Data=NULL;
287             }
288 
289             return lSize;
290 
291         case M_EOI:
292             PRINT("No image in jpeg!\n");
293             if ( Data != NULL ) {
294                 free(Data);
295                 Data=NULL;
296             }
297             return 0;
298 
299         case M_COM: /* Comment section  */
300 
301             break;
302 
303         case M_JFIF:
304 
305             break;
306 
307         case M_EXIF:
308 
309             break;
310 
311         case M_SOF2:
312             PRINT("nProgressive IMAGE!\n");
313             imageinfo->nProgressive=1;
314 
315         case M_SOF0:
316         case M_SOF1:
317         case M_SOF3:
318         case M_SOF5:
319         case M_SOF6:
320         case M_SOF7:
321         case M_SOF9:
322         case M_SOF10:
323         case M_SOF11:
324         case M_SOF13:
325         case M_SOF14:
326         case M_SOF15:
327 
328             imageinfo->nHeight = Get16m(Data+3);
329             imageinfo->nWidth = Get16m(Data+5);
330             imageinfo->format = GetYUVformat(Data);
331             switch (imageinfo->format) {
332             case OMX_COLOR_FormatYUV420PackedPlanar:
333                 printf("APP:: Image chroma format is OMX_COLOR_FormatYUV420PackedPlanar\n");
334                 break;
335             case OMX_COLOR_FormatYUV411Planar:
336                 printf("APP:: Image chroma format is OMX_COLOR_FormatYUV411Planar\n");
337                 break;
338             case OMX_COLOR_FormatCbYCrY:
339                 printf("APP:: Image chroma format is OMX_COLOR_FormatYUV422Interleaved\n");
340                 break;
341             case OMX_COLOR_FormatYUV444Interleaved:
342                  printf("APP:: Image chroma format is OMX_COLOR_FormatYUV444Interleaved\n");
343                  break;
344             case OMX_COLOR_FormatL8:
345                 printf("APP:: Image chroma format is OMX_COLOR_FormatL8 \n");
346                 break;
347             default:
348                  printf("APP:: Cannot find Image chroma format \n");
349                  imageinfo->format = OMX_COLOR_FormatUnused;
350                  break;
351             }
352             printf("APP:: Image Width x Height = %u * %u\n", Get16m(Data+5), Get16m(Data+3)  );
353             /*
354             PRINT("JPEG image is %uw * %uh,\n", Get16m(Data+3), Get16m(Data+5)  );
355 
356             if ( *(Data+9)==0x41 )  {
357                 PRINT("THIS IS A YUV 411 ENCODED IMAGE \n" );
358                 imageinfo->format= 1;
359             }
360             */
361 
362             if ( Data != NULL ) {
363                 free(Data);
364                 Data=NULL;
365             }
366             break;
367         default:
368             /* Skip any other sections.*/
369             break;
370         }
371 
372         if ( Data != NULL ) {
373             free(Data);
374             Data=NULL;
375         }
376     }
377 
378 
379     return 0;
380 }
381 
382 
383 
384 OMX_ERRORTYPE EventHandler(OMX_HANDLETYPE hComponent,
385                                                OMX_PTR pAppData,
386                                                OMX_EVENTTYPE eEvent,
387                                     OMX_U32 nData1,
388                                                OMX_U32 data2,
389                                                OMX_PTR pEventData)
390 {
391     JPEGD_EVENTPRIVATE MyEvent;
392 
393     MyEvent.eEvent = eEvent;
394     MyEvent.nData1 = nData1;
395     MyEvent.nData2 = data2;
396     MyEvent.pAppData = pAppData;
397     MyEvent.pEventInfo = pEventData;
398 
399     PRINT("eEvent = %x, nData1 = %x\n\n", eEvent, (unsigned int)nData1);
400 
401     switch ( eEvent ) {
402         case OMX_EventCmdComplete:
403             PRINT ("Component State Changed To %ld\n", data2);
404             break;
405 
406         case OMX_EventError:
407             if ( nData1 != OMX_ErrorNone ){
408                 printf ("APP:: ErrorNotification received: Error Num %x,\tSeverity = %ld\n", (unsigned int)nData1, data2);
409                 if ((nData1 == OMX_ErrorHardware) || (nData1 == OMX_ErrorInsufficientResources)){
410                     printf("\nAPP:: OMX_ErrorHardware. Deinitialization of the component....\n\n");
411                     break;
412                 }
413                 else if(nData1 == OMX_ErrorResourcesPreempted) {
414                     bPreempted = 1;
415                     PRINT("APP:: OMX_ErrorResourcesPreempted !\n\n");
416                 }
417                 else if(nData1 == OMX_ErrorInvalidState){
418                     return OMX_ErrorNone;
419                 }
420                 else if(nData1 == OMX_ErrorTimeout){
421                     return OMX_ErrorNone;
422                 }
423                 else {
424                     DEINIT_FLAG = 1;
425                 }
426             }
427             break;
428 
429         case OMX_EventResourcesAcquired:
430             bPreempted = 0;
431             break;
432         case OMX_EventBufferFlag:
433             printf("APP:: OMX_EventBufferFlag received\n");
434             break;
435         case OMX_EventPortSettingsChanged:
436         case OMX_EventMax:
437         case OMX_EventMark:
438             break;
439 
440         default:
441             break;
442     }
443 
444     write(Event_Pipe[1], &MyEvent, sizeof(JPEGD_EVENTPRIVATE));
445 
446     return OMX_ErrorNone;
447 }
448 
449 
450 
451 void FillBufferDone (OMX_HANDLETYPE hComponent,
452                      OMX_PTR ptr,
453                      OMX_BUFFERHEADERTYPE* pBuffHead)
454 {
455     PRINT("OutBufHeader %p, pBuffer = %p\n", pBuffHead, pBuffHead->pBuffer);
456     write(OpBuf_Pipe[1], &pBuffHead, sizeof(pBuffHead));
457     /*	if (eError == -1) {
458        PRINT ("Error while writing in OpBuf_pipe from app\n");
459 
460     }*/
461 
462 }
463 
464 
465 
466 
467 void EmptyBufferDone(OMX_HANDLETYPE hComponent,
468                      OMX_PTR ptr,
469                      OMX_BUFFERHEADERTYPE* pBuffer)
470 {
471     write(IpBuf_Pipe[1], &pBuffer, sizeof(pBuffer));
472     /*	if (eError == -1) {
473     	PRINT ("Error while writing in IpBuf_pipe from EmptyBufferDone\n");
474     }*/
475 }
476 
477 
478 
479 #ifdef UNDER_CE
480 int fill_data (OMX_BUFFERHEADERTYPE *pBuf,
481                HANDLE fIn, long lBuffUsed)
482 #else
483 int fill_data (OMX_BUFFERHEADERTYPE *pBuf,
484                FILE *fIn, int lBuffUsed)
485 #endif
486 {
487     int nRead;
488 
489     PRINT(" checking buf address %x\n", (unsigned int)pBuf->pBuffer);
490 
491 #ifdef UNDER_CE
492     lSize = GetFileSize(fIn, NULL );
493     SetFilePointer(fIn, 0, NULL, FILE_BEGIN);
494 #else
495     //fseek (fIn , 0 , SEEK_END);
496     //lSize = ftell (fIn);
497     //rewind (fIn);
498 #endif
499 
500 #ifdef UNDER_CE
501     ReadFile(fIn, pBuf->pBuffer, lBuffUsed, &nRead, NULL);
502 #else
503     nRead = fread(pBuf->pBuffer,1, lBuffUsed, fIn);
504 #endif
505 
506     PRINT ("printing lsize %d \n", (int) lBuffUsed);
507     PRINT( "Read %d bytes from file\n", nRead);
508 
509     pBuf->nFilledLen = nRead;
510     return nRead;
511 }
512 /* This method will wait for the component to get to the event
513  * specified by the DesiredEvent input. */
514 static OMX_ERRORTYPE WaitForEvent_JPEG(OMX_HANDLETYPE* pHandle,
515                                   OMX_EVENTTYPE DesiredEvent,
516                                   OMX_U32 nFDmax,
517                                   OMX_STATETYPE DesiredState)
518 {
519     OMX_ERRORTYPE error = OMX_ErrorNone;
520     OMX_STATETYPE CurrentState;
521     OMX_COMPONENTTYPE *pComponent = (OMX_COMPONENTTYPE *)pHandle;
522     int nRetval;
523     sigset_t set;
524 
525     while(1) {
526 
527         error = pComponent->GetState(pHandle, &CurrentState);
528         if(error || CurrentState == DesiredState) {
529             break;
530         }
531 
532         fd_set rfds;
533         FD_ZERO(&rfds);
534         FD_SET(Event_Pipe[0], &rfds);
535         sigemptyset(&set);
536         sigaddset(&set,SIGALRM);
537 
538         nRetval = pselect(nFDmax+1, &rfds, NULL, NULL, NULL, &set);
539 
540         if ( nRetval == -1 ) {
541 #ifndef UNDER_CE
542             perror("select()");
543 #endif
544             fprintf (stderr, " : Error \n");
545             break;
546         }
547 
548         if ( nRetval == 0 ) {
549             PRINT("Waiting: Desired Event = %x, Desired State = %x \n",DesiredEvent, DesiredState);
550         }
551 
552         if ( FD_ISSET(Event_Pipe[0], &rfds)) {
553 
554             JPEGD_EVENTPRIVATE EventPrivate;
555             read(Event_Pipe[0], &EventPrivate, sizeof(JPEGD_EVENTPRIVATE));
556 
557             if (EventPrivate.eEvent == DesiredEvent &&
558                 EventPrivate.nData1 == OMX_CommandStateSet &&
559                 EventPrivate.nData2 == DesiredState) {
560                 PRINT("OMX_EventCmdComplete :: nData2 = %x\n", (unsigned int)EventPrivate.nData2);
561                 break;
562             }
563             else if (EventPrivate.eEvent == OMX_EventError &&
564                 EventPrivate.nData1 == OMX_ErrorInsufficientResources &&
565                 DesiredState == OMX_StateIdle) {
566                 printf("\n\n Received OMX_EventError: Error = 0x%x,\tSeverity = %ld\n\n", (unsigned int)EventPrivate.nData1, EventPrivate.nData2);
567                 error = OMX_ErrorInsufficientResources;
568                 break;
569             }
570             else if (EventPrivate.eEvent == OMX_EventError &&
571                 EventPrivate.nData1 == OMX_ErrorResourcesLost &&
572                 DesiredState == OMX_StateLoaded) {
573                 printf("\n\n Received OMX_EventError: Error = 0x%x,\tSeverity = %ld\n\n", (unsigned int)EventPrivate.nData1, EventPrivate.nData2);
574                 break;
575             }
576         }
577 
578     }
579 
580     PRINT("Exit from Wait For Event function JPEGD\n");
581     return error;
582 }
583 
584 
585 
586 #ifdef UNDER_CE
587 int _tmain(int argc, TCHAR **argv)
588 #else
589 int main(int argc, char** argv)
590 #endif
591 {
592 
593     OMX_HANDLETYPE pHandle = NULL;
594     OMX_U32 AppData = 100;
595     OMX_CALLBACKTYPE JPEGCaBa = {   (void *)EventHandler,
596                                                             (void*) EmptyBufferDone,
597                                                             (void*)FillBufferDone};
598 
599     OMX_ERRORTYPE eError = OMX_ErrorNone;
600     OMX_BOOL bError = OMX_FALSE;
601     int nRetval;
602     int nWidth;
603     int nHeight;
604     /*int nFramesent= 0;*/
605     long lBuffused;
606     int nOutformat;
607     int nResizeMode;
608     int nIndex1;
609     int nIndex2;
610     OMX_U32 nMCURow = 0;
611     OMX_U32 nXOrg = 0;         /*Sectional decoding: X origin*/
612     OMX_U32 nYOrg = 0;         /*Sectional decoding: Y origin*/
613     OMX_U32 nXLength = 0;      /*Sectional decoding: X lenght*/
614     OMX_U32 nYLength = 0;    /*Sectional decoding: Y lenght*/
615     OMX_U32 i = 0;      /*Temporary counter*/
616 
617     IMAGE_INFO* imageinfo = NULL;
618     OMX_PORT_PARAM_TYPE* pPortParamType = NULL;
619     OMX_PARAM_PORTDEFINITIONTYPE* pParamPortDef = NULL;
620     OMX_PARAM_PORTDEFINITIONTYPE* pInPortDef = NULL;
621     OMX_PARAM_PORTDEFINITIONTYPE* pOutPortDef = NULL;
622     OMX_CONFIG_SCALEFACTORTYPE* pScaleFactor = NULL;
623     OMX_PORT_PARAM_TYPE* pPortType = NULL;
624     OMX_CUSTOM_IMAGE_DECODE_SECTION* pSectionDecode = NULL;
625     OMX_CUSTOM_IMAGE_DECODE_SUBREGION* pSubRegionDecode = NULL;
626 	OMX_CUSTOM_RESOLUTION *pMaxResolution = NULL;
627 
628 #ifdef UNDER_CE
629     TCHAR* szInFile = NULL;
630     TCHAR* szOutFile = NULL;
631     HANDLE fIn = NULL;
632     HANDLE fOut = NULL;
633     DWORD dwWritten;
634 #else
635     char* szInFile = NULL;
636     char* szOutFile = NULL;
637     FILE* fIn = NULL;
638     FILE* fOut = NULL;
639 #endif
640 
641     int nFramesDecoded = 0;
642     double t1 = 0;
643     double t2 = 0;
644     /*int nCountstarted = 0;*/
645     OMX_S32 nPostProcCompId = 200;
646     /*int nDone = 0;*/
647     int nExternal= 0;
648     OMX_U8 * pTemp;
649     OMX_BUFFERHEADERTYPE* pInBuffHead[NUM_OF_BUFFERS];
650     OMX_BUFFERHEADERTYPE* pOutBuffHead[NUM_OF_BUFFERS];
651     OMX_U8* pInBuffer = NULL;
652     OMX_U8* pOutBuffer = NULL;
653     int nFdmax;
654     int nRead;
655     OMX_INDEXTYPE nCustomIndex = OMX_IndexMax;
656     OMX_U16 nBufferHdrSend = 0;
657     OMX_U16 nSampleFactor = 32;
658     OMX_U8 nNUM_OF_DECODING_BUFFERS = 1;
659     sigset_t set;
660     OMX_BOOL bWaitForLoaded = OMX_FALSE;
661     int  nMaxFrames = 1;
662     OMX_BUFFERHEADERTYPE* pInBufferHdr;
663     struct timeval tv1, tv2;
664 
665     /* validate command line args */
666     if ( (argc < 5) || ((argc > 7) && (argc < 11)) ||(argc > 11)) {
667 #ifdef UNDER_CE
668         printf("usage: %S <input.jpg> <output.yuv> <nOutformat-1:420 4:422 9:RGB16 10: RGB24 11:RGB32 12:BGR32> <nResizeMode> <nRepeat> <nSections> <nXOrigin> <nYOrigin> <nXLenght> <nYLenght>\n",
669         argv[0]);
670 #else
671         printf("usage: %s <input.jpg> <output.yuv> <nOutformat-1:Original(default)  4:422 9:RGB16 10: RGB24 11:RGB32 12:BGR32> <nResizeMode> <nRepeat> <nSections> <nXOrigin> <nYOrigin> <nXLenght> <nYLenght>\n",
672         argv[0]);
673 #endif
674         printf("nResizeMode 100:No Rescaling\nnResizeMode 50:Rescale to 50 percent of original size \n");
675         printf("nResizeMode 25:Rescale to 25 percent of original size\nnResizeMode 12:Rescale to 12.5 percent of original size\n\n");
676         printf("Example ./JpegTestCommon patterns/shrek.jpg shrek.yuv 1 50 \n");
677         printf("Input: 720x480. Output: YUV420, 360x240\n\n");
678         printf("nRepeat: It is an optional parameter. Range is 0 to 100. Repeatedly encode the same frame 'nRepeat+1' times");
679         printf("Example ./JpegTestCommon patterns/shrek.jpg shrek.yuv 1 50 0\n");
680         printf("Example ./JpegTestCommon patterns/shrek.jpg shrek.yuv 1 50 9\n");
681         printf("Output: YUV420, 360x240\n\n");
682         printf("<nSections> It's an optional parameter. Values: 0, 1, 2, ...\n");
683         printf("Example ./JpegTestCommon patterns/shrek.jpg shrek.yuv 4 50 0 1\n");
684         printf("Output: YUV422, 360x240\n\n");
685         printf("SubRegion decode:\n");
686         printf("<nXOrigin> <nYOrigin> <nXLenght> <nYLenght>\n");
687         printf("Example ./JpegTestCommon patterns/shrek.jpg shrek.yuv 1 100 0 0 192 48 288 256\n");
688         printf("Output: YUV420, 288x256\n\n");
689         return -1;
690     }
691 
692 
693     szInFile = argv[1];
694     szOutFile = argv[2];
695 #ifdef UNDER_CE
696     nOutformat = _wtoi(argv[3]);
697     nResizeMode = _wtoi(argv[4]);
698 #else
699     nOutformat = atoi(argv[3]);
700     nResizeMode = atoi(argv[4]);
701 #endif
702 
703     if (argc >= 6){
704         nMaxFrames = atoi(argv[5]) + 1;
705     }
706 
707     if(argc >= 7){
708         nMCURow = atoi(argv[6]);
709         if(nOutformat >= 9){
710             printf("\nAPP: WARNING Sectional decoding is not supported for RGB color formats\n\n");
711             nMCURow = 0;
712         }
713         if(nMCURow){
714             nNUM_OF_DECODING_BUFFERS = NUM_OF_BUFFERS;
715         }
716         else{
717             nNUM_OF_DECODING_BUFFERS = 1;
718         }
719     }
720 
721     if(argc > 7){
722         nXOrg = atoi(argv[7]);
723         nYOrg = atoi(argv[8]);
724         nXLength = atoi(argv[9]);
725         nYLength = atoi(argv[10]);
726     }
727 
728     imageinfo = (IMAGE_INFO *)malloc (sizeof (IMAGE_INFO ) );
729     pPortParamType = (OMX_PORT_PARAM_TYPE*)malloc(sizeof(OMX_PORT_PARAM_TYPE));
730     pParamPortDef = (OMX_PARAM_PORTDEFINITIONTYPE*)malloc(sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
731     pInPortDef = (OMX_PARAM_PORTDEFINITIONTYPE*)malloc(sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
732     pOutPortDef = (OMX_PARAM_PORTDEFINITIONTYPE*)malloc(sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
733     pScaleFactor = (OMX_CONFIG_SCALEFACTORTYPE*)malloc(sizeof(OMX_CONFIG_SCALEFACTORTYPE));
734     pPortType = (OMX_PORT_PARAM_TYPE*)malloc(sizeof(OMX_PORT_PARAM_TYPE));
735     pSectionDecode = (OMX_CUSTOM_IMAGE_DECODE_SECTION*)malloc(sizeof(OMX_CUSTOM_IMAGE_DECODE_SECTION));
736     pSubRegionDecode = (OMX_CUSTOM_IMAGE_DECODE_SUBREGION*)malloc(sizeof(OMX_CUSTOM_IMAGE_DECODE_SUBREGION));
737 	pMaxResolution = (OMX_CUSTOM_RESOLUTION *)malloc(sizeof(OMX_CUSTOM_RESOLUTION ));
738 
739 
740     printf("\n------------------------------------------------\n");
741     printf("OMX JPEG Decoder Test App built on " __DATE__ ":" __TIME__ "\n");
742     printf("------------------------------------------------\n");
743     printf("\nAPP:: Output File Name is %s \n", szOutFile);
744 
745     /* Create a pipe used to queue data from the callback. */
746     nRetval = pipe(IpBuf_Pipe);
747     PRINT("Pipe InBuf_Pipe just created\n");
748     if ( nRetval != 0 )	{
749         fprintf(stderr, "Error:Fill Data Pipe failed to open\n");
750         goto EXIT;
751     }
752 
753     PRINT("Pipe OpBuf_Pipe just created\n");
754     nRetval = pipe(OpBuf_Pipe);
755     if ( nRetval != 0 ) {
756         fprintf(stderr, "Error:Empty Data Pipe failed to open\n");
757         goto EXIT;
758     }
759 
760     PRINT("Pipe Event_Pipe just created\n");
761     nRetval = pipe(Event_Pipe);
762     if ( nRetval != 0 ) {
763         fprintf(stderr, "Error:Empty Data Pipe failed to open\n");
764         goto EXIT;
765     }
766 
767     /* save off the "max" of the handles for the selct statement */
768     nFdmax = maxint(IpBuf_Pipe[0], OpBuf_Pipe[0]);
769     nFdmax = maxint(Event_Pipe[0], nFdmax);
770 
771 #ifdef DSP_MMU_FAULT_HANDLING
772     /* LOAD BASE IMAGE FIRST TIME */
773     LoadBaseImage();
774 #endif
775 
776     eError = TIOMX_Init();
777     if ( eError != OMX_ErrorNone ) {
778         PRINT("%d :: Error returned by TIOMX_Init()\n",__LINE__);
779         goto EXIT;
780     }
781 
782     /*--------------------------------------------------------------------------------
783     *
784     * Open the file of data to be rendered.  Since this is a just sample
785     * application, the data is "rendered" to a test mixer.  So, the test
786     * file better contain data that can be printed to the terminal w/o
787     * problems or you will not be a happy [JPEGTest.c] fill_data():473: *** Read 997386 bytes from file
788     **/
789     PRINT("Opening input & output file\n");
790 #ifdef UNDER_CE
791     fOut = CreateFile(szOutFile, GENERIC_WRITE, 0,
792     NULL,CREATE_ALWAYS, 0, NULL);
793     if (INVALID_HANDLE_VALUE == fOut)
794     {
795         PRINT("Error:  failed to create the output file %S\n",
796         szOutFile);
797         goto EXIT;
798     }
799 
800     fIn = CreateFile(szInFile, GENERIC_READ, 0,
801     NULL,OPEN_EXISTING, 0, NULL);
802     if (INVALID_HANDLE_VALUE == fIn) {
803         PRINT("Error:  failed to open the file %s for readonly\n" \
804         "access\n", szInFile);
805         goto EXIT;
806     }
807 
808 #else
809 
810     fIn = fopen(szInFile, "r");
811     if ( fIn == NULL ) {
812         printf("\nError: failed to open the file <%s> for reading\n",
813         szInFile);
814         goto EXIT;
815     }
816     PRINT("APP:: File %s opened \n" , szInFile);
817 #endif
818 
819     lBuffused = ReadJpegSections(fIn , imageinfo);
820 
821     if (lBuffused == 0) {
822         printf("The file size is 0. Maybe the format of the file is not correct\n");
823         goto EXIT;
824     }
825 
826     /* Load the JPEGDecoder Component */
827 
828     PRINT("Calling TIOMX_GetHandle\n");
829     eError = TIOMX_GetHandle(&pHandle,StrJpegDecoder, (void *)&AppData, &JPEGCaBa);
830     if ( (eError != OMX_ErrorNone) ||  (pHandle == NULL) ) {
831         fprintf (stderr,"Error in Get Handle function\n");
832         goto EXIT;
833     }
834 
835     eError = OMX_GetParameter(pHandle, OMX_IndexParamImageInit, pPortType);
836     if ( eError != OMX_ErrorNone ) {
837         goto EXIT;
838     }
839 
840 
841     nIndex1 = pPortType->nStartPortNumber;
842     nIndex2 = nIndex1 + 1;
843     nHeight = imageinfo->nHeight;
844     nWidth = imageinfo->nWidth;
845 
846     FixFrameSize(imageinfo);
847 
848     pScaleFactor->xWidth = (int)nResizeMode;
849     pScaleFactor->xHeight = (int)nResizeMode;
850 
851     eError = OMX_SetConfig (pHandle, OMX_IndexConfigCommonScale, pScaleFactor);
852     if ( eError != OMX_ErrorNone ) {
853         goto EXIT;
854     }
855 
856     eError = OMX_GetParameter (pHandle, OMX_IndexParamPortDefinition, pInPortDef);
857     if ( eError != OMX_ErrorNone ) {
858         eError = OMX_ErrorBadParameter;
859         goto EXIT;
860     }
861 
862     if (pInPortDef->eDir == nIndex1 ) {
863         pInPortDef->nPortIndex = nIndex1;
864     }
865     else {
866         pInPortDef->nPortIndex = nIndex2;
867     }
868 
869     /* Set the component's OMX_PARAM_PORTDEFINITIONTYPE structure (input) */
870     /**********************************************************************/
871 
872     pInPortDef->nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
873     pInPortDef->nVersion.s.nVersionMajor = 0x1;
874     pInPortDef->nVersion.s.nVersionMinor = 0x0;
875     pInPortDef->nVersion.s.nRevision = 0x0;
876     pInPortDef->nVersion.s.nStep = 0x0;
877     pInPortDef->nPortIndex = 0x0;
878     pInPortDef->eDir = OMX_DirInput;
879     pInPortDef->nBufferCountActual =1;
880     pInPortDef->nBufferCountMin = 1;
881     pInPortDef->bEnabled = OMX_TRUE;
882     pInPortDef->bPopulated = OMX_FALSE;
883     pInPortDef->eDomain = OMX_PortDomainImage;
884     pInPortDef->format.image.cMIMEType = "JPEGDEC";
885     pInPortDef->format.image.pNativeRender = NULL;
886     pInPortDef->format.image.nFrameWidth = imageinfo->nWidth;
887     pInPortDef->format.image.nFrameHeight = imageinfo->nHeight;
888     pInPortDef->format.image.nStride = -1;
889     pInPortDef->format.image.nSliceHeight = -1;
890     pInPortDef->format.image.bFlagErrorConcealment = OMX_FALSE;
891     pInPortDef->format.image.eColorFormat =OMX_COLOR_FormatCbYCrY ;
892     pInPortDef->format.image.eCompressionFormat = OMX_IMAGE_CodingJPEG;
893     pInPortDef->nBufferSize = lBuffused;
894 
895 
896     if (imageinfo->format == OMX_COLOR_FormatYCbYCr ||
897         imageinfo->format == OMX_COLOR_FormatYUV444Interleaved ||
898         imageinfo->format == OMX_COLOR_FormatUnused) {
899         pInPortDef->format.image.eColorFormat = OMX_COLOR_FormatCbYCrY;
900     }
901     else {
902         pInPortDef->format.image.eColorFormat = OMX_COLOR_FormatYUV420PackedPlanar;
903     }
904 
905     PRINT("Calling OMX_SetParameter\n");
906 
907 	/* Set max width & height value*/
908     eError = OMX_GetExtensionIndex(pHandle, "OMX.TI.JPEG.decoder.Param.SetMaxResolution", (OMX_INDEXTYPE*)&nCustomIndex);
909     if ( eError != OMX_ErrorNone ) {
910         printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
911         goto EXIT;
912     }
913 
914 	pMaxResolution->nWidth = imageinfo->nWidth;
915 	pMaxResolution->nHeight = imageinfo->nHeight;
916 
917 	eError = OMX_SetParameter (pHandle, nCustomIndex, pMaxResolution);
918     if ( eError != OMX_ErrorNone ) {
919         printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
920         goto EXIT;
921     }
922 
923     eError = OMX_SetParameter (pHandle, OMX_IndexParamPortDefinition, pInPortDef);
924     if ( eError != OMX_ErrorNone ) {
925         eError = OMX_ErrorBadParameter;
926         goto EXIT;
927     }
928 
929     memset(pOutPortDef, 0x0, sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
930     eError = OMX_GetParameter (pHandle, OMX_IndexParamPortDefinition, pOutPortDef);
931     if ( eError != OMX_ErrorNone ) {
932         eError = OMX_ErrorBadParameter;
933         goto EXIT;
934     }
935 
936     if (pOutPortDef->eDir == nIndex1 ) {
937         pOutPortDef->nPortIndex = nIndex1;
938     }
939     else {
940         pOutPortDef->nPortIndex = nIndex2;
941     }
942 
943     /*****************************************************************/
944     /* Set the component's OMX_PARAM_PORTDEFINITIONTYPE structure (Output) */
945     /**********************************************************************/
946     pOutPortDef->nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE);
947     pOutPortDef->nVersion.s.nVersionMajor = 0x1;
948     pOutPortDef->nVersion.s.nVersionMinor = 0x0;
949     pOutPortDef->nVersion.s.nRevision = 0x0;
950     pOutPortDef->nVersion.s.nStep = 0x0;
951     pOutPortDef->nPortIndex = 0x1;
952     pOutPortDef->eDir = OMX_DirOutput;
953     pOutPortDef->nBufferCountActual = nNUM_OF_DECODING_BUFFERS;
954     pOutPortDef->nBufferCountMin = 1;
955     pOutPortDef->bEnabled = OMX_TRUE;
956     pOutPortDef->bPopulated = OMX_FALSE;
957     pOutPortDef->eDomain = OMX_PortDomainImage;
958 
959     /* OMX_IMAGE_PORTDEFINITION values for Output port */
960     pOutPortDef->format.image.cMIMEType = "JPEGDEC";
961     pOutPortDef->format.image.pNativeRender = NULL;
962     pOutPortDef->format.image.nFrameWidth = imageinfo->nWidth;
963     pOutPortDef->format.image.nFrameHeight = imageinfo->nHeight;
964     pOutPortDef->format.image.nStride = -1;
965     pOutPortDef->format.image.nSliceHeight = -1;
966     pOutPortDef->format.image.bFlagErrorConcealment = OMX_FALSE;
967     pOutPortDef->format.image.eCompressionFormat = OMX_IMAGE_CodingUnused;
968 
969     PRINT("nWidth and nHeight = %d and %d\n",nWidth,nHeight);
970     if ( nOutformat == 4 ) {
971         pOutPortDef->format.image.eColorFormat = OMX_COLOR_FormatCbYCrY;
972     }
973     else if (nOutformat == 9) {
974         pOutPortDef->format.image.eColorFormat = OMX_COLOR_Format16bitRGB565;
975         PRINT("color format is %d\n", pOutPortDef->format.image.eColorFormat);
976     }
977     else if (nOutformat == 10) {
978         pOutPortDef->format.image.eColorFormat = OMX_COLOR_Format24bitRGB888;
979     }
980     else if (nOutformat == 11) {
981         pOutPortDef->format.image.eColorFormat = OMX_COLOR_Format32bitARGB8888;
982     }
983     else if (nOutformat == 12) {
984         pOutPortDef->format.image.eColorFormat = OMX_COLOR_Format32bitBGRA8888;
985     }
986     else { /*Set DEFAULT (original) color format*/
987         pOutPortDef->format.image.eColorFormat = imageinfo->format; /*Setting input original format */
988 
989         if(imageinfo->format == OMX_COLOR_Format16bitRGB565 ||
990                 imageinfo->format == OMX_COLOR_Format24bitRGB888 ||
991                 imageinfo->format == OMX_COLOR_Format32bitARGB8888 ||
992                 imageinfo->format == OMX_COLOR_Format32bitBGRA8888 ||
993                 imageinfo->format == OMX_COLOR_FormatL8){
994             for(i = 0; i < strlen(szOutFile); i++){
995                 if(szOutFile[i]=='.'){
996                     if(szOutFile[i+1]=='y'){
997                         szOutFile[i+1]='r';
998                         szOutFile[i+2]='a';
999                         szOutFile[i+3]='w';
1000                         szOutFile[i+4]='\0';
1001                         printf("\n\nAPP::--WARNING:\nIncorrect output file extension. Changing output file name extension--\n");
1002                         printf("APP:: New file name: %s\n\n\n", szOutFile);
1003                         break;
1004                     }
1005                     break;
1006                 }
1007             }
1008         }
1009     }
1010 
1011     fOut = fopen(szOutFile, "w");
1012     if ( fOut == NULL ) {
1013         printf("\nError: failed to open the file <%s> for writing", szOutFile);
1014         goto EXIT;
1015     }
1016 
1017     if(nResizeMode == 800){
1018         nWidth *= 8;
1019         nHeight *= 8;
1020     }
1021     else if(nResizeMode == 400){
1022         nWidth *= 4;
1023         nHeight *= 4;
1024     }
1025     else if(nResizeMode == 200){
1026         nWidth *= 2;
1027         nHeight *= 2;
1028     }
1029     else if (nResizeMode == 50) {
1030         nWidth /= 2;
1031         nHeight /= 2;
1032     } else if (nResizeMode == 25) {
1033         nWidth /= 4;
1034         nHeight /= 4;
1035     } else if (nResizeMode == 12) {
1036         nWidth /= 4;
1037         nHeight /= 4;
1038     }
1039 
1040     if(nMCURow == 0){ /*Full frame decoding*/
1041         if ( nOutformat == 1 ) { /* Buffer size depends on the Original color format*/
1042             if (imageinfo->format == OMX_COLOR_FormatYUV420PackedPlanar ||
1043                 imageinfo->format == OMX_COLOR_FormatYUV411Planar) {
1044                 pOutPortDef->nBufferSize = ( int )((( nWidth * nHeight) *3 ) /2);
1045                 }
1046             else if (imageinfo->format == OMX_COLOR_FormatCbYCrY) {
1047                 pOutPortDef->nBufferSize =  ( int ) ((nWidth * nHeight) *2);
1048             }
1049             else if (imageinfo->format == OMX_COLOR_FormatYUV444Interleaved) {
1050                     pOutPortDef->nBufferSize =  ( int ) ((nWidth * nHeight) *3);
1051             }
1052             else {
1053                 pOutPortDef->nBufferSize = ( int ) (nWidth * nHeight) * 2;
1054             }
1055         }
1056         else if (nOutformat == 4 || nOutformat == 9) {        /* OMX_COLOR_FormatCbYCrY & OMX_COLOR_Format16bitRGB565*/
1057             pOutPortDef->nBufferSize =  (int)((nWidth * nHeight) * 2);
1058         }
1059         else if (nOutformat == 10) { /* OMX_COLOR_Format24bitRGB888 */
1060            pOutPortDef->nBufferSize = (int) ((nWidth * nHeight) * 3);
1061         }
1062         else if (nOutformat == 11 || nOutformat == 12) { /* OMX_COLOR_Format32bitARGB8888 & OMX_COLOR_Format32bitBGRA8888*/
1063            pOutPortDef->nBufferSize = (int) ((nWidth * nHeight) * 4);
1064         }
1065         else {
1066             eError = OMX_ErrorBadParameter;
1067             goto EXIT;
1068         }
1069     }
1070     else{ /*Slice Decoding*/
1071         switch(imageinfo->format){
1072             case OMX_COLOR_FormatYUV420PackedPlanar:
1073                 nSampleFactor = 16;
1074                 break;
1075             case OMX_COLOR_FormatYUV411Planar:
1076             case OMX_COLOR_FormatCbYCrY:
1077             case OMX_COLOR_FormatYUV444Interleaved:
1078                 nSampleFactor = 8;
1079                 break;
1080             default:
1081                 nSampleFactor = 8;
1082                 break;
1083         }
1084 
1085 
1086         if(nResizeMode == 12){ /* setting to 13 instead of 12.5 */
1087             nResizeMode = 13;
1088         }
1089 
1090         if ( nOutformat == 1 ) { /* Buffer size depends on the Original color format*/
1091             if (imageinfo->format == OMX_COLOR_FormatYUV420PackedPlanar ||
1092                     imageinfo->format == OMX_COLOR_FormatYUV411Planar) {
1093                 pOutPortDef->nBufferSize = (OMX_U32)(((nWidth*3)/2)*(nSampleFactor*nMCURow*nResizeMode)/100);
1094 
1095             }
1096             else if (imageinfo->format == OMX_COLOR_FormatCbYCrY){
1097                     pOutPortDef->nBufferSize =  (OMX_U32) ( (nWidth * 2) * (nSampleFactor * nMCURow*nResizeMode)/100);
1098             }
1099             else if (imageinfo->format == OMX_COLOR_FormatYUV444Interleaved) {
1100                 pOutPortDef->nBufferSize =  (OMX_U32) ( (nWidth * 3) * (nSampleFactor * nMCURow*nResizeMode)/100);
1101             }
1102             else{
1103                 pOutPortDef->nBufferSize =  (OMX_U32) ( (nWidth) * (nSampleFactor * nMCURow*nResizeMode)/100);
1104             }
1105         }
1106         else if(nOutformat == 4){ /*YUV422 ILE */
1107             pOutPortDef->nBufferSize = (OMX_U32)((nWidth * 2) * (nSampleFactor * nMCURow * nResizeMode)/100);
1108         }
1109     }
1110 
1111     printf("APP:: Output buffer size is %ld\n", pOutPortDef->nBufferSize);
1112     printf("APP:: Output color format is ");
1113     if (nOutformat == 4){
1114         printf("OMX_COLOR_FormatCbYCrY (YUV422ILE)\n");
1115     }
1116     else if (nOutformat == 9){
1117         printf("OMX_COLOR_Format16bitRGB565 (RGB16)\n");
1118     }
1119     else if (nOutformat == 10){
1120         printf("OMX_COLOR_Format24bitRGB888 (BGR24)\n");
1121     }
1122     else if (nOutformat == 11){
1123         printf("OMX_COLOR_Format32bitARGB8888 (ARGB32)\n");
1124 	}
1125     else if (nOutformat == 12){
1126         printf("OMX_COLOR_Format32bitBGRA8888 (BGRA32)\n");
1127     }
1128     else{
1129          if (imageinfo->format == OMX_COLOR_FormatYUV420PackedPlanar){
1130             printf("OMX_COLOR_FormatYUV420PackedPlanar\n");
1131          }
1132          else if (imageinfo->format == OMX_COLOR_FormatYUV411Planar) {
1133             printf("OMX_COLOR_FormatYUV411Planar\n");
1134         }
1135         else if (imageinfo->format == OMX_COLOR_FormatCbYCrY){
1136                 printf("OMX_COLOR_FormatCbYCrY (YUV422ILE)\n");
1137         }
1138         else if (imageinfo->format == OMX_COLOR_FormatYUV444Interleaved) {
1139             printf("OMX_COLOR_FormatYUV444Interleaved\n");
1140         }
1141         else if (imageinfo->format == OMX_COLOR_FormatL8){
1142             printf("OMX_COLOR_FormatL8 (Gray 8)\n");
1143         }
1144         else{
1145             printf("Unknow format\n");
1146         }
1147     }
1148 
1149     eError = OMX_SetParameter (pHandle, OMX_IndexParamPortDefinition, pOutPortDef);
1150     if ( eError != OMX_ErrorNone ) {
1151         eError = OMX_ErrorBadParameter;
1152         goto EXIT;
1153     }
1154 
1155     eError = OMX_GetExtensionIndex(pHandle, "OMX.TI.JPEG.decoder.Config.ProgressiveFactor", (OMX_INDEXTYPE*)&nCustomIndex);
1156     if ( eError != OMX_ErrorNone ) {
1157         printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1158         goto EXIT;
1159     }
1160     eError = OMX_SetConfig (pHandle, nCustomIndex, &(imageinfo->nProgressive));
1161     if ( eError != OMX_ErrorNone ) {
1162         printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1163         goto EXIT;
1164     }
1165 
1166     eError = OMX_GetExtensionIndex(pHandle, "OMX.TI.JPEG.decoder.Config.OutputColorFormat", (OMX_INDEXTYPE*)&nCustomIndex);
1167     if ( eError != OMX_ErrorNone ) {
1168         printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1169         goto EXIT;
1170     }
1171 
1172     eError = OMX_SetConfig (pHandle, nCustomIndex, &(pOutPortDef->format.image.eColorFormat));
1173     if ( eError != OMX_ErrorNone ) {
1174         printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1175         goto EXIT;
1176     }
1177 
1178     if(nMCURow){
1179         eError = OMX_GetExtensionIndex(pHandle, "OMX.TI.JPEG.decoder.Param.SectionDecode", (OMX_INDEXTYPE*)&nCustomIndex);
1180         if ( eError != OMX_ErrorNone ) {
1181             printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1182             goto EXIT;
1183         }
1184         eError = OMX_GetParameter(pHandle, nCustomIndex, pSectionDecode);
1185         if ( eError != OMX_ErrorNone ) {
1186             printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1187             goto EXIT;
1188         }
1189         pSectionDecode->nMCURow = nMCURow; /*number of slices*/
1190         pSectionDecode->bSectionsInput = OMX_FALSE; /*Should be false at input port. Unsupported slice dec at input port at the moment*/
1191         pSectionDecode->bSectionsOutput = OMX_TRUE; /*Should be true if slice at output port*/
1192         eError = OMX_SetParameter(pHandle, nCustomIndex, pSectionDecode);
1193         if ( eError != OMX_ErrorNone ) {
1194             printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1195             goto EXIT;
1196         }
1197     }
1198 
1199     if(nXOrg || nYOrg || nXLength || nYLength){
1200         eError = OMX_GetExtensionIndex(pHandle, "OMX.TI.JPEG.decoder.Param.SubRegionDecode", (OMX_INDEXTYPE*)&nCustomIndex);
1201         if ( eError != OMX_ErrorNone ) {
1202             printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1203             goto EXIT;
1204         }
1205 
1206         eError = OMX_GetParameter(pHandle, nCustomIndex, pSubRegionDecode);
1207         if ( eError != OMX_ErrorNone ) {
1208             printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1209             goto EXIT;
1210         }
1211 
1212         pSubRegionDecode->nXOrg = nXOrg;
1213         pSubRegionDecode->nYOrg = nYOrg;
1214         pSubRegionDecode->nXLength = nXLength;
1215         pSubRegionDecode->nYLength = nYLength;
1216         eError = OMX_SetParameter(pHandle, nCustomIndex, pSubRegionDecode);
1217         if ( eError != OMX_ErrorNone ) {
1218             printf ("JPEGDec test:: %d:error= %x\n", __LINE__, eError);
1219             goto EXIT;
1220         }
1221         PRINT("pSubRegionDecode set\n");
1222     }
1223 
1224     /********* EXTERNAL BUFFER ****************/
1225 
1226     if ( nExternal == 1 ) {
1227         pTemp=(OMX_U8*)malloc(pInPortDef->nBufferSize+256);
1228         pTemp+=128;
1229         pInBuffer = pTemp;
1230         pTemp=(OMX_U8*)malloc(pOutPortDef->nBufferSize+256);
1231         pTemp+=128;
1232         pOutBuffer = pTemp;
1233 
1234         eError = OMX_UseBuffer(pHandle, &pInBuffHead[0], nIndex1, pInBuffHead, pInPortDef->nBufferSize, pInBuffer);
1235         for(nBufferHdrSend = 0; (nBufferHdrSend < nNUM_OF_DECODING_BUFFERS); nBufferHdrSend++){
1236             eError = OMX_UseBuffer(pHandle, &pOutBuffHead[nBufferHdrSend], nIndex2 , pOutBuffHead, pOutPortDef->nBufferSize, pOutBuffer);
1237         }
1238     }
1239     else {
1240 
1241         OMX_AllocateBuffer(pHandle, &pInBuffHead[0], nIndex1, (void *)&nPostProcCompId, pInPortDef->nBufferSize);
1242 
1243         for(nBufferHdrSend = 0; (nBufferHdrSend < nNUM_OF_DECODING_BUFFERS); nBufferHdrSend++){
1244             OMX_AllocateBuffer(pHandle, &pOutBuffHead[nBufferHdrSend], nIndex2, (void *)&nPostProcCompId, pOutPortDef->nBufferSize);
1245             PRINT("APP:: AllocateBuff Hdr = %p ; pBuffer = %p\n", pOutBuffHead[nBufferHdrSend], pOutBuffHead[nBufferHdrSend]->pBuffer);
1246        }
1247 
1248     }
1249 
1250     gettimeofday(&tv1, NULL);
1251     eError = OMX_SendCommand(pHandle, OMX_CommandStateSet, OMX_StateIdle ,NULL);
1252     if ( eError != OMX_ErrorNone ) {
1253         fprintf (stderr,"Error from SendCommand-Idle(Init) State function\n");
1254         goto EXIT;
1255     }
1256 
1257     WaitForEvent_JPEG(pHandle, OMX_EventCmdComplete, nFdmax, OMX_StateIdle);
1258 
1259     PRINT("Transitioned to IDLE State\n");
1260     /*PRINT("from loaded to idle: %ld %ld %ld %ld\n", tv1.tv_sec, tv1.tv_usec, tv2.tv_sec, tv2.tv_usec);*/
1261 
1262     gettimeofday(&tv1, NULL);
1263     eError = OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateExecuting, NULL);
1264     if ( eError != OMX_ErrorNone ) {
1265         fprintf (stderr,"eError from SendCommand-Executing State function\n");
1266         goto EXIT;
1267     }
1268 
1269     WaitForEvent_JPEG(pHandle, OMX_EventCmdComplete, nFdmax, OMX_StateExecuting);
1270     gettimeofday(&tv2, NULL);
1271 
1272     PRINT("Transitioned to EXECUTE State\n");
1273     /*PRINT("from idle to exec: %ld %ld %ld %ld\n", tv1.tv_sec, tv1.tv_usec, tv2.tv_sec, tv2.tv_usec);*/
1274 
1275     rewind(fIn);
1276     nRead = fill_data(pInBuffHead[0], fIn, lBuffused);
1277 
1278 #ifndef UNDER_CE
1279 
1280     gettimeofday(&tim, NULL);
1281     t1=tim.tv_sec+(tim.tv_usec/1000000.0);
1282 #endif
1283 
1284     pInBuffHead[0]->nFilledLen = nRead;
1285     pInBuffHead[0]->nFlags = OMX_BUFFERFLAG_EOS;
1286 
1287     OMX_EmptyThisBuffer(pHandle, pInBuffHead[0]);
1288     DEINIT_FLAG = 0;
1289 
1290     if(nMCURow){
1291         for(nBufferHdrSend = 0; nBufferHdrSend < nNUM_OF_DECODING_BUFFERS; nBufferHdrSend++){
1292             OMX_FillThisBuffer(pHandle, pOutBuffHead[nBufferHdrSend]);
1293         }
1294     }
1295     else{
1296         OMX_FillThisBuffer(pHandle, pOutBuffHead[0]);
1297     }
1298 
1299     /** Handle the component's requests for data until we run out of data.  Do this
1300     * in a way that will allow the UI to continue to run (if there is a UI, which
1301     * this sample application does NOT have)
1302     **/
1303 
1304     PRINT("\n\n\n*******************************************\n\n\n");
1305 
1306     while (DEINIT_FLAG == 0){
1307 
1308         if (bPreempted){
1309             goto DEINIT2;
1310         }
1311 
1312         fd_set rfds;
1313         FD_ZERO(&rfds);
1314 
1315         FD_SET(IpBuf_Pipe[0], &rfds);
1316         FD_SET(OpBuf_Pipe[0], &rfds);
1317         FD_SET(Event_Pipe[0], &rfds);
1318 
1319         sigemptyset(&set);
1320         sigaddset(&set,SIGALRM);
1321         nRetval = pselect(nFdmax+1, &rfds, NULL, NULL, NULL, &set);
1322         if ( nRetval == -1 ) {
1323 #ifndef UNDER_CE
1324             perror("select()");
1325 #endif
1326             fprintf (stderr, " : Error \n");
1327             break;
1328         }
1329 
1330         /**
1331         * If FD_ISSET then there is data available in the pipe.
1332         * Read it and get the buffer data out.
1333         * Then re-fill the buffer and send it back.
1334         **/
1335         if ( FD_ISSET(Event_Pipe[0], &rfds)) {
1336 
1337             JPEGD_EVENTPRIVATE EventPrivate;
1338             read(Event_Pipe[0], &EventPrivate, sizeof(JPEGD_EVENTPRIVATE));
1339             switch(EventPrivate.eEvent) {
1340 
1341                 case OMX_EventError:
1342                     DEINIT_FLAG = OMX_TRUE;
1343                     bError = OMX_TRUE;
1344                     printf("APP:: Waiting for OMX_StateInvalid... \n");
1345                     WaitForEvent_JPEG(pHandle, OMX_EventCmdComplete, nFdmax, OMX_StateInvalid);
1346                     printf("APP:: At Invalid state.\n");
1347                     goto EXIT;
1348                     break;
1349 
1350                 case OMX_EventBufferFlag:
1351                     printf("APP:: Unloading component...\n");
1352                     break;
1353 
1354                 default:
1355                     printf("APP:: Non-error event rise. Event -> 0x%x\n", EventPrivate.eEvent);
1356                     break;
1357             }
1358         }
1359 
1360         if ( FD_ISSET(IpBuf_Pipe[0], &rfds)){
1361             read(IpBuf_Pipe[0], &pInBufferHdr, sizeof(pInBufferHdr));
1362 
1363             if ( (!nMCURow) &&  (nFramesDecoded < nMaxFrames)){
1364                 pInBuffHead[0]->nFilledLen = nRead;
1365                 pInBuffHead[0]->nFlags = OMX_BUFFERFLAG_EOS;
1366                 OMX_EmptyThisBuffer(pHandle, pInBufferHdr);
1367             }
1368         }
1369 
1370         if ( FD_ISSET(OpBuf_Pipe[0], &rfds) ) {
1371             OMX_BUFFERHEADERTYPE* pBuf;
1372 #ifndef UNDER_CE
1373             gettimeofday(&tim, NULL);
1374             t2=tim.tv_sec+(tim.tv_usec/1000000.0);
1375             /*	printf("\n%.6lf seconds elapsed\n", t2-t1);  */
1376 #endif
1377             read(OpBuf_Pipe[0], &pBuf, sizeof(pBuf));
1378 
1379             PRINT("%d ::App: Read from OpBuf_Pipe OutBufHeader %p, nFilledLen = %d\n", __LINE__, pBuf, (int)pBuf->nFilledLen);
1380 
1381 #ifdef UNDER_CE
1382             WriteFile(fOut, pBuf->pBuffer, pBuf->nFilledLen, &dwWritten, NULL);
1383 #else
1384             fwrite(pBuf->pBuffer, 1, (int ) (int)pBuf->nFilledLen, fOut);
1385             fflush(fOut);
1386 #endif
1387 
1388             nFramesDecoded++;
1389             PRINT("\n\n\n*******************************************\n\n\n");
1390 
1391             if (( (nMCURow) &&  (pBuf->nFlags && OMX_BUFFERFLAG_EOS)) ||
1392                ( (!nMCURow) &&  (nFramesDecoded >= nMaxFrames))){
1393                 break;
1394             }
1395             PRINT("---------------------------- Output Buff FRAME %d ----------------------------\n", nFramesDecoded);
1396 
1397             eError = OMX_FillThisBuffer(pHandle, pBuf);
1398             if ( eError != OMX_ErrorNone ) {
1399                 printf ("Error from OMX_FillThisBuffer\n");
1400                 goto EXIT;
1401             }
1402 
1403             if (!nMCURow){
1404                 rewind(fOut);
1405             }
1406         }
1407     }/***** End of While Loop *****/
1408 
1409     if (bError == OMX_FALSE){
1410         PRINT("APP:: Sending back to Idle\n");
1411 
1412         eError = OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateIdle, NULL);
1413         if ( eError != OMX_ErrorNone ) {
1414             fprintf (stderr,"Error from SendCommand-Idle(nStop) State function\n");
1415             goto EXIT;
1416         }
1417     }
1418 DEINIT2:
1419 
1420     if (bError == OMX_FALSE){
1421         WaitForEvent_JPEG(pHandle, OMX_EventCmdComplete, nFdmax, OMX_StateIdle);
1422 
1423         eError = OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateLoaded, NULL);
1424         if ( eError != OMX_ErrorNone ) {
1425             fprintf (stderr,"Error from SendCommand-Idle State function\n");
1426             goto EXIT;
1427         }
1428 
1429         bWaitForLoaded = OMX_TRUE;
1430     }
1431 //DEINIT1:
1432 
1433     eError = OMX_SendCommand(pHandle, OMX_CommandPortDisable, 0x0, NULL);
1434     if ( eError != OMX_ErrorNone ) {
1435         fprintf (stderr,"APP:: Error from SendCommand-PortDisable function. Input port.\n");
1436         goto EXIT;
1437     }
1438 
1439     eError = OMX_SendCommand(pHandle, OMX_CommandPortDisable, 0x1, NULL);
1440     if ( eError != OMX_ErrorNone ) {
1441         fprintf (stderr,"APP:: Error from SendCommand-PortDisable function. Output port.\n");
1442         goto EXIT;
1443     }
1444 
1445     /* Free buffers */
1446     if ( nExternal==1 )
1447     {
1448         pOutBuffer-=128;
1449         pInBuffer-=128;
1450         eError = OMX_FreeBuffer(pHandle, nIndex1, pInBuffHead[0]);
1451         for(nBufferHdrSend = 0; nBufferHdrSend < nNUM_OF_DECODING_BUFFERS; nBufferHdrSend++){
1452             eError = OMX_FreeBuffer(pHandle, nIndex2, pOutBuffHead[nBufferHdrSend]);
1453         }
1454 
1455         free(pOutBuffer);
1456         free(pInBuffer);
1457 
1458     }
1459     else {
1460         eError = OMX_FreeBuffer(pHandle, nIndex1, pInBuffHead[0]);
1461         for (nBufferHdrSend = 0; nBufferHdrSend < nNUM_OF_DECODING_BUFFERS; nBufferHdrSend ++) {
1462             eError = OMX_FreeBuffer(pHandle, nIndex2, pOutBuffHead[nBufferHdrSend]);
1463         }
1464     }
1465 
1466     if (bWaitForLoaded && (bError == OMX_FALSE)){
1467         WaitForEvent_JPEG(pHandle, OMX_EventCmdComplete, nFdmax, OMX_StateLoaded);
1468     }
1469 
1470 EXIT:
1471     if (pPortParamType) {
1472         free(pPortParamType);
1473         pPortParamType = NULL;
1474     }
1475     if (pParamPortDef) {
1476         free(pParamPortDef);
1477         pParamPortDef = NULL;
1478     }
1479     if (pInPortDef) {
1480         free(pInPortDef);
1481         pInPortDef = NULL;
1482     }
1483     if (pOutPortDef) {
1484         free(pOutPortDef);
1485         pOutPortDef = NULL;
1486     }
1487     if (imageinfo) {
1488         free(imageinfo);
1489         imageinfo = NULL;
1490     }
1491     if (pScaleFactor) {
1492         free(pScaleFactor);
1493         pScaleFactor = NULL;
1494     }
1495     if (pPortType) {
1496         free(pPortType);
1497         pPortType = NULL;
1498     }
1499     if(pSectionDecode){
1500         free(pSectionDecode);
1501         pSectionDecode = NULL;
1502     }
1503     if(pSubRegionDecode){
1504         free(pSubRegionDecode);
1505         pSubRegionDecode = NULL;
1506     }
1507 	if(pMaxResolution) {
1508 		free(pMaxResolution);
1509 		pMaxResolution = NULL;
1510 	}
1511 
1512     if ( fOut != NULL ) {
1513         PRINT("Closing Output File\n");
1514 #ifdef UNDER_CE
1515         CloseHandle(fOut);
1516 #else
1517         fclose(fOut);
1518 #endif
1519     }
1520 
1521     if ( fIn != NULL ) {
1522         PRINT("Closing Input File\n");
1523 #ifdef UNDER_CE
1524         CloseHandle(fIn);
1525 #else
1526         fclose(fIn);
1527 #endif
1528     }
1529 
1530     if (pHandle) {
1531         eError = TIOMX_FreeHandle(pHandle);
1532         if ( (eError != OMX_ErrorNone) )	{
1533             fprintf (stderr,"Error in Free Handle function\n");
1534         }
1535     }
1536 
1537 #ifdef DSP_MMU_FAULT_HANDLING
1538     if(bError) {
1539         LoadBaseImage();
1540     }
1541 #endif
1542 
1543     eError = TIOMX_Deinit();
1544     if ( eError != OMX_ErrorNone ) {
1545         PRINT("Error returned by OMX_Init()\n");
1546         goto EXIT;
1547     }
1548 
1549     return eError;
1550 }
1551 
1552 
1553 #ifdef DSP_MMU_FAULT_HANDLING
1554 
1555 int LoadBaseImage() {
1556     unsigned int uProcId = 0;	/* default proc ID is 0. */
1557     unsigned int index = 0;
1558 
1559     struct DSP_PROCESSORINFO dspInfo;
1560     DSP_HPROCESSOR hProc;
1561     DSP_STATUS status = DSP_SOK;
1562     unsigned int numProcs;
1563     char* argv[2];
1564 
1565     argv[0] = "/lib/dsp/baseimage.dof";
1566 
1567     status = (DBAPI)DspManager_Open(0, NULL);
1568     if (DSP_FAILED(status)) {
1569         printf("DSPManager_Open failed \n");
1570         return -1;
1571     }
1572     while (DSP_SUCCEEDED(DSPManager_EnumProcessorInfo(index,&dspInfo,
1573         (unsigned int)sizeof(struct DSP_PROCESSORINFO),&numProcs))) {
1574         if ((dspInfo.uProcessorType == DSPTYPE_55) ||
1575             (dspInfo.uProcessorType == DSPTYPE_64)) {
1576             uProcId = index;
1577             status = DSP_SOK;
1578             break;
1579         }
1580         index++;
1581     }
1582     status = DSPProcessor_Attach(uProcId, NULL, &hProc);
1583     if (DSP_SUCCEEDED(status)) {
1584         status = DSPProcessor_Stop(hProc);
1585         if (DSP_SUCCEEDED(status)) {
1586             status = DSPProcessor_Load(hProc,1,(const char **)argv,NULL);
1587             if (DSP_SUCCEEDED(status)) {
1588                 status = DSPProcessor_Start(hProc);
1589                 if (DSP_SUCCEEDED(status)) {
1590                 }
1591                 else {
1592                 }
1593             }
1594 			else {
1595             }
1596             DSPProcessor_Detach(hProc);
1597         }
1598         else {
1599         }
1600     }
1601     else {
1602     }
1603     fprintf(stderr,"Baseimage Loaded\n");
1604 
1605     return 0;
1606 }
1607 #endif
1608 
1609