home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2004 March / PCWELT_3_2004.ISO / pcwsoft / flaskmpeg_078_39_src.z.exe / flaskmpeg / Audio / Audio.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2002-10-28  |  30.0 KB  |  1,080 lines

  1. /* 
  2.  *  Audio.cpp 
  3.  *
  4.  *    Copyright (C) Alberto Vigata - January 2000 - ultraflask@yahoo.com
  5.  *
  6.  *  This file is part of FlasKMPEG, a free MPEG to MPEG/AVI converter
  7.  *    
  8.  *  FlasKMPEG is free software; you can redistribute it and/or modify
  9.  *  it under the terms of the GNU General Public License as published by
  10.  *  the Free Software Foundation; either version 2, or (at your option)
  11.  *  any later version.
  12.  *   
  13.  *  FlasKMPEG is distributed in the hope that it will be useful,
  14.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.  *  GNU General Public License for more details.
  17.  *   
  18.  *  You should have received a copy of the GNU General Public License
  19.  *  along with GNU Make; see the file COPYING.  If not, write to
  20.  *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 
  21.  *
  22.  */
  23.  
  24. #include <stdio.h>
  25. #include "Audio.h"
  26. #include "debug.h"
  27.  
  28.  
  29.  
  30. //char *sAC3SampleFreq[4]={"48 Khz","44.1 Khz", "32 Khz","Unexpected"};
  31. int    AC3Acmod[]={ 2, 1, 2, 3, 3, 4, 4, 5 };
  32. int    AC3SampleFreq[4]={48000,44100,32000,0};
  33.  
  34. struct TFrameSize framesize_table[] = {
  35.       { 32  ,{64   ,69   ,96   } },
  36.       { 32  ,{64   ,70   ,96   } },
  37.       { 40  ,{80   ,87   ,120  } },
  38.       { 40  ,{80   ,88   ,120  } },
  39.       { 48  ,{96   ,104  ,144  } },
  40.       { 48  ,{96   ,105  ,144  } },
  41.       { 56  ,{112  ,121  ,168  } },
  42.       { 56  ,{112  ,122  ,168  } },
  43.       { 64  ,{128  ,139  ,192  } },
  44.       { 64  ,{128  ,140  ,192  } },
  45.       { 80  ,{160  ,174  ,240  } },
  46.       { 80  ,{160  ,175  ,240  } },
  47.       { 96  ,{192  ,208  ,288  } },
  48.       { 96  ,{192  ,209  ,288  } },
  49.       { 112 ,{224  ,243  ,336  } },
  50.       { 112 ,{224  ,244  ,336  } },
  51.       { 128 ,{256  ,278  ,384  } },
  52.       { 128 ,{256  ,279  ,384  } },
  53.       { 160 ,{320  ,348  ,480  } },
  54.       { 160 ,{320  ,349  ,480  } },
  55.       { 192 ,{384  ,417  ,576  } },
  56.       { 192 ,{384  ,418  ,576  } },
  57.       { 224 ,{448  ,487  ,672  } },
  58.       { 224 ,{448  ,488  ,672  } },
  59.       { 256 ,{512  ,557  ,768  } },
  60.       { 256 ,{512  ,558  ,768  } },
  61.       { 320 ,{640  ,696  ,960  } },
  62.       { 320 ,{640  ,697  ,960  } },
  63.       { 384 ,{768  ,835  ,1152 } },
  64.       { 384 ,{768  ,836  ,1152 } },
  65.       { 448 ,{896  ,975  ,1344 } },
  66.       { 448 ,{896  ,976  ,1344 } },
  67.       { 512 ,{1024 ,1114 ,1536 } },
  68.       { 512 ,{1024 ,1115 ,1536 } },
  69.       { 576 ,{1152 ,1253 ,1728 } },
  70.       { 576 ,{1152 ,1254 ,1728 } },
  71.       { 640 ,{1280 ,1393 ,1920 } },
  72.       { 640 ,{1280 ,1394 ,1920 } }};
  73.  
  74. static const int mpeg1_bitrate_table[3][15] = {
  75.     { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 },
  76.     { 0, 32, 48, 56,  64,  80,  96, 112, 128, 160, 192, 224, 256, 320, 384 },
  77.     { 0, 32, 40, 48,  56,  64,  80,  96, 112, 128, 160, 192, 224, 256, 320 }
  78. };
  79.  
  80. static const int mpeg1_sampling_frequency[4] = { 44100, 48000, 32000 , 0 };
  81.  
  82. static const int mpeg2_bitrate_table[3][15] = {
  83.     {0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, },
  84.     {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, },
  85.     {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, },
  86. };
  87.  
  88. #define IsAc3Track(streamId, subStreamId) ( (subStreamId>= 0x80 && subStreamId <= 0x87 && streamId==0xBD) )
  89. #define IsMpegTrack(streamId, subStreamId ) ((streamId >= 0xC0) && (streamId <= 0xDF)) 
  90.  
  91. #define IsAudioTrack(streamId, subStreamId) ( IsAc3Track(streamId, subStreamId) || IsMpegTrack(streamId, subStreamId) )
  92.  
  93. #define safedelete(x){delete (x); (x)=NULL;}
  94.  
  95. //////////////////////////////////////////////////////////////////////
  96. // Construction/Destruction
  97. //////////////////////////////////////////////////////////////////////
  98. Audio::Audio()
  99. {
  100.     
  101.     m_nStreamID     = 0;
  102.     m_nSubStreamID  = 0;
  103.   m_bAudioInfoIsValid = false;
  104.  
  105.     resampler                    =  NULL;
  106.     decoded_samples_buffer       =  NULL;
  107.     ResamplerBuffer              =  NULL;
  108.     frameFIFO                    =  NULL;
  109.  
  110.   sampleRate = 0;
  111.  
  112. }
  113.  
  114. Audio::~Audio()
  115. {
  116. }
  117.  
  118. bool Audio::Init(LPTWorkingMism pMismInfo)
  119. {
  120.  
  121.   //Start demuxer
  122.   if(!SetInput(pMismInfo))
  123.     return false;
  124.  
  125.   resampler                    =  NULL;
  126.   decoded_samples_buffer       =  NULL;
  127.   ResamplerBuffer              =  NULL;
  128.   frameFIFO                    =  NULL;
  129.   
  130.   
  131.   //file opened
  132.   CDemux::SetStreamPos(0);
  133.  
  134.   ReadSpanInit();
  135.  
  136.   bool bSuccess = true;
  137.   bool bFoundStream = false;
  138.   ui8 nStreamId, nSubStreamId;
  139.   ui32 nFramesFound=0;
  140.  
  141.   // Create frame FIFO
  142.   frameFIFO = new CAudFrameBuffer();
  143.   // Grab the first audio frame that flies around
  144.  
  145.   while(nFramesFound < 10)
  146.   {
  147.     while(frameFIFO->firstFrame==NULL && bSuccess)
  148.     {
  149.           bSuccess =ReadLPES((unsigned char **)&read_state.PES.data, &read_state.PES.pInfo);
  150.       nStreamId    = read_state.PES.pInfo.streamID;
  151.       nSubStreamId = read_state.PES.pInfo.subStreamID;
  152.  
  153.       // Find first track to know the sample rate
  154.       if( IsAudioTrack( nStreamId, nSubStreamId ) && !bFoundStream )
  155.       {
  156.         // This is the first audio track that passes
  157.         if(IsAc3Track(nStreamId, nSubStreamId))
  158.           m_nFormat = Ac3;
  159.         if( IsMpegTrack(nStreamId, nSubStreamId) )
  160.           m_nFormat = MpegAudio;
  161.  
  162.         bSuccess = true;
  163.         bFoundStream = true;
  164.         m_nStreamID    = nStreamId;
  165.         m_nSubStreamID = nSubStreamId;
  166.       }
  167.     
  168.       if(bFoundStream)
  169.       {
  170.         if(   m_nStreamID  == read_state.PES.pInfo.streamID    && 
  171.             m_nSubStreamID == read_state.PES.pInfo.subStreamID )
  172.           ParseFrameData();
  173.       }
  174.     }
  175.  
  176.     if(bSuccess)
  177.     {
  178.       // We have a frame.
  179.       // Retrieve the info for it
  180.       while(frameFIFO->firstFrame)
  181.       {
  182.         GetPropertiesFromFrame(m_nFormat,frameFIFO->firstFrame->data, &m_sAudioInfo );
  183.  
  184.         if( m_sAudioInfo.sample_rate!=sampleRate )
  185.           nFramesFound = 0;
  186.         else
  187.           nFramesFound++;
  188.  
  189.         sampleRate = m_sAudioInfo.sample_rate;
  190.         m_bAudioInfoIsValid = true;
  191.         frameFIFO->RemoveFirstFrame();
  192.         
  193.       }
  194.     }
  195.   }
  196.   safedelete(frameFIFO);
  197.  
  198.   return bSuccess;
  199. }
  200.  
  201. TAudioInfo * Audio::GetAudioInfo()
  202. {
  203.   if(m_bAudioInfoIsValid)
  204.     return &m_sAudioInfo;
  205.   else
  206.     return NULL;
  207. }
  208.  
  209. bool Audio::GetPropertiesFromFrame(AudioFormat nFormat, ui8* pFrame, TAudioInfo *pTrackInfo) 
  210. {
  211.   if(!pFrame)
  212.     return false;
  213.  
  214.   ui8 *data;
  215.   ui8 fscod, frmsizecode, acmod;
  216.  
  217.   // Mask to determine the position of the lfe bit
  218.   // depending on acmod
  219.   static ui8 lfeon[8] = {0x10, 0x10, 0x04, 0x04, 0x04, 0x01, 0x04, 0x01};
  220.  
  221.   switch( nFormat )
  222.   {
  223.   case Ac3:
  224.     data = pFrame;
  225.     fscod       = (data[4] & 0xC0) >> 6;
  226.     frmsizecode = (data[4] & 0x3F);
  227.     
  228.     pTrackInfo->sample_rate = AC3SampleFreq[fscod];
  229.     pTrackInfo->bit_rate    = framesize_table[frmsizecode].bit_rate;
  230.     
  231.     //Update channels info
  232.     acmod = data[6] >> 5;
  233.  
  234.     // retrieve more info
  235.     pTrackInfo->subwoofer = data[6] & lfeon[acmod];
  236.     
  237.     pTrackInfo->channels = AC3Acmod[acmod];
  238.     
  239.     pTrackInfo->format      = Ac3;
  240.     break;
  241.   case MpegAudio:
  242.     data = pFrame;
  243.     long hdr;
  244.     // Yay!  A valid MPEG header!  Parse it!
  245.     
  246.     // 0000F0FF 12 bits    sync mark
  247.     //
  248.     // 00000800  1 bit    version
  249.     // 00000600  2 bits    layer (3 = layer I, 2 = layer II, 1 = layer III)
  250.     // 00000100  1 bit    error protection (0 = enabled)
  251.     //
  252.     // 00F00000  4 bits    bitrate_index
  253.     // 000C0000  2 bits    sampling_freq
  254.     // 00020000  1 bit    padding
  255.     // 00010000  1 bit    extension
  256.     //
  257.     // C0000000  2 bits    mode (0=stereo, 1=joint stereo, 2=dual channel, 3=mono)
  258.     // 30000000  2 bits    mode_ext
  259.     // 08000000  1 bit    copyright
  260.     // 04000000  1 bit    original
  261.     // 03000000  2 bits    emphasis
  262.     int is_mpeg2, layer, is_errorprotected, br_index, bitrate, sr_index, frequency;
  263.     
  264.     memcpy(&hdr, data, 4);
  265.     //hdr = ((hdr&0xFF000000)>>24) | ((hdr&0x00FF0000)>>8) |
  266.     //      ((hdr&0x0000FF00)<< 8) | ((hdr&0x000000FF)<<24);
  267.     
  268.     is_mpeg2            = !(hdr & 0x00000800);
  269.     layer                = 4 - (hdr>>9)&3;
  270.     is_errorprotected    = !(hdr & 0x00000100);
  271.     br_index            = (hdr>>20)&15;
  272.     bitrate                = (is_mpeg2 ? mpeg2_bitrate_table : mpeg1_bitrate_table)[layer-1][br_index];
  273.     sr_index            = (hdr>>18)&3;
  274.     frequency            = mpeg1_sampling_frequency[sr_index];
  275.     mode                = (hdr>>30)&3;
  276.     
  277.     if (is_mpeg2)
  278.       frequency>>=1;
  279.     
  280.     pTrackInfo->sample_rate = frequency;
  281.     pTrackInfo->bit_rate    = bitrate;
  282.     pTrackInfo->channels    = (mode <= 2) ? 2 : 1;
  283.     pTrackInfo->format      = MpegAudio;
  284.     break;
  285.   case Lpcm:
  286.     break;
  287.   default:
  288.     return false;
  289.   }
  290.   return true;
  291. }
  292.  
  293. #if 0
  294. bool Audio::GetTrackProperties(TAudioTrack *pTrack)
  295. {
  296.     TTimeSpan span;
  297.     span.start=0;
  298.     span.end = 0;
  299.  
  300.  
  301.     // Create frame FIFO
  302.     frameFIFO = new CAudFrameBuffer();
  303.     ReadSpanInit();
  304.  
  305.   while(ReadSpan(&span, 1*MPEG2_CLK_REF) )
  306.   {
  307.     if(frameFIFO->firstFrame==NULL)
  308.       return false;
  309.     else
  310.     {
  311.       GetPropertiesFromFrame(pTrack->nFormat, frameFIFO->firstFrame->data, pTrack);
  312.       return true;
  313.       break;
  314.     }
  315.   }
  316.  
  317.     safedelete(frameFIFO);
  318.     return true;
  319. }
  320.  
  321. #endif 
  322.  
  323. bool Audio::SetTrackIdsAndFormat(TAudioTrack *pTrack)
  324. {
  325.   if(IsAc3Track(pTrack->nStreamId, pTrack->nSubStreamId))
  326.     m_nFormat = Ac3;
  327.   else if (IsMpegTrack(pTrack->nStreamId, pTrack->nSubStreamId))
  328.     m_nFormat = MpegAudio;
  329.   else
  330.     return false;
  331.   
  332.   m_nStreamID    = pTrack->nStreamId;
  333.   m_nSubStreamID = pTrack->nSubStreamId;
  334.  
  335.   return true;
  336. }
  337.  
  338. //DO_AUDIO start
  339. bool Audio::Start(int out_sFreq, int audioMode, TAudioProperties *pAudProps ){
  340.  
  341.   if(!pAudProps)
  342.     return false;
  343.  
  344.   m_sAudioProperties = *pAudProps;
  345.  
  346.  
  347.   // Set some other stuff.
  348.   m_bIsPreview     = (audioMode & AUDIO_PREVIEW)>0;
  349.   m_bDontNormalize = (audioMode & AUDIO_DONT_NORMALIZE)>0;
  350.  
  351.   // From the track told set the format
  352.   if(!SetTrackIdsAndFormat(&pAudProps->sAudioTrack))
  353.     return false;
  354.  
  355.     // read init
  356.     frame_in_progress = false;
  357.   eof_flag          = 0;
  358.     aud_clk           = 0;
  359.     tot_n_samples     = 0;
  360.     StartReadLPES();
  361.  
  362.     if(audioMode&DO_AUDIO)
  363.   {
  364.         ReadSpanInit();
  365.         justStarted      = true;
  366.   
  367.       // Create decoders
  368.     m_pA52Dec  = new CA52Dec;
  369.       m_pA52Dec->Init();
  370.       MPEGDec = new CMPEGDec;
  371.       MPEGDec->Start();
  372.  
  373.     // Set m_pA52Dec properties
  374.     m_pA52Dec->SetProperties(m_sAudioProperties.dolby_surround_downmix, 
  375.                           m_sAudioProperties.multichannel_volume,
  376.                           TAUDIOPROPERTIES_MCHANNEL_MAX_RANGE,
  377.                           m_sAudioProperties.center,
  378.                           m_sAudioProperties.front,
  379.                           m_sAudioProperties.rear);
  380.  
  381.     // Create the frame FIFO queue    
  382.         frameFIFO = new CAudFrameBuffer();
  383.  
  384.         // Connect all the pieces together
  385.         if(out_sFreq!=sampleRate)
  386.     {
  387.       // Input and Output sample frecuencies don't match
  388.       // Calculate relationship between them
  389.             double factor= (double)out_sFreq/(double)sampleRate;
  390.  
  391.       // Create buffer for the decoded samples. Tell him the audio class 
  392.       // is its source of data
  393.             decoded_samples_buffer = new CAsyncBuffer(this, PCM_1SECOND_SIZE, 1);
  394.  
  395.       // Create a resampler object, and tell him where he has to extract the data from
  396.             resampler= new CResampler(factor, 2/*stereo*/,(CAsyncBuffer *)decoded_samples_buffer);
  397.             resampler->ResampleFastStart();
  398.  
  399.       // Create the buffer where resampled samples are going to go
  400.             ResamplerBuffer= new CAsyncBuffer(resampler, 4096, 10);
  401.  
  402.       // Create audio compressor
  403.             AC.CreateCompressor( ResamplerBuffer );
  404.             compressed_samples_buffer = new CAsyncBuffer( (CDataSource *)&AC , RMS_WINDOW*4, 20 );
  405.  
  406.             destination_buffer = compressed_samples_buffer;
  407.             
  408.         }
  409.         else
  410.     {
  411.             decoded_samples_buffer= new CAsyncBuffer((CDataSource *)this, PCM_1SECOND_SIZE,1);
  412.  
  413.             AC.CreateCompressor( decoded_samples_buffer );
  414.             compressed_samples_buffer = new CAsyncBuffer( (CDataSource *)&AC , RMS_WINDOW*4, 20 );
  415.  
  416.             destination_buffer = compressed_samples_buffer;
  417.         }
  418.     // Set the compressor properties
  419.     AC.SetProperties(m_sAudioProperties.drc, m_sAudioProperties.drc_value);
  420.    
  421.         return true;
  422.     }
  423.     return false;
  424. }
  425.  
  426.  
  427. int Audio::SetAudioMode(int audioMode)
  428.  
  429. {
  430.  
  431.     Audio::audioMode=audioMode;
  432.  
  433.  
  434.  
  435.     return 1;
  436.  
  437. }
  438.  
  439.  
  440.  
  441.  
  442. //DSC start
  443. int Audio::Start(char *inputFileName, int audioMode)
  444. {    
  445.     StartReadLPES();
  446.     //eos
  447.     resampler=NULL;
  448.     decoded_samples_buffer=NULL;
  449.     ResamplerBuffer=NULL;
  450.     frameFIFO=NULL;
  451.     
  452.     frameFIFO = new CAudFrameBuffer();
  453.     ReadSpanInit();
  454.     char szTemp[1024];
  455.     
  456.     if(audioMode&DSC){
  457.         justStarted=true;
  458.         if(m_nFormat==Ac3){
  459.  
  460.             strcpy(szTemp, inputFileName);
  461.             strcat(szTemp, ".AC3");
  462.             if((hOutputFile=fopen(szTemp,"wb"))==NULL)
  463.                 return 0;
  464.         }
  465.         else{
  466.             strcpy(szTemp, inputFileName);
  467.             strcat(szTemp, ".mp2");
  468.             if((hOutputFile=fopen(szTemp,"wb"))==NULL)
  469.                 return 0;
  470.         }
  471.  
  472.         //AlignFrame();
  473.         justStarted=true;
  474.         firstPTSfound=false;
  475.     }
  476.  
  477.  
  478.     return 1;
  479. }
  480.  
  481. int Audio::Stop()
  482. {
  483.     stopDecoder=true;
  484.     justStarted=false;
  485.  
  486.     if(audioMode==DSC){
  487.         //EndWritingFrame();
  488.         //close file
  489.         fclose(hOutputFile);
  490.     }
  491.     else if(audioMode==DO_AUDIO)
  492.     {
  493.         if(resampler)
  494.     {
  495.             resampler->ResampleFastStop();
  496.             safedelete(resampler);
  497.         }
  498.         if(decoded_samples_buffer)
  499.       safedelete(decoded_samples_buffer);
  500.     
  501.     if(ResamplerBuffer)
  502.             safedelete(ResamplerBuffer);
  503.  
  504.       if(m_pA52Dec)
  505.       safedelete(m_pA52Dec);
  506.  
  507.         if(MPEGDec)
  508.       safedelete(MPEGDec) ;
  509.     }
  510.   if(frameFIFO)
  511.     safedelete(frameFIFO);
  512.  
  513.     return 1;
  514. }
  515. /*
  516. int Audio::GetAudio()
  517. {
  518.     int bytesRead;
  519.     if( (bytesRead=ReadStream( buffer, AUDIO_BUFFER_SIZE)) == AUDIO_BUFFER_SIZE){
  520.         fwrite( buffer, 1, bytesRead, hOutputFile); 
  521.         return 1;
  522.     }
  523.     else{
  524.             fwrite( buffer, 1, bytesRead, hOutputFile); 
  525.             goto end;
  526.     }
  527.  
  528. end:
  529. //    decoderStopped=true;
  530.     return 0;
  531.  
  532. }
  533. */
  534. //GetAudio Direct Stream Copy
  535. int Audio::GetAudioDSC(i64 PTS, i64 videoStreamPos)
  536. {
  537.     TTimeSpan span;
  538.  
  539.     //Parse packets up to videoStreamPos
  540.  
  541.     while( CDemux::GetStreamPos() < (ui64)videoStreamPos){
  542.         ReadSpan(&span, MPEG2_CLK_REF);
  543.         while( frameFIFO->firstFrame ){
  544.             fwrite( frameFIFO->firstFrame->data, frameFIFO->firstFrame->datasize , 1, hOutputFile); 
  545.             frameFIFO->RemoveFrame( frameFIFO->firstFrame );
  546.         }
  547.     }
  548.     return 1;
  549. }
  550.  
  551. int Audio::GetSamples(int frame, short **buffer, int nSamples)
  552. {
  553.   // React to some real time changes
  554.   if(m_bIsPreview)
  555.   {
  556.     AC.SetProperties(m_sAudioProperties.drc, m_sAudioProperties.drc_value);
  557.  
  558.     if(m_pA52Dec)
  559.         m_pA52Dec->SetProperties(m_sAudioProperties.dolby_surround_downmix, 
  560.                               m_sAudioProperties.multichannel_volume,
  561.                               TAUDIOPROPERTIES_MCHANNEL_MAX_RANGE,
  562.                               m_sAudioProperties.center,
  563.                               m_sAudioProperties.front,
  564.                               m_sAudioProperties.rear);
  565.   }
  566.  
  567. //  try 
  568. //  {
  569.       destination_buffer->ReadBuffer((char **)buffer, nSamples*4);
  570.  
  571.     if(m_sAudioProperties.normalize && !m_bDontNormalize)
  572.       Normalize((i16*)*buffer, nSamples, (float)m_sAudioProperties.normalize_value/100.0f);
  573. //  }
  574. //  catch( ... )
  575. //  {
  576. //    DBG_STR((str, "Audio::GetSamples - Exception thrown!\n"))
  577. //    eof_flag = 1;
  578. //  }
  579.  
  580.     return !eof_flag;
  581. }
  582.  
  583. void Audio::Normalize(i16 *pData, ui32 nSamples, float gain)
  584. {
  585. #define saturate(x) (((x)>32767) ? 32767 : (x) < -32768 ? -32768 : (x) )
  586.   ui32 i;
  587.   for(i=0; i<nSamples; i++)
  588.   {
  589.     pData[2*i] = (i16)saturate((float)pData[2*i] * gain);
  590.     pData[2*i+1] = (i16)saturate((float)pData[2*i+1] * gain);
  591.   }
  592. }
  593.  
  594. //-----------------------------------------------------------------------------
  595. #define ROUND(x) ( ((x-floor(x)) > 0.5) ? ceil(x) : floor(x) )
  596. int Audio::read(char *buffer){
  597.   
  598.   TTimeSpan span;
  599.   span.start=0;
  600.   span.end = 0;
  601.   
  602.   CAudioFrame  *frame, *nextframe = NULL;
  603.    
  604.   eof_flag = !ReadSpan(&span, 1*MPEG2_CLK_REF);
  605.   
  606.   if( (span.end - span.start)> (3*MPEG2_CLK_REF)/2 ) {
  607.     DBG_STR(( str, "Audio::read - span: %I64d, %I64d ms !!\n", span.end - span.start, (span.end - span.start)/27000 ))
  608.     span.end = span.start + (3*MPEG2_CLK_REF)/2;
  609.     eof_flag = 1;
  610.   }
  611.  
  612.   // Initialize local variables
  613.   i32   diff;
  614.   ui32  span_samples_offset =0;
  615.   ui32  frame_pcm_samples;
  616.   ui32  span_ptr = 0;
  617.   
  618.   // Update local audio clock, number of samples for this span,
  619.   //      and total number of samples.
  620.   aud_clk        += span.end - span.start;
  621.   ui32 n_samples  = (ui32)ROUND((double)(aud_clk*(i64)sampleRate)/(double)MPEG2_CLK_REF) - tot_n_samples;
  622.   tot_n_samples  += n_samples;
  623.   
  624.   
  625.   frame_pcm_samples = m_nFormat==Ac3 ? 1536 : (m_nFormat==MpegAudio ? 1152 : 0) ;
  626.   ui32 frame_duration = (ui32)(((double)frame_pcm_samples/(double)sampleRate) * (double)MPEG2_CLK_REF);
  627.   
  628.   short *samples = (short *)buffer;
  629.   memset(samples, 0, n_samples*4);
  630.   
  631.  
  632.  
  633.   // If there was a frame in progress from the previous
  634.   // call, copy the remaining data
  635.   if(frame_in_progress)
  636.   {
  637.     memcpy( &samples[span_ptr*2], &temp_decoded_frame[temp_decoded_ptr*2], fip_remaining_bytes);
  638.     span_ptr += (fip_remaining_bytes>>2);
  639.     frame_in_progress = false;
  640.   }
  641.   
  642.   // Loop through the frame buffer
  643.   // and parse the frames
  644.  
  645.   // If there are any frames
  646.   if(frameFIFO->firstFrame)
  647.   {
  648.     if(!m_bAudioInfoIsValid)
  649.     {
  650.       GetPropertiesFromFrame(m_nFormat, frameFIFO->firstFrame->data, &m_sAudioInfo);
  651.       m_bAudioInfoIsValid = true;
  652.     }
  653.     // Take first frame
  654.     frame = frameFIFO->firstFrame;
  655.     while( span_ptr < n_samples )
  656.     {
  657.       // we update nextframe here because it's likely to remove the
  658.       // present frame during this iteration
  659.       nextframe = frame->next;
  660.       // If the frame doesn't fit in this span
  661.       if( (span_ptr + frame_pcm_samples ) > n_samples)
  662.       {
  663.         frame_in_progress=true;
  664.         decodeFrame( frame, temp_decoded_frame );
  665.         temp_decoded_ptr = n_samples - span_ptr;
  666.         memcpy( &samples[span_ptr*2], temp_decoded_frame, temp_decoded_ptr*4);
  667.         
  668.         fip_remaining_bytes = (frame_pcm_samples*4) - (temp_decoded_ptr*4);
  669.         frameFIFO->RemoveFrame(frame);
  670.         span_ptr += temp_decoded_ptr;
  671.         goto end;
  672.       }
  673.       if(frame->pInfo.hasPTS)
  674.       {    
  675.         if( (frame->pInfo.PTS >= span.start) )
  676.         {
  677.           if(frame->pInfo.PTS > span.end)
  678.             //frame out of the span
  679.             goto end;
  680.           // The frame starts inside this span
  681.           /*                    if( (span.end - frame->pInfo.PTS) < frame_duration ){
  682.           if(frame_in_progress){ //Oddly there is already a frame in progress. Remove it
  683.           frameFIFO->RemoveFrame(frame);
  684.           goto end;
  685.           }
  686.           //The frame doesn't completely fit into this span
  687.           frame_in_progress=true;
  688.           
  689.             decodeFrame(frame, temp_decoded_frame);
  690.             
  691.               temp_decoded_ptr = n_samples - span_ptr;
  692.               memcpy( &samples[span_ptr*2], temp_decoded_frame, temp_decoded_ptr*4);
  693.               
  694.                 fip_remaining_bytes = (frame_pcm_samples*4) - (temp_decoded_ptr*4);
  695.                 frameFIFO->RemoveFrame(frame);
  696.                 span_ptr += temp_decoded_ptr;
  697.                 
  698.                   }
  699.           else{*/
  700.           span_samples_offset = (ui32)ROUND((double)((frame->pInfo.PTS - span.start)*sampleRate)/(double)MPEG2_CLK_REF);
  701.           /*if(span_samples_offset < span_ptr){
  702.           //Something went wrong with this PTS. Put this frame
  703.           // behind the decoded data if there is room for it
  704.           if( (span_ptr+1536) <= n_samples ){
  705.           m_pA52Dec->decodeFrame((short *)frame->data, &samples[span_ptr*2]);
  706.           frameFIFO->RemoveFrame(frame);
  707.           span_ptr+= 1536;
  708.           }
  709.           goto end;
  710.         }*/
  711.           //Handle small clock jitter
  712.           diff=span_samples_offset-span_ptr;
  713.           if( diff < 0 )
  714.             span_samples_offset = span_ptr;
  715.           else
  716.           {
  717.             diff = (diff>0) ? diff : -diff;
  718.             if( diff < CLK_THRESHOLD )
  719.               span_samples_offset = span_ptr;
  720.           }
  721.           
  722.           decodeFrame(frame, &samples[span_samples_offset*2]);
  723.           
  724.           span_ptr = span_samples_offset + frame_pcm_samples;
  725.           frameFIFO->RemoveFrame(frame);
  726.           /*}*/
  727.         }
  728.         else
  729.         { 
  730.           //The frame has a PTS previous to this span. ┐┐??
  731.           //HACK
  732.           // Decode the frame if the PTS from the current time
  733.           //    is just a little bit behind
  734.           int clk_span = (int)(((double)span_ptr/(double)sampleRate) * (double)MPEG2_CLK_REF);
  735.           if( ((span.start+clk_span) - frame->pInfo.PTS)  < CLK_THRESHOLD_SPAN)
  736.           {
  737.             decodeFrame( frame, &samples[span_ptr*2] );
  738.             span_ptr += frame_pcm_samples;
  739.           }
  740.           frameFIFO->RemoveFrame(frame);
  741.         }
  742.         
  743.       }
  744.       else
  745.       {
  746.         // decode frame right away
  747.         decodeFrame( frame, &samples[span_ptr*2] );
  748.         span_ptr += frame_pcm_samples;
  749.         frameFIFO->RemoveFrame(frame);
  750.       }
  751.       
  752. end:
  753.       if( nextframe==NULL )
  754.         break;
  755.       else
  756.         frame = nextframe;
  757.     }
  758.   }
  759.   //else There are no frames to be decoded in this span
  760.  
  761.   return n_samples*4;
  762. }
  763.  
  764. //-----------------------------------------------------------------------------
  765. // SetTrack() resets the audio format
  766. void Audio::SetTrack(TAudioTrack *pAudioTrack)
  767. {
  768.   // From the track told set the format
  769.   if(!SetTrackIdsAndFormat(pAudioTrack))
  770.     return;
  771.  
  772.   if(frameFIFO)
  773.     frameFIFO->RemoveAllFrames();
  774.  
  775.   //Reset the state of all frames being grabbed
  776.   read_state.frame_in_course       = false;
  777.   read_state.header_in_course      = false;
  778.   read_state.frame_size            = 0;
  779.   read_state.frame_remaining_bytes = 0;
  780.   header_pos = 0;
  781.  
  782.   // Invalidate info
  783.   m_bAudioInfoIsValid = false;
  784. }
  785. //-----------------------------------------------------------------------------
  786. int inline Audio::ReadSpan(TTimeSpan *span, i64 time)
  787. {
  788.     int   not_eof;
  789.  
  790.     not_eof=1;
  791.     span->start = read_state.lastSCR;
  792.     span->end   = span->start;
  793.     while( ((span->end - span->start) < time) && not_eof)
  794.     {
  795.         if(       m_nStreamID == read_state.PES.pInfo.streamID    && 
  796.                  m_nSubStreamID == read_state.PES.pInfo.subStreamID )
  797.                 ParseFrameData();
  798.  
  799.         not_eof=ReadLPES((unsigned char **)&read_state.PES.data, &read_state.PES.pInfo);
  800.         if(!not_eof)
  801.             break;
  802.  
  803.         span->end   = read_state.PES.pInfo.SCR;
  804.  
  805.         // Update variables for next loop
  806.         read_state.lastSCR       = read_state.PES.pInfo.SCR;
  807.     }
  808.     return not_eof;
  809. }
  810.  
  811.  
  812. //-----------------------------------------------------------------------------
  813. int inline Audio::RetrieveFrameData()
  814. {
  815.       ui32 PES_bytes_left  = read_state.PES.pInfo.payloadSize - read_state.in_ptr;
  816.         ui8 *optr            = &read_state.frame_data[read_state.out_ptr];
  817.         ui8 *iptr            = read_state.PES.data + read_state.in_ptr;
  818.  
  819.         if(read_state.frame_remaining_bytes <= PES_bytes_left){
  820.             memcpy(optr, iptr, read_state.frame_remaining_bytes);
  821.             // Add frame to the FIFO
  822.             frameFIFO->AddFrame( read_state.frame_data, 
  823.                                  read_state.frame_size,
  824.                                 &read_state.frame_pInfo);
  825.             read_state.frame_in_course = false;
  826.             read_state.in_ptr += read_state.frame_remaining_bytes;
  827.             return 1;
  828.         }
  829.         else{
  830.             memcpy(optr, iptr, PES_bytes_left);
  831.             read_state.frame_in_course = true;
  832.             read_state.out_ptr               += PES_bytes_left;
  833.             read_state.frame_remaining_bytes -= PES_bytes_left;
  834.             return 0;
  835.         }
  836. }
  837.  
  838.  
  839. //-----------------------------------------------------------------------------
  840. void inline Audio::ParseFrameData()
  841. {
  842.     ui32 headers_found = 0;
  843.  
  844.     read_state.in_ptr = 0;
  845.  
  846.     // take any possible audio frame and put it in the audio frame FIFO
  847.     // we enter in this function when a PES of our ID was found
  848.  
  849.     // parse the frame in course
  850.     if(read_state.frame_in_course){
  851.         if(!RetrieveFrameData())
  852.             return;
  853.     }
  854.     // wh
  855.     while( read_state.in_ptr < read_state.PES.pInfo.payloadSize ){
  856.         if(FindHeader(headers_found)){
  857.             //An audio header was found
  858.             headers_found++;
  859.             if(!RetrieveFrameData())
  860.                 return;
  861.         }
  862.         else
  863.             break;
  864.     }
  865.     
  866. }
  867.  
  868. //-----------------------------------------------------------------------------
  869. int inline Audio::ParseHeader(ui32 headers_found)
  870. {
  871.   
  872.   
  873.   ui8  *data = read_state.PES.data;
  874.   ui8  fscod;
  875.   ui8  frmsizecode;
  876.   
  877.   
  878.   
  879.   if(m_nFormat==Ac3){
  880.     if( data[read_state.in_ptr]==0x0B && header_pos==0){
  881.       read_state.header_in_course = true;
  882.       header_pos = 1;
  883.       //Handle presentation info
  884.       if( (read_state.PES.pInfo.PTS != 0) && (headers_found==0)  )
  885.       {
  886.         read_state.frame_pInfo.hasPTS = true;
  887.         read_state.frame_pInfo.PTS = read_state.PES.pInfo.PTS;
  888.         // Now reset the PTS so its not used again
  889.         read_state.PES.pInfo.PTS = 0;
  890.       }
  891.       else
  892.       {
  893.         read_state.frame_pInfo.hasPTS = false;
  894.         read_state.frame_pInfo.PTS    = 0;
  895.       }
  896.       return 0;
  897.     }
  898.     
  899.     if( data[read_state.in_ptr]==0x77 && header_pos==1){
  900.       read_state.header_in_course = true;
  901.       header_pos = 2;
  902.       return 0;
  903.     }
  904.     if( header_pos==2 ){
  905.       read_state.header_in_course = true;
  906.       hdr2 = data[read_state.in_ptr];
  907.       header_pos = 3;
  908.       return 0;
  909.     }
  910.     if( header_pos==3 ){
  911.       read_state.header_in_course = true;
  912.       hdr3 = data[read_state.in_ptr];
  913.       header_pos = 4;
  914.       return 0;
  915.     } 
  916.     if( header_pos==4 ){
  917.       read_state.header_in_course = true;
  918.       fscod       = (data[read_state.in_ptr] & 0xC0) >> 6;
  919.       frmsizecode = (data[read_state.in_ptr] & 0x3F);    
  920.       
  921.       // Check fscod and frmsizecode for valid parameters
  922.       if( (fscod!=3) && (frmsizecode<38) ){
  923.         read_state.frame_size = framesize_table[frmsizecode].frm_size[fscod]*2;            
  924.         
  925.         //Reconstruct frame header
  926.         read_state.frame_data[0] = 0x0B;
  927.         read_state.frame_data[1] = 0x77;
  928.         read_state.frame_data[2] = hdr2;
  929.         read_state.frame_data[3] = hdr3;
  930.         read_state.frame_data[4] = data[read_state.in_ptr];
  931.         
  932.         
  933.         
  934.         read_state.frame_remaining_bytes = read_state.frame_size - 5;
  935.         read_state.out_ptr               = 5;
  936.         header_pos = 0;
  937.         return 1;
  938.       }
  939.     }
  940.   }
  941.   
  942.   if(m_nFormat==MpegAudio)
  943.   {
  944.     if( data[read_state.in_ptr]==0xFF && header_pos==0)
  945.     {
  946.       // MPEG audio header 0xFFF-
  947.       read_state.header_in_course = true;
  948.       header_pos = 1;
  949.       //Handle presentation info
  950.       if(    (read_state.PES.pInfo.PTS != 0) && (headers_found==0)  )
  951.       {
  952.         read_state.frame_pInfo.hasPTS = true;
  953.         read_state.frame_pInfo.PTS = read_state.PES.pInfo.PTS;
  954.         // Now reset the PTS so its not used again
  955.         read_state.PES.pInfo.PTS = 0;
  956.       }
  957.       else
  958.       {
  959.         read_state.frame_pInfo.hasPTS = false;
  960.         read_state.frame_pInfo.PTS    = 0;
  961.       }
  962.       mpeg_header[0] = data[read_state.in_ptr];
  963.       return 0;
  964.     }
  965.     if( (data[read_state.in_ptr]&0xF8)==0xF8 && header_pos==1)
  966.     {
  967.       // MPEG audio header
  968.       
  969.       mpeg_layer = (data[read_state.in_ptr]&0x06)>>1;
  970.       if( mpeg_layer==3 ) //If the frame is Layer I
  971.         mpeg_layer=1;
  972.       else
  973.         if( mpeg_layer==1 ) //If the frame is Layer III
  974.           mpeg_layer=3;
  975.         if( !mpeg_layer )
  976.           header_pos = 0;
  977.         else
  978.           header_pos = 2;
  979.         
  980.         mpeg_header[1] = data[read_state.in_ptr];
  981.         
  982.         read_state.header_in_course = true;
  983.         header_pos = 2;
  984.         return 0;
  985.     }
  986.     if( header_pos==2 )
  987.     {
  988.       read_state.header_in_course = true;
  989.       
  990.       bit_rate_index = (data[read_state.in_ptr]&0xF0)>>4;
  991.       if( bit_rate_index == 16  ||  bit_rate_index == 0 )
  992.       {
  993.         header_pos = 0;
  994.         return 0;
  995.       }
  996.       bitrate            = mpeg1_bitrate_table[mpeg_layer-1][bit_rate_index]*1000;
  997.       sampling_frequency = (data[read_state.in_ptr]&0x0C)>>2;
  998.       if( sampling_frequency == 3 )
  999.       {
  1000.         header_pos = 0;
  1001.         return 0;
  1002.       }
  1003.       padding_bit        = (data[read_state.in_ptr]&0x02)>>1;
  1004.       //Find number of slots and frame size
  1005.       if(mpeg_layer == 1)
  1006.       {
  1007.         N = (i32)floor( (12 *(double)bitrate)/(double)mpeg1_sampling_frequency[sampling_frequency] );
  1008.         N = padding_bit ? (N+1) : N;
  1009.         read_state.frame_size = N*4;
  1010.       }
  1011.       else
  1012.       {
  1013.         N = (i32)floor( (144*(double)bitrate)/(double)mpeg1_sampling_frequency[sampling_frequency] );
  1014.         N = padding_bit ? (N+1) : N;
  1015.         read_state.frame_size = N;
  1016.       }
  1017.       
  1018.       mpeg_header[2] = data[read_state.in_ptr];
  1019.       memcpy( read_state.frame_data, mpeg_header, 3);
  1020.       
  1021.       read_state.frame_remaining_bytes = read_state.frame_size - 3;
  1022.       read_state.out_ptr               = 3;
  1023.       header_pos = 0;
  1024.       return 1;
  1025.     }
  1026.   }
  1027.   header_pos = 0;
  1028.   read_state.header_in_course = false;
  1029.   return 0;
  1030. }
  1031.  
  1032. int inline Audio::FindHeader(ui32 headers_found)
  1033. {
  1034.     int header_found = false;
  1035.  
  1036.  
  1037.     //Search for an audio header from the current position
  1038.     while( read_state.in_ptr < read_state.PES.pInfo.payloadSize ){
  1039.         header_found = ParseHeader(headers_found);
  1040.         read_state.in_ptr++;
  1041.         if(header_found)
  1042.                 break;
  1043.     }
  1044.  
  1045.     return header_found;
  1046.  
  1047. }
  1048. int Audio::ReadSpanInit()
  1049. {
  1050.  
  1051.     //Force first time
  1052.     read_state.frame_in_course       = false;
  1053.     read_state.header_in_course      = false;
  1054.     read_state.frame_size            = 0;
  1055.     read_state.frame_remaining_bytes = 0;
  1056.     read_state.lastSCR = 0;
  1057.     read_state.delta = 0;    
  1058.     header_pos = 0;
  1059.     ReadLPES((unsigned char **)&read_state.PES.data, &read_state.PES.pInfo);
  1060.  
  1061.     return 1;
  1062. }
  1063.  
  1064. int inline Audio::decodeFrame(CAudioFrame *frame, short *pcm_samples)
  1065. {    
  1066.     if(m_nFormat==Ac3)
  1067.   {
  1068.         if(m_pA52Dec)
  1069.             m_pA52Dec->decodeFrame((ui8 *)pcm_samples, frame->data, frame->datasize );
  1070.         return 1536;
  1071.     }
  1072.     if(m_nFormat==MpegAudio)
  1073.   {
  1074.             MPEGDec->decodeFrame( (ui8 *)pcm_samples, frame->data, frame->datasize );
  1075.         return 1152;
  1076.     }
  1077.     return 0;
  1078. }
  1079.  
  1080.