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/**
25* @file PcmEncTest.c
26*
27* This file implements Test for PCM encoder OMX Component, which is fully
28* compliant with the Khronos 1.0 specification.
29*
30* @path  $(CSLPATH)\
31*
32* @rev  1.0
33*/
34/* ----------------------------------------------------------------------------
35*!
36*! Revision History
37*! ===================================
38*! 24-Jan-2006 rg:  Initial Version. Change required per OMAPSWxxxxxxxxx
39*! to provide _________________.
40*!
41* ============================================================================= */
42
43#include <unistd.h>
44#include <stdlib.h>
45#include <sys/ioctl.h>
46#include <sys/select.h>
47#include <string.h>
48#include <stdio.h>
49#include <fcntl.h>
50#include <errno.h>
51#include <linux/vt.h>
52#include <signal.h>
53#include <sys/stat.h>
54
55#include <OMX_Index.h>
56#include <OMX_Types.h>
57#include <OMX_Component.h>
58#include <OMX_Core.h>
59#include <OMX_Audio.h>
60/*#include <TIDspOmx.h>*/
61
62#include <pthread.h>
63#include <stdio.h>
64#include <linux/soundcard.h>
65#ifdef DSP_RENDERING_ON
66#include <AudioManagerAPI.h>
67#endif
68#include <time.h>
69#ifdef OMX_GETTIME
70#include <OMX_Common_Utils.h>
71#include <OMX_GetTime.h>     /*Headers for Performance & measuremet    */
72#endif
73
74FILE *fpRes;
75/**flush*/
76int num_flush = 0;
77int nNextFlushFrame = 100;
78/***/
79
80#define OMX_AMRDEC_NonMIME 0
81#define MIME_HEADER_LEN 6
82
83#undef APP_DEBUG
84#undef APP_MEMCHECK
85#define DASF 1
86#undef USE_BUFFER
87
88#ifdef APP_DEBUG
89    #define APP_DPRINT(...)    fprintf(stderr,__VA_ARGS__)
90#else
91    #define APP_DPRINT(...)
92#endif
93
94#ifdef APP_MEMCHECK
95    #define APP_MEMPRINT(...)    fprintf(stderr,__VA_ARGS__)
96#else
97    #define APP_MEMPRINT(...)
98#endif
99
100/* Borrowed from http://www.dtek.chalmers.se/groups/dvd/dist/oss_audio.c */
101/* AFMT_AC3 is really IEC61937 / IEC60958, mpeg/ac3/dts over spdif */
102#ifndef AFMT_AC3
103#define AFMT_AC3        0x00000400  /* Dolby Digital AC3 */
104#endif
105#ifndef AFMT_S32_LE
106#define AFMT_S32_LE     0x00001000  /* 32/24-bits, in 24bit use the msbs */
107#endif
108#ifndef AFMT_S32_BE
109#define AFMT_S32_BE     0x00002000  /* 32/24-bits, in 24bit use the msbs */
110#endif
111
112
113#define FIFO1 "/dev/fifo.1"
114#define FIFO2 "/dev/fifo.2"
115
116
117/* ======================================================================= */
118/**
119 * @def    OUTPUT_WBAMRDEC_BUFFER_SIZE   Default output buffer size
120 *
121 */
122/* ======================================================================= */
123#define OUTPUT_WBAMRDEC_BUFFER_SIZE 640
124
125/* ======================================================================= */
126/**
127 * @def    INPUT_WBAMRDEC_BUFFER_SIZE   Default input buffer size
128 *
129 */
130/* ======================================================================= */
131#define INPUT_WBAMRDEC_BUFFER_SIZE 116
132
133/* ======================================================================= */
134/**
135 * @def    APP_DEBUGMEM    This Macro turns On the logic to detec memory
136 *                         leaks on the App. To debug the component,
137 *                         WBAMRDEC_DEBUGMEM must be defined.
138 */
139/* ======================================================================= */
140#undef APP_DEBUGMEM
141/*#define APP_DEBUGMEM*/
142
143
144#ifdef APP_DEBUGMEM
145void *arr[500];
146int lines[500];
147int bytes[500];
148char file[500][50];
149int ind=0;
150
151#define newmalloc(x) mymalloc(__LINE__,__FILE__,x)
152#define newfree(z) myfree(z,__LINE__,__FILE__)
153
154void * mymalloc(int line, char *s, int size);
155int myfree(void *dp, int line, char *s);
156
157#else
158
159#define newmalloc(x) malloc(x)
160#define newfree(z) free(z)
161
162#endif
163
164#ifdef OMX_GETTIME
165  OMX_ERRORTYPE eError = OMX_ErrorNone;
166  int GT_FlagE = 0;  /* Fill Buffer 1 = First Buffer,  0 = Not First Buffer  */
167  int GT_FlagF = 0;  /*Empty Buffer  1 = First Buffer,  0 = Not First Buffer  */
168  static OMX_NODE* pListHead = NULL;
169#endif
170
171enum
172{
173    NEXT_BITRATE_UNCHANGED = 0,
174    NEXT_BITRATE_CHANGED
175};
176
177typedef enum
178{
179    MIME_NO_SUPPORT = 0,
180    MIME_SUPPORTED
181}MIME_Settings;
182
183
184/* ======================================================================= */
185/** WBAMRDEC_BUFDATA
186*
187*  @param  nFrames           # of Frames processed on the Output Buffer.
188*
189*/
190/*  ==================================================================== */
191typedef struct WBAMRDEC_BUFDATA {
192   OMX_U8 nFrames;
193}WBAMRDEC_BUFDATA;
194
195int GetInfoFromBufferHeader(unsigned char **pBufPtr, int *pCurBitRate,
196                                                int *pNextBitRateFlag);
197
198void ResetBufferPointers(unsigned char **pBuffer);
199int maxint(int a, int b);
200
201/*int gMimeFlag = 0;*/
202OMX_S16 WBAmrFrameFormat = 0;
203int gStateNotifi = 0;
204int gState;
205int inputPortDisabled = 0;
206int outputPortDisabled = 0;
207int alternate = 0;
208int numRead;
209int cnn=1;
210int cnnn=1;
211int testCaseNo = 0;
212OMX_U8 NextBuffer[INPUT_WBAMRDEC_BUFFER_SIZE*3];
213OMX_U8 TempBuffer[INPUT_WBAMRDEC_BUFFER_SIZE];
214
215#undef  WAITFORRESOURCES
216pthread_mutex_t WaitForState_mutex;
217pthread_cond_t  WaitForState_threshold;
218OMX_U8          WaitForState_flag;
219OMX_U8      TargetedState;
220/**flush*/
221pthread_mutex_t WaitForOUTFlush_mutex;
222pthread_cond_t  WaitForOUTFlush_threshold;
223pthread_mutex_t WaitForINFlush_mutex;
224pthread_cond_t  WaitForINFlush_threshold;
225/*****/
226int FirstTime = 1;
227int nRead=0;
228static OMX_BOOL bInvalidState;
229void* ArrayOfPointers[6];
230WBAMRDEC_BUFDATA* OutputFrames;
231
232#ifdef DSP_RENDERING_ON
233AM_COMMANDDATATYPE cmd_data;
234#endif
235int fill_data (OMX_U8 *pBuf, int mode, FILE *fIn);
236
237#ifndef USE_BUFFER
238int FreeAllResources( OMX_HANDLETYPE *pHandle,
239			                OMX_BUFFERHEADERTYPE* pBufferIn,
240			                OMX_BUFFERHEADERTYPE* pBufferOut,
241			                int NIB, int NOB,
242			                FILE* fIn, FILE* fOut);
243#else
244int  FreeAllResources(OMX_HANDLETYPE *pHandle,
245						  OMX_U8* UseInpBuf[],
246						  OMX_U8* UseOutBuf[],
247						  int NIB, int NOB,
248						  FILE* fIn, FILE* fOut);
249#endif
250typedef enum COMPONENTS {
251    COMP_1,
252    COMP_2
253}COMPONENTS;
254void ConfigureAudio();
255
256OMX_STRING strAmrEncoder = "OMX.TI.WBAMR.decode";
257int IpBuf_Pipe[2];
258int OpBuf_Pipe[2];
259int Event_Pipe[2];
260
261int preempted = 0;
262
263OMX_ERRORTYPE send_input_buffer (OMX_HANDLETYPE pHandle, OMX_BUFFERHEADERTYPE* pBuffer, FILE *fIn);
264OMX_ERRORTYPE StopComponent(OMX_HANDLETYPE *pHandle);
265OMX_ERRORTYPE PauseComponent(OMX_HANDLETYPE *pHandle);
266OMX_ERRORTYPE PlayComponent(OMX_HANDLETYPE *pHandle);
267
268fd_set rfds;
269
270OMX_S16 dasfmode = 0;
271
272/* safe routine to get the maximum of 2 integers */
273int maxint(int a, int b)
274{
275         return (a>b) ? a : b;
276}
277
278/* This method will wait for the component to get to the state
279 * specified by the DesiredState input. */
280static OMX_ERRORTYPE WaitForState(OMX_HANDLETYPE* pHandle,
281                                  OMX_STATETYPE DesiredState)
282{
283     OMX_STATETYPE CurState = OMX_StateInvalid;
284     OMX_ERRORTYPE eError = OMX_ErrorNone;
285     OMX_COMPONENTTYPE *pComponent = (OMX_COMPONENTTYPE *)pHandle;
286     eError = pComponent->GetState(pHandle, &CurState);
287     if (CurState == OMX_StateInvalid && bInvalidState == OMX_TRUE)
288	 {
289		 	eError = OMX_ErrorInvalidState;
290	 }
291
292    if(CurState != DesiredState){
293        WaitForState_flag = 1;
294        TargetedState = DesiredState;
295        pthread_mutex_lock(&WaitForState_mutex);
296        pthread_cond_wait(&WaitForState_threshold, &WaitForState_mutex);/*Going to sleep till signal arrives*/
297        pthread_mutex_unlock(&WaitForState_mutex);
298    }
299
300	return eError;
301}
302
303/* ================================================================================= */
304/**
305* @fn EventHandler() description for SendCommand
306EventHandler().
307App event handler
308*
309*  @see         OMX_Core.h
310*/
311/* ================================================================================ */
312
313OMX_ERRORTYPE EventHandler(
314        OMX_HANDLETYPE hComponent,
315        OMX_PTR pAppData,
316        OMX_EVENTTYPE eEvent,
317        OMX_U32 nData1,
318        OMX_U32 nData2,
319        OMX_PTR pEventData)
320{
321
322   OMX_COMPONENTTYPE *pComponent = (OMX_COMPONENTTYPE *)hComponent;
323   OMX_STATETYPE state;
324   OMX_ERRORTYPE eError;
325
326   OMX_U8 writeValue;
327
328#ifdef APP_DEBUG
329   int iComp = *((int *)(pAppData));
330#endif
331   eError = pComponent->GetState (hComponent, &state);
332   if(eError != OMX_ErrorNone) {
333       APP_DPRINT("%d :: App: Error returned from GetState\n",__LINE__);
334   }
335
336   switch (eEvent) {
337       case OMX_EventCmdComplete:
338	   	  /**flush*/
339			if (nData1 == OMX_CommandFlush){
340	            if(nData2 == 0){
341	                pthread_mutex_lock(&WaitForINFlush_mutex);
342	                pthread_cond_signal(&WaitForINFlush_threshold);
343	                pthread_mutex_unlock(&WaitForINFlush_mutex);
344	            }
345	            if(nData2 == 1){
346	                pthread_mutex_lock(&WaitForOUTFlush_mutex);
347	                pthread_cond_signal(&WaitForOUTFlush_threshold);
348	                pthread_mutex_unlock(&WaitForOUTFlush_mutex);
349	            }
350	        }
351		/****/
352           APP_DPRINT ( "%d :: App: Component State Changed To %d\n", __LINE__,state);
353
354		if (nData1 == OMX_CommandPortDisable) {
355			if (nData2 == OMX_DirInput) {
356				inputPortDisabled = 1;
357			}
358			if (nData2 == OMX_DirOutput) {
359				outputPortDisabled = 1;
360			}
361		}
362		if ((nData1 == OMX_CommandStateSet) && (TargetedState == nData2) &&
363            (WaitForState_flag)){
364            WaitForState_flag = 0;
365            pthread_mutex_lock(&WaitForState_mutex);
366            pthread_cond_signal(&WaitForState_threshold);
367            pthread_mutex_unlock(&WaitForState_mutex);
368		}
369           break;
370
371       case OMX_EventError:
372		   if (nData1 == OMX_ErrorInvalidState) {
373		   		bInvalidState =OMX_TRUE;
374		   }
375
376		   else if(nData1 == OMX_ErrorResourcesPreempted) {
377            preempted=1;
378            writeValue = 0;
379            write(Event_Pipe[1], &writeValue, sizeof(OMX_U8));
380	       }
381	       else if (nData1 == OMX_ErrorResourcesLost) {
382	            WaitForState_flag = 0;
383	            pthread_mutex_lock(&WaitForState_mutex);
384	            pthread_cond_signal(&WaitForState_threshold);/*Sending Waking Up Signal*/
385	            pthread_mutex_unlock(&WaitForState_mutex);
386	        }
387
388           break;
389       case OMX_EventMax:
390           break;
391       case OMX_EventMark:
392           break;
393#ifdef WAITFORRESOURCES
394	   case OMX_EventBufferFlag:
395       	   APP_DPRINT( "%d :: App: Component OMX_EventBufferFlag = %d\n", __LINE__,eEvent);
396		   writeValue = 2;
397	       write(Event_Pipe[1], &writeValue, sizeof(OMX_U8));
398           break;
399#endif
400       case OMX_EventResourcesAcquired:
401       	   APP_DPRINT( "%d :: App: Component OMX_EventResourcesAcquired = %d\n", __LINE__,eEvent);
402		   writeValue = 1;
403           write(Event_Pipe[1], &writeValue, sizeof(OMX_U8));
404           preempted=0;
405
406       	   break;
407
408       default:
409           break;
410   }
411	return eError;
412}
413/* ================================================================================= */
414/**
415* @fn FillBufferDone() description for FillBufferDone
416FillBufferDone().
417Called by the component when an output buffer has been filled
418*
419*  @see         OMX_Core.h
420*/
421/* ================================================================================ */
422
423void FillBufferDone (OMX_HANDLETYPE hComponent, OMX_PTR ptr, OMX_BUFFERHEADERTYPE* pBuffer)
424{
425    APP_DPRINT ("APP:::: OUTPUT BUFFER = %p && %p\n",pBuffer, pBuffer->pBuffer);
426    APP_DPRINT ("APP:::: pBuffer->nFilledLen = %ld\n",pBuffer->nFilledLen);
427/*    OutputFrames = pBuffer->pOutputPortPrivate;
428    printf("Receiving output %d Frames\n",OutputFrames->nFrames);*/
429
430    write(OpBuf_Pipe[1], &pBuffer, sizeof(pBuffer));
431	#ifdef OMX_GETTIME
432      if (GT_FlagF == 1 ) /* First Buffer Reply*/  /* 1 = First Buffer,  0 = Not First Buffer  */
433      {
434        GT_END("Call to FillBufferDone  <First: FillBufferDone>");
435        GT_FlagF = 0 ;   /* 1 = First Buffer,  0 = Not First Buffer  */
436      }
437    #endif
438}
439
440/* ================================================================================= */
441/**
442* @fn EmptyBufferDone() description for EmptyBufferDone
443EmptyBufferDone().
444Called by the component when an input buffer has been emptied
445*
446*  @see         OMX_Core.h
447*/
448/* ================================================================================ */
449
450void EmptyBufferDone(OMX_HANDLETYPE hComponent, OMX_PTR ptr, OMX_BUFFERHEADERTYPE* pBuffer)
451{
452	OMX_S16 ret;
453    APP_DPRINT ("APP:::: INPUT BUFFER = %p && %p\n",pBuffer, pBuffer->pBuffer);
454
455	if (!preempted)
456		ret = write(IpBuf_Pipe[1], &pBuffer, sizeof(pBuffer));
457#ifdef OMX_GETTIME
458    if (GT_FlagE == 1 ) /* First Buffer Reply*/  /* 1 = First Buffer,  0 = Not First Buffer  */
459    {
460      GT_END("Call to EmptyBufferDone <First: EmptyBufferDone>");
461	  GT_FlagE = 0;   /* 1 = First Buffer,  0 = Not First Buffer  */
462    }
463#endif
464}
465
466
467FILE *inputToSN;
468
469/* ================================================================================= */
470/**
471* @fn main() description for main
472main().
473Test app main function
474*
475*  @see         OMX_Core.h
476*/
477/* ================================================================================ */
478
479int main(int argc, char* argv[])
480      {
481
482
483    OMX_CALLBACKTYPE AmrCaBa = {(void *)EventHandler,
484				(void*)EmptyBufferDone,
485                                (void*)FillBufferDone};
486    OMX_HANDLETYPE pHandle;
487    OMX_ERRORTYPE error = OMX_ErrorNone;
488    OMX_U32 AppData = 100;
489    OMX_PARAM_PORTDEFINITIONTYPE* pCompPrivateStruct;
490    OMX_AUDIO_PARAM_AMRTYPE *pAmrParam;
491    OMX_COMPONENTTYPE *pComponent = (OMX_COMPONENTTYPE *)pHandle;
492    OMX_STATETYPE state;
493	/* TODO: Set a max number of buffers */
494    OMX_BUFFERHEADERTYPE* pInputBufferHeader[10];
495	/* TODO: Set a max number of buffers */
496    OMX_BUFFERHEADERTYPE* pOutputBufferHeader[10];
497    OMX_BUFFERHEADERTYPE* pBuf;
498    bInvalidState=OMX_FALSE;
499    /* TI_OMX_DATAPATH dataPath;*/
500    FILE* fOut = NULL;
501    FILE* fIn = fopen(argv[1], "r");
502
503
504#ifdef USE_BUFFER
505    OMX_U8* pInputBuffer[10];
506    OMX_U8* pOutputBuffer[10];
507#endif
508
509
510
511	int numInputBuffers = 0;
512	int numOutputBuffers = 0;
513    struct timeval tv;
514    int retval, i, j,k;
515    int frmCount = 0;
516	int testcnt = 1;
517	int testcnt1 = 1;
518    OMX_INDEXTYPE index;
519    OMX_U32	streamId;
520    int count=0;
521#ifdef DSP_RENDERING_ON
522    int wbamrdecfdwrite;
523    int wbamrdecfdread;
524#endif
525
526    /*TI_OMX_DSP_DEFINITION* audioinfo;*/
527    OMX_AUDIO_CONFIG_MUTETYPE* pCompPrivateStructMute = NULL;
528    OMX_AUDIO_CONFIG_VOLUMETYPE* pCompPrivateStructVolume = NULL;
529
530	/*TI_OMX_STREAM_INFO *streaminfo;
531    streaminfo = newmalloc(sizeof(TI_OMX_STREAM_INFO));
532	audioinfo = newmalloc(sizeof(TI_OMX_DSP_DEFINITION));
533
534    APP_MEMPRINT("%d :: [TESTAPPALLOC] audioinfo = %p\n",__LINE__,audioinfo);
535    if(NULL == audioinfo) {
536        APP_DPRINT("%d :: Malloc Failed\n",__LINE__);
537        error = OMX_ErrorInsufficientResources;
538        goto EXIT;
539    }
540
541    ArrayOfPointers[0]=(TI_OMX_STREAM_INFO*)streaminfo;
542    ArrayOfPointers[1]=(TI_OMX_DSP_DEFINITION*)audioinfo;*/
543
544    pthread_mutex_init(&WaitForState_mutex, NULL);
545    pthread_cond_init (&WaitForState_threshold, NULL);
546    WaitForState_flag = 0;
547	/**flush*/
548	pthread_mutex_init(&WaitForOUTFlush_mutex, NULL);
549    pthread_cond_init (&WaitForOUTFlush_threshold, NULL);
550    pthread_mutex_init(&WaitForINFlush_mutex, NULL);
551    pthread_cond_init (&WaitForINFlush_threshold, NULL);
552	/*****/
553
554	APP_DPRINT("------------------------------------------------------\n");
555    APP_DPRINT("This is Main Thread In WBAMR DECODER Test Application:\n");
556    APP_DPRINT("Test Core 1.5 - " __DATE__ ":" __TIME__ "\n");
557    APP_DPRINT("------------------------------------------------------\n");
558
559#ifdef OMX_GETTIME
560    printf("Line %d\n",__LINE__);
561      GTeError = OMX_ListCreate(&pListHead);
562        printf("Line %d\n",__LINE__);
563      printf("eError = %d\n",GTeError);
564      GT_START();
565  printf("Line %d\n",__LINE__);
566#endif
567
568    /* check the input parameters */
569    if((argc < 11) || (argc > 12))
570    {
571        printf( "Usage:  test infile [outfile]\n");
572        goto EXIT;
573    }
574
575	numInputBuffers = atoi(argv[9]);
576	numOutputBuffers = atoi(argv[10]);
577
578	if ( (numInputBuffers < 1) || (numInputBuffers >4)){
579        APP_DPRINT ("%d :: App: ERROR: No. of input buffers not valid (0-4) \n",__LINE__);
580		goto EXIT;
581	}
582
583	if ( (numOutputBuffers< 1) || (numOutputBuffers>4)){
584        APP_DPRINT ("%d :: App: ERROR: No. of output buffers not valid (0-4) \n",__LINE__);
585		goto EXIT;
586	}
587
588	/* check to see that the input file exists */
589    struct stat sb = {0};
590    OMX_S16 status = stat(argv[1], &sb);
591    if( status != 0 ) {
592        APP_DPRINT( "Cannot find file %s. (%u)\n", argv[1], errno);
593        goto EXIT;
594    }
595
596    /* Open the file of data to be rendered. */
597    if( fIn == NULL ) {
598        APP_DPRINT( "Error:  failed to open the file %s for readonly\access\n", argv[1]);
599        goto EXIT;
600    }
601    else{
602         printf("------------\n");
603         }
604
605	APP_DPRINT("file is %x\n",fIn);
606
607    /*FILE* fOut = NULL;*/
608        fOut = fopen(argv[2], "w");
609        if( fOut == NULL ) {
610            APP_DPRINT( "Error:  failed to create the output file %s\n", argv[2]);
611            goto EXIT;
612        }
613
614    /* Create a pipe used to queue data from the callback. */
615    retval = pipe(IpBuf_Pipe);
616    if( retval != 0) {
617        APP_DPRINT( "Error:Fill Data Pipe failed to open\n");
618        goto EXIT;
619    }
620
621    retval = pipe(OpBuf_Pipe);
622    if( retval != 0) {
623        APP_DPRINT( "Error:Empty Data Pipe failed to open\n");
624        goto EXIT;
625    }
626
627	retval = pipe(Event_Pipe);
628    if( retval != 0) {
629		    APP_DPRINT( "Error:Empty Event Pipe failed to open\n");
630		    goto EXIT;
631	}
632
633    /* save off the "max" of the handles for the selct statement */
634    OMX_S16 fdmax = maxint(IpBuf_Pipe[0], OpBuf_Pipe[0]);
635	fdmax = maxint(fdmax,Event_Pipe[0]);
636
637    APP_DPRINT("%d :: AmrTest\n",__LINE__);
638    error = TIOMX_Init();
639    APP_DPRINT("%d :: AmrTest\n",__LINE__);
640    if(error != OMX_ErrorNone) {
641        APP_DPRINT("%d :: Error returned by OMX_Init()\n",__LINE__);
642        goto EXIT;
643    }
644    int command;
645    command = atoi(argv[6]);
646    APP_DPRINT("%d :: AmrTest\n",__LINE__);
647    switch (command ) {
648        case 1:
649            printf ("-------------------------------------\n");
650            printf ("Testing Simple PLAY till EOF \n");
651            printf ("-------------------------------------\n");
652            break;
653        case 2:
654            printf ("-------------------------------------\n");
655            printf ("Testing Stop and Play \n");
656            printf ("-------------------------------------\n");
657            testcnt = 2;
658            break;
659        case 3:
660            printf ("-------------------------------------\n");
661            printf ("Testing PAUSE & RESUME Command\n");
662            printf ("-------------------------------------\n");
663            break;
664        case 4:
665            printf ("---------------------------------------------\n");
666            printf ("Testing STOP Command by Stopping In-Between\n");
667            printf ("---------------------------------------------\n");
668            break;
669        case 5:
670            printf ("-------------------------------------------------\n");
671            printf ("Testing Repeated PLAY without Deleting Component\n");
672            printf ("-------------------------------------------------\n");
673            if (argc == 12)
674            {
675                testcnt = atoi(argv[11]);
676            }
677            else
678            {
679                testcnt = 20;  /*20 cycles by default*/
680            }
681            break;
682        case 6:
683            printf ("------------------------------------------------\n");
684            printf ("Testing Repeated PLAY with Deleting Component\n");
685            printf ("------------------------------------------------\n");
686            if (argc == 12)
687            {
688                testcnt1 = atoi(argv[11]);
689            }
690            else
691            {
692                testcnt1 = 20;  /*20 cycles by default*/
693            }
694            break;
695        case 7:
696            printf ("----------------------------------------------------------\n");
697            printf ("Testing Multiframe with each buffer size = 2 x frameLength\n");
698            printf ("----------------------------------------------------------\n");
699            testCaseNo = 7;
700            break;
701        case 8:
702            printf ("------------------------------------------------------------\n");
703            printf ("Testing Multiframe with each buffer size = 1/2 x frameLength\n");
704            printf ("------------------------------------------------------------\n");
705            testCaseNo = 8;
706            break;
707        case 9:
708            printf ("------------------------------------------------------------\n");
709            printf ("Testing Multiframe with alternating buffer sizes\n");
710            printf ("------------------------------------------------------------\n");
711            testCaseNo = 9;
712            break;
713        case 10:
714            printf ("------------------------------------------------------------\n");
715            printf ("Testing Mute/Unmute for Playback Stream\n");
716            printf ("------------------------------------------------------------\n");
717            break;
718        case 11:
719            printf ("------------------------------------------------------------\n");
720            printf ("Testing Set Volume for Playback Stream\n");
721            printf ("------------------------------------------------------------\n");
722            break;
723        case 12:
724  	  	  	printf ("------------------------------------------------------------\n");
725  	  	  	printf ("Testing Frame Lost Suport\n");
726  	  	  	printf ("------------------------------------------------------------\n");
727  	  	  	break;
728		case 13:
729		   printf ("------------------------------------------------------------\n");
730		   printf ("Testing Ringtone test\n");
731		   printf ("------------------------------------------------------------\n");
732		   testcnt = 10;
733		   break;
734    }
735
736    APP_DPRINT("%d :: AmrTest\n",__LINE__);
737		dasfmode = atoi(argv[7]);
738
739    APP_DPRINT("%d :: AmrTest\n",__LINE__);
740	for(j = 0; j < testcnt1; j++) {
741
742    #ifdef DSP_RENDERING_ON
743
744        if((wbamrdecfdwrite=open(FIFO1,O_WRONLY))<0) {
745            printf("[AMRTEST] - failure to open WRITE pipe\n");
746        }
747        else {
748            printf("[AMRTEST] - opened WRITE pipe\n");
749        }
750
751        if((wbamrdecfdread=open(FIFO2,O_RDONLY))<0) {
752            printf("[AMRTEST] - failure to open READ pipe\n");
753            goto EXIT;
754        }
755        else {
756            printf("[AMRTEST] - opened READ pipe\n");
757        }
758
759	#endif
760
761        if(j >= 1) {
762            printf ("Decoding the file for %d Time\n",j+1);
763			close(IpBuf_Pipe[0]);
764			close(IpBuf_Pipe[1]);
765			close(OpBuf_Pipe[0]);
766			close(OpBuf_Pipe[1]);
767	APP_DPRINT("file is %x\n",fIn);
768		    /* Create a pipe used to queue data from the callback. */
769			retval = pipe(IpBuf_Pipe);
770			if( retval != 0) {
771				APP_DPRINT( "Error:Fill Data Pipe failed to open\n");
772				goto EXIT;
773			}
774
775			retval = pipe(OpBuf_Pipe);
776			if( retval != 0) {
777				APP_DPRINT( "Error:Empty Data Pipe failed to open\n");
778				goto EXIT;
779			}
780            fIn = fopen(argv[1], "r");
781            if( fIn == NULL ) {
782                fprintf(stderr, "Error:  failed to open the file %s for readonly\
783                                                                   access\n", argv[1]);
784                goto EXIT;
785            }
786
787            fOut = fopen(argv[2], "a");
788            if( fOut == NULL ) {
789                fprintf(stderr, "Error:  failed to create the output file \n");
790                goto EXIT;
791            }
792		    error = TIOMX_Init();
793			inputToSN = fopen("outputSecondTime.log","w");
794
795         }
796		else {
797			inputToSN = fopen("outputFirstTime.log","w");
798		}
799
800    /* Load the WBAMR Encoder Component */
801    APP_DPRINT("%d :: AmrTest\n",__LINE__);
802
803#ifdef OMX_GETTIME
804	GT_START();
805    error = OMX_GetHandle(&pHandle, strAmrEncoder, &AppData, &AmrCaBa);
806	GT_END("Call to GetHandle");
807#else
808	error = TIOMX_GetHandle(&pHandle, strAmrEncoder, &AppData, &AmrCaBa);
809#endif
810    APP_DPRINT("%d :: AmrTest\n",__LINE__);
811    if((error != OMX_ErrorNone) || (pHandle == NULL)) {
812        APP_DPRINT ("Error in Get Handle function\n");
813        goto EXIT;
814    }
815
816    APP_DPRINT("%d :: AmrTest\n",__LINE__);
817    pCompPrivateStruct = newmalloc (sizeof (OMX_PARAM_PORTDEFINITIONTYPE));
818	if (pCompPrivateStruct == 0) {
819		printf("Malloc failed\n");
820		error = -1;
821		goto EXIT;
822	}
823    ArrayOfPointers[2]=(OMX_PARAM_PORTDEFINITIONTYPE*)pCompPrivateStruct;
824
825    pCompPrivateStructMute = newmalloc (sizeof(OMX_AUDIO_CONFIG_MUTETYPE));
826    if(pCompPrivateStructMute == NULL) {
827         printf("%d :: App: Malloc Failed\n",__LINE__);
828         goto EXIT;
829     }
830     ArrayOfPointers[3] = (OMX_AUDIO_CONFIG_MUTETYPE*)pCompPrivateStructMute;
831
832     pCompPrivateStructVolume = newmalloc (sizeof(OMX_AUDIO_CONFIG_VOLUMETYPE));
833     if(pCompPrivateStructVolume == NULL) {
834         printf("%d :: App: Malloc Failed\n",__LINE__);
835         goto EXIT;
836     }
837     ArrayOfPointers[4] = (OMX_AUDIO_CONFIG_VOLUMETYPE*)pCompPrivateStructVolume;
838
839    APP_MEMPRINT("%d:::[TESTAPPALLOC] %p\n",__LINE__,pCompPrivateStruct);
840
841    APP_DPRINT("%d :: AmrTest\n",__LINE__);
842    pCompPrivateStruct->nSize = sizeof (OMX_PARAM_PORTDEFINITIONTYPE);
843    pCompPrivateStruct->nVersion.s.nVersionMajor = 0xF1;
844    pCompPrivateStruct->nVersion.s.nVersionMinor = 0xF2;
845    pCompPrivateStruct->nPortIndex = OMX_DirInput;
846    error = OMX_GetParameter (pHandle,OMX_IndexParamPortDefinition,pCompPrivateStruct);
847
848    /* Send input port config */
849
850    if(!(strcmp(argv[3],"MIME")))
851    {
852        WBAmrFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
853	}
854    else if(!(strcmp(argv[3],"NONMIME")))
855    {
856	    WBAmrFrameFormat = OMX_AUDIO_AMRFrameFormatConformance;
857	}
858    else if(!(strcmp(argv[3],"IF2")))
859    {
860		WBAmrFrameFormat = OMX_AUDIO_AMRFrameFormatIF2;
861	}
862	else
863    {
864		printf("Enter proper Frame Format Type MIME, NON MIME or IF2\nExit\n");
865		goto EXIT;
866	}
867
868
869    pCompPrivateStruct->eDir = OMX_DirInput;
870    pCompPrivateStruct->nBufferCountActual = numInputBuffers;
871    pCompPrivateStruct->nBufferCountMin                    = numInputBuffers;
872    pCompPrivateStruct->nBufferSize = INPUT_WBAMRDEC_BUFFER_SIZE;
873    pCompPrivateStruct->eDomain                            = OMX_PortDomainAudio;
874    pCompPrivateStruct->format.audio.eEncoding = OMX_AUDIO_CodingAMR;
875#ifdef OMX_GETTIME
876	GT_START();
877    error = OMX_SetParameter (pHandle,OMX_IndexParamPortDefinition,pCompPrivateStruct);
878	GT_END("Set Parameter Test-SetParameter");
879#else
880    error = OMX_SetParameter (pHandle,OMX_IndexParamPortDefinition,pCompPrivateStruct);
881#endif
882    if (error != OMX_ErrorNone) {
883        error = OMX_ErrorBadParameter;
884        printf ("%d:: OMX_ErrorBadParameter\n",__LINE__);
885        goto EXIT;
886    }
887
888    pCompPrivateStruct->nSize = sizeof (OMX_PARAM_PORTDEFINITIONTYPE);
889    pCompPrivateStruct->nVersion.s.nVersionMajor = 0xF1;
890    pCompPrivateStruct->nVersion.s.nVersionMinor = 0xF2;
891    pCompPrivateStruct->nPortIndex = OMX_DirOutput;
892    error = OMX_GetParameter (pHandle,OMX_IndexParamPortDefinition,pCompPrivateStruct);
893
894    /* Send output port config */
895    pCompPrivateStruct->eDir = OMX_DirOutput;
896    pCompPrivateStruct->nBufferCountActual = numOutputBuffers;
897    pCompPrivateStruct->nBufferCountMin                    = numOutputBuffers;
898    pCompPrivateStruct->nBufferSize = OUTPUT_WBAMRDEC_BUFFER_SIZE;
899    pCompPrivateStruct->eDomain                            = OMX_PortDomainAudio;
900
901    if(dasfmode )
902    {
903           pCompPrivateStruct->nBufferCountActual = 0;
904	}
905#ifdef OMX_GETTIME
906	GT_START();
907    error = OMX_SetParameter (pHandle,OMX_IndexParamPortDefinition,pCompPrivateStruct);
908	GT_END("Set Parameter Test-SetParameter");
909#else
910    error = OMX_SetParameter (pHandle,OMX_IndexParamPortDefinition,pCompPrivateStruct);
911#endif
912    if (error != OMX_ErrorNone) {
913        error = OMX_ErrorBadParameter;
914        printf ("%d:: OMX_ErrorBadParameter\n",__LINE__);
915        goto EXIT;
916    }
917
918	pAmrParam = newmalloc (sizeof (OMX_AUDIO_PARAM_AMRTYPE));
919    APP_MEMPRINT("%d:::[TESTAPPALLOC] %p\n",__LINE__,pAmrParam);
920    pAmrParam->nSize = sizeof (OMX_AUDIO_PARAM_AMRTYPE);
921    pAmrParam->nVersion.s.nVersionMajor = 0xF1;
922    pAmrParam->nVersion.s.nVersionMinor = 0xF2;
923    pAmrParam->nPortIndex = OMX_DirInput;
924    pAmrParam->nChannels = 1;
925    pAmrParam->nBitRate = 8000;
926	pAmrParam->eAMRBandMode = atoi(argv[5]);
927    APP_DPRINT("\n%d :: App: pAmrParam->eAMRBandMode --> %d \n",__LINE__,
928    												pAmrParam->eAMRBandMode);
929
930      ArrayOfPointers[5] = (OMX_AUDIO_PARAM_AMRTYPE *)pAmrParam;
931
932#ifndef USE_BUFFER
933
934	for (i=0; i < numInputBuffers; i++) {
935		/* allocate input buffer */
936		APP_DPRINT("%d :: About to call OMX_AllocateBuffer\n",__LINE__);
937		error = OMX_AllocateBuffer(pHandle,&pInputBufferHeader[i],0,NULL,INPUT_WBAMRDEC_BUFFER_SIZE*3);
938		APP_DPRINT("%d :: called OMX_AllocateBuffer\n",__LINE__);
939		if(error != OMX_ErrorNone) {
940	        APP_DPRINT("%d :: Error returned by OMX_AllocateBuffer()\n",__LINE__);
941			goto EXIT;
942		}
943
944	}
945        for (i=0; i < numOutputBuffers; i++) {
946	          /* allocate output buffer */
947	          APP_DPRINT("%d :: About to call OMX_AllocateBuffer\n",__LINE__);
948	          printf("About to call OMX_AllocateBuffer\n");
949	          if ((testCaseNo != 7)&&(testCaseNo != 9))
950    	          error = OMX_AllocateBuffer(pHandle,&pOutputBufferHeader[i],1,NULL,OUTPUT_WBAMRDEC_BUFFER_SIZE*1);
951              else
952                  error = OMX_AllocateBuffer(pHandle,&pOutputBufferHeader[i],1,NULL,OUTPUT_WBAMRDEC_BUFFER_SIZE*2);
953	          APP_DPRINT("%d :: called OMX_AllocateBuffer\n",__LINE__);
954	          if(error != OMX_ErrorNone) {
955			      APP_DPRINT("%d :: Error returned by OMX_AllocateBuffer()\n",__LINE__);
956			      goto EXIT;
957		      }
958	    }
959
960#else
961
962	printf("%d::USE BUFFER\n",__LINE__);
963    APP_DPRINT("%d :: About to call OMX_UseBuffer\n",__LINE__);
964
965	for (i=0; i < numInputBuffers; i++) {
966        pInputBuffer[i] = (OMX_U8*)newmalloc(INPUT_WBAMRDEC_BUFFER_SIZE*3 + 256);
967        APP_MEMPRINT("%d:::[TESTAPPALLOC] %p\n",__LINE__,pInputBuffer[i]);
968        pInputBuffer[i] = pInputBuffer[i] + 128;
969        /* allocate input buffer */
970        APP_DPRINT("%d :: About to call OMX_UseBuffer\n",__LINE__);
971        error = OMX_UseBuffer(pHandle,&pInputBufferHeader[i],0,NULL,INPUT_WBAMRDEC_BUFFER_SIZE*3,pInputBuffer[i]);
972        APP_DPRINT("%d :: called OMX_UseBuffer\n",__LINE__);
973        if(error != OMX_ErrorNone) {
974            APP_DPRINT("%d :: Error returned by OMX_UseBuffer()\n",__LINE__);
975            goto EXIT;
976            }
977    }
978
979	for (i=0; i < numOutputBuffers; i++) {
980        if ((testCaseNo != 7)&&(testCaseNo != 9)){
981            pOutputBuffer[i]= newmalloc (OUTPUT_WBAMRDEC_BUFFER_SIZE*1 + 256);
982            APP_MEMPRINT("%d:::[TESTAPPALLOC] %p\n",__LINE__,pOutputBuffer[i]);
983            pOutputBuffer[i] = pOutputBuffer[i] + 128;
984            error = OMX_UseBuffer(pHandle,&pOutputBufferHeader[i],1,NULL,OUTPUT_WBAMRDEC_BUFFER_SIZE*1,pOutputBuffer[i]);
985            APP_DPRINT("%d :: called OMX_UseBuffer\n",__LINE__);
986            if(error != OMX_ErrorNone) {
987                APP_DPRINT("%d :: Error returned by OMX_UseBuffer()\n",__LINE__);
988                goto EXIT;
989            }
990        }
991        else{
992            pOutputBuffer[i]= newmalloc (OUTPUT_WBAMRDEC_BUFFER_SIZE*2 + 256);
993            APP_MEMPRINT("%d:::[TESTAPPALLOC] %p\n",__LINE__,pOutputBuffer[i]);
994            pOutputBuffer[i] = pOutputBuffer[i] + 128;
995            error = OMX_UseBuffer(pHandle,&pOutputBufferHeader[i],1,NULL,OUTPUT_WBAMRDEC_BUFFER_SIZE*2,pOutputBuffer[i]);
996            APP_DPRINT("%d :: called OMX_UseBuffer\n",__LINE__);
997            if(error != OMX_ErrorNone) {
998                APP_DPRINT("%d :: Error returned by OMX_UseBuffer()\n",__LINE__);
999                goto EXIT;
1000            }
1001
1002        }
1003	}
1004#endif
1005
1006
1007    if(!(strcmp(argv[4],"DTXON"))) {
1008    	/**< AMR Discontinuous Transmission Mode is enabled  */
1009    	pAmrParam->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOnVAD1;
1010    	APP_DPRINT("\n%d :: App: pAmrParam->eAMRDTXMode --> %s \n",__LINE__,
1011    												argv[4]);
1012	}
1013	if(!(strcmp(argv[4],"DTXOFF"))) {
1014		/**< AMR Discontinuous Transmission Mode is disabled */
1015		pAmrParam->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff;
1016    	APP_DPRINT("\n%d :: App: pAmrParam->eAMRDTXMode --> %s \n",__LINE__,
1017    												argv[4]);
1018	}
1019
1020    if(!(strcmp(argv[4],"WBAMR_EFR"))) {
1021    	/**< DTX as WBAMR_EFR instead of AMR standard  */
1022    	pAmrParam->eAMRDTXMode = OMX_AUDIO_AMRDTXasEFR;
1023    	APP_DPRINT("\n%d :: App: pAmrParam->eAMRDTXMode --> %s \n",__LINE__,
1024    												argv[4]);
1025	}
1026
1027    pAmrParam->eAMRFrameFormat = WBAmrFrameFormat;
1028
1029	/*if(gMimeFlag == 1){
1030			pAmrParam->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
1031	}
1032	else if(gMimeFlag == 0){
1033			 pAmrParam->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatConformance;
1034	}
1035	else {
1036			printf("Enter proper MIME mode\n");
1037			printf("MIME:0\n");
1038			printf("NON MIME:1\n");
1039			goto EXIT;
1040	}*/
1041
1042
1043#ifdef OMX_GETTIME
1044	GT_START();
1045    error = OMX_SetParameter (pHandle,OMX_IndexParamAudioAmr,pAmrParam);
1046	GT_END("Set Parameter Test-SetParameter");
1047#else
1048    error = OMX_SetParameter (pHandle,OMX_IndexParamAudioAmr,pAmrParam);
1049#endif
1050	if (error != OMX_ErrorNone) {
1051        error = OMX_ErrorBadParameter;
1052        printf ("%d:: OMX_ErrorBadParameter\n",__LINE__);
1053        goto EXIT;
1054    }
1055    pAmrParam->nPortIndex = OMX_DirOutput;
1056    pAmrParam->nChannels = 1;
1057    pAmrParam->nBitRate = 8000;
1058#ifdef OMX_GETTIME
1059	GT_START();
1060    error = OMX_SetParameter (pHandle,OMX_IndexParamAudioAmr,
1061                                           pAmrParam);
1062	GT_END("Set Parameter Test-SetParameter");
1063#else
1064    error = OMX_SetParameter (pHandle,OMX_IndexParamAudioAmr,
1065                                           pAmrParam);
1066#endif
1067    if (error != OMX_ErrorNone) {
1068        error = OMX_ErrorBadParameter;
1069        printf ("%d:: OMX_ErrorBadParameter\n",__LINE__);
1070        goto EXIT;
1071    }
1072
1073	/* get TeeDN or ACDN mode */
1074	/*audioinfo->acousticMode = atoi(argv[8]);*/
1075	/*
1076    if (audioinfo->acousticMode == OMX_TRUE) {
1077        printf("Using Acoustic Device Node Path\n");
1078	dataPath = DATAPATH_ACDN;
1079    }*/
1080    else if (dasfmode) {
1081#ifdef RTM_PATH
1082        printf("Using Real Time Mixer Path\n");
1083        dataPath = DATAPATH_APPLICATION_RTMIXER;
1084#endif
1085
1086#ifdef ETEEDN_PATH
1087        printf("Using Eteedn Path\n");
1088        dataPath = DATAPATH_APPLICATION;
1089#endif
1090    }
1091
1092    /*audioinfo->dasfMode = dasfmode;*/
1093    error = OMX_GetExtensionIndex(pHandle, "OMX.TI.index.config.wbamrheaderinfo",&index);
1094	if (error != OMX_ErrorNone) {
1095		printf("Error getting extension index\n");
1096		goto EXIT;
1097	}
1098
1099#ifdef DSP_RENDERING_ON
1100	cmd_data.hComponent = pHandle;
1101    cmd_data.AM_Cmd = AM_CommandIsOutputStreamAvailable;
1102
1103    /* for encoder, using AM_CommandIsInputStreamAvailable */
1104    cmd_data.param1 = 0;
1105
1106    if((write(wbamrdecfdwrite, &cmd_data, sizeof(cmd_data)))<0) {
1107        printf("%d ::OMX_WbAmrDecoder.c ::[WBAMR Dec Component] - send command to audio manager\n", __LINE__);
1108    }
1109    if((read(wbamrdecfdread, &cmd_data, sizeof(cmd_data)))<0) {
1110        printf("%d ::OMX_WbAmrDecoder.c ::[WBAMR Dec Component] - failure to get data from the audio manager\n", __LINE__);
1111		goto EXIT;
1112    }
1113
1114    audioinfo->streamId = cmd_data.streamID;
1115    streamId = audioinfo->streamId;
1116#endif
1117
1118	/*error = OMX_SetConfig (pHandle, index, audioinfo);
1119    if(error != OMX_ErrorNone) {
1120        error = OMX_ErrorBadParameter;
1121        APP_DPRINT("%d :: Error from OMX_SetConfig() function\n",__LINE__);
1122        goto EXIT;
1123    }
1124	*/
1125    /*error = OMX_GetExtensionIndex(pHandle, "OMX.TI.index.config.wbamr.datapath",&index);
1126	if (error != OMX_ErrorNone) {
1127		printf("Error getting extension index\n");
1128		goto EXIT;
1129	}*/
1130
1131
1132	/*error = OMX_SetConfig (pHandle, index, &dataPath);
1133    if(error != OMX_ErrorNone) {
1134        error = OMX_ErrorBadParameter;
1135        APP_DPRINT("%d :: AmrDecTest.c :: Error from OMX_SetConfig() function\n",__LINE__);
1136        goto EXIT;
1137    }*/
1138
1139
1140     /* default setting for Mute/Unmute */
1141     pCompPrivateStructMute->nSize = sizeof (OMX_AUDIO_CONFIG_MUTETYPE);
1142     pCompPrivateStructMute->nVersion.s.nVersionMajor    = 0xF1;
1143     pCompPrivateStructMute->nVersion.s.nVersionMinor    = 0xF2;
1144     pCompPrivateStructMute->nPortIndex                  = OMX_DirInput;
1145     pCompPrivateStructMute->bMute                       = OMX_FALSE;
1146
1147     /* default setting for volume */
1148     pCompPrivateStructVolume->nSize = sizeof(OMX_AUDIO_CONFIG_VOLUMETYPE);
1149     pCompPrivateStructVolume->nVersion.s.nVersionMajor  = 0xF1;
1150     pCompPrivateStructVolume->nVersion.s.nVersionMinor  = 0xF2;
1151     pCompPrivateStructVolume->nPortIndex                = OMX_DirInput;
1152     pCompPrivateStructVolume->bLinear                   = OMX_FALSE;
1153     pCompPrivateStructVolume->sVolume.nValue            = 50;               /* actual volume */
1154     pCompPrivateStructVolume->sVolume.nMin              = 0;                /* min volume */
1155     pCompPrivateStructVolume->sVolume.nMax              = 100;              /* max volume */
1156#ifdef OMX_GETTIME
1157	GT_START();
1158#endif
1159    error = OMX_SendCommand(pHandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
1160    if(error != OMX_ErrorNone) {
1161        APP_DPRINT ("Error from SendCommand-Idle(Init) State function\n");
1162        goto EXIT;
1163    }
1164    /* Wait for startup to complete */
1165    error = WaitForState(pHandle, OMX_StateIdle);
1166#ifdef OMX_GETTIME
1167	GT_END("Call to SendCommand <OMX_StateIdle>");
1168#endif
1169    if(error != OMX_ErrorNone) {
1170        APP_DPRINT( "Error:  WaitForState reports an error %X\n", error);
1171        goto EXIT;
1172    }
1173  if (dasfmode) {
1174    	/* get streamID back to application */
1175     	error = OMX_GetExtensionIndex(pHandle, "OMX.TI.index.config.wbamrstreamIDinfo",&index);
1176      	if (error != OMX_ErrorNone) {
1177       		printf("Error getting extension index\n");
1178         		goto EXIT;
1179           	}
1180	    printf("***************StreamId=%ld******************\n", streamId);
1181    }
1182    for(i = 0; i < testcnt; i++) {
1183        if(i > 0) {
1184            printf ("Decoding the file for %d Time\n",i+1);
1185
1186			close(IpBuf_Pipe[0]);
1187			close(IpBuf_Pipe[1]);
1188			close(OpBuf_Pipe[0]);
1189			close(OpBuf_Pipe[1]);
1190
1191		    /* Create a pipe used to queue data from the callback. */
1192			retval = pipe(IpBuf_Pipe);
1193			if( retval != 0) {
1194				APP_DPRINT( "Error:Fill Data Pipe failed to open\n");
1195				goto EXIT;
1196			}
1197
1198			retval = pipe(OpBuf_Pipe);
1199			if( retval != 0) {
1200				APP_DPRINT( "Error:Empty Data Pipe failed to open\n");
1201				goto EXIT;
1202			}
1203
1204            fIn = fopen(argv[1], "r");
1205            if(fIn == NULL) {
1206                fprintf(stderr, "Error:  failed to open the file %s for readonly access\n", argv[1]);
1207                goto EXIT;
1208            }
1209            fOut = fopen(argv[2], "a");
1210            if(fOut == NULL) {
1211                fprintf(stderr, "Error:  failed to create the output file \n");
1212                goto EXIT;
1213            }
1214        }
1215
1216
1217    if((command == 13)){
1218		if (i == 0){
1219			printf ("Basic Function:: Sending OMX_StateExecuting Command\n");
1220#ifdef OMX_GETTIME
1221			GT_START();
1222#endif
1223		    error = OMX_SendCommand(pHandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
1224		    if(error != OMX_ErrorNone) {
1225		        APP_DPRINT ("Error from SendCommand-Executing State function\n");
1226		        goto EXIT;
1227		    }
1228		    pComponent = (OMX_COMPONENTTYPE *)pHandle;
1229
1230		    error = WaitForState(pHandle, OMX_StateExecuting);
1231#ifdef OMX_GETTIME
1232			GT_END("Call to SendCommand <OMX_StateExecuting>");
1233#endif
1234		    if(error != OMX_ErrorNone) {
1235		        APP_DPRINT( "Error:  WaitForState reports an error %X\n", error);
1236		        goto EXIT;
1237		    }
1238		}
1239	}else{
1240		printf ("Basic Function(else):: Sending OMX_StateExecuting Command\n");
1241#ifdef OMX_GETTIME
1242		GT_START();
1243#endif
1244		error = OMX_SendCommand(pHandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
1245		if(error != OMX_ErrorNone) {
1246			APP_DPRINT ("Error from SendCommand-Executing State function\n");
1247			goto EXIT;
1248		}
1249		pComponent = (OMX_COMPONENTTYPE *)pHandle;
1250
1251		error = WaitForState(pHandle, OMX_StateExecuting);
1252#ifdef OMX_GETTIME
1253		GT_END("Call to SendCommand <OMX_StateExecuting>");
1254#endif
1255		if(error != OMX_ErrorNone) {
1256			APP_DPRINT( "Error:  WaitForState reports an error %X\n", error);
1257			goto EXIT;
1258		}
1259	}
1260
1261
1262
1263	for (k=0; k < numInputBuffers; k++) {
1264	#ifdef OMX_GETTIME
1265        if (k==0)
1266        {
1267			GT_FlagE=1;  /* 1 = First Buffer,  0 = Not First Buffer  */
1268            GT_START(); /* Empty Bufffer */
1269        }
1270	#endif
1271        error = send_input_buffer (pHandle, pInputBufferHeader[k], fIn);
1272
1273	}
1274
1275	if (dasfmode == 0) {
1276		for (k=0; k < numOutputBuffers; k++) {
1277		#ifdef OMX_GETTIME
1278			if (k==0)
1279			{
1280				GT_FlagF=1;  /* 1 = First Buffer,  0 = Not First Buffer  */
1281				GT_START(); /* Fill Buffer */
1282			}
1283		#endif
1284			pComponent->FillThisBuffer(pHandle,  pOutputBufferHeader[k]);
1285		}
1286	}
1287
1288    pComponent->GetState(pHandle, &state);
1289    retval = 1;
1290#ifndef WAITFORRESOURCES
1291   while( (error == OMX_ErrorNone) && ((state != OMX_StateIdle) || (count < 2))  )
1292    {
1293	if(1)
1294    {
1295#else
1296   while(1)
1297   {
1298        if((eError == OMX_ErrorNone) && (state != OMX_StateIdle) || (count < 2))  )
1299
1300        {
1301#endif
1302
1303        FD_ZERO(&rfds);
1304        FD_SET(IpBuf_Pipe[0], &rfds);
1305        FD_SET(OpBuf_Pipe[0], &rfds);
1306		FD_SET(Event_Pipe[0], &rfds);
1307        tv.tv_sec = 1;
1308        tv.tv_usec = 0;
1309
1310        retval = select(fdmax+1, &rfds, NULL, NULL, &tv);
1311        if(retval == -1)
1312        {
1313            perror("select()");
1314            APP_DPRINT ( " : Error \n");
1315            break;
1316        }
1317
1318    if (retval == 0)
1319           count++;
1320    if (count ==3){
1321		if(command != 13){
1322			fprintf(stderr, "Shutting down Since there is nothing else to send nor read---------- \n");
1323			StopComponent(pHandle);
1324		}else{
1325			if(i != 9){
1326				printf("**RING_TONE: Lets play again!\n");
1327				printf("counter= %d \n",i);
1328				goto my_exit;
1329
1330			}else{
1331				StopComponent(pHandle);
1332				printf("stopcomponent\n");
1333			}
1334		}
1335    }
1336
1337	if(FD_ISSET(IpBuf_Pipe[0], &rfds)){
1338		OMX_BUFFERHEADERTYPE* pBuffer;
1339		read(IpBuf_Pipe[0], &pBuffer, sizeof(pBuffer));
1340		frmCount++;
1341		pBuffer->nFlags = 0;
1342
1343		if( ((2==command) || (4==command) ) && (50 == frmCount)){ /*Stop Tests*/
1344				fprintf(stderr, "Send Stop Command to component ---------- \n");
1345				StopComponent(pHandle);
1346		}
1347
1348		/**flush*/
1349		/*if ((frmCount >= nNextFlushFrame) && (num_flush < 5000)){*/
1350		/*
1351		if (frmCount >= nNextFlushFrame){
1352			printf("Flush #%d\n", num_flush++);
1353            error = OMX_SendCommand(pHandle, OMX_CommandStateSet, OMX_StatePause, NULL);
1354            if(error != OMX_ErrorNone) {
1355				fprintf (stderr,"Error from SendCommand-Pasue State function\n");
1356                goto EXIT;
1357            }
1358            error = WaitForState(pHandle, OMX_StatePause);
1359            if(error != OMX_ErrorNone) {
1360				fprintf(stderr, "Error:  WBAmrDecoder->WaitForState reports an error %X\n", error);
1361				goto EXIT;
1362            }
1363            error = OMX_SendCommand(pHandle, OMX_CommandFlush, 0, NULL);
1364            pthread_mutex_lock(&WaitForINFlush_mutex);
1365            pthread_cond_wait(&WaitForINFlush_threshold,
1366							&WaitForINFlush_mutex);
1367            pthread_mutex_unlock(&WaitForINFlush_mutex);
1368
1369            error = OMX_SendCommand(pHandle, OMX_CommandFlush, 1, NULL);
1370            pthread_mutex_lock(&WaitForOUTFlush_mutex);
1371            pthread_cond_wait(&WaitForOUTFlush_threshold,
1372							&WaitForOUTFlush_mutex);
1373            pthread_mutex_unlock(&WaitForOUTFlush_mutex);
1374
1375            error = OMX_SendCommand(pHandle, OMX_CommandStateSet,OMX_StateExecuting, NULL);
1376            if(error != OMX_ErrorNone) {
1377				fprintf (stderr,"Error from SendCommand-Executing State function\n");
1378				goto EXIT;
1379            }
1380            error = WaitForState(pHandle, OMX_StateExecuting);
1381            if(error != OMX_ErrorNone) {
1382                fprintf(stderr, "Error:  AmrDecoder->WaitForState reports an error %X\n", error);
1383                goto EXIT;
1384            }
1385
1386            fseek(fIn, 0, SEEK_SET);
1387            frmCount = 0;
1388            nNextFlushFrame = 5 + 50 * ((rand() * 1.0) / RAND_MAX);
1389            printf("nNextFlushFrame d= %d\n", nNextFlushFrame);
1390        }*/
1391		if (state == OMX_StateExecuting){/**/
1392			error = send_input_buffer (pHandle, pBuffer, fIn);
1393				if (error != OMX_ErrorNone) {
1394					printf("goto EXIT %d\n",__LINE__);
1395					goto EXIT;
1396				}
1397	     }/**/
1398
1399		if(3 == command){ /*Pause Test*/
1400			if(frmCount == 100) {   /*100 Frames processed */
1401				printf ("Sending Pause command to Codec \n");
1402				PauseComponent(pHandle);
1403				printf("5 secs sleep...\n");
1404				sleep(5);
1405				printf ("Sending Resume command to Codec \n");
1406				PlayComponent(pHandle);
1407        		}
1408		}
1409		else if ( 10 == command ){	/*Mute and UnMuteTest*/
1410				if(frmCount == 50){
1411					printf("************Mute the playback stream*****************\n");
1412					pCompPrivateStructMute->bMute = OMX_TRUE;
1413					error = OMX_SetConfig(pHandle, OMX_IndexConfigAudioMute, pCompPrivateStructMute);
1414					if (error != OMX_ErrorNone)
1415					{
1416						error = OMX_ErrorBadParameter;
1417						goto EXIT;
1418					}
1419				}
1420				else if(frmCount == 120) {
1421						printf("************Unmute the playback stream*****************\n");
1422						pCompPrivateStructMute->bMute = OMX_FALSE;
1423						error = OMX_SetConfig(pHandle, OMX_IndexConfigAudioMute, pCompPrivateStructMute);
1424						if (error != OMX_ErrorNone) {
1425							error = OMX_ErrorBadParameter;
1426							goto EXIT;
1427						}
1428					}
1429
1430			}
1431		else if ( 11 == command ) { /*Set Volume Test*/
1432					if(frmCount == 35) {
1433						printf("************Set stream volume to high*****************\n");
1434						pCompPrivateStructVolume->sVolume.nValue = 0x8000;
1435						error = OMX_SetConfig(pHandle, OMX_IndexConfigAudioVolume, pCompPrivateStructVolume);
1436						if (error != OMX_ErrorNone) {
1437							error = OMX_ErrorBadParameter;
1438							goto EXIT;
1439						}
1440					}
1441					if(frmCount == 120) {
1442						printf("************Set stream volume to low*****************\n");
1443						pCompPrivateStructVolume->sVolume.nValue = 0x1000;
1444						error = OMX_SetConfig(pHandle, OMX_IndexConfigAudioVolume, pCompPrivateStructVolume);
1445						if (error != OMX_ErrorNone) {
1446							error = OMX_ErrorBadParameter;
1447							goto EXIT;
1448						}
1449					}
1450			}
1451       else if (command == 12) { /* frame lost test */
1452  	  	  	          if(frmCount == 35 || frmCount == 120) {
1453  	  	  	             printf("************Sending lost frame*****************\n");
1454  	  	  	             error = OMX_GetExtensionIndex(pHandle, "OMX.TI.index.config.wbamr.framelost",&index);
1455  	  	                 error = OMX_SetConfig(pHandle, index, NULL);
1456  	  	  	    	     if (error != OMX_ErrorNone) {
1457  	  	  		             error = OMX_ErrorBadParameter;
1458  	  	  		             goto EXIT;
1459  	  	  		         }
1460  	  	  	           }
1461  	  	  	}
1462		}
1463
1464        if( FD_ISSET(OpBuf_Pipe[0], &rfds) ) {
1465            read(OpBuf_Pipe[0], &pBuf, sizeof(pBuf));
1466            if(pBuf->nFlags == OMX_BUFFERFLAG_EOS){
1467                    /*printf("EOS received by App, Stopping the component\n");*/
1468                    pBuf->nFlags = 0;
1469                   /* StopComponent(pHandle);*/
1470            }
1471			/**/fwrite(pBuf->pBuffer, 1, pBuf->nFilledLen, fOut);
1472			fflush(fOut);
1473			if (state == OMX_StateExecuting ) {
1474				pComponent->FillThisBuffer(pHandle, pBuf);
1475			}
1476        }
1477
1478		if( FD_ISSET(Event_Pipe[0], &rfds) ) {
1479                OMX_U8 pipeContents;
1480                read(Event_Pipe[0], &pipeContents, sizeof(OMX_U8));
1481	            if (pipeContents == 0) {
1482                    printf("Test app received OMX_ErrorResourcesPreempted\n");
1483                    WaitForState(pHandle,OMX_StateIdle);
1484
1485					for(i=0; i < numInputBuffers; i++) {
1486						APP_DPRINT("%d :: App: About to newfree pInputBufferHeader[%d]\n",__LINE__, i);
1487						error = OMX_FreeBuffer(pHandle, OMX_DirInput, pInputBufferHeader[i]);
1488						if((error != OMX_ErrorNone)) {
1489							APP_DPRINT("%d:: Error in FreeBuffer function\n",__LINE__);
1490							goto EXIT;
1491						}
1492
1493					}
1494
1495					for(i=0; i < numOutputBuffers; i++) {
1496						APP_DPRINT("%d :: App: About to newfree pOutputBufferHeader[%d]\n",__LINE__, i);
1497						error = OMX_FreeBuffer(pHandle, OMX_DirOutput, pOutputBufferHeader[i]);
1498						if((error != OMX_ErrorNone)) {
1499							APP_DPRINT("%d :: Error in Free Buffer function\n",__LINE__);
1500							goto EXIT;
1501						}
1502
1503				    }
1504#ifdef USE_BUFFER
1505
1506		for(i=0; i < numOutputBuffers; i++) {
1507			if(pInputBuffer[i] != NULL){
1508	       		APP_MEMPRINT("%d :: App: [TESTAPPFREE] pInputBuffer[%d] = %p\n",__LINE__,i,pInputBuffer[i]);
1509	            pInputBuffer[i] = pInputBuffer[i] - 128;
1510				newfree(pInputBuffer[i]);
1511				pInputBuffer[i] = NULL;
1512			}
1513		}
1514
1515#endif
1516
1517                	OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateLoaded, NULL);
1518                    WaitForState(pHandle, OMX_StateLoaded);
1519
1520                    OMX_SendCommand(pHandle,OMX_CommandStateSet,OMX_StateWaitForResources,NULL);
1521                    WaitForState(pHandle,OMX_StateWaitForResources);
1522                }
1523                else if (pipeContents == 1) {
1524                    printf("Test app received OMX_ErrorResourcesAcquired\n");
1525
1526                    OMX_SendCommand(pHandle,OMX_CommandStateSet,OMX_StateIdle,NULL);
1527			 		for (i=0; i < numOutputBuffers; i++) {
1528				          /* allocate output buffer */
1529				          APP_DPRINT("%d :: About to call OMX_AllocateBuffer\n",__LINE__);
1530			                  error = OMX_AllocateBuffer(pHandle,&pOutputBufferHeader[i],1,NULL,OUTPUT_WBAMRDEC_BUFFER_SIZE*2);
1531				          APP_DPRINT("%d :: called OMX_AllocateBuffer\n",__LINE__);
1532				          if(error != OMX_ErrorNone) {
1533						      APP_DPRINT("%d :: Error returned by OMX_AllocateBuffer()\n",__LINE__);
1534						      goto EXIT;
1535					      }
1536				    }
1537
1538                    WaitForState(pHandle,OMX_StateIdle);
1539
1540                    OMX_SendCommand(pHandle,OMX_CommandStateSet,OMX_StateExecuting,NULL);
1541                    WaitForState(pHandle,OMX_StateExecuting);
1542
1543                    rewind(fIn);
1544
1545                    send_input_buffer (pHandle, (OMX_BUFFERHEADERTYPE*)pOutputBufferHeader, fIn);
1546                }
1547
1548                if (pipeContents == 2) {
1549
1550				if(command !=13){
1551					APP_DPRINT("%d :: AmrDecTest.c :: StopComponent\n",__LINE__);
1552                     StopComponent(pHandle);
1553#ifdef WAITFORRESOURCES
1554					for(i=0; i < numInputBuffers; i++) {
1555						APP_DPRINT("%d :: App: About to newfree pInputBufferHeader[%d]\n",__LINE__, i);
1556						error = OMX_FreeBuffer(pHandle, OMX_DirInput, pInputBufferHeader[i]);
1557						if((error != OMX_ErrorNone)) {
1558							APP_DPRINT("%d:: Error in FreeBuffer function\n",__LINE__);
1559							goto EXIT;
1560						}
1561
1562					}
1563
1564					for(i=0; i < numOutputBuffers; i++) {
1565						APP_DPRINT("%d :: App: About to newfree pOutputBufferHeader[%d]\n",__LINE__, i);
1566						error = OMX_FreeBuffer(pHandle, OMX_DirOutput, pOutputBufferHeader[i]);
1567						if((error != OMX_ErrorNone)) {
1568							APP_DPRINT("%d :: Error in Free Buffer function\n",__LINE__);
1569							goto EXIT;
1570						}
1571
1572				    }
1573
1574                	OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateLoaded, NULL);
1575                    WaitForState(pHandle, OMX_StateLoaded);
1576
1577                    goto SHUTDOWN;
1578#endif
1579				}else{
1580				printf("**RING_TONE: !!!!\n");
1581					if(i != 9){
1582						printf("**RING_TONE: Lets play again!\n");
1583						printf("counter= %d \n",i);
1584		                goto my_exit;
1585
1586		            }else{
1587						StopComponent(pHandle);
1588						printf("stopcomponent\n");
1589		            }
1590				}
1591              }
1592            }
1593        error = pComponent->GetState(pHandle, &state);
1594        if(error != OMX_ErrorNone) {
1595              APP_DPRINT("%d:: Warning:  hAmrEncoder->GetState has returned status %X\n",
1596              																  __LINE__, error);
1597              goto EXIT;
1598        }
1599		}
1600        else if (preempted) {
1601            sched_yield();
1602        }
1603        else {
1604            goto SHUTDOWN;
1605        }
1606
1607} /* While Loop Ending Here */
1608/*-----------------------------------------*/
1609    printf ("The current state of the component = %d \n",state);
1610my_exit:
1611    fclose(fOut);
1612    fclose(fIn);
1613    FirstTime = 1;
1614    count=0;
1615
1616    } /*Inner for loop ends here */
1617	/* newfree buffers */
1618	for (i=0; i < numInputBuffers; i++) {
1619		error = OMX_FreeBuffer(pHandle,OMX_DirInput,pInputBufferHeader[i]);
1620		if( (error != OMX_ErrorNone)) {
1621	        APP_DPRINT ("%d:: Error in Free Handle function\n",__LINE__);
1622			goto EXIT;
1623		}
1624	}
1625	for (i=0; i < numOutputBuffers; i++) {
1626		error = OMX_FreeBuffer(pHandle,OMX_DirOutput,pOutputBufferHeader[i]);
1627		if( (error != OMX_ErrorNone)) {
1628	        APP_DPRINT ("%d:: Error in Free Handle function\n",__LINE__);
1629			goto EXIT;
1630		}
1631	}
1632
1633#ifdef USE_BUFFER
1634
1635	/* newfree the App Allocated Buffers */
1636	printf("%d :: App: Freeing the App Allocated Buffers in TestApp\n",__LINE__);
1637	for(i=0; i < numInputBuffers; i++) {
1638		if(pInputBuffer[i] != NULL){
1639            APP_MEMPRINT("%d :: App: [TESTAPPFREE] pInputBuffer[%d] = %p\n",__LINE__,i,pInputBuffer[i]);
1640	    	pInputBuffer[i] = pInputBuffer[i] - 128;
1641			newfree(pInputBuffer[i]);
1642			pInputBuffer[i] = NULL;
1643		}
1644	}
1645
1646	for(i=0; i < numOutputBuffers; i++) {
1647		if(pOutputBuffer[i] != NULL){
1648    		APP_MEMPRINT("%d :: App: [TESTAPPFREE] pOutputBuffer[%d] = %p\n",__LINE__,i, pOutputBuffer[i]);
1649	    	pOutputBuffer[i] = pOutputBuffer[i] - 128;
1650			newfree(pOutputBuffer[i]);
1651			pOutputBuffer[i] = NULL;
1652		}
1653	}
1654
1655#endif
1656	printf ("Sending the StateLoaded Command\n");
1657
1658#ifdef OMX_GETTIME
1659	GT_START();
1660#endif
1661    error = OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateLoaded, NULL);
1662    if(error != OMX_ErrorNone) {
1663        APP_DPRINT ("%d:: Error from SendCommand-Idle State function\n",__LINE__);
1664        goto EXIT;
1665    }
1666    error = WaitForState(pHandle, OMX_StateLoaded);
1667#ifdef OMX_GETTIME
1668	GT_END("Call to SendCommand <OMX_StateLoaded>");
1669#endif
1670    if(error != OMX_ErrorNone) {
1671        APP_DPRINT( "Error:  WaitForState reports an error %X\n", error);
1672        goto EXIT;
1673    }
1674
1675	error = OMX_SendCommand(pHandle, OMX_CommandPortDisable, -1, NULL);
1676
1677
1678
1679#ifdef WAITFORRESOURCES
1680    error = OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateWaitForResources, NULL);
1681    if(error != OMX_ErrorNone) {
1682        APP_DPRINT ("%d Error from SendCommand-Idle State function\n",__LINE__);
1683        goto EXIT;
1684    }
1685    error = WaitForState(pHandle, OMX_StateWaitForResources);
1686
1687    /* temporarily put this here until I figure out what should really happen here */
1688    sleep(10);
1689    /* temporarily put this here until I figure out what should really happen here */
1690#endif
1691SHUTDOWN:
1692#ifdef DSP_RENDERING_ON
1693	cmd_data.hComponent = pHandle;
1694    cmd_data.AM_Cmd = AM_Exit;
1695
1696    if((write(wbamrdecfdwrite, &cmd_data, sizeof(cmd_data)))<0)
1697        printf("%d ::OMX_AmrDecoder.c :: [NBAMR Dec Component] - send command to audio manager\n",__LINE__);
1698	close(wbamrdecfdwrite);
1699    close(wbamrdecfdread);
1700#endif
1701    printf ("Free the Component handle\n");
1702
1703    /* Unload the WBAMR Encoder Component */
1704
1705    APP_MEMPRINT("%d:::[TESTAPPFREE] %p\n",__LINE__,pAmrParam);
1706    newfree(pAmrParam);
1707
1708    APP_MEMPRINT("%d:::[TESTAPPFREE] %p\n",__LINE__,pCompPrivateStruct);
1709    newfree(pCompPrivateStruct);
1710    APP_MEMPRINT("%d:::[TESTAPPFREE] %p\n",__LINE__,pCompPrivateStructMute);
1711    newfree(pCompPrivateStructMute);
1712    APP_MEMPRINT("%d:::[TESTAPPFREE] %p\n",__LINE__,pCompPrivateStructVolume);
1713    newfree(pCompPrivateStructVolume);
1714
1715    error = TIOMX_FreeHandle(pHandle);
1716
1717		if( (error != OMX_ErrorNone)) {
1718        APP_DPRINT ("%d:: Error in Free Handle function\n",__LINE__);
1719        goto EXIT;
1720    }
1721
1722	close(IpBuf_Pipe[0]);
1723	close(IpBuf_Pipe[1]);
1724	close(OpBuf_Pipe[0]);
1725	close(OpBuf_Pipe[1]);
1726
1727	fclose(inputToSN);
1728    APP_DPRINT ("%d:: Free Handle returned Successfully \n\n\n\n",__LINE__);
1729
1730	} /*Outer for loop ends here */
1731
1732	pthread_mutex_destroy(&WaitForState_mutex);
1733    pthread_cond_destroy(&WaitForState_threshold);
1734
1735	/**flush	*/
1736	pthread_mutex_destroy(&WaitForOUTFlush_mutex);
1737	pthread_cond_destroy(&WaitForOUTFlush_threshold);
1738	pthread_mutex_destroy(&WaitForINFlush_mutex);
1739	pthread_cond_destroy(&WaitForINFlush_threshold);
1740	/***/
1741
1742  	error = TIOMX_Deinit();
1743    if( (error != OMX_ErrorNone))
1744    {
1745			APP_DPRINT("APP: Error in Deinit Core function\n");
1746			goto EXIT;
1747    }
1748
1749    /*newfree(audioinfo);
1750
1751    newfree(streaminfo);*/
1752
1753
1754
1755EXIT:
1756	if(bInvalidState==OMX_TRUE)
1757	{
1758#ifndef USE_BUFFER
1759		error = FreeAllResources(pHandle,
1760								pInputBufferHeader[0],
1761								pOutputBufferHeader[0],
1762								numInputBuffers,
1763								numOutputBuffers,
1764								fIn,
1765                                fOut);
1766#else
1767		error = FreeAllResources(pHandle,
1768									pInputBuffer,
1769									pOutputBuffer,
1770									numInputBuffers,
1771									numOutputBuffers,
1772									fIn,
1773                                    fOut);
1774#endif
1775   }
1776#ifdef APP_DEBUGMEM
1777    printf("\n-Printing memory not deleted-\n");
1778    for(i=0;i<500;i++){
1779        if (lines[i]!=0){
1780             printf(" --->%d Bytes allocated on %p File:%s Line: %d\n",bytes[i], arr[i],file[i],lines[i]);
1781             }
1782    }
1783#endif
1784
1785#ifdef OMX_GETTIME
1786	GT_END("WBAMR_DEC test <End>");
1787	OMX_ListDestroy(pListHead);
1788#endif
1789    return error;
1790
1791 }
1792
1793/* ================================================================================= */
1794/**
1795* @fn send_input_buffer() description for send_input_buffer
1796send_input_buffer().
1797Sends input buffer to component
1798*
1799*/
1800/* ================================================================================ */
1801OMX_ERRORTYPE send_input_buffer(OMX_HANDLETYPE pHandle, OMX_BUFFERHEADERTYPE* pBuffer, FILE *fIn)
1802{
1803        OMX_ERRORTYPE error = OMX_ErrorNone;
1804        OMX_COMPONENTTYPE *pComponent = (OMX_COMPONENTTYPE *)pHandle;
1805        APP_DPRINT ("*************************\n");
1806        APP_DPRINT ("%d :: pBuffer = %p nRead = %d\n",__LINE__,pBuffer,nRead);
1807        APP_DPRINT ("*************************\n");
1808
1809    if(FirstTime)
1810    {
1811        nRead = fill_data (pBuffer->pBuffer, WBAmrFrameFormat, fIn);
1812        pBuffer->nFilledLen = nRead;
1813    }
1814        else
1815        {
1816            memcpy(pBuffer->pBuffer, NextBuffer,nRead);
1817            pBuffer->nFilledLen = nRead;
1818        }
1819
1820         nRead = fill_data (NextBuffer, WBAmrFrameFormat, fIn);
1821
1822         if (WBAmrFrameFormat == OMX_AUDIO_AMRFrameFormatConformance)
1823         {
1824                if( nRead<numRead )
1825                      pBuffer->nFlags = OMX_BUFFERFLAG_EOS;
1826                else
1827                      pBuffer->nFlags = 0;
1828         }
1829
1830        else
1831        {
1832                if( 0 == nRead )
1833                      pBuffer->nFlags = OMX_BUFFERFLAG_EOS;
1834                else
1835                   pBuffer->nFlags = 0;
1836        }
1837
1838        if(pBuffer->nFilledLen!=0)
1839        {
1840                if (pBuffer->nFlags == OMX_BUFFERFLAG_EOS)
1841                    printf("EOS send on last data buffer\n");
1842
1843                pBuffer->nTimeStamp = rand() % 100;
1844                error = pComponent->EmptyThisBuffer(pHandle, pBuffer);
1845                if (error == OMX_ErrorIncorrectStateOperation)
1846                        error = 0;
1847
1848
1849
1850        }
1851        FirstTime=0;
1852        /*printf("Fin de send_input buffer...");*/
1853
1854        return error;
1855}
1856
1857/* ================================================================================= */
1858/**
1859* @fn fill_data() description for fill_data
1860fill_data().
1861Fills input buffer
1862*
1863*/
1864/* ================================================================================ */
1865
1866int fill_data (OMX_U8 *pBuf, int mode, FILE *fIn)
1867{
1868    int nBytesRead = 0;
1869    static unsigned long totalRead = 0;
1870    static int fileHdrReadFlag = 0;
1871
1872    if (OMX_AUDIO_AMRFrameFormatConformance == mode)
1873    {
1874         if (!fileHdrReadFlag)
1875         {
1876            fprintf (stderr, "Reading the file in Frame Format Conformance Mode\n");
1877            fileHdrReadFlag = 1;
1878         }
1879
1880		if (testCaseNo == 7) {
1881			numRead = 2*INPUT_WBAMRDEC_BUFFER_SIZE;
1882		}
1883		else if (testCaseNo == 8) {
1884			numRead = INPUT_WBAMRDEC_BUFFER_SIZE/2;
1885		}
1886		else if (testCaseNo == 9) {
1887			if (alternate == 0) {
1888				numRead = 2*INPUT_WBAMRDEC_BUFFER_SIZE;
1889				alternate = 1;
1890			}
1891			else {
1892				numRead = INPUT_WBAMRDEC_BUFFER_SIZE/2;
1893				alternate = 0;
1894			}
1895		}
1896		else {
1897			numRead = INPUT_WBAMRDEC_BUFFER_SIZE;
1898		}
1899        nBytesRead = fread(pBuf, 1, numRead , fIn);
1900
1901    }
1902
1903    else if(OMX_AUDIO_AMRFrameFormatFSF == mode)
1904    { /*Mime Mode*/
1905        static const unsigned char FrameLength[] = {18, 24, 33, 37, 41, 47, 51, 59, 61,6};
1906        char size = 0;
1907        int index = 45; /* some invalid value*/
1908        signed char first_char;
1909        if (!fileHdrReadFlag) {
1910           fprintf (stderr, "Reading the file in MIME Mode\n");
1911           /* Read the file header */
1912           if((fgetc(fIn) != 0x23) || (fgetc(fIn) != 0x21) ||
1913              (fgetc(fIn) != 0x41) || (fgetc(fIn) != 0x4d) ||
1914              (fgetc(fIn) != 0x52) || (fgetc(fIn) != 0x2d) ||
1915              (fgetc(fIn) != 0x57) || (fgetc(fIn) != 0x42) ||
1916              (fgetc(fIn) != 0x0a)) {
1917                   fprintf(stderr, "Error:  File does not have correct header\n");
1918           }
1919           fileHdrReadFlag = 1;
1920        }
1921        first_char = fgetc(fIn);
1922        if (EOF == first_char) {
1923            fprintf(stderr, "Got EOF character\n");
1924            nBytesRead = 0;
1925            goto EXIT;
1926        }
1927        index = (first_char>>3) & 0xf;
1928
1929        if((index>=0) && (index<10))
1930        {
1931            size = FrameLength[index];
1932            *((OMX_S8*)(pBuf)) = first_char;
1933            nBytesRead = fread(((char*)(pBuf))+1, 1, size - 1, fIn);
1934            nBytesRead += 1;
1935        }
1936        else if (index == 14) {
1937            *((char*)(pBuf)) = first_char;
1938            nBytesRead = 1;
1939        }
1940        else if (index == 15) {
1941            *((char*)(pBuf)) = first_char;
1942            nBytesRead = 1;
1943        }
1944        else {
1945            nBytesRead = 0;
1946            fprintf(stderr, "Invalid Index in the frame index1 = %d \n", index);
1947            goto EXIT;
1948        }
1949    }
1950
1951    else if(OMX_AUDIO_AMRFrameFormatIF2 == mode)
1952    {/*IF2*/
1953        static const OMX_U8 FrameLength[] = {18, 23, 33, 37, 41, 47, 51, 59, 61, 6};/*List of valid IF2 frame length*/
1954        OMX_S8 size = 0;
1955        OMX_S16 index = 45; /* some invalid value*/
1956        OMX_S8 first_char;
1957
1958        if (!fileHdrReadFlag) {
1959           fprintf (stderr, "Reading the file in IF2 Mode\n");
1960           fileHdrReadFlag = 1;
1961        }
1962
1963        first_char = fgetc(fIn);
1964        if (EOF == first_char) {
1965            fprintf(stderr, "Got EOF character\n");
1966            nBytesRead = 0;
1967            goto EXIT;
1968        }
1969        index = (first_char>>4) & 0xf;
1970        if((index>=0) && (index<=9))
1971        {
1972            size = FrameLength[index];
1973            *((OMX_S8*)(pBuf)) = first_char;
1974            nBytesRead = fread(((OMX_S8*)(pBuf))+1, 1, size - 1, fIn);
1975            nBytesRead += 1;
1976		} else if (index == 14) {
1977            *((char*)(pBuf)) = first_char;
1978            nBytesRead = 1;
1979        } else if (index == 15) {
1980            *((OMX_S8*)(pBuf)) = first_char;
1981            nBytesRead = 1;
1982        } else {
1983            nRead = 0;
1984            printf("Invalid Index in the frame index2 = %d \n", index);
1985            goto EXIT;
1986        }
1987
1988
1989
1990
1991    }
1992
1993    totalRead += nBytesRead;
1994EXIT:
1995    return nBytesRead;
1996}
1997
1998OMX_ERRORTYPE StopComponent(OMX_HANDLETYPE *pHandle)
1999{
2000    OMX_ERRORTYPE error = OMX_ErrorNone;
2001#ifdef OMX_GETTIME
2002	GT_START();
2003#endif
2004    error = OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateIdle, NULL);
2005	if(error != OMX_ErrorNone) {
2006                    fprintf (stderr,"\nError from SendCommand-Idle(Stop) State function!!!!!!!!\n");
2007                    goto EXIT;
2008		}
2009	error =	WaitForState(pHandle, OMX_StateIdle);
2010#ifdef OMX_GETTIME
2011	GT_END("Call to SendCommand <OMX_StateIdle>");
2012#endif
2013    if(error != OMX_ErrorNone) {
2014					fprintf(stderr, "\nError:  WaitForState reports an error %X!!!!!!!\n", error);
2015					goto EXIT;
2016	}
2017EXIT:
2018    return error;
2019}
2020
2021OMX_ERRORTYPE PauseComponent(OMX_HANDLETYPE *pHandle)
2022{
2023    OMX_ERRORTYPE error = OMX_ErrorNone;
2024#ifdef OMX_GETTIME
2025	GT_START();
2026#endif
2027    error = OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StatePause, NULL);
2028	if(error != OMX_ErrorNone) {
2029                    fprintf (stderr,"\nError from SendCommand-Pasue State function!!!!!!\n");
2030                    goto EXIT;
2031		}
2032	error =	WaitForState(pHandle, OMX_StatePause);
2033#ifdef OMX_GETTIME
2034	GT_END("Call to SendCommand <OMX_StatePause>");
2035#endif
2036    if(error != OMX_ErrorNone) {
2037					fprintf(stderr, "\nError:  WaitForState reports an error %X!!!!!!!\n", error);
2038					goto EXIT;
2039	}
2040EXIT:
2041    return error;
2042}
2043
2044OMX_ERRORTYPE PlayComponent(OMX_HANDLETYPE *pHandle)
2045{
2046    OMX_ERRORTYPE error = OMX_ErrorNone;
2047
2048#ifdef OMX_GETTIME
2049	GT_START();
2050#endif
2051    error = OMX_SendCommand(pHandle,OMX_CommandStateSet, OMX_StateExecuting, NULL);
2052	if(error != OMX_ErrorNone) {
2053                    fprintf (stderr,"\nError from SendCommand-Executing State function!!!!!!!\n");
2054                    goto EXIT;
2055		}
2056	error =	WaitForState(pHandle, OMX_StateExecuting);
2057#ifdef OMX_GETTIME
2058	GT_END("Call to SendCommand <OMX_StateExecuting>");
2059#endif
2060    if(error != OMX_ErrorNone) {
2061					fprintf(stderr, "\nError:  WaitForState reports an error %X!!!!!!!\n", error);
2062					goto EXIT;
2063	}
2064EXIT:
2065    return error;
2066}
2067
2068#ifdef APP_DEBUGMEM
2069void * mymalloc(int line, char *s, int size)
2070{
2071   void *p;
2072   int e=0;
2073   p = malloc(size);
2074   if(p==NULL){
2075       printf("Memory not available\n");
2076       exit(1);
2077       }
2078   else{
2079         while((lines[e]!=0)&& (e<500) ){
2080              e++;
2081         }
2082         arr[e]=p;
2083         lines[e]=line;
2084         bytes[e]=size;
2085         strcpy(file[e],s);
2086         printf("Allocating %d bytes on address %p, line %d file %s\n", size, p, line, s);
2087         return p;
2088   }
2089}
2090
2091int myfree(void *dp, int line, char *s){
2092    int q;
2093    if (dp==NULL){
2094       printf("Null Memory can not be deleted line: %d  file: %s\n", line, s);
2095       return 0;
2096    }
2097
2098    for(q=0;q<500;q++){
2099        if(arr[q]==dp){
2100           printf("Deleting %d bytes on address %p, line %d file %s\n", bytes[q],dp, line, s);
2101           free(dp);
2102           dp = NULL;
2103           lines[q]=0;
2104           strcpy(file[q],"");
2105           break;
2106        }
2107     }
2108     if(500==q)
2109         printf("\n\nPointer not found. Line:%d    File%s!!\n\n",line, s);
2110     return 1;
2111}
2112#endif
2113/*=================================================================
2114
2115							Freeing All allocated resources
2116
2117==================================================================*/
2118#ifndef USE_BUFFER
2119int FreeAllResources( OMX_HANDLETYPE *pHandle,
2120			                OMX_BUFFERHEADERTYPE* pBufferIn,
2121			                OMX_BUFFERHEADERTYPE* pBufferOut,
2122			                int NIB, int NOB,
2123			                FILE* fileIn, FILE* fileOut)
2124{
2125	printf("%d::Freeing all resources by state invalid \n",__LINE__);
2126	OMX_ERRORTYPE eError = OMX_ErrorNone;
2127	OMX_U16 i;
2128	for(i=0; i < NIB; i++) {
2129		   printf("%d :: APP: About to free pInputBufferHeader[%d]\n",__LINE__, i);
2130		   eError = OMX_FreeBuffer(pHandle, OMX_DirInput, pBufferIn+i);
2131
2132	}
2133
2134
2135	for(i=0; i < NOB; i++) {
2136		   printf("%d :: APP: About to free pOutputBufferHeader[%d]\n",__LINE__, i);
2137		   eError = OMX_FreeBuffer(pHandle, OMX_DirOutput, pBufferOut+i);
2138	}
2139
2140	/*i value is fixed by the number calls to malloc in the App */
2141	for(i=0; i<6;i++)
2142	{
2143		if (ArrayOfPointers[i] != NULL)
2144			free(ArrayOfPointers[i]);
2145	}
2146
2147
2148	    eError = close (IpBuf_Pipe[0]);
2149	    eError = close (IpBuf_Pipe[1]);
2150	    eError = close (OpBuf_Pipe[0]);
2151	    eError = close (OpBuf_Pipe[1]);
2152		eError = close (Event_Pipe[0]);
2153		eError = close (Event_Pipe[1]);
2154	if(fileOut != NULL)	/* Could have been closed  previously */
2155	{
2156		fclose(fileOut);
2157		fileOut=NULL;
2158	}
2159
2160	if(fileIn != NULL)
2161	{	fclose(fileIn);
2162		fileIn=NULL;
2163	}
2164
2165	TIOMX_FreeHandle(pHandle);
2166
2167	return eError;
2168
2169}
2170
2171
2172/*=================================================================
2173
2174							Freeing the resources with USE_BUFFER define
2175
2176==================================================================*/
2177#else
2178
2179int FreeAllResources(OMX_HANDLETYPE *pHandle,
2180							OMX_U8* UseInpBuf[],
2181							OMX_U8* UseOutBuf[],
2182							int NIB,int NOB,
2183							FILE* fileIn, FILE* fileOut)
2184{
2185
2186		OMX_ERRORTYPE eError = OMX_ErrorNone;
2187		OMX_U16 i;
2188		printf("%d::Freeing all resources by state invalid \n",__LINE__);
2189    	/* free the UseBuffers */
2190	    for(i=0; i < NIB; i++) {
2191		   UseInpBuf[i] = UseInpBuf[i] - 128;
2192		   printf("%d :: [TESTAPPFREE] pInputBuffer[%d] = %p\n",__LINE__,i,(UseInpBuf[i]));
2193		   if(UseInpBuf[i] != NULL){
2194			  newfree(UseInpBuf[i]);
2195			  UseInpBuf[i] = NULL;
2196		   }
2197		}
2198
2199	    for(i=0; i < NOB; i++) {
2200		   UseOutBuf[i] = UseOutBuf[i] - 128;
2201		   printf("%d :: [TESTAPPFREE] pOutputBuffer[%d] = %p\n",__LINE__,i, UseOutBuf[i]);
2202		   if(UseOutBuf[i] != NULL){
2203			  newfree(UseOutBuf[i]);
2204			  UseOutBuf[i] = NULL;
2205		   }
2206		}
2207
2208	/*i value is fixed by the number calls to malloc in the App */
2209		for(i=0; i<6;i++)
2210		{
2211			if (ArrayOfPointers[i] != NULL)
2212				free(ArrayOfPointers[i]);
2213		}
2214
2215			eError = close (IpBuf_Pipe[0]);
2216			eError = close (IpBuf_Pipe[1]);
2217			eError = close (OpBuf_Pipe[0]);
2218			eError = close (OpBuf_Pipe[1]);
2219
2220		if (fileOut != NULL)	/* Could have been closed  previously */
2221		{
2222			fclose(fileOut);
2223			fileOut=NULL;
2224		}
2225
2226		if (fileIn != NULL)
2227		{	fclose(fileIn);
2228			fileIn=NULL;
2229		}
2230
2231		OMX_FreeHandle(pHandle);
2232
2233		return eError;
2234}
2235
2236#endif
2237