1/*--------------------------------------------------------------------------
2Copyright (c) 2010-2014, The Linux Foundation. All rights reserved.
3
4Redistribution and use in source and binary forms, with or without
5modification, are permitted provided that the following conditions are met:
6    * Redistributions of source code must retain the above copyright
7      notice, this list of conditions and the following disclaimer.
8    * Redistributions in binary form must reproduce the above copyright
9      notice, this list of conditions and the following disclaimer in the
10      documentation and/or other materials provided with the distribution.
11    * Neither the name of The Linux Foundation nor
12      the names of its contributors may be used to endorse or promote
13      products derived from this software without specific prior written
14      permission.
15
16THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
20CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
23OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
25OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
26ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27--------------------------------------------------------------------------*/
28
29
30/*
31    An Open max test application ....
32*/
33
34#include <stdio.h>
35#include <string.h>
36#include <stdlib.h>
37#include <unistd.h>
38#include <fcntl.h>
39#include <sys/types.h>
40#include <sys/mman.h>
41#include <time.h>
42#include <sys/ioctl.h>
43#include "OMX_Core.h"
44#include "OMX_Component.h"
45#include "pthread.h"
46#include <signal.h>
47
48#include <stdio.h>
49#include <stdlib.h>
50#include <fcntl.h>
51#include <stdint.h>
52#include <sys/mman.h>
53#include <sys/ioctl.h>
54#include<unistd.h>
55#include<string.h>
56#include <pthread.h>
57#include "QOMX_AudioExtensions.h"
58#include "QOMX_AudioIndexExtensions.h"
59#ifdef AUDIOV2
60#include "control.h"
61#endif
62#include <linux/ioctl.h>
63
64typedef unsigned char uint8;
65typedef unsigned char byte;
66typedef unsigned int  uint32;
67typedef unsigned int  uint16;
68#define AUDAAC_MAX_ADIF_HEADER_LENGTH 64
69/* ADTS variable frame header, frame length field  */
70#define AUDAAC_ADTS_FRAME_LENGTH_SIZE    13
71QOMX_AUDIO_STREAM_INFO_DATA streaminfoparam;
72void audaac_rec_install_bits
73(
74  uint8   *input,
75  byte    num_bits_reqd,
76  uint32  value,
77  uint16  *hdr_bit_index
78);
79
80/* maximum ADTS frame header length                */
81#define AUDAAC_MAX_ADTS_HEADER_LENGTH 7
82void audaac_rec_install_adts_header_variable (uint16  byte_num);
83void Release_Encoder();
84
85#ifdef AUDIOV2
86unsigned short session_id;
87int device_id;
88int control = 0;
89const char *device="handset_tx";
90#define DIR_TX 2
91#endif
92
93#define AACHDR_LAYER_SIZE             2
94#define AACHDR_CRC_SIZE               1
95#define AAC_PROFILE_SIZE              2
96#define AAC_SAMPLING_FREQ_INDEX_SIZE  4
97#define AAC_ORIGINAL_COPY_SIZE        1
98#define AAC_HOME_SIZE                 1
99
100#define MIN(A,B)    (((A) < (B))?(A):(B))
101
102uint8   audaac_header[AUDAAC_MAX_ADTS_HEADER_LENGTH];
103unsigned int audaac_hdr_bit_index;
104
105
106FILE *F1 = NULL;
107
108uint32_t samplerate = 44100;
109uint32_t channels = 2;
110uint32_t bitrate = 128000;
111uint32_t pcmplayback = 0;
112uint32_t tunnel      = 0;
113uint32_t rectime     = 0;
114uint32_t format = 1;
115uint32_t profile = OMX_AUDIO_AACObjectLC;
116#define DEBUG_PRINT printf
117unsigned to_idle_transition = 0;
118
119typedef enum adts_sample_index__ {
120
121ADTS_SAMPLE_INDEX_96000=0x0,
122ADTS_SAMPLE_INDEX_88200,
123ADTS_SAMPLE_INDEX_64000,
124ADTS_SAMPLE_INDEX_48000,
125ADTS_SAMPLE_INDEX_44100,
126ADTS_SAMPLE_INDEX_32000,
127ADTS_SAMPLE_INDEX_24000,
128ADTS_SAMPLE_INDEX_22050,
129ADTS_SAMPLE_INDEX_16000,
130ADTS_SAMPLE_INDEX_12000,
131ADTS_SAMPLE_INDEX_11025,
132ADTS_SAMPLE_INDEX_8000,
133ADTS_SAMPLE_INDEX_7350,
134ADTS_SAMPLE_INDEX_MAX
135
136}adts_sample_index;
137/************************************************************************/
138/*                #DEFINES                            */
139/************************************************************************/
140#define false 0
141#define true 1
142
143#define CONFIG_VERSION_SIZE(param) \
144    param.nVersion.nVersion = CURRENT_OMX_SPEC_VERSION;\
145    param.nSize = sizeof(param);
146
147#define FAILED(result) (result != OMX_ErrorNone)
148
149#define SUCCEEDED(result) (result == OMX_ErrorNone)
150
151/************************************************************************/
152/*                GLOBAL DECLARATIONS                     */
153/************************************************************************/
154
155pthread_mutex_t lock;
156pthread_cond_t cond;
157pthread_mutex_t elock;
158pthread_cond_t econd;
159pthread_cond_t fcond;
160pthread_mutex_t etb_lock;
161pthread_mutex_t etb_lock1;
162pthread_cond_t etb_cond;
163FILE * inputBufferFile;
164FILE * outputBufferFile;
165OMX_PARAM_PORTDEFINITIONTYPE inputportFmt;
166OMX_PARAM_PORTDEFINITIONTYPE outputportFmt;
167OMX_AUDIO_PARAM_AACPROFILETYPE aacparam;
168OMX_AUDIO_PARAM_PCMMODETYPE    pcmparam;
169OMX_PORT_PARAM_TYPE portParam;
170OMX_ERRORTYPE error;
171
172
173
174
175#define ID_RIFF 0x46464952
176#define ID_WAVE 0x45564157
177#define ID_FMT  0x20746d66
178#define ID_DATA 0x61746164
179
180#define FORMAT_PCM 1
181
182struct wav_header {
183  uint32_t riff_id;
184  uint32_t riff_sz;
185  uint32_t riff_fmt;
186  uint32_t fmt_id;
187  uint32_t fmt_sz;
188  uint16_t audio_format;
189  uint16_t num_channels;
190  uint32_t sample_rate;
191  uint32_t byte_rate;       /* sample_rate * num_channels * bps / 8 */
192  uint16_t block_align;     /* num_channels * bps / 8 */
193  uint16_t bits_per_sample;
194  uint32_t data_id;
195  uint32_t data_sz;
196};
197struct enc_meta_out{
198        unsigned int offset_to_frame;
199        unsigned int frame_size;
200        unsigned int encoded_pcm_samples;
201        unsigned int msw_ts;
202        unsigned int lsw_ts;
203        unsigned int nflags;
204} __attribute__ ((packed));
205
206static int totaldatalen = 0;
207/************************************************************************/
208/*                GLOBAL INIT                    */
209/************************************************************************/
210
211unsigned int input_buf_cnt = 0;
212unsigned int output_buf_cnt = 0;
213int used_ip_buf_cnt = 0;
214volatile int event_is_done = 0;
215volatile int ebd_event_is_done = 0;
216volatile int fbd_event_is_done = 0;
217volatile int etb_event_is_done = 0;
218int ebd_cnt;
219int bInputEosReached = 0;
220int bOutputEosReached = 0;
221int bInputEosReached_tunnel = 0;
222static int etb_done = 0;
223int bFlushing = false;
224int bPause    = false;
225const char *in_filename;
226const char *out_filename;
227
228int timeStampLfile = 0;
229int timestampInterval = 100;
230
231//* OMX Spec Version supported by the wrappers. Version = 1.1 */
232const OMX_U32 CURRENT_OMX_SPEC_VERSION = 0x00000101;
233OMX_COMPONENTTYPE* aac_enc_handle = 0;
234
235OMX_BUFFERHEADERTYPE  **pInputBufHdrs = NULL;
236OMX_BUFFERHEADERTYPE  **pOutputBufHdrs = NULL;
237
238/************************************************************************/
239/*                GLOBAL FUNC DECL                        */
240/************************************************************************/
241int Init_Encoder(char*);
242int Play_Encoder();
243OMX_STRING aud_comp;
244/**************************************************************************/
245/*                STATIC DECLARATIONS                       */
246/**************************************************************************/
247
248static int open_audio_file ();
249static int Read_Buffer(OMX_BUFFERHEADERTYPE  *pBufHdr );
250static OMX_ERRORTYPE Allocate_Buffer ( OMX_COMPONENTTYPE *aac_enc_handle,
251                                       OMX_BUFFERHEADERTYPE  ***pBufHdrs,
252                                       OMX_U32 nPortIndex,
253                                       unsigned int bufCntMin, unsigned int bufSize);
254
255
256static OMX_ERRORTYPE EventHandler(OMX_IN OMX_HANDLETYPE hComponent,
257                                  OMX_IN OMX_PTR pAppData,
258                                  OMX_IN OMX_EVENTTYPE eEvent,
259                                  OMX_IN OMX_U32 nData1, OMX_IN OMX_U32 nData2,
260                                  OMX_IN OMX_PTR pEventData);
261static OMX_ERRORTYPE EmptyBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
262                                     OMX_IN OMX_PTR pAppData,
263                                     OMX_IN OMX_BUFFERHEADERTYPE* pBuffer);
264
265static OMX_ERRORTYPE FillBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
266                                     OMX_IN OMX_PTR pAppData,
267                                     OMX_IN OMX_BUFFERHEADERTYPE* pBuffer);
268static OMX_ERRORTYPE  parse_pcm_header();
269void wait_for_event(void)
270{
271    pthread_mutex_lock(&lock);
272    DEBUG_PRINT("%s: event_is_done=%d", __FUNCTION__, event_is_done);
273    while (event_is_done == 0) {
274        pthread_cond_wait(&cond, &lock);
275    }
276    event_is_done = 0;
277    pthread_mutex_unlock(&lock);
278}
279
280void event_complete(void )
281{
282    pthread_mutex_lock(&lock);
283    if (event_is_done == 0) {
284        event_is_done = 1;
285        pthread_cond_broadcast(&cond);
286    }
287    pthread_mutex_unlock(&lock);
288}
289
290void etb_wait_for_event(void)
291{
292    pthread_mutex_lock(&etb_lock1);
293    DEBUG_PRINT("%s: etb_event_is_done=%d", __FUNCTION__, etb_event_is_done);
294    while (etb_event_is_done == 0) {
295        pthread_cond_wait(&etb_cond, &etb_lock1);
296    }
297    etb_event_is_done = 0;
298    pthread_mutex_unlock(&etb_lock1);
299}
300
301void etb_event_complete(void )
302{
303    pthread_mutex_lock(&etb_lock1);
304    if (etb_event_is_done == 0) {
305        etb_event_is_done = 1;
306        pthread_cond_broadcast(&etb_cond);
307    }
308    pthread_mutex_unlock(&etb_lock1);
309}
310
311
312OMX_ERRORTYPE EventHandler(OMX_IN OMX_HANDLETYPE hComponent,
313                           OMX_IN OMX_PTR pAppData,
314                           OMX_IN OMX_EVENTTYPE eEvent,
315                           OMX_IN OMX_U32 nData1, OMX_IN OMX_U32 nData2,
316                           OMX_IN OMX_PTR pEventData)
317{
318    DEBUG_PRINT("Function %s \n", __FUNCTION__);
319    /* To remove warning for unused variable to keep prototype same */
320    (void)hComponent;
321    (void)pAppData;
322    (void)pEventData;
323
324    switch(eEvent) {
325        case OMX_EventCmdComplete:
326        DEBUG_PRINT("\n OMX_EventCmdComplete event=%d data1=%u data2=%u\n",(OMX_EVENTTYPE)eEvent,
327                                                                               nData1,nData2);
328            event_complete();
329        break;
330        case OMX_EventError:
331        DEBUG_PRINT("\n OMX_EventError \n");
332        break;
333         case OMX_EventBufferFlag:
334             DEBUG_PRINT("\n OMX_EventBufferFlag \n");
335             bOutputEosReached = true;
336             event_complete();
337             break;
338        case OMX_EventPortSettingsChanged:
339        DEBUG_PRINT("\n OMX_EventPortSettingsChanged \n");
340        break;
341        default:
342        DEBUG_PRINT("\n Unknown Event \n");
343        break;
344    }
345    return OMX_ErrorNone;
346}
347
348OMX_ERRORTYPE FillBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
349                              OMX_IN OMX_PTR pAppData,
350                              OMX_IN OMX_BUFFERHEADERTYPE* pBuffer)
351{
352    size_t bytes_writen = 0;
353    size_t total_bytes_writen = 0;
354    size_t len = 0;
355    struct enc_meta_out *meta = NULL;
356    OMX_U8 *src = pBuffer->pBuffer;
357    unsigned int num_of_frames = 1;
358
359    /* To remove warning for unused variable to keep prototype same */
360    (void)pAppData;
361
362        if(((pBuffer->nFlags & OMX_BUFFERFLAG_EOS) == OMX_BUFFERFLAG_EOS)) {
363            DEBUG_PRINT("FBD::EOS on output port\n ");
364            bOutputEosReached = true;
365            return OMX_ErrorNone;
366        }
367        if(bInputEosReached_tunnel || bOutputEosReached)
368        {
369            DEBUG_PRINT("EOS REACHED NO MORE PROCESSING OF BUFFERS\n");
370            return OMX_ErrorNone;
371        }
372        if(num_of_frames != src[0]){
373
374            printf("Data corrupt\n");
375            return OMX_ErrorNone;
376        }
377        /* Skip the first bytes */
378
379
380
381        src += sizeof(unsigned char);
382        meta = (struct enc_meta_out *)src;
383        while (num_of_frames > 0) {
384            meta = (struct enc_meta_out *)src;
385            /*printf("offset=%d framesize=%d encoded_pcm[%d] msw_ts[%d]lsw_ts[%d] nflags[%d]\n",
386                                                                       meta->offset_to_frame,
387                                                                       meta->frame_size,
388                          meta->encoded_pcm_samples, meta->msw_ts, meta->lsw_ts, meta->nflags);*/
389            len = meta->frame_size;
390
391            if(format == 6)
392            {
393                audaac_rec_install_adts_header_variable((uint16_t)(len + AUDAAC_MAX_ADTS_HEADER_LENGTH));
394                bytes_writen = fwrite(audaac_header,1,AUDAAC_MAX_ADTS_HEADER_LENGTH,outputBufferFile);
395                if(bytes_writen < AUDAAC_MAX_ADTS_HEADER_LENGTH)
396                {
397                    DEBUG_PRINT("error: invalid adts header length\n");
398                    return OMX_ErrorNone;
399                }
400            }
401            bytes_writen = fwrite(pBuffer->pBuffer + sizeof(unsigned char) + meta->offset_to_frame,1,len,outputBufferFile);
402            if(bytes_writen < len)
403            {
404                DEBUG_PRINT("error: invalid AAC encoded data \n");
405                return OMX_ErrorNone;
406            }
407            src += sizeof(struct enc_meta_out);
408            num_of_frames--;
409            total_bytes_writen += len;
410        }
411        DEBUG_PRINT(" FillBufferDone size writen to file  %zu\n",total_bytes_writen);
412        totaldatalen = totaldatalen + (int)total_bytes_writen;
413
414        DEBUG_PRINT(" FBD calling FTB\n");
415        OMX_FillThisBuffer(hComponent,pBuffer);
416
417        return OMX_ErrorNone;
418}
419
420OMX_ERRORTYPE EmptyBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
421                              OMX_IN OMX_PTR pAppData,
422                              OMX_IN OMX_BUFFERHEADERTYPE* pBuffer)
423{
424    int readBytes =0;
425
426    /* To remove warning for unused variable to keep prototype same */
427    (void)pAppData;
428
429    ebd_cnt++;
430    used_ip_buf_cnt--;
431    pthread_mutex_lock(&etb_lock);
432    if(!etb_done)
433    {
434        DEBUG_PRINT("\n*********************************************\n");
435        DEBUG_PRINT("Wait till first set of buffers are given to component\n");
436        DEBUG_PRINT("\n*********************************************\n");
437        etb_done++;
438        pthread_mutex_unlock(&etb_lock);
439        etb_wait_for_event();
440    }
441    else
442    {
443        pthread_mutex_unlock(&etb_lock);
444    }
445
446
447    if(bInputEosReached)
448    {
449        DEBUG_PRINT("\n*********************************************\n");
450        DEBUG_PRINT("   EBD::EOS on input port\n ");
451        DEBUG_PRINT("*********************************************\n");
452        return OMX_ErrorNone;
453    }else if (bFlushing == true) {
454      DEBUG_PRINT("omx_aac_adec_test: bFlushing is set to TRUE used_ip_buf_cnt=%d\n",used_ip_buf_cnt);
455      if (used_ip_buf_cnt == 0) {
456        bFlushing = false;
457      } else {
458        DEBUG_PRINT("omx_aac_adec_test: more buffer to come back used_ip_buf_cnt=%d\n",used_ip_buf_cnt);
459        return OMX_ErrorNone;
460      }
461    }
462
463    if((readBytes = Read_Buffer(pBuffer)) > 0) {
464        pBuffer->nFilledLen = (OMX_U32)readBytes;
465        used_ip_buf_cnt++;
466        OMX_EmptyThisBuffer(hComponent,pBuffer);
467    }
468    else{
469        pBuffer->nFlags |= OMX_BUFFERFLAG_EOS;
470        used_ip_buf_cnt++;
471        bInputEosReached = true;
472        pBuffer->nFilledLen = 0;
473        OMX_EmptyThisBuffer(hComponent,pBuffer);
474        DEBUG_PRINT("EBD..Either EOS or Some Error while reading file\n");
475    }
476    return OMX_ErrorNone;
477}
478
479void signal_handler(int sig_id) {
480
481  /* Flush */
482  if (sig_id == SIGUSR1) {
483    DEBUG_PRINT("%s Initiate flushing\n", __FUNCTION__);
484    bFlushing = true;
485    OMX_SendCommand(aac_enc_handle, OMX_CommandFlush, OMX_ALL, NULL);
486  } else if (sig_id == SIGUSR2) {
487    if (bPause == true) {
488      DEBUG_PRINT("%s resume playback\n", __FUNCTION__);
489      bPause = false;
490      OMX_SendCommand(aac_enc_handle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
491    } else {
492      DEBUG_PRINT("%s pause playback\n", __FUNCTION__);
493      bPause = true;
494      OMX_SendCommand(aac_enc_handle, OMX_CommandStateSet, OMX_StatePause, NULL);
495    }
496  }
497}
498
499int main(int argc, char **argv)
500{
501     unsigned int bufCnt=0;
502     OMX_ERRORTYPE result;
503
504    struct sigaction sa;
505
506    memset(&sa, 0, sizeof(sa));
507    sa.sa_handler = &signal_handler;
508    sigaction(SIGABRT, &sa, NULL);
509    sigaction(SIGUSR1, &sa, NULL);
510    sigaction(SIGUSR2, &sa, NULL);
511
512   (void) signal(SIGINT, Release_Encoder);
513
514    pthread_cond_init(&cond, 0);
515    pthread_mutex_init(&lock, 0);
516    pthread_cond_init(&etb_cond, 0);
517    pthread_mutex_init(&etb_lock, 0);
518    pthread_mutex_init(&etb_lock1, 0);
519
520    if (argc >= 9) {
521      in_filename = argv[1];
522      out_filename = argv[2];
523      samplerate = (uint32_t)atoi(argv[3]);
524      channels = (uint32_t)atoi(argv[4]);
525      tunnel  = (uint32_t)atoi(argv[5]);
526      rectime = (uint32_t)atoi(argv[6]);
527      bitrate = (uint32_t)atoi(argv[7]);
528      format =  (uint32_t)atoi(argv[8]);
529      profile = (uint32_t)atoi(argv[9]);
530
531	  DEBUG_PRINT("Input parameters: samplerate = %d, channels = %d, tunnel = %d,"
532				  " rectime = %d, bitrate = %d, format = %d, profile = %d\n",
533				  samplerate, channels, tunnel, rectime, bitrate, format, profile);
534
535	  if (!((profile == 2) || (profile == 5) || (profile == 29))) {
536		  DEBUG_PRINT("profile = %d, not supported. Supported "
537					  "profile values are AAC_LC(2), AAC+(5), EAAC+(29)\n", profile);
538		  return 0;
539	  }
540	  if (!((format == 1) || (format == 6)))  {
541		  DEBUG_PRINT("format = %d, not supported. Supported "
542					  "formats are ADTS(1), RAW(6)\n", format);
543		  return 0;
544	  }
545	  if ((channels > 2) || (channels <= 0)) {
546		  DEBUG_PRINT("channels = %d, not supported. Supported "
547					  "number of channels are 1 and 2\n", channels);
548		  return 0;
549	  }
550	  if ((samplerate < 8000) && (samplerate > 48000)) {
551		  DEBUG_PRINT("samplerate = %d, not supported, Supported "
552					  "samplerates are 8000, 11025, 12000, 16000, 22050, "
553					  "24000, 32000, 44100, 48000\n", samplerate);
554		  return 0;
555	  } else {
556		  if ((profile == 5) || (profile == 29)) {
557			  if (samplerate < 24000) {
558				  DEBUG_PRINT("samplerate = %d, not supported for AAC+/EAAC+."
559							  " Supported samplerates are 24000, 32000,"
560							  " 44100, 48000\n", samplerate);
561				  return 0;
562			  }
563		  }
564	  }
565    } else {
566        DEBUG_PRINT(" invalid format: \n");
567        DEBUG_PRINT("ex: ./mm-aenc-omxaac INPUTFILE AAC_OUTPUTFILE SAMPFREQ CHANNEL TUNNEL RECORDTIME BITRATE FORMAT PROFILE\n");
568        DEBUG_PRINT("FOR TUNNEL MOD PASS INPUT FILE AS ZERO\n");
569        DEBUG_PRINT("RECORDTIME in seconds for AST Automation ...TUNNEL MODE ONLY\n");
570        DEBUG_PRINT("FORMAT::ADTS(1), RAW(6)\n");
571        DEBUG_PRINT("BITRATE in bits/sec \n");
572        DEBUG_PRINT("PROFILE::AAC_LC(2), AAC+(5), EAAC+(29)\n");
573        return 0;
574    }
575    if(tunnel == 0)
576        aud_comp = "OMX.qcom.audio.encoder.aac";
577    else
578        aud_comp = "OMX.qcom.audio.encoder.tunneled.aac";
579    if(Init_Encoder(aud_comp)!= 0x00)
580    {
581        DEBUG_PRINT("Decoder Init failed\n");
582        return -1;
583    }
584
585    fcntl(0, F_SETFL, O_NONBLOCK);
586
587    if(Play_Encoder() != 0x00)
588    {
589        DEBUG_PRINT("Play_Decoder failed\n");
590        return -1;
591    }
592
593    // Wait till EOS is reached...
594        if(rectime && tunnel)
595        {
596            sleep(rectime);
597            rectime = 0;
598            bInputEosReached_tunnel = 1;
599            DEBUG_PRINT("\EOS ON INPUT PORT\n");
600        }
601        else
602        {
603            wait_for_event();
604        }
605
606        if((bInputEosReached_tunnel) || ((bOutputEosReached) && !tunnel))
607        {
608
609            DEBUG_PRINT("\nMoving the decoder to idle state \n");
610            OMX_SendCommand(aac_enc_handle, OMX_CommandStateSet, OMX_StateIdle,0);
611            wait_for_event();
612            DEBUG_PRINT("\nMoving the encoder to loaded state \n");
613            OMX_SendCommand(aac_enc_handle, OMX_CommandStateSet, OMX_StateLoaded,0);
614            sleep(1);
615            if (!tunnel)
616            {
617                DEBUG_PRINT("\nFillBufferDone: Deallocating i/p buffers \n");
618                for(bufCnt=0; bufCnt < input_buf_cnt; ++bufCnt) {
619                    OMX_FreeBuffer(aac_enc_handle, 0, pInputBufHdrs[bufCnt]);
620                }
621            }
622
623            DEBUG_PRINT ("\nFillBufferDone: Deallocating o/p buffers \n");
624            for(bufCnt=0; bufCnt < output_buf_cnt; ++bufCnt) {
625                OMX_FreeBuffer(aac_enc_handle, 1, pOutputBufHdrs[bufCnt]);
626            }
627            wait_for_event();
628
629            result = OMX_FreeHandle(aac_enc_handle);
630            if (result != OMX_ErrorNone) {
631                DEBUG_PRINT ("\nOMX_FreeHandle error. Error code: %d\n", result);
632            }
633            /* Deinit OpenMAX */
634            if(tunnel)
635            {
636                #ifdef AUDIOV2
637                if (msm_route_stream(DIR_TX,session_id,device_id, 0))
638                {
639                    DEBUG_PRINT("\ncould not set stream routing\n");
640                    return -1;
641                }
642                if (msm_en_device(device_id, 0))
643                {
644                    DEBUG_PRINT("\ncould not enable device\n");
645                    return -1;
646                }
647                msm_mixer_close();
648                #endif
649            }
650            OMX_Deinit();
651            ebd_cnt=0;
652            bOutputEosReached = false;
653            bInputEosReached_tunnel = false;
654            bInputEosReached = 0;
655            aac_enc_handle = NULL;
656            pthread_cond_destroy(&cond);
657            pthread_mutex_destroy(&lock);
658            fclose(outputBufferFile);
659            DEBUG_PRINT("*****************************************\n");
660            DEBUG_PRINT("******...AAC ENC TEST COMPLETED...***************\n");
661            DEBUG_PRINT("*****************************************\n");
662        }
663        return 0;
664}
665
666void Release_Encoder()
667{
668    static int cnt=0;
669    OMX_ERRORTYPE result;
670
671    DEBUG_PRINT("END OF AAC ENCODING: EXITING PLEASE WAIT\n");
672    bInputEosReached_tunnel = 1;
673    event_complete();
674    cnt++;
675    if(cnt > 1)
676    {
677        /* FORCE RESET  */
678        aac_enc_handle = NULL;
679        ebd_cnt=0;
680        bInputEosReached_tunnel = false;
681
682        result = OMX_FreeHandle(aac_enc_handle);
683        if (result != OMX_ErrorNone) {
684            DEBUG_PRINT ("\nOMX_FreeHandle error. Error code: %d\n", result);
685        }
686
687        /* Deinit OpenMAX */
688
689        OMX_Deinit();
690
691        pthread_cond_destroy(&cond);
692        pthread_mutex_destroy(&lock);
693            DEBUG_PRINT("*****************************************\n");
694            DEBUG_PRINT("******...AAC ENC TEST COMPLETED...***************\n");
695            DEBUG_PRINT("*****************************************\n");
696        exit(0);
697    }
698}
699
700int Init_Encoder(OMX_STRING audio_component)
701{
702    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
703    OMX_ERRORTYPE omxresult;
704    OMX_U32 total = 0;
705    typedef OMX_U8* OMX_U8_PTR;
706    char *role ="audio_encoder";
707
708    static OMX_CALLBACKTYPE call_back = {
709        &EventHandler,&EmptyBufferDone,&FillBufferDone
710    };
711
712    /* Init. the OpenMAX Core */
713    DEBUG_PRINT("\nInitializing OpenMAX Core....\n");
714    omxresult = OMX_Init();
715
716    if(OMX_ErrorNone != omxresult) {
717        DEBUG_PRINT("\n Failed to Init OpenMAX core");
718          return -1;
719    }
720    else {
721        DEBUG_PRINT("\nOpenMAX Core Init Done\n");
722    }
723
724    /* Query for audio decoders*/
725    DEBUG_PRINT("Aac_test: Before entering OMX_GetComponentOfRole");
726    OMX_GetComponentsOfRole(role, &total, 0);
727    DEBUG_PRINT ("\nTotal components of role=%s :%u", role, total);
728
729
730    omxresult = OMX_GetHandle((OMX_HANDLETYPE*)(&aac_enc_handle),
731                        (OMX_STRING)audio_component, NULL, &call_back);
732    if (FAILED(omxresult)) {
733        DEBUG_PRINT("\nFailed to Load the component:%s\n", audio_component);
734    return -1;
735    }
736    else
737    {
738        DEBUG_PRINT("\nComponent %s is in LOADED state\n", audio_component);
739    }
740
741    /* Get the port information */
742    CONFIG_VERSION_SIZE(portParam);
743    omxresult = OMX_GetParameter(aac_enc_handle, OMX_IndexParamAudioInit,
744                                (OMX_PTR)&portParam);
745
746    if(FAILED(omxresult)) {
747        DEBUG_PRINT("\nFailed to get Port Param\n");
748    return -1;
749    }
750    else
751    {
752        DEBUG_PRINT("\nportParam.nPorts:%u\n", portParam.nPorts);
753    DEBUG_PRINT("\nportParam.nStartPortNumber:%u\n",
754                                             portParam.nStartPortNumber);
755    }
756    return 0;
757}
758
759int Play_Encoder()
760{
761    unsigned int i;
762    int Size=0;
763    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
764    OMX_ERRORTYPE ret;
765    OMX_INDEXTYPE index;
766#ifdef __LP64__
767    DEBUG_PRINT("sizeof[%ld]\n", sizeof(OMX_BUFFERHEADERTYPE));
768#else
769    DEBUG_PRINT("sizeof[%d]\n", sizeof(OMX_BUFFERHEADERTYPE));
770#endif
771
772    /* open the i/p and o/p files based on the video file format passed */
773    if(open_audio_file()) {
774        DEBUG_PRINT("\n Returning -1");
775    return -1;
776    }
777
778    /* Query the encoder input min buf requirements */
779    CONFIG_VERSION_SIZE(inputportFmt);
780
781    /* Port for which the Client needs to obtain info */
782    inputportFmt.nPortIndex = portParam.nStartPortNumber;
783
784    OMX_GetParameter(aac_enc_handle,OMX_IndexParamPortDefinition,&inputportFmt);
785    DEBUG_PRINT ("\nEnc Input Buffer Count %u\n", inputportFmt.nBufferCountMin);
786    DEBUG_PRINT ("\nEnc: Input Buffer Size %u\n", inputportFmt.nBufferSize);
787
788    if(OMX_DirInput != inputportFmt.eDir) {
789        DEBUG_PRINT ("\nEnc: Expect Input Port\n");
790    return -1;
791    }
792
793    pcmparam.nPortIndex   = 0;
794    pcmparam.nChannels    =  channels;
795    pcmparam.nSamplingRate = samplerate;
796    OMX_SetParameter(aac_enc_handle,OMX_IndexParamAudioPcm,&pcmparam);
797
798
799    /* Query the encoder outport's min buf requirements */
800    CONFIG_VERSION_SIZE(outputportFmt);
801    /* Port for which the Client needs to obtain info */
802    outputportFmt.nPortIndex = portParam.nStartPortNumber + 1;
803
804    OMX_GetParameter(aac_enc_handle,OMX_IndexParamPortDefinition,&outputportFmt);
805    DEBUG_PRINT ("\nEnc: Output Buffer Count %u\n", outputportFmt.nBufferCountMin);
806    DEBUG_PRINT ("\nEnc: Output Buffer Size %u\n", outputportFmt.nBufferSize);
807
808    if(OMX_DirOutput != outputportFmt.eDir) {
809        DEBUG_PRINT ("\nEnc: Expect Output Port\n");
810    return -1;
811    }
812
813
814    CONFIG_VERSION_SIZE(aacparam);
815
816
817    aacparam.nPortIndex   =  1;
818    aacparam.nChannels    =  channels; //2 ; /* 1-> mono 2-> stereo*/
819    aacparam.nBitRate     =  bitrate;
820    aacparam.nSampleRate  =  samplerate;
821    aacparam.eChannelMode =  OMX_AUDIO_ChannelModeStereo;
822    aacparam.eAACStreamFormat    =  (OMX_AUDIO_AACSTREAMFORMATTYPE)format;
823    aacparam.eAACProfile = (OMX_AUDIO_AACPROFILETYPE)profile;
824    OMX_SetParameter(aac_enc_handle,OMX_IndexParamAudioAac,&aacparam);
825    OMX_GetExtensionIndex(aac_enc_handle,"OMX.Qualcomm.index.audio.sessionId",&index);
826    OMX_GetParameter(aac_enc_handle,index,&streaminfoparam);
827    if(tunnel)
828    {
829    #ifdef AUDIOV2
830    session_id = streaminfoparam.sessionId;
831    control = msm_mixer_open("/dev/snd/controlC0", 0);
832    if(control < 0)
833    printf("ERROR opening the device\n");
834    device_id = msm_get_device(device);
835    DEBUG_PRINT ("\ndevice_id = %d\n",device_id);
836    DEBUG_PRINT("\nsession_id = %d\n",session_id);
837    if (msm_en_device(device_id, 1))
838    {
839        perror("could not enable device\n");
840        return -1;
841    }
842
843    if (msm_route_stream(DIR_TX,session_id,device_id, 1))
844    {
845        perror("could not set stream routing\n");
846        return -1;
847    }
848    #endif
849    }
850    DEBUG_PRINT ("\nOMX_SendCommand Encoder -> IDLE\n");
851    OMX_SendCommand(aac_enc_handle, OMX_CommandStateSet, OMX_StateIdle,0);
852    /* wait_for_event(); should not wait here event complete status will
853       not come until enough buffer are allocated */
854    if (tunnel == 0)
855    {
856        input_buf_cnt = inputportFmt.nBufferCountActual; //  inputportFmt.nBufferCountMin + 5;
857        DEBUG_PRINT("Transition to Idle State succesful...\n");
858        /* Allocate buffer on decoder's i/p port */
859        error = Allocate_Buffer(aac_enc_handle, &pInputBufHdrs, inputportFmt.nPortIndex,
860                            input_buf_cnt, inputportFmt.nBufferSize);
861        if (error != OMX_ErrorNone || pInputBufHdrs == NULL) {
862            DEBUG_PRINT ("\nOMX_AllocateBuffer Input buffer error\n");
863        return -1;
864    }
865    else {
866        DEBUG_PRINT ("\nOMX_AllocateBuffer Input buffer success\n");
867    }
868    }
869    output_buf_cnt = outputportFmt.nBufferCountMin ;
870
871    /* Allocate buffer on encoder's O/Pp port */
872    error = Allocate_Buffer(aac_enc_handle, &pOutputBufHdrs, outputportFmt.nPortIndex,
873                            output_buf_cnt, outputportFmt.nBufferSize);
874    if (error != OMX_ErrorNone || pOutputBufHdrs == NULL) {
875        DEBUG_PRINT ("\nOMX_AllocateBuffer Output buffer error\n");
876    return -1;
877    }
878    else {
879        DEBUG_PRINT ("\nOMX_AllocateBuffer Output buffer success\n");
880    }
881
882    wait_for_event();
883
884
885    if (tunnel == 1)
886    {
887        DEBUG_PRINT ("\nOMX_SendCommand to enable TUNNEL MODE during IDLE\n");
888        OMX_SendCommand(aac_enc_handle, OMX_CommandPortDisable,0,0); // disable input port
889        wait_for_event();
890    }
891
892    DEBUG_PRINT ("\nOMX_SendCommand encoder -> Executing\n");
893    OMX_SendCommand(aac_enc_handle, OMX_CommandStateSet, OMX_StateExecuting,0);
894    wait_for_event();
895
896    DEBUG_PRINT(" Start sending OMX_FILLthisbuffer\n");
897
898    for(i=0; i < output_buf_cnt; i++) {
899        DEBUG_PRINT ("\nOMX_FillThisBuffer on output buf no.%d\n",i);
900        pOutputBufHdrs[i]->nOutputPortIndex = 1;
901        pOutputBufHdrs[i]->nFlags = pOutputBufHdrs[i]->nFlags & (unsigned)~OMX_BUFFERFLAG_EOS;
902        ret = OMX_FillThisBuffer(aac_enc_handle, pOutputBufHdrs[i]);
903        if (OMX_ErrorNone != ret) {
904            DEBUG_PRINT("OMX_FillThisBuffer failed with result %d\n", ret);
905    }
906        else {
907            DEBUG_PRINT("OMX_FillThisBuffer success!\n");
908    }
909    }
910
911if(tunnel == 0)
912{
913    DEBUG_PRINT(" Start sending OMX_emptythisbuffer\n");
914    for (i = 0;i < input_buf_cnt;i++) {
915        DEBUG_PRINT ("\nOMX_EmptyThisBuffer on Input buf no.%d\n",i);
916        pInputBufHdrs[i]->nInputPortIndex = 0;
917        Size = Read_Buffer(pInputBufHdrs[i]);
918        if(Size <=0 ){
919          DEBUG_PRINT("NO DATA READ\n");
920          bInputEosReached = true;
921          pInputBufHdrs[i]->nFlags= OMX_BUFFERFLAG_EOS;
922        }
923        pInputBufHdrs[i]->nFilledLen = (OMX_U32)Size;
924        pInputBufHdrs[i]->nInputPortIndex = 0;
925        used_ip_buf_cnt++;
926        ret = OMX_EmptyThisBuffer(aac_enc_handle, pInputBufHdrs[i]);
927        if (OMX_ErrorNone != ret) {
928            DEBUG_PRINT("OMX_EmptyThisBuffer failed with result %d\n", ret);
929        }
930        else {
931            DEBUG_PRINT("OMX_EmptyThisBuffer success!\n");
932        }
933        if(Size <=0 ){
934            break;//eos reached
935        }
936    }
937    pthread_mutex_lock(&etb_lock);
938    if(etb_done)
939{
940        DEBUG_PRINT("Component is waiting for EBD to be released.\n");
941        etb_event_complete();
942    }
943    else
944    {
945        DEBUG_PRINT("\n****************************\n");
946        DEBUG_PRINT("EBD not yet happened ...\n");
947        DEBUG_PRINT("\n****************************\n");
948        etb_done++;
949    }
950    pthread_mutex_unlock(&etb_lock);
951}
952
953    return 0;
954}
955
956
957
958static OMX_ERRORTYPE Allocate_Buffer ( OMX_COMPONENTTYPE *avc_enc_handle,
959                                       OMX_BUFFERHEADERTYPE  ***pBufHdrs,
960                                       OMX_U32 nPortIndex,
961                                       unsigned int bufCntMin, unsigned int bufSize)
962{
963    DEBUG_PRINT("Inside %s \n", __FUNCTION__);
964    OMX_ERRORTYPE error=OMX_ErrorNone;
965    unsigned int bufCnt=0;
966    /* To remove warning for unused variable to keep prototype same */
967    (void)avc_enc_handle;
968
969    *pBufHdrs= (OMX_BUFFERHEADERTYPE **)
970                   malloc(sizeof(OMX_BUFFERHEADERTYPE*)*bufCntMin);
971
972    for(bufCnt=0; bufCnt < bufCntMin; ++bufCnt) {
973        DEBUG_PRINT("\n OMX_AllocateBuffer No %d \n", bufCnt);
974        error = OMX_AllocateBuffer(aac_enc_handle, &((*pBufHdrs)[bufCnt]),
975                                   nPortIndex, NULL, bufSize);
976    }
977
978    return error;
979}
980
981
982
983
984static int Read_Buffer (OMX_BUFFERHEADERTYPE  *pBufHdr )
985{
986
987    size_t bytes_read=0;
988
989
990    pBufHdr->nFilledLen = 0;
991    pBufHdr->nFlags |= OMX_BUFFERFLAG_EOS;
992
993     bytes_read = fread(pBufHdr->pBuffer, 1, pBufHdr->nAllocLen , inputBufferFile);
994
995      pBufHdr->nFilledLen = (OMX_U32)bytes_read;
996        if(bytes_read == 0)
997        {
998
999          pBufHdr->nFlags |= OMX_BUFFERFLAG_EOS;
1000          DEBUG_PRINT ("\nBytes read zero\n");
1001        }
1002        else
1003        {
1004            pBufHdr->nFlags = pBufHdr->nFlags & (unsigned)~OMX_BUFFERFLAG_EOS;
1005        }
1006
1007    return (int)bytes_read;
1008}
1009
1010
1011
1012//In Encoder this Should Open a PCM or WAV file for input.
1013
1014static int open_audio_file ()
1015{
1016    int error_code = 0;
1017
1018    if (!tunnel)
1019    {
1020        DEBUG_PRINT("Inside %s filename=%s\n", __FUNCTION__, in_filename);
1021        inputBufferFile = fopen (in_filename, "rb");
1022        if (inputBufferFile == NULL) {
1023            DEBUG_PRINT("\ni/p file %s could NOT be opened\n",
1024                                         in_filename);
1025        error_code = -1;
1026        }
1027        if(parse_pcm_header() != 0x00)
1028        {
1029            DEBUG_PRINT("PCM parser failed \n");
1030            return -1;
1031        }
1032    }
1033
1034    DEBUG_PRINT("Inside %s filename=%s\n", __FUNCTION__, out_filename);
1035    outputBufferFile = fopen (out_filename, "wb");
1036    if (outputBufferFile == NULL) {
1037        DEBUG_PRINT("\ni/p file %s could NOT be opened\n",
1038                                         out_filename);
1039    error_code = -1;
1040    }
1041    return error_code;
1042}
1043
1044
1045void audaac_rec_install_bits
1046(
1047  uint8   *input,
1048  byte    num_bits_reqd,
1049  uint32  value,
1050  uint16  *hdr_bit_index
1051)
1052{
1053  uint32 byte_index;
1054  byte   bit_index;
1055  byte   bits_avail_in_byte;
1056  byte   num_to_copy;
1057  byte   byte_to_copy;
1058
1059  byte   num_remaining = num_bits_reqd;
1060  uint8  bit_mask;
1061
1062  bit_mask = 0xFF;
1063
1064  while (num_remaining) {
1065
1066    byte_index = (*hdr_bit_index) >> 3;
1067    bit_index  = (*hdr_bit_index) &  0x07;
1068
1069    bits_avail_in_byte = (uint8)(8 - bit_index);
1070
1071    num_to_copy = MIN(bits_avail_in_byte, num_remaining);
1072
1073    byte_to_copy = (uint8)(((value >> (num_remaining - num_to_copy)) & 0xFF) <<
1074                    (bits_avail_in_byte - num_to_copy));
1075
1076    input[byte_index] &= ((uint8)(bit_mask << bits_avail_in_byte));
1077    input[byte_index] |= byte_to_copy;
1078
1079    *hdr_bit_index += num_to_copy;
1080
1081    num_remaining = (uint8)(num_remaining - num_to_copy);
1082  } /* while (num_remaining) */
1083} /* audaac_rec_install_bits */
1084
1085adts_sample_index  map_adts_sample_index(uint32 srate)
1086{
1087  adts_sample_index ret;
1088
1089  switch(srate){
1090
1091     case 96000:
1092     ret= ADTS_SAMPLE_INDEX_96000;
1093     break;
1094     case 88200:
1095     ret= ADTS_SAMPLE_INDEX_88200;
1096     break;
1097     case 64000:
1098     ret= ADTS_SAMPLE_INDEX_64000;
1099     break;
1100     case 48000:
1101     ret=ADTS_SAMPLE_INDEX_48000;
1102     break;
1103     case 44100:
1104     ret=ADTS_SAMPLE_INDEX_44100;
1105     break;
1106     case 32000:
1107     ret=ADTS_SAMPLE_INDEX_32000;
1108     break;
1109     case 24000:
1110     ret=ADTS_SAMPLE_INDEX_24000;
1111     break;
1112     case 22050:
1113     ret=ADTS_SAMPLE_INDEX_22050;
1114     break;
1115     case 16000:
1116     ret=ADTS_SAMPLE_INDEX_16000;
1117     break;
1118     case 12000:
1119     ret=ADTS_SAMPLE_INDEX_12000;
1120     break;
1121     case 11025:
1122     ret=ADTS_SAMPLE_INDEX_11025;
1123     break;
1124     case 8000:
1125     ret=ADTS_SAMPLE_INDEX_8000;
1126     break;
1127     case 7350:
1128     ret=ADTS_SAMPLE_INDEX_7350;
1129     break;
1130     default:
1131     ret=ADTS_SAMPLE_INDEX_44100;
1132     break;
1133    }
1134  return ret;
1135}
1136
1137void audaac_rec_install_adts_header_variable (uint16  byte_num)
1138{
1139  //uint16  bit_index=0;
1140
1141  adts_sample_index srate_enum;
1142  uint32  value;
1143
1144  uint32   sample_index = samplerate;
1145  uint8   channel_config = (uint8)channels;
1146
1147  /* Store Sync word first */
1148  audaac_header[0] = 0xFF;
1149  audaac_header[1] = 0xF0;
1150
1151  audaac_hdr_bit_index = 12;
1152
1153  if ((format == OMX_AUDIO_AACStreamFormatRAW) &&
1154      ((profile == OMX_AUDIO_AACObjectHE) ||
1155       (profile == OMX_AUDIO_AACObjectHE_PS))){
1156      if (samplerate >= 24000)
1157          sample_index = samplerate/2;
1158  }
1159
1160  /* ID field, 1 bit */
1161  value = 1;
1162  audaac_rec_install_bits(audaac_header,
1163                          1,
1164                          value,
1165                          &(audaac_hdr_bit_index));
1166
1167  /* Layer field, 2 bits */
1168  value = 0;
1169  audaac_rec_install_bits(audaac_header,
1170                          AACHDR_LAYER_SIZE,
1171                          value,
1172                          &(audaac_hdr_bit_index));
1173
1174  /* Protection_absent field, 1 bit */
1175  value = 1;
1176  audaac_rec_install_bits(audaac_header,
1177                          AACHDR_CRC_SIZE,
1178                          value,
1179                          &(audaac_hdr_bit_index));
1180
1181  /* profile_ObjectType field, 2 bit */
1182  value = 1;
1183  audaac_rec_install_bits(audaac_header,
1184                          AAC_PROFILE_SIZE,
1185                          value,
1186                          &(audaac_hdr_bit_index));
1187
1188  /* sampling_frequency_index field, 4 bits */
1189  srate_enum = map_adts_sample_index(sample_index);
1190  audaac_rec_install_bits(audaac_header,
1191                          AAC_SAMPLING_FREQ_INDEX_SIZE,
1192                          (uint32)srate_enum,
1193                          &(audaac_hdr_bit_index));
1194
1195  DEBUG_PRINT("%s: sample_index=%d; srate_enum = %d \n",
1196			  __FUNCTION__, sample_index, srate_enum);
1197
1198  /* pravate_bit field, 1 bits */
1199  audaac_rec_install_bits(audaac_header,
1200                          1,
1201                          0,
1202                          &(audaac_hdr_bit_index));
1203
1204  /* channel_configuration field, 3 bits */
1205  audaac_rec_install_bits(audaac_header,
1206                          3,
1207                          channel_config,
1208                          &(audaac_hdr_bit_index));
1209
1210
1211  /* original/copy field, 1 bits */
1212  audaac_rec_install_bits(audaac_header,
1213                          AAC_ORIGINAL_COPY_SIZE,
1214                          0,
1215                          &(audaac_hdr_bit_index));
1216
1217
1218  /* home field, 1 bits */
1219  audaac_rec_install_bits(audaac_header,
1220                          AAC_HOME_SIZE,
1221                          0,
1222                          &(audaac_hdr_bit_index));
1223
1224 // bit_index = audaac_hdr_bit_index;
1225 // bit_index += 2;
1226
1227    /* copyr. id. bit, 1 bits */
1228  audaac_rec_install_bits(audaac_header,
1229                          1,
1230                          0,
1231                          &(audaac_hdr_bit_index));
1232
1233    /* copyr. id. start, 1 bits */
1234  audaac_rec_install_bits(audaac_header,
1235                          1,
1236                          0,
1237                          &(audaac_hdr_bit_index));
1238
1239  /* aac_frame_length field, 13 bits */
1240  audaac_rec_install_bits(audaac_header,
1241                          AUDAAC_ADTS_FRAME_LENGTH_SIZE,
1242                          byte_num,
1243                          &audaac_hdr_bit_index);
1244
1245  /* adts_buffer_fullness field, 11 bits */
1246  audaac_rec_install_bits(audaac_header,
1247                          11,
1248                          0x660,/*0x660 = CBR,0x7FF = VBR*/
1249                          &audaac_hdr_bit_index);
1250
1251  /* number_of_raw_data_blocks_in_frame, 2 bits */
1252  audaac_rec_install_bits(audaac_header,
1253                          2,
1254                          0,
1255                          &audaac_hdr_bit_index);
1256
1257} /* audaac_rec_install_adts_header_variable */
1258
1259static OMX_ERRORTYPE parse_pcm_header()
1260{
1261    struct wav_header hdr;
1262
1263    DEBUG_PRINT("\n***************************************************************\n");
1264    if(fread(&hdr, 1, sizeof(hdr),inputBufferFile)!=sizeof(hdr))
1265    {
1266        DEBUG_PRINT("Wav file cannot read header\n");
1267        return -1;
1268    }
1269
1270    if ((hdr.riff_id != ID_RIFF) ||
1271        (hdr.riff_fmt != ID_WAVE)||
1272        (hdr.fmt_id != ID_FMT))
1273    {
1274        DEBUG_PRINT("Wav file is not a riff/wave file\n");
1275        return -1;
1276    }
1277
1278    if (hdr.audio_format != FORMAT_PCM)
1279    {
1280        DEBUG_PRINT("Wav file is not adpcm format %d and fmt size is %d\n",
1281                      hdr.audio_format, hdr.fmt_sz);
1282        return -1;
1283    }
1284
1285    DEBUG_PRINT("Samplerate is %d\n", hdr.sample_rate);
1286    DEBUG_PRINT("Channel Count is %d\n", hdr.num_channels);
1287    DEBUG_PRINT("\n***************************************************************\n");
1288
1289    samplerate = hdr.sample_rate;
1290    channels = hdr.num_channels;
1291
1292    return OMX_ErrorNone;
1293}
1294